`, 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 index(() => {\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__*/React.createElement(\"div\", _extends({\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 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 (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(event);\n if (!contains(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 index(() => {\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 insideReactTreeRef = React.useRef(false);\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 ? getChildren(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(event)) == null || _getTarget.removeEventListener('keydown', callback);\n };\n (_getTarget2 = getTarget(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 = insideReactTreeRef.current;\n insideReactTreeRef.current = 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(event);\n const inertSelector = \"[\" + createAttribute('inert') + \"]\";\n const markers = getDocument(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(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(targetRootAncestor, marker))) {\n return;\n }\n\n // Check if the click occurred on the scrollbar\n if (isHTMLElement(target) && floating) {\n // In Firefox, `target.scrollWidth > target.clientWidth` for inline\n // elements.\n const canScrollX = target.clientWidth > 0 && target.scrollWidth > target.clientWidth;\n const canScrollY = target.clientHeight > 0 && target.scrollHeight > target.clientHeight;\n let xCond = canScrollY && event.offsetX > target.clientWidth;\n\n // In some browsers it is possible to change the (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 if (canScrollY) {\n const isRTL = getComputedStyle(target).direction === 'rtl';\n if (isRTL) {\n xCond = event.offsetX <= target.offsetWidth - target.clientWidth;\n }\n }\n if (xCond || canScrollX && event.offsetY > target.clientHeight) {\n return;\n }\n }\n const nodeId = (_dataRef$current$floa2 = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa2.nodeId;\n const targetIsInsideChildren = tree && getChildren(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 ? getChildren(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(event)) == null || _getTarget3.removeEventListener(outsidePressEvent, callback);\n };\n (_getTarget4 = getTarget(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(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 insideReactTreeRef.current = false;\n }, [outsidePress, outsidePressEvent]);\n const reference = React.useMemo(() => ({\n onKeyDown: closeOnEscapeKeyDown,\n [bubbleHandlerKeys[referencePressEvent]]: event => {\n if (referencePress) {\n onOpenChange(false, event.nativeEvent, 'reference-press');\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 insideReactTreeRef.current = true;\n }\n }), [closeOnEscapeKeyDown, outsidePressEvent]);\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(() => createPubSub());\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 index(() => {\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 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 index(() => {\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\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();\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(elements.domReference))) {\n blockFocusRef.current = true;\n }\n }\n function onKeyDown() {\n keyboardModalityRef.current = true;\n }\n win.addEventListener('blur', onBlur);\n win.addEventListener('keydown', onKeyDown, true);\n return () => {\n win.removeEventListener('blur', onBlur);\n win.removeEventListener('keydown', onKeyDown, true);\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 clearTimeout(timeoutRef.current);\n };\n }, []);\n const reference = React.useMemo(() => ({\n onPointerDown(event) {\n if (isVirtualPointerEvent(event.nativeEvent)) return;\n keyboardModalityRef.current = false;\n },\n onMouseLeave() {\n blockFocusRef.current = false;\n },\n onFocus(event) {\n if (blockFocusRef.current) return;\n const target = getTarget(event.nativeEvent);\n if (visibleOnly && isElement(target)) {\n try {\n // Mac Safari unreliably matches `:focus-visible` on the reference\n // if focus was outside the page initially - use the fallback\n // instead.\n if (isSafari() && isMac()) throw Error();\n if (!target.matches(':focus-visible')) return;\n } catch (e) {\n // Old browsers will throw an error when using `:focus-visible`.\n if (!keyboardModalityRef.current && !isTypeableElement(target)) {\n return;\n }\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((_dataRef$current$floa = dataRef.current.floatingContext) == null ? void 0 : _dataRef$current$floa.refs.floating.current, activeEl) || contains(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\nconst ACTIVE_KEY = 'active';\nconst SELECTED_KEY = 'selected';\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\nlet isPreventScrollSupported = false;\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) {\n const vertical = rtl ? key === ARROW_RIGHT : key === ARROW_LEFT;\n const horizontal = key === ARROW_UP;\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 } = 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 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 const onNavigate = useEffectEvent(unstable_onNavigate);\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 forceSyncFocus = 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(function (listRef, indexRef, forceScrollIntoView) {\n if (forceScrollIntoView === void 0) {\n forceScrollIntoView = false;\n }\n function runFocus(item) {\n if (virtual) {\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 preventScroll: true,\n // Mac Safari does not move the virtual cursor unless the focus call\n // is sync. However, for the very first focus call, we need to wait\n // for the position to be ready in order to prevent unwanted\n // scrolling. This means the virtual cursor will not move to the first\n // item when first opening the floating element, but will on\n // subsequent calls. `preventScroll` is supported in modern Safari,\n // so we can use that instead.\n // iOS Safari must be async or the first item will not be focused.\n sync: isMac() && isSafari() ? isPreventScrollSupported || forceSyncFocus.current : false\n });\n }\n }\n const initialItem = listRef.current[indexRef.current];\n if (initialItem) {\n runFocus(initialItem);\n }\n requestAnimationFrame(() => {\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 index(() => {\n document.createElement('div').focus({\n get preventScroll() {\n isPreventScrollSupported = true;\n return false;\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 index(() => {\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(selectedIndex);\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(null);\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 index(() => {\n if (!enabled) return;\n if (open && elements.floating) {\n if (activeIndex == null) {\n forceSyncFocus.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(listRef, indexRef);\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 ? getMinIndex(listRef, disabledIndicesRef.current) : getMaxIndex(listRef, disabledIndicesRef.current);\n keyRef.current = null;\n onNavigate(indexRef.current);\n }\n };\n waitForListPopulated();\n }\n } else if (!isIndexOutOfBounds(listRef, activeIndex)) {\n indexRef.current = activeIndex;\n focusItem(listRef, indexRef, forceScrollIntoViewRef.current);\n forceScrollIntoViewRef.current = false;\n }\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 index(() => {\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(elements.floating));\n const treeContainsActiveEl = nodes.some(node => node.context && contains(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 index(() => {\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 index(() => {\n previousOnNavigateRef.current = onNavigate;\n previousMountedRef.current = !!elements.floating;\n });\n index(() => {\n if (!open) {\n keyRef.current = null;\n }\n }, [open]);\n index(() => {\n previousOpenRef.current = open;\n }, [open]);\n const hasActiveIndex = activeIndex != null;\n const item = React.useMemo(() => {\n function syncCurrentTarget(currentTarget) {\n if (!open) return;\n const index = listRef.current.indexOf(currentTarget);\n if (index !== -1) {\n onNavigate(index);\n }\n }\n const props = {\n onFocus(_ref) {\n let {\n currentTarget\n } = _ref;\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 ...(focusItemOnHover && {\n onMouseMove(_ref3) {\n let {\n currentTarget\n } = _ref3;\n syncCurrentTarget(currentTarget);\n },\n onPointerLeave(_ref4) {\n let {\n pointerType\n } = _ref4;\n if (!isPointerModalityRef.current || pointerType === 'touch') {\n return;\n }\n indexRef.current = -1;\n focusItem(listRef, indexRef);\n onNavigate(null);\n if (!virtual) {\n enqueueFocus(floatingFocusElementRef.current, {\n preventScroll: true\n });\n }\n }\n })\n };\n return props;\n }, [open, floatingFocusElementRef, focusItem, focusItemOnHover, listRef, onNavigate, virtual]);\n const commonOnKeyDown = useEffectEvent(event => {\n isPointerModalityRef.current = false;\n forceSyncFocus.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)) {\n stopEvent(event);\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 = getMinIndex(listRef, disabledIndices);\n const maxIndex = getMaxIndex(listRef, disabledIndices);\n if (!typeableComboboxReference) {\n if (event.key === 'Home') {\n stopEvent(event);\n indexRef.current = minIndex;\n onNavigate(indexRef.current);\n }\n if (event.key === 'End') {\n stopEvent(event);\n indexRef.current = maxIndex;\n onNavigate(indexRef.current);\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 = buildCellMap(sizes, cols, dense);\n const minGridIndex = cellMap.findIndex(index => index != null && !isDisabled(listRef.current, index, disabledIndices));\n // last enabled index\n const maxGridIndex = cellMap.reduce((foundIndex, index, cellIndex) => index != null && !isDisabled(listRef.current, 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: getCellIndices([...(disabledIndices || listRef.current.map((_, index) => isDisabled(listRef.current, index) ? index : undefined)), undefined], cellMap),\n minIndex: minGridIndex,\n maxIndex: maxGridIndex,\n prevIndex: getCellIndexOfCorner(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(indexRef.current);\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(indexRef.current);\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 : findNonDisabledIndex(listRef, {\n startingIndex: currentIndex,\n disabledIndices\n });\n } else {\n indexRef.current = Math.min(maxIndex, findNonDisabledIndex(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 : findNonDisabledIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n });\n } else {\n indexRef.current = Math.max(minIndex, findNonDisabledIndex(listRef, {\n startingIndex: currentIndex,\n decrement: true,\n disabledIndices\n }));\n }\n }\n if (isIndexOutOfBounds(listRef, indexRef.current)) {\n onNavigate(null);\n } else {\n onNavigate(indexRef.current);\n }\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 ...(!isTypeableCombobox(elements.domReference) && ariaActiveDescendantProp),\n onKeyDown: commonOnKeyDown,\n onPointerMove() {\n isPointerModalityRef.current = true;\n }\n };\n }, [ariaActiveDescendantProp, commonOnKeyDown, elements.domReference, orientation]);\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);\n const isMainKey = isMainOrientationKey(event.key, orientation);\n const isNavigationKey = (nested ? isCrossOpenKey : 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\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 keyRef.current = nested && isMainKey ? null : event.key;\n }\n if (nested) {\n if (isCrossOpenKey) {\n stopEvent(event);\n if (open) {\n indexRef.current = getMinIndex(listRef, disabledIndicesRef.current);\n onNavigate(indexRef.current);\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(indexRef.current);\n }\n }\n },\n onFocus() {\n if (open && !virtual) {\n onNavigate(null);\n }\n },\n onPointerDown: checkVirtualPointer,\n onMouseDown: checkVirtualMouse,\n onClick: checkVirtualMouse\n };\n }, [activeId, ariaActiveDescendantProp, commonOnKeyDown, disabledIndicesRef, focusItemOnOpen, listRef, nested, onNavigate, onOpenChange, open, openOnArrowKeyDown, orientation, 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 _componentRoleToAriaR;\n if (props === void 0) {\n props = {};\n }\n const {\n open,\n floatingId\n } = context;\n const {\n enabled = true,\n role = 'dialog'\n } = props;\n const ariaRole = (_componentRoleToAriaR = componentRoleToAriaRoleMap.get(role)) != null ? _componentRoleToAriaR : role;\n const referenceId = useId();\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 + \"-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 return {\n ...commonProps,\n 'aria-selected': active && selected\n };\n case 'combobox':\n {\n return {\n ...commonProps,\n ...(active && {\n 'aria-selected': true\n })\n };\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 index(() => {\n if (!floating) return;\n if (open) {\n setStatus('initial');\n const frame = requestAnimationFrame(() => {\n setStatus('open');\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 index(() => {\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();\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 index(() => {\n if (open) {\n clearTimeout(timeoutIdRef.current);\n matchIndexRef.current = null;\n stringRef.current = '';\n }\n }, [open]);\n index(() => {\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 clearTimeout(timeoutIdRef.current);\n timeoutIdRef.current = 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 */\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 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 detectOverflow(getArgsWithCustomFloatingHeight(nextArgs, scrollEl.scrollHeight + clientTop + floating.clientTop), detectOverflowOptions);\n const refOverflow = await 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 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 */\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 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 let timeoutId;\n let hasLanded = false;\n let lastX = null;\n let lastY = null;\n let lastCursorTime = performance.now();\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 clearTimeout(timeoutId);\n onClose();\n }\n clearTimeout(timeoutId);\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 && getChildren(tree.nodesRef.current, nodeId).some(_ref2 => {\n let {\n context\n } = _ref2;\n return context == null ? void 0 : context.open;\n })) {\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(_ref3) {\n let [x, y] = _ref3;\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 timeoutId = 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, inner, safePolygon, useClick, useClientPoint, useDelayGroup, useDelayGroupContext, useDismiss, useFloating, useFloatingNodeId, useFloatingParentNodeId, useFloatingPortalNode, useFloatingRootContext, useFloatingTree, useFocus, useHover, useId, useInnerOffset, useInteractions, useListItem, useListNavigation, useMergeRefs, useRole, useTransitionStatus, useTransitionStyles, useTypeahead };\n","function memo(getDeps, fn, opts) {\n let deps = opts.initialDeps ?? [];\n let result;\n return () => {\n var _a, _b, _c, _d;\n let depTime;\n if (opts.key && ((_a = opts.debug) == null ? void 0 : _a.call(opts))) depTime = Date.now();\n const newDeps = getDeps();\n const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);\n if (!depsChanged) {\n return result;\n }\n deps = newDeps;\n let resultTime;\n if (opts.key && ((_b = opts.debug) == null ? void 0 : _b.call(opts))) resultTime = Date.now();\n result = fn(...newDeps);\n if (opts.key && ((_c = opts.debug) == null ? void 0 : _c.call(opts))) {\n const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;\n const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;\n const resultFpsPercentage = resultEndTime / 16;\n const pad = (str, num) => {\n str = String(str);\n while (str.length < num) {\n str = \" \" + str;\n }\n return str;\n };\n console.info(\n `%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`,\n `\n font-size: .6rem;\n font-weight: bold;\n color: hsl(${Math.max(\n 0,\n Math.min(120 - 120 * resultFpsPercentage, 120)\n )}deg 100% 31%);`,\n opts == null ? void 0 : opts.key\n );\n }\n (_d = opts == null ? void 0 : opts.onChange) == null ? void 0 : _d.call(opts, result);\n return result;\n };\n}\nfunction notUndefined(value, msg) {\n if (value === void 0) {\n throw new Error(`Unexpected undefined${msg ? `: ${msg}` : \"\"}`);\n } else {\n return value;\n }\n}\nconst approxEqual = (a, b) => Math.abs(a - b) < 1;\nconst debounce = (targetWindow, fn, ms) => {\n let timeoutId;\n return function(...args) {\n targetWindow.clearTimeout(timeoutId);\n timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms);\n };\n};\nexport {\n approxEqual,\n debounce,\n memo,\n notUndefined\n};\n//# sourceMappingURL=utils.js.map\n","import { debounce, memo, notUndefined, approxEqual } from \"./utils.js\";\nconst defaultKeyExtractor = (index) => index;\nconst defaultRangeExtractor = (range) => {\n const start = Math.max(range.startIndex - range.overscan, 0);\n const end = Math.min(range.endIndex + range.overscan, range.count - 1);\n const arr = [];\n for (let i = start; i <= end; i++) {\n arr.push(i);\n }\n return arr;\n};\nconst observeElementRect = (instance, cb) => {\n const element = instance.scrollElement;\n if (!element) {\n return;\n }\n const targetWindow = instance.targetWindow;\n if (!targetWindow) {\n return;\n }\n const handler = (rect) => {\n const { width, height } = rect;\n cb({ width: Math.round(width), height: Math.round(height) });\n };\n handler(element.getBoundingClientRect());\n if (!targetWindow.ResizeObserver) {\n return () => {\n };\n }\n const observer = new targetWindow.ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry == null ? void 0 : entry.borderBoxSize) {\n const box = entry.borderBoxSize[0];\n if (box) {\n handler({ width: box.inlineSize, height: box.blockSize });\n return;\n }\n }\n handler(element.getBoundingClientRect());\n });\n observer.observe(element, { box: \"border-box\" });\n return () => {\n observer.unobserve(element);\n };\n};\nconst addEventListenerOptions = {\n passive: true\n};\nconst observeWindowRect = (instance, cb) => {\n const element = instance.scrollElement;\n if (!element) {\n return;\n }\n const handler = () => {\n cb({ width: element.innerWidth, height: element.innerHeight });\n };\n handler();\n element.addEventListener(\"resize\", handler, addEventListenerOptions);\n return () => {\n element.removeEventListener(\"resize\", handler);\n };\n};\nconst supportsScrollend = typeof window == \"undefined\" ? true : \"onscrollend\" in window;\nconst observeElementOffset = (instance, cb) => {\n const element = instance.scrollElement;\n if (!element) {\n return;\n }\n const targetWindow = instance.targetWindow;\n if (!targetWindow) {\n return;\n }\n let offset = 0;\n const fallback = instance.options.useScrollendEvent && supportsScrollend ? () => void 0 : debounce(\n targetWindow,\n () => {\n cb(offset, false);\n },\n instance.options.isScrollingResetDelay\n );\n const createHandler = (isScrolling) => () => {\n const { horizontal, isRtl } = instance.options;\n offset = horizontal ? element[\"scrollLeft\"] * (isRtl && -1 || 1) : element[\"scrollTop\"];\n fallback();\n cb(offset, isScrolling);\n };\n const handler = createHandler(true);\n const endHandler = createHandler(false);\n endHandler();\n element.addEventListener(\"scroll\", handler, addEventListenerOptions);\n element.addEventListener(\"scrollend\", endHandler, addEventListenerOptions);\n return () => {\n element.removeEventListener(\"scroll\", handler);\n element.removeEventListener(\"scrollend\", endHandler);\n };\n};\nconst observeWindowOffset = (instance, cb) => {\n const element = instance.scrollElement;\n if (!element) {\n return;\n }\n const targetWindow = instance.targetWindow;\n if (!targetWindow) {\n return;\n }\n let offset = 0;\n const fallback = instance.options.useScrollendEvent && supportsScrollend ? () => void 0 : debounce(\n targetWindow,\n () => {\n cb(offset, false);\n },\n instance.options.isScrollingResetDelay\n );\n const createHandler = (isScrolling) => () => {\n offset = element[instance.options.horizontal ? \"scrollX\" : \"scrollY\"];\n fallback();\n cb(offset, isScrolling);\n };\n const handler = createHandler(true);\n const endHandler = createHandler(false);\n endHandler();\n element.addEventListener(\"scroll\", handler, addEventListenerOptions);\n element.addEventListener(\"scrollend\", endHandler, addEventListenerOptions);\n return () => {\n element.removeEventListener(\"scroll\", handler);\n element.removeEventListener(\"scrollend\", endHandler);\n };\n};\nconst measureElement = (element, entry, instance) => {\n if (entry == null ? void 0 : entry.borderBoxSize) {\n const box = entry.borderBoxSize[0];\n if (box) {\n const size = Math.round(\n box[instance.options.horizontal ? \"inlineSize\" : \"blockSize\"]\n );\n return size;\n }\n }\n return Math.round(\n element.getBoundingClientRect()[instance.options.horizontal ? \"width\" : \"height\"]\n );\n};\nconst windowScroll = (offset, {\n adjustments = 0,\n behavior\n}, instance) => {\n var _a, _b;\n const toOffset = offset + adjustments;\n (_b = (_a = instance.scrollElement) == null ? void 0 : _a.scrollTo) == null ? void 0 : _b.call(_a, {\n [instance.options.horizontal ? \"left\" : \"top\"]: toOffset,\n behavior\n });\n};\nconst elementScroll = (offset, {\n adjustments = 0,\n behavior\n}, instance) => {\n var _a, _b;\n const toOffset = offset + adjustments;\n (_b = (_a = instance.scrollElement) == null ? void 0 : _a.scrollTo) == null ? void 0 : _b.call(_a, {\n [instance.options.horizontal ? \"left\" : \"top\"]: toOffset,\n behavior\n });\n};\nclass Virtualizer {\n constructor(opts) {\n this.unsubs = [];\n this.scrollElement = null;\n this.targetWindow = null;\n this.isScrolling = false;\n this.scrollToIndexTimeoutId = null;\n this.measurementsCache = [];\n this.itemSizeCache = /* @__PURE__ */ new Map();\n this.pendingMeasuredCacheIndexes = [];\n this.scrollRect = null;\n this.scrollOffset = null;\n this.scrollDirection = null;\n this.scrollAdjustments = 0;\n this.elementsCache = /* @__PURE__ */ new Map();\n this.observer = /* @__PURE__ */ (() => {\n let _ro = null;\n const get = () => {\n if (_ro) {\n return _ro;\n }\n if (!this.targetWindow || !this.targetWindow.ResizeObserver) {\n return null;\n }\n return _ro = new this.targetWindow.ResizeObserver((entries) => {\n entries.forEach((entry) => {\n this._measureElement(entry.target, entry);\n });\n });\n };\n return {\n disconnect: () => {\n var _a;\n (_a = get()) == null ? void 0 : _a.disconnect();\n _ro = null;\n },\n observe: (target) => {\n var _a;\n return (_a = get()) == null ? void 0 : _a.observe(target, { box: \"border-box\" });\n },\n unobserve: (target) => {\n var _a;\n return (_a = get()) == null ? void 0 : _a.unobserve(target);\n }\n };\n })();\n this.range = null;\n this.setOptions = (opts2) => {\n Object.entries(opts2).forEach(([key, value]) => {\n if (typeof value === \"undefined\") delete opts2[key];\n });\n this.options = {\n debug: false,\n initialOffset: 0,\n overscan: 1,\n paddingStart: 0,\n paddingEnd: 0,\n scrollPaddingStart: 0,\n scrollPaddingEnd: 0,\n horizontal: false,\n getItemKey: defaultKeyExtractor,\n rangeExtractor: defaultRangeExtractor,\n onChange: () => {\n },\n measureElement,\n initialRect: { width: 0, height: 0 },\n scrollMargin: 0,\n gap: 0,\n indexAttribute: \"data-index\",\n initialMeasurementsCache: [],\n lanes: 1,\n isScrollingResetDelay: 150,\n enabled: true,\n isRtl: false,\n useScrollendEvent: true,\n ...opts2\n };\n };\n this.notify = (sync) => {\n var _a, _b;\n (_b = (_a = this.options).onChange) == null ? void 0 : _b.call(_a, this, sync);\n };\n this.maybeNotify = memo(\n () => {\n this.calculateRange();\n return [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null\n ];\n },\n (isScrolling) => {\n this.notify(isScrolling);\n },\n {\n key: process.env.NODE_ENV !== \"production\" && \"maybeNotify\",\n debug: () => this.options.debug,\n initialDeps: [\n this.isScrolling,\n this.range ? this.range.startIndex : null,\n this.range ? this.range.endIndex : null\n ]\n }\n );\n this.cleanup = () => {\n this.unsubs.filter(Boolean).forEach((d) => d());\n this.unsubs = [];\n this.observer.disconnect();\n this.scrollElement = null;\n this.targetWindow = null;\n };\n this._didMount = () => {\n return () => {\n this.cleanup();\n };\n };\n this._willUpdate = () => {\n var _a;\n const scrollElement = this.options.enabled ? this.options.getScrollElement() : null;\n if (this.scrollElement !== scrollElement) {\n this.cleanup();\n if (!scrollElement) {\n this.maybeNotify();\n return;\n }\n this.scrollElement = scrollElement;\n if (this.scrollElement && \"ownerDocument\" in this.scrollElement) {\n this.targetWindow = this.scrollElement.ownerDocument.defaultView;\n } else {\n this.targetWindow = ((_a = this.scrollElement) == null ? void 0 : _a.window) ?? null;\n }\n this.elementsCache.forEach((cached) => {\n this.observer.observe(cached);\n });\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: void 0,\n behavior: void 0\n });\n this.unsubs.push(\n this.options.observeElementRect(this, (rect) => {\n this.scrollRect = rect;\n this.maybeNotify();\n })\n );\n this.unsubs.push(\n this.options.observeElementOffset(this, (offset, isScrolling) => {\n this.scrollAdjustments = 0;\n this.scrollDirection = isScrolling ? this.getScrollOffset() < offset ? \"forward\" : \"backward\" : null;\n this.scrollOffset = offset;\n this.isScrolling = isScrolling;\n this.maybeNotify();\n })\n );\n }\n };\n this.getSize = () => {\n if (!this.options.enabled) {\n this.scrollRect = null;\n return 0;\n }\n this.scrollRect = this.scrollRect ?? this.options.initialRect;\n return this.scrollRect[this.options.horizontal ? \"width\" : \"height\"];\n };\n this.getScrollOffset = () => {\n if (!this.options.enabled) {\n this.scrollOffset = null;\n return 0;\n }\n this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset === \"function\" ? this.options.initialOffset() : this.options.initialOffset);\n return this.scrollOffset;\n };\n this.getFurthestMeasurement = (measurements, index) => {\n const furthestMeasurementsFound = /* @__PURE__ */ new Map();\n const furthestMeasurements = /* @__PURE__ */ new Map();\n for (let m = index - 1; m >= 0; m--) {\n const measurement = measurements[m];\n if (furthestMeasurementsFound.has(measurement.lane)) {\n continue;\n }\n const previousFurthestMeasurement = furthestMeasurements.get(\n measurement.lane\n );\n if (previousFurthestMeasurement == null || measurement.end > previousFurthestMeasurement.end) {\n furthestMeasurements.set(measurement.lane, measurement);\n } else if (measurement.end < previousFurthestMeasurement.end) {\n furthestMeasurementsFound.set(measurement.lane, true);\n }\n if (furthestMeasurementsFound.size === this.options.lanes) {\n break;\n }\n }\n return furthestMeasurements.size === this.options.lanes ? Array.from(furthestMeasurements.values()).sort((a, b) => {\n if (a.end === b.end) {\n return a.index - b.index;\n }\n return a.end - b.end;\n })[0] : void 0;\n };\n this.getMeasurementOptions = memo(\n () => [\n this.options.count,\n this.options.paddingStart,\n this.options.scrollMargin,\n this.options.getItemKey,\n this.options.enabled\n ],\n (count, paddingStart, scrollMargin, getItemKey, enabled) => {\n this.pendingMeasuredCacheIndexes = [];\n return {\n count,\n paddingStart,\n scrollMargin,\n getItemKey,\n enabled\n };\n },\n {\n key: false\n }\n );\n this.getMeasurements = memo(\n () => [this.getMeasurementOptions(), this.itemSizeCache],\n ({ count, paddingStart, scrollMargin, getItemKey, enabled }, itemSizeCache) => {\n if (!enabled) {\n this.measurementsCache = [];\n this.itemSizeCache.clear();\n return [];\n }\n if (this.measurementsCache.length === 0) {\n this.measurementsCache = this.options.initialMeasurementsCache;\n this.measurementsCache.forEach((item) => {\n this.itemSizeCache.set(item.key, item.size);\n });\n }\n const min = this.pendingMeasuredCacheIndexes.length > 0 ? Math.min(...this.pendingMeasuredCacheIndexes) : 0;\n this.pendingMeasuredCacheIndexes = [];\n const measurements = this.measurementsCache.slice(0, min);\n for (let i = min; i < count; i++) {\n const key = getItemKey(i);\n const furthestMeasurement = this.options.lanes === 1 ? measurements[i - 1] : this.getFurthestMeasurement(measurements, i);\n const start = furthestMeasurement ? furthestMeasurement.end + this.options.gap : paddingStart + scrollMargin;\n const measuredSize = itemSizeCache.get(key);\n const size = typeof measuredSize === \"number\" ? measuredSize : this.options.estimateSize(i);\n const end = start + size;\n const lane = furthestMeasurement ? furthestMeasurement.lane : i % this.options.lanes;\n measurements[i] = {\n index: i,\n start,\n size,\n end,\n key,\n lane\n };\n }\n this.measurementsCache = measurements;\n return measurements;\n },\n {\n key: process.env.NODE_ENV !== \"production\" && \"getMeasurements\",\n debug: () => this.options.debug\n }\n );\n this.calculateRange = memo(\n () => [this.getMeasurements(), this.getSize(), this.getScrollOffset()],\n (measurements, outerSize, scrollOffset) => {\n return this.range = measurements.length > 0 && outerSize > 0 ? calculateRange({\n measurements,\n outerSize,\n scrollOffset\n }) : null;\n },\n {\n key: process.env.NODE_ENV !== \"production\" && \"calculateRange\",\n debug: () => this.options.debug\n }\n );\n this.getIndexes = memo(\n () => [\n this.options.rangeExtractor,\n this.calculateRange(),\n this.options.overscan,\n this.options.count\n ],\n (rangeExtractor, range, overscan, count) => {\n return range === null ? [] : rangeExtractor({\n startIndex: range.startIndex,\n endIndex: range.endIndex,\n overscan,\n count\n });\n },\n {\n key: process.env.NODE_ENV !== \"production\" && \"getIndexes\",\n debug: () => this.options.debug\n }\n );\n this.indexFromElement = (node) => {\n const attributeName = this.options.indexAttribute;\n const indexStr = node.getAttribute(attributeName);\n if (!indexStr) {\n console.warn(\n `Missing attribute name '${attributeName}={index}' on measured element.`\n );\n return -1;\n }\n return parseInt(indexStr, 10);\n };\n this._measureElement = (node, entry) => {\n const index = this.indexFromElement(node);\n const item = this.measurementsCache[index];\n if (!item) {\n return;\n }\n const key = item.key;\n const prevNode = this.elementsCache.get(key);\n if (prevNode !== node) {\n if (prevNode) {\n this.observer.unobserve(prevNode);\n }\n this.observer.observe(node);\n this.elementsCache.set(key, node);\n }\n if (node.isConnected) {\n this.resizeItem(index, this.options.measureElement(node, entry, this));\n }\n };\n this.resizeItem = (index, size) => {\n const item = this.measurementsCache[index];\n if (!item) {\n return;\n }\n const itemSize = this.itemSizeCache.get(item.key) ?? item.size;\n const delta = size - itemSize;\n if (delta !== 0) {\n if (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(item, delta, this) : item.start < this.getScrollOffset() + this.scrollAdjustments) {\n if (process.env.NODE_ENV !== \"production\" && this.options.debug) {\n console.info(\"correction\", delta);\n }\n this._scrollToOffset(this.getScrollOffset(), {\n adjustments: this.scrollAdjustments += delta,\n behavior: void 0\n });\n }\n this.pendingMeasuredCacheIndexes.push(item.index);\n this.itemSizeCache = new Map(this.itemSizeCache.set(item.key, size));\n this.notify(false);\n }\n };\n this.measureElement = (node) => {\n if (!node) {\n this.elementsCache.forEach((cached, key) => {\n if (!cached.isConnected) {\n this.observer.unobserve(cached);\n this.elementsCache.delete(key);\n }\n });\n return;\n }\n this._measureElement(node, void 0);\n };\n this.getVirtualItems = memo(\n () => [this.getIndexes(), this.getMeasurements()],\n (indexes, measurements) => {\n const virtualItems = [];\n for (let k = 0, len = indexes.length; k < len; k++) {\n const i = indexes[k];\n const measurement = measurements[i];\n virtualItems.push(measurement);\n }\n return virtualItems;\n },\n {\n key: process.env.NODE_ENV !== \"production\" && \"getVirtualItems\",\n debug: () => this.options.debug\n }\n );\n this.getVirtualItemForOffset = (offset) => {\n const measurements = this.getMeasurements();\n if (measurements.length === 0) {\n return void 0;\n }\n return notUndefined(\n measurements[findNearestBinarySearch(\n 0,\n measurements.length - 1,\n (index) => notUndefined(measurements[index]).start,\n offset\n )]\n );\n };\n this.getOffsetForAlignment = (toOffset, align) => {\n const size = this.getSize();\n const scrollOffset = this.getScrollOffset();\n if (align === \"auto\") {\n if (toOffset >= scrollOffset + size) {\n align = \"end\";\n }\n }\n if (align === \"end\") {\n toOffset -= size;\n }\n const scrollSizeProp = this.options.horizontal ? \"scrollWidth\" : \"scrollHeight\";\n const scrollSize = this.scrollElement ? \"document\" in this.scrollElement ? this.scrollElement.document.documentElement[scrollSizeProp] : this.scrollElement[scrollSizeProp] : 0;\n const maxOffset = scrollSize - size;\n return Math.max(Math.min(maxOffset, toOffset), 0);\n };\n this.getOffsetForIndex = (index, align = \"auto\") => {\n index = Math.max(0, Math.min(index, this.options.count - 1));\n const item = this.measurementsCache[index];\n if (!item) {\n return void 0;\n }\n const size = this.getSize();\n const scrollOffset = this.getScrollOffset();\n if (align === \"auto\") {\n if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {\n align = \"end\";\n } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {\n align = \"start\";\n } else {\n return [scrollOffset, align];\n }\n }\n const centerOffset = item.start - this.options.scrollPaddingStart + (item.size - size) / 2;\n switch (align) {\n case \"center\":\n return [this.getOffsetForAlignment(centerOffset, align), align];\n case \"end\":\n return [\n this.getOffsetForAlignment(\n item.end + this.options.scrollPaddingEnd,\n align\n ),\n align\n ];\n default:\n return [\n this.getOffsetForAlignment(\n item.start - this.options.scrollPaddingStart,\n align\n ),\n align\n ];\n }\n };\n this.isDynamicMode = () => this.elementsCache.size > 0;\n this.cancelScrollToIndex = () => {\n if (this.scrollToIndexTimeoutId !== null && this.targetWindow) {\n this.targetWindow.clearTimeout(this.scrollToIndexTimeoutId);\n this.scrollToIndexTimeoutId = null;\n }\n };\n this.scrollToOffset = (toOffset, { align = \"start\", behavior } = {}) => {\n this.cancelScrollToIndex();\n if (behavior === \"smooth\" && this.isDynamicMode()) {\n console.warn(\n \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n );\n }\n this._scrollToOffset(this.getOffsetForAlignment(toOffset, align), {\n adjustments: void 0,\n behavior\n });\n };\n this.scrollToIndex = (index, { align: initialAlign = \"auto\", behavior } = {}) => {\n index = Math.max(0, Math.min(index, this.options.count - 1));\n this.cancelScrollToIndex();\n if (behavior === \"smooth\" && this.isDynamicMode()) {\n console.warn(\n \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n );\n }\n const offsetAndAlign = this.getOffsetForIndex(index, initialAlign);\n if (!offsetAndAlign) return;\n const [offset, align] = offsetAndAlign;\n this._scrollToOffset(offset, { adjustments: void 0, behavior });\n if (behavior !== \"smooth\" && this.isDynamicMode() && this.targetWindow) {\n this.scrollToIndexTimeoutId = this.targetWindow.setTimeout(() => {\n this.scrollToIndexTimeoutId = null;\n const elementInDOM = this.elementsCache.has(\n this.options.getItemKey(index)\n );\n if (elementInDOM) {\n const [latestOffset] = notUndefined(\n this.getOffsetForIndex(index, align)\n );\n if (!approxEqual(latestOffset, this.getScrollOffset())) {\n this.scrollToIndex(index, { align, behavior });\n }\n } else {\n this.scrollToIndex(index, { align, behavior });\n }\n });\n }\n };\n this.scrollBy = (delta, { behavior } = {}) => {\n this.cancelScrollToIndex();\n if (behavior === \"smooth\" && this.isDynamicMode()) {\n console.warn(\n \"The `smooth` scroll behavior is not fully supported with dynamic size.\"\n );\n }\n this._scrollToOffset(this.getScrollOffset() + delta, {\n adjustments: void 0,\n behavior\n });\n };\n this.getTotalSize = () => {\n var _a;\n const measurements = this.getMeasurements();\n let end;\n if (measurements.length === 0) {\n end = this.options.paddingStart;\n } else {\n end = this.options.lanes === 1 ? ((_a = measurements[measurements.length - 1]) == null ? void 0 : _a.end) ?? 0 : Math.max(\n ...measurements.slice(-this.options.lanes).map((m) => m.end)\n );\n }\n return Math.max(\n end - this.options.scrollMargin + this.options.paddingEnd,\n 0\n );\n };\n this._scrollToOffset = (offset, {\n adjustments,\n behavior\n }) => {\n this.options.scrollToFn(offset, { behavior, adjustments }, this);\n };\n this.measure = () => {\n this.itemSizeCache = /* @__PURE__ */ new Map();\n this.notify(false);\n };\n this.setOptions(opts);\n }\n}\nconst findNearestBinarySearch = (low, high, getCurrentValue, value) => {\n while (low <= high) {\n const middle = (low + high) / 2 | 0;\n const currentValue = getCurrentValue(middle);\n if (currentValue < value) {\n low = middle + 1;\n } else if (currentValue > value) {\n high = middle - 1;\n } else {\n return middle;\n }\n }\n if (low > 0) {\n return low - 1;\n } else {\n return 0;\n }\n};\nfunction calculateRange({\n measurements,\n outerSize,\n scrollOffset\n}) {\n const count = measurements.length - 1;\n const getOffset = (index) => measurements[index].start;\n const startIndex = findNearestBinarySearch(0, count, getOffset, scrollOffset);\n let endIndex = startIndex;\n while (endIndex < count && measurements[endIndex].end < scrollOffset + outerSize) {\n endIndex++;\n }\n return { startIndex, endIndex };\n}\nexport {\n Virtualizer,\n approxEqual,\n debounce,\n defaultKeyExtractor,\n defaultRangeExtractor,\n elementScroll,\n measureElement,\n memo,\n notUndefined,\n observeElementOffset,\n observeElementRect,\n observeWindowOffset,\n observeWindowRect,\n windowScroll\n};\n//# sourceMappingURL=index.js.map\n","import * as React from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { observeElementRect, observeElementOffset, elementScroll, observeWindowRect, observeWindowOffset, windowScroll, Virtualizer } from \"@tanstack/virtual-core\";\nexport * from \"@tanstack/virtual-core\";\nconst useIsomorphicLayoutEffect = typeof document !== \"undefined\" ? React.useLayoutEffect : React.useEffect;\nfunction useVirtualizerBase(options) {\n const rerender = React.useReducer(() => ({}), {})[1];\n const resolvedOptions = {\n ...options,\n onChange: (instance2, sync) => {\n var _a;\n if (sync) {\n flushSync(rerender);\n } else {\n rerender();\n }\n (_a = options.onChange) == null ? void 0 : _a.call(options, instance2, sync);\n }\n };\n const [instance] = React.useState(\n () => new Virtualizer(resolvedOptions)\n );\n instance.setOptions(resolvedOptions);\n useIsomorphicLayoutEffect(() => {\n return instance._didMount();\n }, []);\n useIsomorphicLayoutEffect(() => {\n return instance._willUpdate();\n });\n return instance;\n}\nfunction useVirtualizer(options) {\n return useVirtualizerBase({\n observeElementRect,\n observeElementOffset,\n scrollToFn: elementScroll,\n ...options\n });\n}\nfunction useWindowVirtualizer(options) {\n return useVirtualizerBase({\n getScrollElement: () => typeof document !== \"undefined\" ? window : null,\n observeElementRect: observeWindowRect,\n observeElementOffset: observeWindowOffset,\n scrollToFn: windowScroll,\n initialOffset: () => typeof document !== \"undefined\" ? window.scrollY : 0,\n ...options\n });\n}\nexport {\n useVirtualizer,\n useWindowVirtualizer\n};\n//# sourceMappingURL=index.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2, Checkbox, Button } from '@grafana/ui';\nimport React, { forwardRef, useId } from 'react';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nconst DropdownItem = forwardRef(\n function DropdownItem2(_a, ref) {\n var _b = _a, { children, active, addGroupBottomBorder, isMultiValueEdit, checked } = _b, rest = __objRest(_b, [\"children\", \"active\", \"addGroupBottomBorder\", \"isMultiValueEdit\", \"checked\"]);\n const styles = useStyles2(getStyles);\n const id = useId();\n return /* @__PURE__ */ React.createElement(\"div\", __spreadValues({\n ref,\n role: \"option\",\n id,\n \"aria-selected\": active,\n className: cx(styles.option, active && styles.optionFocused, addGroupBottomBorder && styles.groupBottomBorder)\n }, rest), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.optionBody,\n \"data-testid\": `data-testid ad hoc filter option value ${children}`\n }, /* @__PURE__ */ React.createElement(\"span\", null, isMultiValueEdit ? /* @__PURE__ */ React.createElement(Checkbox, {\n tabIndex: -1,\n checked,\n className: styles.checkbox\n }) : null, children)));\n }\n);\nconst getStyles = (theme) => ({\n option: css({\n label: \"grafana-select-option\",\n top: 0,\n left: 0,\n width: \"100%\",\n position: \"absolute\",\n padding: theme.spacing(1),\n display: \"flex\",\n alignItems: \"center\",\n flexDirection: \"row\",\n flexShrink: 0,\n whiteSpace: \"nowrap\",\n cursor: \"pointer\",\n \"&:hover\": {\n background: theme.colors.action.hover,\n \"@media (forced-colors: active), (prefers-contrast: more)\": {\n border: `1px solid ${theme.colors.primary.border}`\n }\n }\n }),\n optionFocused: css({\n label: \"grafana-select-option-focused\",\n background: theme.colors.action.focus,\n \"@media (forced-colors: active), (prefers-contrast: more)\": {\n border: `1px solid ${theme.colors.primary.border}`\n }\n }),\n optionBody: css({\n label: \"grafana-select-option-body\",\n display: \"flex\",\n fontWeight: theme.typography.fontWeightMedium,\n flexDirection: \"column\",\n flexGrow: 1\n }),\n groupBottomBorder: css({\n borderBottom: `1px solid ${theme.colors.border.weak}`\n }),\n checkbox: css({\n paddingRight: theme.spacing(0.5)\n }),\n multiValueApplyWrapper: css({\n position: \"fixed\",\n top: 0,\n left: 0,\n display: \"flex\",\n backgroundColor: theme.colors.background.primary,\n color: theme.colors.text.primary,\n boxShadow: theme.shadows.z2,\n overflowY: \"auto\",\n zIndex: theme.zIndex.dropdown,\n gap: theme.spacing(1.5),\n padding: `${theme.spacing(1.5)} ${theme.spacing(1)}`\n })\n});\nconst LoadingOptionsPlaceholder = () => {\n return /* @__PURE__ */ React.createElement(DropdownItem, {\n onClick: (e) => e.stopPropagation()\n }, \"Loading options...\");\n};\nconst NoOptionsPlaceholder = () => {\n return /* @__PURE__ */ React.createElement(DropdownItem, {\n onClick: (e) => e.stopPropagation()\n }, \"No options found\");\n};\nconst OptionsErrorPlaceholder = ({ handleFetchOptions }) => {\n return /* @__PURE__ */ React.createElement(DropdownItem, {\n onClick: handleFetchOptions\n }, \"An error has occurred fetching labels. Click to retry\");\n};\nconst MultiValueApplyButton = ({\n onApply,\n floatingElement,\n maxOptionWidth,\n menuHeight\n}) => {\n const styles = useStyles2(getStyles);\n const floatingElementRect = floatingElement == null ? void 0 : floatingElement.getBoundingClientRect();\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.multiValueApplyWrapper,\n style: {\n width: `${maxOptionWidth}px`,\n transform: `translate(${floatingElementRect == null ? void 0 : floatingElementRect.left}px,${floatingElementRect ? floatingElementRect.top + menuHeight : 0}px)`\n }\n }, /* @__PURE__ */ React.createElement(Button, {\n onClick: onApply,\n size: \"sm\",\n tabIndex: -1\n }, \"Apply\"));\n};\n\nexport { DropdownItem, LoadingOptionsPlaceholder, MultiValueApplyButton, NoOptionsPlaceholder, OptionsErrorPlaceholder };\n//# sourceMappingURL=DropdownItem.js.map\n","import { isMultiValueOperator } from '../AdHocFiltersVariable.js';\nimport { getFuzzySearcher } from '../../utils.js';\n\nconst VIRTUAL_LIST_WIDTH_ESTIMATE_MULTIPLIER = 8;\nconst VIRTUAL_LIST_DESCRIPTION_WIDTH_ESTIMATE_MULTIPLIER = 6;\nconst VIRTUAL_LIST_PADDING = 8;\nconst VIRTUAL_LIST_OVERSCAN = 5;\nconst VIRTUAL_LIST_ITEM_HEIGHT = 38;\nconst VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION = 60;\nconst ERROR_STATE_DROPDOWN_WIDTH = 366;\nconst REGEXP_NON_ASCII = /[^ -~]/m;\nfunction searchOptions(options) {\n const haystack = options.map((o) => {\n var _a;\n return (_a = o.label) != null ? _a : o.value;\n });\n const fuzzySearch = getFuzzySearcher(haystack);\n return (search, filterInputType) => {\n if (REGEXP_NON_ASCII.test(search)) {\n return options.filter((o) => {\n var _a, _b;\n return ((_a = o.label) == null ? void 0 : _a.includes(search)) || ((_b = o.value) == null ? void 0 : _b.includes(search)) || false;\n });\n }\n if (filterInputType === \"operator\" && search !== \"\") {\n search = `\"${search}\"`;\n }\n return fuzzySearch(search).map((i) => options[i]);\n };\n}\nconst flattenOptionGroups = (options) => options.flatMap((option) => option.options ? [option, ...option.options] : [option]);\nconst setupDropdownAccessibility = (options, listRef, disabledIndicesRef) => {\n var _a, _b, _c, _d;\n let maxOptionWidth = 182;\n const listRefArr = [];\n const disabledIndices = [];\n for (let i = 0; i < options.length; i++) {\n listRefArr.push(null);\n if ((_a = options[i]) == null ? void 0 : _a.options) {\n disabledIndices.push(i);\n }\n let label = (_c = (_b = options[i].label) != null ? _b : options[i].value) != null ? _c : \"\";\n let multiplierToUse = VIRTUAL_LIST_WIDTH_ESTIMATE_MULTIPLIER;\n if (label.length * VIRTUAL_LIST_WIDTH_ESTIMATE_MULTIPLIER < (((_d = options[i].description) == null ? void 0 : _d.length) || 0) * VIRTUAL_LIST_DESCRIPTION_WIDTH_ESTIMATE_MULTIPLIER) {\n label = options[i].description;\n multiplierToUse = VIRTUAL_LIST_DESCRIPTION_WIDTH_ESTIMATE_MULTIPLIER;\n }\n const widthEstimate = (options[i].isCustom ? label.length + 18 : label.length) * multiplierToUse + VIRTUAL_LIST_PADDING * 2;\n if (widthEstimate > maxOptionWidth) {\n maxOptionWidth = widthEstimate;\n }\n }\n listRef.current = [...listRefArr];\n disabledIndicesRef.current = [...disabledIndices];\n return maxOptionWidth;\n};\nconst nextInputTypeMap = {\n key: \"operator\",\n operator: \"value\",\n value: \"key\"\n};\nconst switchToNextInputType = (filterInputType, setInputType, handleChangeViewMode, element, shouldFocusOnPillWrapperOverride) => switchInputType(\n nextInputTypeMap[filterInputType],\n setInputType,\n filterInputType === \"value\" ? handleChangeViewMode : void 0,\n element,\n shouldFocusOnPillWrapperOverride\n);\nconst switchInputType = (filterInputType, setInputType, handleChangeViewMode, element, shouldFocusOnPillWrapperOverride) => {\n setInputType(filterInputType);\n handleChangeViewMode == null ? void 0 : handleChangeViewMode(void 0, shouldFocusOnPillWrapperOverride);\n setTimeout(() => element == null ? void 0 : element.focus());\n};\nconst generateFilterUpdatePayload = ({\n filterInputType,\n item,\n filter,\n setFilterMultiValues,\n onAddCustomValue\n}) => {\n var _a, _b, _c, _d, _e;\n if (filterInputType === \"key\") {\n return {\n key: item.value,\n keyLabel: item.label ? item.label : item.value,\n meta: item == null ? void 0 : item.meta\n };\n }\n if (filterInputType === \"value\") {\n if (item.isCustom && onAddCustomValue) {\n return onAddCustomValue(item, filter);\n }\n return {\n value: item.value,\n valueLabels: [item.label ? item.label : item.value]\n };\n }\n if (filterInputType === \"operator\") {\n if (isMultiValueOperator(filter.operator) && !isMultiValueOperator(item.value)) {\n setFilterMultiValues([]);\n return {\n operator: item.value,\n valueLabels: [((_a = filter.valueLabels) == null ? void 0 : _a[0]) || ((_b = filter.values) == null ? void 0 : _b[0]) || filter.value],\n values: void 0\n };\n }\n if (isMultiValueOperator(item.value) && !isMultiValueOperator(filter.operator)) {\n const valueLabels = [((_c = filter.valueLabels) == null ? void 0 : _c[0]) || ((_d = filter.values) == null ? void 0 : _d[0]) || filter.value];\n const values = [filter.value];\n if (values[0]) {\n setFilterMultiValues([\n {\n value: values[0],\n label: (_e = valueLabels == null ? void 0 : valueLabels[0]) != null ? _e : values[0]\n }\n ]);\n }\n return {\n operator: item.value,\n valueLabels,\n values\n };\n }\n }\n return {\n [filterInputType]: item.value\n };\n};\nconst INPUT_PLACEHOLDER = \"Filter by label values\";\nconst generatePlaceholder = (filter, filterInputType, isMultiValueEdit, isAlwaysWip) => {\n var _a;\n if (filterInputType === \"key\") {\n return INPUT_PLACEHOLDER;\n }\n if (filterInputType === \"value\") {\n if (isMultiValueEdit) {\n return \"Edit values\";\n }\n return ((_a = filter.valueLabels) == null ? void 0 : _a[0]) || \"\";\n }\n return filter[filterInputType] && !isAlwaysWip ? `${filter[filterInputType]}` : INPUT_PLACEHOLDER;\n};\nconst populateInputValueOnInputTypeSwitch = ({\n populateInputOnEdit,\n item,\n filterInputType,\n setInputValue,\n filter\n}) => {\n var _a, _b, _c;\n if (populateInputOnEdit && !isMultiValueOperator(item.value || \"\") && nextInputTypeMap[filterInputType] === \"value\") {\n setInputValue((_c = (_b = (_a = filter == null ? void 0 : filter.valueLabels) == null ? void 0 : _a[0]) != null ? _b : filter == null ? void 0 : filter.value) != null ? _c : \"\");\n } else {\n setInputValue(\"\");\n }\n};\n\nexport { ERROR_STATE_DROPDOWN_WIDTH, VIRTUAL_LIST_ITEM_HEIGHT, VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION, VIRTUAL_LIST_OVERSCAN, flattenOptionGroups, generateFilterUpdatePayload, generatePlaceholder, populateInputValueOnInputTypeSwitch, searchOptions, setupDropdownAccessibility, switchInputType, switchToNextInputType };\n//# sourceMappingURL=utils.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2, Button, Icon } from '@grafana/ui';\nimport React, { useCallback } from 'react';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst MultiValuePill = ({\n item,\n handleRemoveMultiValue,\n index,\n handleEditMultiValuePill\n}) => {\n var _a, _b;\n const styles = useStyles2(getStyles);\n const editMultiValuePill = useCallback(\n (e) => {\n e.stopPropagation();\n e.preventDefault();\n handleEditMultiValuePill(item);\n },\n [handleEditMultiValuePill, item]\n );\n const editMultiValuePillWithKeyboard = useCallback(\n (e) => {\n if (e.key === \"Enter\") {\n editMultiValuePill(e);\n }\n },\n [editMultiValuePill]\n );\n const removePillHandler = useCallback(\n (e) => {\n e.stopPropagation();\n e.preventDefault();\n handleRemoveMultiValue(item);\n },\n [handleRemoveMultiValue, item]\n );\n const removePillHandlerWithKeyboard = useCallback(\n (e) => {\n if (e.key === \"Enter\") {\n removePillHandler(e);\n }\n },\n [removePillHandler]\n );\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.basePill, styles.valuePill),\n onClick: editMultiValuePill,\n onKeyDown: editMultiValuePillWithKeyboard,\n tabIndex: 0,\n id: `${item.value}-${index}`\n }, (_a = item.label) != null ? _a : item.value, /* @__PURE__ */ React.createElement(Button, {\n onClick: removePillHandler,\n onKeyDownCapture: removePillHandlerWithKeyboard,\n fill: \"text\",\n size: \"sm\",\n variant: \"secondary\",\n className: styles.removeButton,\n tooltip: `Remove filter value - ${(_b = item.label) != null ? _b : item.value}`\n }, /* @__PURE__ */ React.createElement(Icon, {\n name: \"times\",\n size: \"md\",\n id: `${item.value}-${index}-close-icon`\n })));\n};\nconst getStyles = (theme) => ({\n basePill: css(__spreadProps(__spreadValues({\n display: \"flex\",\n alignItems: \"center\",\n background: theme.colors.action.disabledBackground,\n border: `1px solid ${theme.colors.border.weak}`,\n padding: theme.spacing(0.125, 1, 0.125, 1),\n color: theme.colors.text.primary,\n overflow: \"hidden\",\n whiteSpace: \"nowrap\",\n minHeight: theme.spacing(2.75)\n }, theme.typography.bodySmall), {\n cursor: \"pointer\"\n })),\n valuePill: css({\n background: theme.colors.action.selected,\n padding: theme.spacing(0.125, 0, 0.125, 1)\n }),\n removeButton: css({\n marginInline: theme.spacing(0.5),\n height: \"100%\",\n padding: 0,\n cursor: \"pointer\",\n \"&:hover\": {\n color: theme.colors.text.primary\n }\n })\n});\n\nexport { MultiValuePill };\n//# sourceMappingURL=MultiValuePill.js.map\n","import React, { forwardRef, useState, useRef, useId, useMemo, useCallback, useImperativeHandle, useEffect, useLayoutEffect } from 'react';\nimport { FloatingPortal, FloatingFocusManager } from '@floating-ui/react';\nimport { useStyles2, Spinner, Text } from '@grafana/ui';\nimport { cx, css } from '@emotion/css';\nimport { isMultiValueOperator } from '../AdHocFiltersVariable.js';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport { LoadingOptionsPlaceholder, OptionsErrorPlaceholder, NoOptionsPlaceholder, DropdownItem, MultiValueApplyButton } from './DropdownItem.js';\nimport { searchOptions, flattenOptionGroups, setupDropdownAccessibility, VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION, VIRTUAL_LIST_ITEM_HEIGHT, VIRTUAL_LIST_OVERSCAN, generateFilterUpdatePayload, populateInputValueOnInputTypeSwitch, switchToNextInputType, switchInputType, generatePlaceholder, ERROR_STATE_DROPDOWN_WIDTH } from './utils.js';\nimport { handleOptionGroups } from '../../utils.js';\nimport { useFloatingInteractions, MAX_MENU_HEIGHT } from './useFloatingInteractions.js';\nimport { MultiValuePill } from './MultiValuePill.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst AdHocCombobox = forwardRef(function AdHocCombobox2({ filter, model, isAlwaysWip, handleChangeViewMode, focusOnWipInputRef, populateInputOnEdit }, parentRef) {\n var _a, _b, _c, _d;\n const [open, setOpen] = useState(false);\n const [options, setOptions] = useState([]);\n const [optionsLoading, setOptionsLoading] = useState(false);\n const [optionsError, setOptionsError] = useState(false);\n const [inputValue, setInputValue] = useState(\"\");\n const [activeIndex, setActiveIndex] = useState(null);\n const [filterInputType, setInputType] = useState(!isAlwaysWip ? \"value\" : \"key\");\n const [preventFiltering, setPreventFiltering] = useState(!isAlwaysWip && filterInputType === \"value\");\n const styles = useStyles2(getStyles);\n const [filterMultiValues, setFilterMultiValues] = useState([]);\n const [_, setForceRefresh] = useState({});\n const allowCustomValue = (_a = model.state.allowCustomValue) != null ? _a : true;\n const multiValuePillWrapperRef = useRef(null);\n const hasMultiValueOperator = isMultiValueOperator((filter == null ? void 0 : filter.operator) || \"\");\n const isMultiValueEdit = hasMultiValueOperator && filterInputType === \"value\";\n const operatorIdentifier = useId();\n const listRef = useRef([]);\n const disabledIndicesRef = useRef([]);\n const filterInputTypeRef = useRef(!isAlwaysWip ? \"value\" : \"key\");\n const optionsSearcher = useMemo(() => searchOptions(options), [options]);\n const isLastFilter = useMemo(() => {\n if (isAlwaysWip) {\n return false;\n }\n if (model.state.filters.at(-1) === filter) {\n return true;\n }\n return false;\n }, [filter, isAlwaysWip, model.state.filters]);\n const handleResetWip = useCallback(() => {\n if (isAlwaysWip) {\n model._addWip();\n setInputType(\"key\");\n setInputValue(\"\");\n }\n }, [model, isAlwaysWip]);\n const handleMultiValueFilterCommit = useCallback(\n (model2, filter2, filterMultiValues2, preventFocus) => {\n if (filterMultiValues2.length) {\n const valueLabels = [];\n const values = [];\n filterMultiValues2.forEach((item) => {\n var _a2;\n valueLabels.push((_a2 = item.label) != null ? _a2 : item.value);\n values.push(item.value);\n });\n model2._updateFilter(filter2, { valueLabels, values, value: values[0] });\n setFilterMultiValues([]);\n }\n if (!preventFocus) {\n setTimeout(() => {\n var _a2;\n return (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();\n });\n }\n },\n []\n );\n const handleLocalMultiValueChange = useCallback((selectedItem) => {\n setFilterMultiValues((items) => {\n if (items.some((item) => item.value === selectedItem.value)) {\n return items.filter((item) => item.value !== selectedItem.value);\n }\n return [...items, selectedItem];\n });\n }, []);\n const onOpenChange = useCallback(\n (nextOpen, _2, reason) => {\n setOpen(nextOpen);\n if (reason && [\"outside-press\", \"escape-key\"].includes(reason)) {\n if (isMultiValueEdit) {\n handleMultiValueFilterCommit(model, filter, filterMultiValues);\n }\n handleResetWip();\n handleChangeViewMode == null ? void 0 : handleChangeViewMode();\n }\n },\n [\n filter,\n filterMultiValues,\n handleChangeViewMode,\n handleMultiValueFilterCommit,\n handleResetWip,\n isMultiValueEdit,\n model\n ]\n );\n const outsidePressIdsToIgnore = useMemo(() => {\n return [\n operatorIdentifier,\n ...filterMultiValues.reduce(\n (acc, item, i) => [...acc, `${item.value}-${i}`, `${item.value}-${i}-close-icon`],\n []\n )\n ];\n }, [operatorIdentifier, filterMultiValues]);\n const { refs, floatingStyles, context, getReferenceProps, getFloatingProps, getItemProps } = useFloatingInteractions({\n open,\n onOpenChange,\n activeIndex,\n setActiveIndex,\n outsidePressIdsToIgnore,\n listRef,\n disabledIndicesRef\n });\n useImperativeHandle(parentRef, () => () => {\n var _a2;\n return (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();\n }, [refs.domReference]);\n function onChange(event) {\n const value = event.target.value;\n setInputValue(value);\n setActiveIndex(0);\n if (preventFiltering) {\n setPreventFiltering(false);\n }\n }\n const handleRemoveMultiValue = useCallback(\n (item) => {\n setFilterMultiValues((selected) => selected.filter((option) => option.value !== item.value));\n setTimeout(() => {\n var _a2;\n return (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();\n });\n },\n [refs.domReference]\n );\n const filteredDropDownItems = flattenOptionGroups(\n handleOptionGroups(optionsSearcher(preventFiltering ? \"\" : inputValue, filterInputType))\n );\n if (allowCustomValue && filterInputType !== \"operator\" && inputValue) {\n filteredDropDownItems.push({\n value: inputValue.trim(),\n label: inputValue.trim(),\n isCustom: true\n });\n }\n const onAddCustomValue = model.state.onAddCustomValue;\n const maxOptionWidth = setupDropdownAccessibility(filteredDropDownItems, listRef, disabledIndicesRef);\n const handleFetchOptions = useCallback(\n async (inputType) => {\n var _a2;\n setOptionsError(false);\n setOptionsLoading(true);\n setOptions([]);\n let options2 = [];\n try {\n if (inputType === \"key\") {\n options2 = await model._getKeys(null);\n } else if (inputType === \"operator\") {\n options2 = model._getOperators();\n } else if (inputType === \"value\") {\n options2 = await model._getValuesFor(filter);\n }\n if (filterInputTypeRef.current !== inputType) {\n return;\n }\n setOptions(options2);\n if ((_a2 = options2[0]) == null ? void 0 : _a2.group) {\n setActiveIndex(1);\n } else {\n setActiveIndex(0);\n }\n } catch (e) {\n setOptionsError(true);\n }\n setOptionsLoading(false);\n },\n [filter, model]\n );\n const rowVirtualizer = useVirtualizer({\n count: filteredDropDownItems.length,\n getScrollElement: () => refs.floating.current,\n estimateSize: (index) => filteredDropDownItems[index].description ? VIRTUAL_LIST_ITEM_HEIGHT_WITH_DESCRIPTION : VIRTUAL_LIST_ITEM_HEIGHT,\n overscan: VIRTUAL_LIST_OVERSCAN\n });\n const handleBackspaceInput = useCallback(\n (event, multiValueEdit) => {\n if (event.key === \"Backspace\" && !inputValue) {\n if (filterInputType === \"value\") {\n if (multiValueEdit) {\n if (filterMultiValues.length) {\n setFilterMultiValues((items) => {\n const updated = [...items];\n updated.splice(-1, 1);\n return updated;\n });\n return;\n }\n }\n setInputType(\"operator\");\n return;\n }\n focusOnWipInputRef == null ? void 0 : focusOnWipInputRef();\n model._handleComboboxBackspace(filter);\n if (isAlwaysWip) {\n handleResetWip();\n }\n }\n },\n [\n inputValue,\n filterInputType,\n model,\n filter,\n isAlwaysWip,\n filterMultiValues.length,\n handleResetWip,\n focusOnWipInputRef\n ]\n );\n const handleTabInput = useCallback(\n (event, multiValueEdit) => {\n var _a2;\n if (event.key === \"Tab\" && !event.shiftKey) {\n if (multiValueEdit) {\n event.preventDefault();\n handleMultiValueFilterCommit(model, filter, filterMultiValues);\n (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();\n }\n handleChangeViewMode == null ? void 0 : handleChangeViewMode();\n handleResetWip();\n }\n },\n [\n filter,\n filterMultiValues,\n handleChangeViewMode,\n handleMultiValueFilterCommit,\n handleResetWip,\n model,\n refs.domReference\n ]\n );\n const handleShiftTabInput = useCallback(\n (event, multiValueEdit) => {\n if (event.key === \"Tab\" && event.shiftKey) {\n if (multiValueEdit) {\n event.preventDefault();\n handleMultiValueFilterCommit(model, filter, filterMultiValues, true);\n }\n handleChangeViewMode == null ? void 0 : handleChangeViewMode();\n handleResetWip();\n }\n },\n [filter, filterMultiValues, handleChangeViewMode, handleMultiValueFilterCommit, handleResetWip, model]\n );\n const handleEnterInput = useCallback(\n (event, multiValueEdit) => {\n if (event.key === \"Enter\" && activeIndex != null) {\n if (!filteredDropDownItems[activeIndex]) {\n return;\n }\n const selectedItem = filteredDropDownItems[activeIndex];\n if (multiValueEdit) {\n handleLocalMultiValueChange(selectedItem);\n setInputValue(\"\");\n } else {\n model._updateFilter(\n filter,\n generateFilterUpdatePayload({\n filterInputType,\n item: selectedItem,\n filter,\n setFilterMultiValues,\n onAddCustomValue\n })\n );\n populateInputValueOnInputTypeSwitch({\n populateInputOnEdit,\n item: selectedItem,\n filterInputType,\n setInputValue,\n filter\n });\n switchToNextInputType(\n filterInputType,\n setInputType,\n handleChangeViewMode,\n refs.domReference.current,\n isLastFilter ? false : void 0\n );\n setActiveIndex(null);\n if (isLastFilter) {\n focusOnWipInputRef == null ? void 0 : focusOnWipInputRef();\n }\n }\n }\n },\n [\n activeIndex,\n filteredDropDownItems,\n handleLocalMultiValueChange,\n model,\n filter,\n filterInputType,\n populateInputOnEdit,\n handleChangeViewMode,\n refs.domReference,\n isLastFilter,\n focusOnWipInputRef,\n onAddCustomValue\n ]\n );\n const handleEditMultiValuePill = useCallback(\n (value) => {\n var _a2;\n const valueLabel = value.label || value.value;\n setFilterMultiValues((prev) => prev.filter((item) => item.value !== value.value));\n setPreventFiltering(true);\n setInputValue(valueLabel);\n (_a2 = refs.domReference.current) == null ? void 0 : _a2.focus();\n setTimeout(() => {\n var _a3;\n (_a3 = refs.domReference.current) == null ? void 0 : _a3.select();\n });\n },\n [refs.domReference]\n );\n useEffect(() => {\n if (open) {\n handleFetchOptions(filterInputType);\n }\n }, [open, filterInputType]);\n useEffect(() => {\n var _a2, _b2, _c2, _d2;\n if (!isAlwaysWip) {\n if (hasMultiValueOperator && ((_a2 = filter == null ? void 0 : filter.values) == null ? void 0 : _a2.length)) {\n const multiValueOptions = filter.values.reduce(\n (acc, value, i) => {\n var _a3;\n return [\n ...acc,\n {\n label: ((_a3 = filter.valueLabels) == null ? void 0 : _a3[i]) || value,\n value\n }\n ];\n },\n []\n );\n setFilterMultiValues(multiValueOptions);\n }\n if (!hasMultiValueOperator && populateInputOnEdit) {\n setInputValue((_c2 = (_b2 = filter == null ? void 0 : filter.valueLabels) == null ? void 0 : _b2[0]) != null ? _c2 : (filter == null ? void 0 : filter.value) || \"\");\n setTimeout(() => {\n var _a3;\n (_a3 = refs.domReference.current) == null ? void 0 : _a3.select();\n });\n }\n (_d2 = refs.domReference.current) == null ? void 0 : _d2.focus();\n }\n }, []);\n useEffect(() => {\n if (isMultiValueEdit && filterMultiValues) {\n setTimeout(() => setForceRefresh({}));\n }\n }, [filterMultiValues, isMultiValueEdit]);\n useLayoutEffect(() => {\n if (filterInputTypeRef.current) {\n filterInputTypeRef.current = filterInputType;\n }\n }, [filterInputType]);\n useLayoutEffect(() => {\n var _a2, _b2;\n if (activeIndex !== null && rowVirtualizer.range && (activeIndex > ((_a2 = rowVirtualizer.range) == null ? void 0 : _a2.endIndex) || activeIndex < ((_b2 = rowVirtualizer.range) == null ? void 0 : _b2.startIndex))) {\n rowVirtualizer.scrollToIndex(activeIndex);\n }\n }, [activeIndex, rowVirtualizer]);\n const keyLabel = (_b = filter == null ? void 0 : filter.keyLabel) != null ? _b : filter == null ? void 0 : filter.key;\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.comboboxWrapper\n }, filter ? /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.pillWrapper\n }, (filter == null ? void 0 : filter.key) ? /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.basePill, styles.keyPill)\n }, keyLabel) : null, (filter == null ? void 0 : filter.key) && (filter == null ? void 0 : filter.operator) && filterInputType !== \"operator\" ? /* @__PURE__ */ React.createElement(\"div\", {\n id: operatorIdentifier,\n className: cx(styles.basePill, styles.operatorPill, operatorIdentifier),\n role: \"button\",\n \"aria-label\": \"Edit filter operator\",\n tabIndex: 0,\n onClick: (event) => {\n event.stopPropagation();\n setInputValue(\"\");\n switchInputType(\"operator\", setInputType, void 0, refs.domReference.current);\n },\n onKeyDown: (event) => {\n handleShiftTabInput(event, hasMultiValueOperator);\n if (event.key === \"Enter\") {\n setInputValue(\"\");\n switchInputType(\"operator\", setInputType, void 0, refs.domReference.current);\n }\n }\n }, filter.operator) : null, /* @__PURE__ */ React.createElement(\"div\", {\n ref: multiValuePillWrapperRef\n }), isMultiValueEdit ? filterMultiValues.map((item, i) => /* @__PURE__ */ React.createElement(MultiValuePill, {\n key: `${item.value}-${i}`,\n item,\n index: i,\n handleRemoveMultiValue,\n handleEditMultiValuePill\n })) : null) : null, /* @__PURE__ */ React.createElement(\"input\", __spreadProps(__spreadValues({}, getReferenceProps({\n ref: refs.setReference,\n onChange,\n value: inputValue,\n placeholder: generatePlaceholder(filter, filterInputType, isMultiValueEdit, isAlwaysWip),\n \"aria-autocomplete\": \"list\",\n onKeyDown(event) {\n if (!open) {\n setOpen(true);\n return;\n }\n if (filterInputType === \"operator\") {\n handleShiftTabInput(event);\n }\n handleBackspaceInput(event, isMultiValueEdit);\n handleTabInput(event, isMultiValueEdit);\n handleEnterInput(event, isMultiValueEdit);\n }\n })), {\n className: cx(styles.inputStyle, { [styles.loadingInputPadding]: !optionsLoading }),\n onClick: (event) => {\n event.stopPropagation();\n setOpen(true);\n },\n onFocus: () => {\n setOpen(true);\n }\n })), optionsLoading ? /* @__PURE__ */ React.createElement(Spinner, {\n className: styles.loadingIndicator,\n inline: true\n }) : null, /* @__PURE__ */ React.createElement(FloatingPortal, null, open && /* @__PURE__ */ React.createElement(FloatingFocusManager, {\n context,\n initialFocus: -1,\n visuallyHiddenDismiss: true,\n modal: false\n }, /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(\"div\", {\n style: __spreadProps(__spreadValues({}, floatingStyles), {\n width: `${optionsError ? ERROR_STATE_DROPDOWN_WIDTH : maxOptionWidth}px`,\n transform: isMultiValueEdit ? `translate(${((_c = multiValuePillWrapperRef.current) == null ? void 0 : _c.getBoundingClientRect().left) || 0}px, ${(((_d = refs.domReference.current) == null ? void 0 : _d.getBoundingClientRect().bottom) || 0) + 10}px )` : floatingStyles.transform\n }),\n ref: refs.setFloating,\n className: styles.dropdownWrapper,\n tabIndex: -1\n }, /* @__PURE__ */ React.createElement(\"div\", __spreadProps(__spreadValues({\n style: {\n height: `${rowVirtualizer.getTotalSize() || VIRTUAL_LIST_ITEM_HEIGHT}px`\n }\n }, getFloatingProps()), {\n tabIndex: -1\n }), optionsLoading ? /* @__PURE__ */ React.createElement(LoadingOptionsPlaceholder, null) : optionsError ? /* @__PURE__ */ React.createElement(OptionsErrorPlaceholder, {\n handleFetchOptions: () => handleFetchOptions(filterInputType)\n }) : !filteredDropDownItems.length && (!allowCustomValue || filterInputType === \"operator\" || !inputValue) ? /* @__PURE__ */ React.createElement(NoOptionsPlaceholder, null) : rowVirtualizer.getVirtualItems().map((virtualItem) => {\n var _a2;\n const item = filteredDropDownItems[virtualItem.index];\n const index = virtualItem.index;\n if (item.options) {\n return /* @__PURE__ */ React.createElement(\"div\", {\n key: `${item.label}+${index}`,\n className: cx(styles.optionGroupLabel, styles.groupTopBorder),\n style: {\n height: `${virtualItem.size}px`,\n transform: `translateY(${virtualItem.start}px)`\n }\n }, /* @__PURE__ */ React.createElement(Text, {\n weight: \"bold\",\n variant: \"bodySmall\",\n color: \"secondary\"\n }, item.label));\n }\n const nextItem = filteredDropDownItems[virtualItem.index + 1];\n const shouldAddBottomBorder = nextItem && !nextItem.group && !nextItem.options && item.group;\n return /* @__PURE__ */ React.createElement(DropdownItem, __spreadProps(__spreadValues({}, getItemProps({\n key: `${item.value}-${index}`,\n ref(node) {\n listRef.current[index] = node;\n },\n onClick(event) {\n var _a3;\n if (filterInputType !== \"value\") {\n event.stopPropagation();\n }\n if (isMultiValueEdit) {\n event.preventDefault();\n event.stopPropagation();\n handleLocalMultiValueChange(item);\n setInputValue(\"\");\n (_a3 = refs.domReference.current) == null ? void 0 : _a3.focus();\n } else {\n model._updateFilter(\n filter,\n generateFilterUpdatePayload({\n filterInputType,\n item,\n filter,\n setFilterMultiValues,\n onAddCustomValue\n })\n );\n populateInputValueOnInputTypeSwitch({\n populateInputOnEdit,\n item,\n filterInputType,\n setInputValue,\n filter\n });\n switchToNextInputType(\n filterInputType,\n setInputType,\n handleChangeViewMode,\n refs.domReference.current,\n false\n );\n }\n }\n })), {\n active: activeIndex === index,\n addGroupBottomBorder: shouldAddBottomBorder,\n style: {\n height: `${virtualItem.size}px`,\n transform: `translateY(${virtualItem.start}px)`\n },\n \"aria-setsize\": filteredDropDownItems.length,\n \"aria-posinset\": virtualItem.index + 1,\n isMultiValueEdit,\n checked: filterMultiValues.some((val) => val.value === item.value)\n }), /* @__PURE__ */ React.createElement(\"span\", null, item.isCustom ? \"Use custom value: \" : \"\", \" \", (_a2 = item.label) != null ? _a2 : item.value), item.description ? /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.descriptionText\n }, item.description) : null);\n }))), isMultiValueEdit && !optionsLoading && !optionsError && filteredDropDownItems.length ? /* @__PURE__ */ React.createElement(MultiValueApplyButton, {\n onApply: () => {\n handleMultiValueFilterCommit(model, filter, filterMultiValues);\n },\n floatingElement: refs.floating.current,\n maxOptionWidth,\n menuHeight: Math.min(rowVirtualizer.getTotalSize(), MAX_MENU_HEIGHT)\n }) : null))));\n});\nconst getStyles = (theme) => ({\n comboboxWrapper: css({\n display: \"flex\",\n flexWrap: \"wrap\"\n }),\n pillWrapper: css({\n display: \"flex\",\n alignItems: \"center\",\n flexWrap: \"wrap\"\n }),\n basePill: css(__spreadProps(__spreadValues({\n display: \"flex\",\n alignItems: \"center\",\n background: theme.colors.action.disabledBackground,\n border: `1px solid ${theme.colors.border.weak}`,\n padding: theme.spacing(0.125, 1, 0.125, 1),\n color: theme.colors.text.primary,\n overflow: \"hidden\",\n whiteSpace: \"nowrap\",\n minHeight: theme.spacing(2.75)\n }, theme.typography.bodySmall), {\n cursor: \"pointer\"\n })),\n keyPill: css({\n fontWeight: theme.typography.fontWeightBold,\n cursor: \"default\"\n }),\n operatorPill: css({\n \"&:hover\": {\n background: theme.colors.action.hover\n }\n }),\n dropdownWrapper: css({\n backgroundColor: theme.colors.background.primary,\n color: theme.colors.text.primary,\n boxShadow: theme.shadows.z2,\n overflowY: \"auto\",\n zIndex: theme.zIndex.dropdown\n }),\n inputStyle: css({\n paddingBlock: 0,\n \"&:focus\": {\n outline: \"none\"\n }\n }),\n loadingIndicator: css({\n color: theme.colors.text.secondary,\n marginLeft: theme.spacing(0.5)\n }),\n loadingInputPadding: css({\n paddingRight: theme.spacing(2.5)\n }),\n optionGroupLabel: css({\n padding: theme.spacing(1),\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\"\n }),\n groupTopBorder: css({\n \"&:not(:first-child)\": {\n borderTop: `1px solid ${theme.colors.border.weak}`\n }\n }),\n descriptionText: css(__spreadProps(__spreadValues({}, theme.typography.bodySmall), {\n color: theme.colors.text.secondary,\n paddingTop: theme.spacing(0.5)\n }))\n});\n\nexport { AdHocCombobox };\n//# sourceMappingURL=AdHocFiltersCombobox.js.map\n","import { useFloating, autoUpdate, offset, flip, size, useRole, useDismiss, useListNavigation, useInteractions } from '@floating-ui/react';\n\nconst MAX_MENU_HEIGHT = 300;\nconst useFloatingInteractions = ({\n open,\n onOpenChange,\n activeIndex,\n setActiveIndex,\n outsidePressIdsToIgnore,\n listRef,\n disabledIndicesRef\n}) => {\n const { refs, floatingStyles, context } = useFloating({\n whileElementsMounted: autoUpdate,\n open,\n onOpenChange,\n placement: \"bottom-start\",\n middleware: [\n offset(10),\n flip({ padding: 10 }),\n size({\n apply({ availableHeight, availableWidth, elements }) {\n elements.floating.style.maxHeight = `${Math.min(MAX_MENU_HEIGHT, availableHeight)}px`;\n elements.floating.style.maxWidth = `${availableWidth}px`;\n },\n padding: 10\n })\n ],\n strategy: \"fixed\"\n });\n const role = useRole(context, { role: \"listbox\" });\n const dismiss = useDismiss(context, {\n outsidePress: (event) => {\n var _a;\n if (event.currentTarget instanceof Element) {\n const target = event.currentTarget;\n let idToCompare = target.id;\n if (target.nodeName === \"path\") {\n idToCompare = ((_a = target.parentElement) == null ? void 0 : _a.id) || \"\";\n }\n if (outsidePressIdsToIgnore.includes(idToCompare)) {\n return false;\n }\n }\n return true;\n }\n });\n const listNav = useListNavigation(context, {\n listRef,\n activeIndex,\n onNavigate: setActiveIndex,\n virtual: true,\n loop: true,\n disabledIndices: disabledIndicesRef.current\n });\n const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions([role, dismiss, listNav]);\n return {\n refs,\n floatingStyles,\n context,\n getReferenceProps,\n getFloatingProps,\n getItemProps\n };\n};\n\nexport { MAX_MENU_HEIGHT, useFloatingInteractions };\n//# sourceMappingURL=useFloatingInteractions.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2, Tooltip, IconButton } from '@grafana/ui';\nimport React, { useState, useRef, useCallback, useEffect } from 'react';\nimport { AdHocCombobox } from './AdHocFiltersCombobox.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nfunction AdHocFilterPill({ filter, model, readOnly, focusOnWipInputRef }) {\n var _a, _b, _c;\n const styles = useStyles2(getStyles);\n const [viewMode, setViewMode] = useState(true);\n const [shouldFocusOnPillWrapper, setShouldFocusOnPillWrapper] = useState(false);\n const pillWrapperRef = useRef(null);\n const [populateInputOnEdit, setPopulateInputOnEdit] = useState(false);\n const keyLabel = (_a = filter.keyLabel) != null ? _a : filter.key;\n const valueLabel = ((_b = filter.valueLabels) == null ? void 0 : _b.join(\", \")) || ((_c = filter.values) == null ? void 0 : _c.join(\", \")) || filter.value;\n const handleChangeViewMode = useCallback(\n (event, shouldFocusOnPillWrapperOverride) => {\n event == null ? void 0 : event.stopPropagation();\n if (readOnly) {\n return;\n }\n setShouldFocusOnPillWrapper(shouldFocusOnPillWrapperOverride != null ? shouldFocusOnPillWrapperOverride : !viewMode);\n setViewMode(!viewMode);\n },\n [readOnly, viewMode]\n );\n useEffect(() => {\n var _a2;\n if (shouldFocusOnPillWrapper) {\n (_a2 = pillWrapperRef.current) == null ? void 0 : _a2.focus();\n setShouldFocusOnPillWrapper(false);\n }\n }, [shouldFocusOnPillWrapper]);\n useEffect(() => {\n if (filter.forceEdit && viewMode) {\n setViewMode(false);\n model._updateFilter(filter, { forceEdit: void 0 });\n }\n }, [filter, model, viewMode]);\n useEffect(() => {\n if (viewMode) {\n setPopulateInputOnEdit((prevValue) => prevValue ? false : prevValue);\n }\n }, [viewMode]);\n if (viewMode) {\n const pillText = /* @__PURE__ */ React.createElement(\"span\", {\n className: styles.pillText\n }, keyLabel, \" \", filter.operator, \" \", valueLabel);\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.combinedFilterPill, { [styles.readOnlyCombinedFilter]: readOnly }),\n onClick: (e) => {\n e.stopPropagation();\n setPopulateInputOnEdit(true);\n handleChangeViewMode();\n },\n onKeyDown: (e) => {\n if (e.key === \"Enter\") {\n setPopulateInputOnEdit(true);\n handleChangeViewMode();\n }\n },\n role: \"button\",\n \"aria-label\": `Edit filter with key ${keyLabel}`,\n tabIndex: 0,\n ref: pillWrapperRef\n }, valueLabel.length < 20 ? pillText : /* @__PURE__ */ React.createElement(Tooltip, {\n content: /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.tooltipText\n }, valueLabel),\n placement: \"top\"\n }, pillText), !readOnly ? /* @__PURE__ */ React.createElement(IconButton, {\n onClick: (e) => {\n e.stopPropagation();\n model._removeFilter(filter);\n setTimeout(() => focusOnWipInputRef == null ? void 0 : focusOnWipInputRef());\n },\n onKeyDownCapture: (e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n e.stopPropagation();\n model._removeFilter(filter);\n setTimeout(() => focusOnWipInputRef == null ? void 0 : focusOnWipInputRef());\n }\n },\n name: \"times\",\n size: \"md\",\n className: styles.removeButton,\n tooltip: `Remove filter with key ${keyLabel}`\n }) : null);\n }\n return /* @__PURE__ */ React.createElement(AdHocCombobox, {\n filter,\n model,\n handleChangeViewMode,\n focusOnWipInputRef,\n populateInputOnEdit\n });\n}\nconst getStyles = (theme) => ({\n combinedFilterPill: css(__spreadProps(__spreadValues({\n display: \"flex\",\n alignItems: \"center\",\n background: theme.colors.action.selected,\n borderRadius: theme.shape.radius.default,\n border: `1px solid ${theme.colors.border.weak}`,\n padding: theme.spacing(0.125, 0, 0.125, 1),\n color: theme.colors.text.primary,\n overflow: \"hidden\",\n whiteSpace: \"nowrap\",\n minHeight: theme.spacing(2.75)\n }, theme.typography.bodySmall), {\n fontWeight: theme.typography.fontWeightBold,\n cursor: \"pointer\",\n \"&:hover\": {\n background: theme.colors.action.hover\n }\n })),\n readOnlyCombinedFilter: css({\n paddingRight: theme.spacing(1),\n cursor: \"text\",\n \"&:hover\": {\n background: theme.colors.action.selected\n }\n }),\n removeButton: css({\n marginInline: theme.spacing(0.5),\n cursor: \"pointer\",\n \"&:hover\": {\n color: theme.colors.text.primary\n }\n }),\n pillText: css({\n maxWidth: \"200px\",\n width: \"100%\",\n textOverflow: \"ellipsis\",\n overflow: \"hidden\"\n }),\n tooltipText: css({\n textAlign: \"center\"\n })\n});\n\nexport { AdHocFilterPill };\n//# sourceMappingURL=AdHocFilterPill.js.map\n","import React, { forwardRef, useLayoutEffect } from 'react';\nimport { AdHocCombobox } from './AdHocFiltersCombobox.js';\n\nconst AdHocFiltersAlwaysWipCombobox = forwardRef(function AdHocFiltersAlwaysWipCombobox2({ model }, parentRef) {\n const { _wip } = model.useState();\n useLayoutEffect(() => {\n if (!_wip) {\n model._addWip();\n }\n }, [_wip]);\n return /* @__PURE__ */ React.createElement(AdHocCombobox, {\n model,\n filter: _wip,\n isAlwaysWip: true,\n ref: parentRef\n });\n});\n\nexport { AdHocFiltersAlwaysWipCombobox };\n//# sourceMappingURL=AdHocFiltersAlwaysWipCombobox.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2, Icon } from '@grafana/ui';\nimport React, { memo, useRef } from 'react';\nimport { AdHocFilterPill } from './AdHocFilterPill.js';\nimport { AdHocFiltersAlwaysWipCombobox } from './AdHocFiltersAlwaysWipCombobox.js';\n\nconst AdHocFiltersComboboxRenderer = memo(function AdHocFiltersComboboxRenderer2({ model }) {\n const { filters, readOnly } = model.useState();\n const styles = useStyles2(getStyles);\n const focusOnWipInputRef = useRef();\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.comboboxWrapper, { [styles.comboboxFocusOutline]: !readOnly }),\n onClick: () => {\n var _a;\n (_a = focusOnWipInputRef.current) == null ? void 0 : _a.call(focusOnWipInputRef);\n }\n }, /* @__PURE__ */ React.createElement(Icon, {\n name: \"filter\",\n className: styles.filterIcon,\n size: \"lg\"\n }), filters.map((filter, index) => /* @__PURE__ */ React.createElement(AdHocFilterPill, {\n key: `${index}-${filter.key}`,\n filter,\n model,\n readOnly,\n focusOnWipInputRef: focusOnWipInputRef.current\n })), !readOnly ? /* @__PURE__ */ React.createElement(AdHocFiltersAlwaysWipCombobox, {\n model,\n ref: focusOnWipInputRef\n }) : null);\n});\nconst getStyles = (theme) => ({\n comboboxWrapper: css({\n display: \"flex\",\n flexWrap: \"wrap\",\n alignItems: \"center\",\n columnGap: theme.spacing(1),\n rowGap: theme.spacing(0.5),\n minHeight: theme.spacing(4),\n backgroundColor: theme.components.input.background,\n border: `1px solid ${theme.colors.border.strong}`,\n borderRadius: theme.shape.radius.default,\n paddingInline: theme.spacing(1),\n paddingBlock: theme.spacing(0.5),\n flexGrow: 1\n }),\n comboboxFocusOutline: css({\n \"&:focus-within\": {\n outline: \"2px dotted transparent\",\n outlineOffset: \"2px\",\n boxShadow: `0 0 0 2px ${theme.colors.background.canvas}, 0 0 0px 4px ${theme.colors.primary.main}`,\n transitionTimingFunction: `cubic-bezier(0.19, 1, 0.22, 1)`,\n transitionDuration: \"0.2s\",\n transitionProperty: \"outline, outline-offset, box-shadow\",\n zIndex: 2\n }\n }),\n filterIcon: css({\n color: theme.colors.text.secondary,\n alignSelf: \"center\"\n })\n});\n\nexport { AdHocFiltersComboboxRenderer };\n//# sourceMappingURL=AdHocFiltersComboboxRenderer.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { SceneVariableValueChangedEvent } from '../types.js';\nimport { dataFromResponse, getQueriesForVariables, responseHasError, renderPrometheusLabelFilters } from '../utils.js';\nimport { patchGetAdhocFilters } from './patchGetAdhocFilters.js';\nimport { useStyles2 } from '@grafana/ui';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { AdHocFilterBuilder } from './AdHocFilterBuilder.js';\nimport { AdHocFilterRenderer } from './AdHocFilterRenderer.js';\nimport { getDataSourceSrv } from '@grafana/runtime';\nimport { AdHocFiltersVariableUrlSyncHandler } from './AdHocFiltersVariableUrlSyncHandler.js';\nimport { css } from '@emotion/css';\nimport { getEnrichedFiltersRequest } from '../getEnrichedFiltersRequest.js';\nimport { AdHocFiltersComboboxRenderer } from './AdHocFiltersCombobox/AdHocFiltersComboboxRenderer.js';\nimport { wrapInSafeSerializableSceneObject } from '../../utils/wrapInSafeSerializableSceneObject.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst OPERATORS = [\n {\n value: \"=\",\n description: \"Equals\"\n },\n {\n value: \"!=\",\n description: \"Not equal\"\n },\n {\n value: \"=|\",\n description: \"One of. Use to filter on multiple values.\",\n isMulti: true\n },\n {\n value: \"!=|\",\n description: \"Not one of. Use to exclude multiple values.\",\n isMulti: true\n },\n {\n value: \"=~\",\n description: \"Matches regex\",\n isRegex: true\n },\n {\n value: \"!~\",\n description: \"Does not match regex\",\n isRegex: true\n },\n {\n value: \"<\",\n description: \"Less than\"\n },\n {\n value: \">\",\n description: \"Greater than\"\n }\n];\nclass AdHocFiltersVariable extends SceneObjectBase {\n constructor(state) {\n var _a, _b;\n super(__spreadValues({\n type: \"adhoc\",\n name: (_a = state.name) != null ? _a : \"Filters\",\n filters: [],\n datasource: null,\n applyMode: \"auto\",\n filterExpression: (_b = state.filterExpression) != null ? _b : renderExpression(state.expressionBuilder, state.filters)\n }, state));\n this._scopedVars = { __sceneObject: wrapInSafeSerializableSceneObject(this) };\n this._dataSourceSrv = getDataSourceSrv();\n this._urlSync = new AdHocFiltersVariableUrlSyncHandler(this);\n if (this.state.applyMode === \"auto\") {\n patchGetAdhocFilters(this);\n }\n }\n setState(update) {\n let filterExpressionChanged = false;\n if (update.filters && update.filters !== this.state.filters && !update.filterExpression) {\n update.filterExpression = renderExpression(this.state.expressionBuilder, update.filters);\n filterExpressionChanged = update.filterExpression !== this.state.filterExpression;\n }\n super.setState(update);\n if (filterExpressionChanged) {\n this.publishEvent(new SceneVariableValueChangedEvent(this), true);\n }\n }\n updateFilters(filters, options) {\n let filterExpressionChanged = false;\n let filterExpression = void 0;\n if (filters && filters !== this.state.filters) {\n filterExpression = renderExpression(this.state.expressionBuilder, filters);\n filterExpressionChanged = filterExpression !== this.state.filterExpression;\n }\n super.setState({\n filters,\n filterExpression\n });\n if (filterExpressionChanged && (options == null ? void 0 : options.skipPublish) !== true || (options == null ? void 0 : options.forcePublish)) {\n this.publishEvent(new SceneVariableValueChangedEvent(this), true);\n }\n }\n getValue() {\n return this.state.filterExpression;\n }\n _updateFilter(filter, update) {\n const { filters, _wip } = this.state;\n if (filter === _wip) {\n if (\"value\" in update && update[\"value\"] !== \"\") {\n this.setState({ filters: [...filters, __spreadValues(__spreadValues({}, _wip), update)], _wip: void 0 });\n } else {\n this.setState({ _wip: __spreadValues(__spreadValues({}, filter), update) });\n }\n return;\n }\n const updatedFilters = this.state.filters.map((f) => {\n return f === filter ? __spreadValues(__spreadValues({}, f), update) : f;\n });\n this.setState({ filters: updatedFilters });\n }\n _removeFilter(filter) {\n if (filter === this.state._wip) {\n this.setState({ _wip: void 0 });\n return;\n }\n this.setState({ filters: this.state.filters.filter((f) => f !== filter) });\n }\n _removeLastFilter() {\n const filterToRemove = this.state.filters.at(-1);\n if (filterToRemove) {\n this._removeFilter(filterToRemove);\n }\n }\n _handleComboboxBackspace(filter) {\n if (this.state.filters.length) {\n let filterToForceIndex = this.state.filters.length - 1;\n if (filter !== this.state._wip) {\n filterToForceIndex = -1;\n }\n this.setState({\n filters: this.state.filters.reduce((acc, f, index) => {\n if (index === filterToForceIndex) {\n return [\n ...acc,\n __spreadProps(__spreadValues({}, f), {\n forceEdit: true\n })\n ];\n }\n if (f === filter) {\n return acc;\n }\n return [...acc, f];\n }, [])\n });\n }\n }\n async _getKeys(currentKey) {\n var _a, _b, _c;\n const override = await ((_b = (_a = this.state).getTagKeysProvider) == null ? void 0 : _b.call(_a, this, currentKey));\n if (override && override.replace) {\n return dataFromResponse(override.values).map(toSelectableValue);\n }\n if (this.state.defaultKeys) {\n return this.state.defaultKeys.map(toSelectableValue);\n }\n const ds = await this._dataSourceSrv.get(this.state.datasource, this._scopedVars);\n if (!ds || !ds.getTagKeys) {\n return [];\n }\n const otherFilters = this.state.filters.filter((f) => f.key !== currentKey).concat((_c = this.state.baseFilters) != null ? _c : []);\n const timeRange = sceneGraph.getTimeRange(this).state.value;\n const queries = this.state.useQueriesAsFilterForOptions ? getQueriesForVariables(this) : void 0;\n const response = await ds.getTagKeys(__spreadValues({\n filters: otherFilters,\n queries,\n timeRange\n }, getEnrichedFiltersRequest(this)));\n if (responseHasError(response)) {\n this.setState({ error: response.error.message });\n }\n let keys = dataFromResponse(response);\n if (override) {\n keys = keys.concat(dataFromResponse(override.values));\n }\n const tagKeyRegexFilter = this.state.tagKeyRegexFilter;\n if (tagKeyRegexFilter) {\n keys = keys.filter((f) => f.text.match(tagKeyRegexFilter));\n }\n return keys.map(toSelectableValue);\n }\n async _getValuesFor(filter) {\n var _a, _b, _c;\n const override = await ((_b = (_a = this.state).getTagValuesProvider) == null ? void 0 : _b.call(_a, this, filter));\n if (override && override.replace) {\n return dataFromResponse(override.values).map(toSelectableValue);\n }\n const ds = await this._dataSourceSrv.get(this.state.datasource, this._scopedVars);\n if (!ds || !ds.getTagValues) {\n return [];\n }\n const otherFilters = this.state.filters.filter((f) => f.key !== filter.key).concat((_c = this.state.baseFilters) != null ? _c : []);\n const timeRange = sceneGraph.getTimeRange(this).state.value;\n const queries = this.state.useQueriesAsFilterForOptions ? getQueriesForVariables(this) : void 0;\n const response = await ds.getTagValues(__spreadValues({\n key: filter.key,\n filters: otherFilters,\n timeRange,\n queries\n }, getEnrichedFiltersRequest(this)));\n if (responseHasError(response)) {\n this.setState({ error: response.error.message });\n }\n let values = dataFromResponse(response);\n if (override) {\n values = values.concat(dataFromResponse(override.values));\n }\n return values.map(toSelectableValue);\n }\n _addWip() {\n this.setState({\n _wip: { key: \"\", value: \"\", operator: \"=\", condition: \"\" }\n });\n }\n _getOperators() {\n const { supportsMultiValueOperators, allowCustomValue } = this.state;\n return OPERATORS.filter(({ isMulti, isRegex }) => {\n if (!supportsMultiValueOperators && isMulti) {\n return false;\n }\n if (!allowCustomValue && isRegex) {\n return false;\n }\n return true;\n }).map(({ value, description }) => ({\n label: value,\n value,\n description\n }));\n }\n}\nAdHocFiltersVariable.Component = AdHocFiltersVariableRenderer;\nfunction renderExpression(builder, filters) {\n return (builder != null ? builder : renderPrometheusLabelFilters)(filters != null ? filters : []);\n}\nfunction AdHocFiltersVariableRenderer({ model }) {\n const { filters, readOnly, addFilterButtonText } = model.useState();\n const styles = useStyles2(getStyles);\n if (model.state.layout === \"combobox\") {\n return /* @__PURE__ */ React.createElement(AdHocFiltersComboboxRenderer, {\n model\n });\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.wrapper\n }, filters.filter((filter) => !filter.hidden).map((filter, index) => /* @__PURE__ */ React.createElement(React.Fragment, {\n key: index\n }, /* @__PURE__ */ React.createElement(AdHocFilterRenderer, {\n filter,\n model\n }))), !readOnly && /* @__PURE__ */ React.createElement(AdHocFilterBuilder, {\n model,\n key: \"'builder\",\n addFilterButtonText\n }));\n}\nconst getStyles = (theme) => ({\n wrapper: css({\n display: \"flex\",\n flexWrap: \"wrap\",\n alignItems: \"flex-end\",\n columnGap: theme.spacing(2),\n rowGap: theme.spacing(1)\n })\n});\nfunction toSelectableValue(input) {\n const { text, value } = input;\n const result = {\n label: String(text),\n value: String(value != null ? value : text)\n };\n if (\"group\" in input) {\n result.group = input.group;\n }\n if (\"meta\" in input) {\n result.meta = input.meta;\n }\n return result;\n}\nfunction isFilterComplete(filter) {\n return filter.key !== \"\" && filter.operator !== \"\" && filter.value !== \"\";\n}\nfunction isMultiValueOperator(operatorValue) {\n const operator = OPERATORS.find((o) => o.value === operatorValue);\n if (!operator) {\n return false;\n }\n return Boolean(operator.isMulti);\n}\n\nexport { AdHocFiltersVariable, AdHocFiltersVariableRenderer, OPERATORS, isFilterComplete, isMultiValueOperator, toSelectableValue };\n//# sourceMappingURL=AdHocFiltersVariable.js.map\n","import { merge, mergeAll, filter, map, finalize } from 'rxjs';\n\nclass DataLayersMerger {\n constructor() {\n this._resultsMap = /* @__PURE__ */ new Map();\n this._prevLayers = [];\n }\n getMergedStream(layers) {\n if (areDifferentLayers(layers, this._prevLayers)) {\n this._resultsMap = /* @__PURE__ */ new Map();\n this._prevLayers = layers;\n }\n const resultStreams = layers.map((l) => l.getResultsStream());\n const deactivationHandlers = [];\n for (const layer of layers) {\n deactivationHandlers.push(layer.activate());\n }\n return merge(resultStreams).pipe(\n mergeAll(),\n filter((v) => {\n return this._resultsMap.get(v.origin.state.key) !== v;\n }),\n map((v) => {\n this._resultsMap.set(v.origin.state.key, v);\n return this._resultsMap.values();\n }),\n finalize(() => {\n deactivationHandlers.forEach((handler) => handler());\n })\n );\n }\n}\nfunction areDifferentLayers(a, b) {\n if (a.length !== b.length) {\n return true;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return true;\n }\n }\n return false;\n}\n\nexport { DataLayersMerger };\n//# sourceMappingURL=DataLayersMerger.js.map\n","import { isEqual, cloneDeep } from 'lodash';\nimport { ReplaySubject, forkJoin } from 'rxjs';\nimport { LoadingState } from '@grafana/schema';\nimport { preProcessPanelData, DataTopic, DataFrameView, rangeUtil } from '@grafana/data';\nimport { getRunRequest, toDataQueryError, isExpressionReference } from '@grafana/runtime';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { getDataSource } from '../utils/getDataSource.js';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig.js';\nimport { writeSceneLog } from '../utils/writeSceneLog.js';\nimport { VariableValueRecorder } from '../variables/VariableValueRecorder.js';\nimport { emptyPanelData } from '../core/SceneDataNode.js';\nimport { getClosest } from '../core/sceneGraph/utils.js';\nimport { isExtraQueryProvider } from './ExtraQueryProvider.js';\nimport { extraQueryProcessingOperator, passthroughProcessor } from './extraQueryProcessingOperator.js';\nimport { filterAnnotations } from './layers/annotations/filterAnnotations.js';\nimport { getEnrichedDataRequest } from './getEnrichedDataRequest.js';\nimport { findActiveAdHocFilterVariableByUid } from '../variables/adhoc/patchGetAdhocFilters.js';\nimport { registerQueryWithController } from './registerQueryWithController.js';\nimport { findActiveGroupByVariablesByUid } from '../variables/groupby/findActiveGroupByVariablesByUid.js';\nimport { GroupByVariable } from '../variables/groupby/GroupByVariable.js';\nimport { AdHocFiltersVariable, isFilterComplete } from '../variables/adhoc/AdHocFiltersVariable.js';\nimport { DataLayersMerger } from './DataLayersMerger.js';\nimport { interpolate } from '../core/sceneGraph/sceneGraph.js';\nimport { wrapInSafeSerializableSceneObject } from '../utils/wrapInSafeSerializableSceneObject.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nlet counter = 100;\nfunction getNextRequestId() {\n return \"SQR\" + counter++;\n}\nclass SceneQueryRunner extends SceneObjectBase {\n constructor(initialState) {\n super(initialState);\n this._dataLayersMerger = new DataLayersMerger();\n this._variableValueRecorder = new VariableValueRecorder();\n this._results = new ReplaySubject(1);\n this._scopedVars = { __sceneObject: wrapInSafeSerializableSceneObject(this) };\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"queries\", \"datasource\", \"minInterval\"],\n onVariableUpdateCompleted: this.onVariableUpdatesCompleted.bind(this),\n onAnyVariableChanged: this.onAnyVariableChanged.bind(this)\n });\n this.onDataReceived = (data) => {\n const preProcessedData = preProcessPanelData(data, this.state.data);\n this._resultAnnotations = data.annotations;\n const dataWithLayersApplied = this._combineDataLayers(preProcessedData);\n let hasFetchedData = this.state._hasFetchedData;\n if (!hasFetchedData && preProcessedData.state !== LoadingState.Loading) {\n hasFetchedData = true;\n }\n this.setState({ data: dataWithLayersApplied, _hasFetchedData: hasFetchedData });\n this._results.next({ origin: this, data: dataWithLayersApplied });\n };\n this.addActivationHandler(() => this._onActivate());\n }\n getResultsStream() {\n return this._results;\n }\n _onActivate() {\n if (this.isQueryModeAuto()) {\n const timeRange = sceneGraph.getTimeRange(this);\n const providers = this.getClosestExtraQueryProviders();\n for (const provider of providers) {\n this._subs.add(\n provider.subscribeToState((n, p) => {\n if (provider.shouldRerun(p, n, this.state.queries)) {\n this.runQueries();\n }\n })\n );\n }\n this.subscribeToTimeRangeChanges(timeRange);\n if (this.shouldRunQueriesOnActivate()) {\n this.runQueries();\n }\n }\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n return () => this._onDeactivate();\n }\n _handleDataLayers() {\n const dataLayers = sceneGraph.getDataLayers(this);\n if (dataLayers.length === 0) {\n return;\n }\n this._dataLayersSub = this._dataLayersMerger.getMergedStream(dataLayers).subscribe(this._onLayersReceived.bind(this));\n }\n _onLayersReceived(results) {\n var _a, _b, _c, _d, _e;\n const timeRange = sceneGraph.getTimeRange(this);\n const { dataLayerFilter } = this.state;\n let annotations = [];\n let alertStates = [];\n let alertState;\n for (const result of results) {\n for (let frame of result.data.series) {\n if (((_a = frame.meta) == null ? void 0 : _a.dataTopic) === DataTopic.Annotations) {\n annotations = annotations.concat(frame);\n }\n if (((_b = frame.meta) == null ? void 0 : _b.dataTopic) === DataTopic.AlertStates) {\n alertStates = alertStates.concat(frame);\n }\n }\n }\n if (dataLayerFilter == null ? void 0 : dataLayerFilter.panelId) {\n if (annotations.length > 0) {\n annotations = filterAnnotations(annotations, dataLayerFilter);\n }\n if (alertStates.length > 0) {\n for (const frame of alertStates) {\n const frameView = new DataFrameView(frame);\n for (const row of frameView) {\n if (row.panelId === dataLayerFilter.panelId) {\n alertState = row;\n break;\n }\n }\n }\n }\n }\n if (allFramesEmpty(annotations) && allFramesEmpty(this._layerAnnotations) && isEqual(alertState, (_c = this.state.data) == null ? void 0 : _c.alertState)) {\n return;\n }\n this._layerAnnotations = annotations;\n const baseStateUpdate = this.state.data ? this.state.data : __spreadProps(__spreadValues({}, emptyPanelData), { timeRange: timeRange.state.value });\n this.setState({\n data: __spreadProps(__spreadValues({}, baseStateUpdate), {\n annotations: [...(_d = this._resultAnnotations) != null ? _d : [], ...annotations],\n alertState: alertState != null ? alertState : (_e = this.state.data) == null ? void 0 : _e.alertState\n })\n });\n }\n onVariableUpdatesCompleted() {\n if (this.isQueryModeAuto()) {\n this.runQueries();\n }\n }\n onAnyVariableChanged(variable) {\n if (this._adhocFiltersVar === variable || this._groupByVar === variable || !this.isQueryModeAuto()) {\n return;\n }\n if (variable instanceof AdHocFiltersVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n if (variable instanceof GroupByVariable && this._isRelevantAutoVariable(variable)) {\n this.runQueries();\n }\n }\n _isRelevantAutoVariable(variable) {\n var _a, _b;\n const datasource = (_a = this.state.datasource) != null ? _a : findFirstDatasource(this.state.queries);\n return variable.state.applyMode === \"auto\" && (datasource == null ? void 0 : datasource.uid) === ((_b = variable.state.datasource) == null ? void 0 : _b.uid);\n }\n shouldRunQueriesOnActivate() {\n if (this._variableValueRecorder.hasDependenciesChanged(this)) {\n writeSceneLog(\n \"SceneQueryRunner\",\n \"Variable dependency changed while inactive, shouldRunQueriesOnActivate returns true\"\n );\n return true;\n }\n if (!this.state.data) {\n return true;\n }\n if (this._isDataTimeRangeStale(this.state.data)) {\n return true;\n }\n return false;\n }\n _isDataTimeRangeStale(data) {\n const timeRange = sceneGraph.getTimeRange(this);\n const stateTimeRange = timeRange.state.value;\n const dataTimeRange = data.timeRange;\n if (stateTimeRange.from.unix() === dataTimeRange.from.unix() && stateTimeRange.to.unix() === dataTimeRange.to.unix()) {\n return false;\n }\n writeSceneLog(\"SceneQueryRunner\", \"Data time range is stale\");\n return true;\n }\n _onDeactivate() {\n var _a;\n if (this._querySub) {\n this._querySub.unsubscribe();\n this._querySub = void 0;\n }\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = void 0;\n }\n (_a = this._timeSub) == null ? void 0 : _a.unsubscribe();\n this._timeSub = void 0;\n this._timeSubRange = void 0;\n this._adhocFiltersVar = void 0;\n this._groupByVar = void 0;\n this._variableValueRecorder.recordCurrentDependencyValuesForSceneObject(this);\n }\n setContainerWidth(width) {\n if (!this._containerWidth && width > 0) {\n this._containerWidth = width;\n if (this.state.maxDataPointsFromWidth && !this.state.maxDataPoints) {\n setTimeout(() => {\n if (this.isActive && !this.state._hasFetchedData) {\n this.runQueries();\n }\n }, 0);\n }\n } else {\n if (width > 0) {\n this._containerWidth = width;\n }\n }\n }\n isDataReadyToDisplay() {\n return Boolean(this.state._hasFetchedData);\n }\n subscribeToTimeRangeChanges(timeRange) {\n if (this._timeSubRange === timeRange) {\n return;\n }\n if (this._timeSub) {\n this._timeSub.unsubscribe();\n }\n this._timeSubRange = timeRange;\n this._timeSub = timeRange.subscribeToState(() => {\n this.runWithTimeRange(timeRange);\n });\n }\n runQueries() {\n const timeRange = sceneGraph.getTimeRange(this);\n if (this.isQueryModeAuto()) {\n this.subscribeToTimeRangeChanges(timeRange);\n }\n this.runWithTimeRange(timeRange);\n }\n getMaxDataPoints() {\n var _a;\n if (this.state.maxDataPoints) {\n return this.state.maxDataPoints;\n }\n return this.state.maxDataPointsFromWidth ? (_a = this._containerWidth) != null ? _a : 500 : 500;\n }\n cancelQuery() {\n var _a;\n (_a = this._querySub) == null ? void 0 : _a.unsubscribe();\n if (this._dataLayersSub) {\n this._dataLayersSub.unsubscribe();\n this._dataLayersSub = void 0;\n }\n this.setState({\n data: __spreadProps(__spreadValues({}, this.state.data), { state: LoadingState.Done })\n });\n }\n async runWithTimeRange(timeRange) {\n var _a, _b, _c;\n if (!this.state.maxDataPoints && this.state.maxDataPointsFromWidth && !this._containerWidth) {\n return;\n }\n if (!this._dataLayersSub) {\n this._handleDataLayers();\n }\n (_a = this._querySub) == null ? void 0 : _a.unsubscribe();\n if (this._variableDependency.hasDependencyInLoadingState()) {\n writeSceneLog(\"SceneQueryRunner\", \"Variable dependency is in loading state, skipping query execution\");\n this.setState({ data: __spreadProps(__spreadValues({}, (_b = this.state.data) != null ? _b : emptyPanelData), { state: LoadingState.Loading }) });\n return;\n }\n const { queries } = this.state;\n if (!(queries == null ? void 0 : queries.length)) {\n this._setNoDataState();\n return;\n }\n try {\n const datasource = (_c = this.state.datasource) != null ? _c : findFirstDatasource(queries);\n const ds = await getDataSource(datasource, this._scopedVars);\n this.findAndSubscribeToAdHocFilters(ds.uid);\n const runRequest = getRunRequest();\n const { primary, secondaries, processors } = this.prepareRequests(timeRange, ds);\n writeSceneLog(\"SceneQueryRunner\", \"Starting runRequest\", this.state.key);\n let stream = runRequest(ds, primary);\n if (secondaries.length > 0) {\n const secondaryStreams = secondaries.map((r) => runRequest(ds, r));\n const op = extraQueryProcessingOperator(processors);\n stream = forkJoin([stream, ...secondaryStreams]).pipe(op);\n }\n stream = stream.pipe(\n registerQueryWithController({\n type: \"data\",\n request: primary,\n origin: this,\n cancel: () => this.cancelQuery()\n })\n );\n this._querySub = stream.subscribe(this.onDataReceived);\n } catch (err) {\n console.error(\"PanelQueryRunner Error\", err);\n this.onDataReceived(__spreadProps(__spreadValues(__spreadValues({}, emptyPanelData), this.state.data), {\n state: LoadingState.Error,\n errors: [toDataQueryError(err)]\n }));\n }\n }\n clone(withState) {\n var _a;\n const clone = super.clone(withState);\n if (this._resultAnnotations) {\n clone[\"_resultAnnotations\"] = this._resultAnnotations.map((frame) => __spreadValues({}, frame));\n }\n if (this._layerAnnotations) {\n clone[\"_layerAnnotations\"] = this._layerAnnotations.map((frame) => __spreadValues({}, frame));\n }\n clone[\"_variableValueRecorder\"] = this._variableValueRecorder.cloneAndRecordCurrentValuesForSceneObject(this);\n clone[\"_containerWidth\"] = this._containerWidth;\n clone[\"_results\"].next({ origin: this, data: (_a = this.state.data) != null ? _a : emptyPanelData });\n return clone;\n }\n prepareRequests(timeRange, ds) {\n var _a;\n const { minInterval, queries } = this.state;\n let request = __spreadValues({\n app: \"scenes\",\n requestId: getNextRequestId(),\n timezone: timeRange.getTimeZone(),\n range: timeRange.state.value,\n interval: \"1s\",\n intervalMs: 1e3,\n targets: cloneDeep(queries),\n maxDataPoints: this.getMaxDataPoints(),\n scopedVars: this._scopedVars,\n startTime: Date.now(),\n liveStreaming: this.state.liveStreaming,\n rangeRaw: {\n from: timeRange.state.from,\n to: timeRange.state.to\n },\n cacheTimeout: this.state.cacheTimeout,\n queryCachingTTL: this.state.queryCachingTTL\n }, getEnrichedDataRequest(this));\n if (this._adhocFiltersVar) {\n request.filters = this._adhocFiltersVar.state.filters.filter(isFilterComplete);\n }\n if (this._groupByVar) {\n request.groupByKeys = this._groupByVar.state.value;\n }\n request.targets = request.targets.map((query) => {\n var _a2;\n if (!query.datasource || query.datasource.uid !== ds.uid && !((_a2 = ds.meta) == null ? void 0 : _a2.mixed) && isExpressionReference && !isExpressionReference(query.datasource)) {\n query.datasource = ds.getRef();\n }\n return query;\n });\n const lowerIntervalLimit = minInterval ? interpolate(this, minInterval) : ds.interval;\n const norm = rangeUtil.calculateInterval(timeRange.state.value, request.maxDataPoints, lowerIntervalLimit);\n request.scopedVars = Object.assign({}, request.scopedVars, {\n __interval: { text: norm.interval, value: norm.interval },\n __interval_ms: { text: norm.intervalMs.toString(), value: norm.intervalMs }\n });\n request.interval = norm.interval;\n request.intervalMs = norm.intervalMs;\n const primaryTimeRange = timeRange.state.value;\n let secondaryRequests = [];\n let secondaryProcessors = /* @__PURE__ */ new Map();\n for (const provider of (_a = this.getClosestExtraQueryProviders()) != null ? _a : []) {\n for (const { req, processor } of provider.getExtraQueries(request)) {\n const requestId = getNextRequestId();\n secondaryRequests.push(__spreadProps(__spreadValues({}, req), { requestId }));\n secondaryProcessors.set(requestId, processor != null ? processor : passthroughProcessor);\n }\n }\n request.range = primaryTimeRange;\n return { primary: request, secondaries: secondaryRequests, processors: secondaryProcessors };\n }\n _combineDataLayers(data) {\n if (this._layerAnnotations && this._layerAnnotations.length > 0) {\n data.annotations = (data.annotations || []).concat(this._layerAnnotations);\n }\n if (this.state.data && this.state.data.alertState) {\n data.alertState = this.state.data.alertState;\n }\n return data;\n }\n _setNoDataState() {\n if (this.state.data !== emptyPanelData) {\n this.setState({ data: emptyPanelData });\n }\n }\n getClosestExtraQueryProviders() {\n const found = /* @__PURE__ */ new Map();\n if (!this.parent) {\n return [];\n }\n getClosest(this.parent, (s) => {\n if (isExtraQueryProvider(s) && !found.has(s.constructor)) {\n found.set(s.constructor, s);\n }\n s.forEachChild((child) => {\n if (isExtraQueryProvider(child) && !found.has(child.constructor)) {\n found.set(child.constructor, child);\n }\n });\n return null;\n });\n return Array.from(found.values());\n }\n findAndSubscribeToAdHocFilters(interpolatedUid) {\n const filtersVar = findActiveAdHocFilterVariableByUid(interpolatedUid);\n if (this._adhocFiltersVar !== filtersVar) {\n this._adhocFiltersVar = filtersVar;\n this._updateExplicitVariableDependencies();\n }\n const groupByVar = findActiveGroupByVariablesByUid(interpolatedUid);\n if (this._groupByVar !== groupByVar) {\n this._groupByVar = groupByVar;\n this._updateExplicitVariableDependencies();\n }\n }\n _updateExplicitVariableDependencies() {\n const explicitDependencies = [];\n if (this._adhocFiltersVar) {\n explicitDependencies.push(this._adhocFiltersVar.state.name);\n }\n if (this._groupByVar) {\n explicitDependencies.push(this._groupByVar.state.name);\n }\n this._variableDependency.setVariableNames(explicitDependencies);\n }\n isQueryModeAuto() {\n var _a;\n return ((_a = this.state.runQueriesMode) != null ? _a : \"auto\") === \"auto\";\n }\n}\nfunction findFirstDatasource(targets) {\n var _a, _b;\n return (_b = (_a = targets.find((t) => t.datasource !== null)) == null ? void 0 : _a.datasource) != null ? _b : void 0;\n}\nfunction allFramesEmpty(frames) {\n if (!frames) {\n return true;\n }\n for (let i = 0; i < frames.length; i++) {\n if (frames[i].length > 0) {\n return false;\n }\n }\n return true;\n}\n\nexport { SceneQueryRunner, findFirstDatasource, getNextRequestId };\n//# sourceMappingURL=SceneQueryRunner.js.map\n","/**\n* Copyright (c) 2024, Leon Sorokin\n* All rights reserved. (MIT Licensed)\n*\n* uFuzzy.js (μFuzzy)\n* A tiny, efficient fuzzy matcher that doesn't suck\n* https://github.com/leeoniya/uFuzzy (v1.0.17)\n*/\n\nconst cmp = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }).compare;\n\nconst inf = Infinity;\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping\nconst escapeRegExp = str => str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n// meh, magic tmp placeholder, must be tolerant to toLocaleLowerCase(), interSplit, and intraSplit\nconst EXACT_HERE = 'eexxaacctt';\n\nconst PUNCT_RE = /\\p{P}/gu;\n\nconst LATIN_UPPER = 'A-Z';\nconst LATIN_LOWER = 'a-z';\n\nconst swapAlpha = (str, upper, lower) => str.replace(LATIN_UPPER, upper).replace(LATIN_LOWER, lower);\n\nconst OPTS = {\n\t// whether regexps use a /u unicode flag\n\tunicode: false,\n\n\talpha: null,\n\n\t// term segmentation & punct/whitespace merging\n\tinterSplit: \"[^A-Za-z\\\\d']+\",\n\tintraSplit: \"[a-z][A-Z]\",\n\n\t// inter bounds that will be used to increase lft2/rgt2 info counters\n\tinterBound: \"[^A-Za-z\\\\d]\",\n\t// intra bounds that will be used to increase lft1/rgt1 info counters\n\tintraBound: \"[A-Za-z]\\\\d|\\\\d[A-Za-z]|[a-z][A-Z]\",\n\n\t// inter-bounds mode\n\t// 2 = strict (will only match 'man' on whitepace and punct boundaries: Mega Man, Mega_Man, mega.man)\n\t// 1 = loose (plus allowance for alpha-num and case-change boundaries: MegaMan, 0007man)\n\t// 0 = any (will match 'man' as any substring: megamaniac)\n\tinterLft: 0,\n\tinterRgt: 0,\n\n\t// allowance between terms\n\tinterChars: '.',\n\tinterIns: inf,\n\n\t// allowance between chars in terms\n\tintraChars: \"[a-z\\\\d']\", // internally case-insensitive\n\tintraIns: null,\n\n\tintraContr: \"'[a-z]{1,2}\\\\b\",\n\n\t// multi-insert or single-error mode\n\tintraMode: 0,\n\n\t// single-error bounds for errors within terms, default requires exact first char\n\tintraSlice: [1, inf],\n\n\t// single-error tolerance toggles\n\tintraSub: null,\n\tintraTrn: null,\n\tintraDel: null,\n\n\t// can post-filter matches that are too far apart in distance or length\n\t// (since intraIns is between each char, it can accum to nonsense matches)\n\tintraFilt: (term, match, index) => true, // should this also accept WIP info?\n\n\t// final sorting fn\n\tsort: (info, haystack, needle) => {\n\t\tlet {\n\t\t\tidx,\n\t\t\tchars,\n\t\t\tterms,\n\t\t\tinterLft2,\n\t\t\tinterLft1,\n\t\t//\tinterRgt2,\n\t\t//\tinterRgt1,\n\t\t\tstart,\n\t\t\tintraIns,\n\t\t\tinterIns,\n\t\t\tcases,\n\t\t} = info;\n\n\t\treturn idx.map((v, i) => i).sort((ia, ib) => (\n\t\t\t// most contig chars matched\n\t\t\tchars[ib] - chars[ia] ||\n\t\t\t// least char intra-fuzz (most contiguous)\n\t\t\tintraIns[ia] - intraIns[ib] ||\n\t\t\t// most prefix bounds, boosted by full term matches\n\t\t\t(\n\t\t\t\t(terms[ib] + interLft2[ib] + 0.5 * interLft1[ib]) -\n\t\t\t\t(terms[ia] + interLft2[ia] + 0.5 * interLft1[ia])\n\t\t\t) ||\n\t\t\t// highest density of match (least span)\n\t\t//\tspan[ia] - span[ib] ||\n\t\t\t// highest density of match (least term inter-fuzz)\n\t\t\tinterIns[ia] - interIns[ib] ||\n\t\t\t// earliest start of match\n\t\t\tstart[ia] - start[ib] ||\n\t\t\t// case match\n\t\t\tcases[ib] - cases[ia] ||\n\t\t\t// alphabetic\n\t\t\tcmp(haystack[idx[ia]], haystack[idx[ib]])\n\t\t));\n\t},\n};\n\nconst lazyRepeat = (chars, limit) => (\n\tlimit == 0 ? '' :\n\tlimit == 1 ? chars + '??' :\n\tlimit == inf ? chars + '*?' :\n\t chars + `{0,${limit}}?`\n);\n\nconst mode2Tpl = '(?:\\\\b|_)';\n\nfunction uFuzzy(opts) {\n\topts = Object.assign({}, OPTS, opts);\n\n\tlet {\n\t\tunicode,\n\t\tinterLft,\n\t\tinterRgt,\n\t\tintraMode,\n\t\tintraSlice,\n\t\tintraIns,\n\t\tintraSub,\n\t\tintraTrn,\n\t\tintraDel,\n\t\tintraContr,\n\t\tintraSplit: _intraSplit,\n\t\tinterSplit: _interSplit,\n\t\tintraBound: _intraBound,\n\t\tinterBound: _interBound,\n\t\tintraChars,\n\t} = opts;\n\n\tintraIns ??= intraMode;\n\tintraSub ??= intraMode;\n\tintraTrn ??= intraMode;\n\tintraDel ??= intraMode;\n\n\tlet alpha = opts.letters ?? opts.alpha;\n\n\tif (alpha != null) {\n\t\tlet upper = alpha.toLocaleUpperCase();\n\t\tlet lower = alpha.toLocaleLowerCase();\n\n\t\t_interSplit = swapAlpha(_interSplit, upper, lower);\n\t\t_intraSplit = swapAlpha(_intraSplit, upper, lower);\n\t\t_interBound = swapAlpha(_interBound, upper, lower);\n\t\t_intraBound = swapAlpha(_intraBound, upper, lower);\n\t\tintraChars = swapAlpha(intraChars, upper, lower);\n\t\tintraContr = swapAlpha(intraContr, upper, lower);\n\t}\n\n\tlet uFlag = unicode ? 'u' : '';\n\n\tconst quotedAny = '\".+?\"';\n\tconst EXACTS_RE = new RegExp(quotedAny, 'gi' + uFlag);\n\tconst NEGS_RE = new RegExp(`(?:\\\\s+|^)-(?:${intraChars}+|${quotedAny})`, 'gi' + uFlag);\n\n\tlet { intraRules } = opts;\n\n\tif (intraRules == null) {\n\t\tintraRules = p => {\n\t\t\t// default is exact term matches only\n\t\t\tlet _intraSlice = OPTS.intraSlice, // requires first char\n\t\t\t\t_intraIns = 0,\n\t\t\t\t_intraSub = 0,\n\t\t\t\t_intraTrn = 0,\n\t\t\t\t_intraDel = 0;\n\n\t\t\t// only-digits strings should match exactly, else special rules for short strings\n\t\t\tif (/[^\\d]/.test(p)) {\n\t\t\t\tlet plen = p.length;\n\n\t\t\t\t// prevent junk matches by requiring stricter rules for short terms\n\t\t\t\tif (plen <= 4) {\n\t\t\t\t\tif (plen >= 3) {\n\t\t\t\t\t\t// one swap in non-first char when 3-4 chars\n\t\t\t\t\t\t_intraTrn = Math.min(intraTrn, 1);\n\n\t\t\t\t\t\t// or one insertion when 4 chars\n\t\t\t\t\t\tif (plen == 4)\n\t\t\t\t\t\t\t_intraIns = Math.min(intraIns, 1);\n\t\t\t\t\t}\n\t\t\t\t\t// else exact match when 1-2 chars\n\t\t\t\t}\n\t\t\t\t// use supplied opts\n\t\t\t\telse {\n\t\t\t\t\t_intraSlice = intraSlice;\n\t\t\t\t\t_intraIns = intraIns,\n\t\t\t\t\t_intraSub = intraSub,\n\t\t\t\t\t_intraTrn = intraTrn,\n\t\t\t\t\t_intraDel = intraDel;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tintraSlice: _intraSlice,\n\t\t\t\tintraIns: _intraIns,\n\t\t\t\tintraSub: _intraSub,\n\t\t\t\tintraTrn: _intraTrn,\n\t\t\t\tintraDel: _intraDel,\n\t\t\t};\n\t\t};\n\t}\n\n\tlet withIntraSplit = !!_intraSplit;\n\n\tlet intraSplit = new RegExp(_intraSplit, 'g' + uFlag);\n\tlet interSplit = new RegExp(_interSplit, 'g' + uFlag);\n\n\tlet trimRe = new RegExp('^' + _interSplit + '|' + _interSplit + '$', 'g' + uFlag);\n\tlet contrsRe = new RegExp(intraContr, 'gi' + uFlag);\n\n\tconst split = (needle, keepCase = false) => {\n\t\tlet exacts = [];\n\n\t\tneedle = needle.replace(EXACTS_RE, m => {\n\t\t\texacts.push(m);\n\t\t\treturn EXACT_HERE;\n\t\t});\n\n\t\tneedle = needle.replace(trimRe, '');\n\n\t\tif (!keepCase)\n\t\t\tneedle = needle.toLocaleLowerCase();\n\n\t\tif (withIntraSplit)\n\t\t\tneedle = needle.replace(intraSplit, m => m[0] + ' ' + m[1]);\n\n\t\tlet j = 0;\n\t\treturn needle.split(interSplit).filter(t => t != '').map(v => v === EXACT_HERE ? exacts[j++] : v);\n\t};\n\n\tconst NUM_OR_ALPHA_RE = /[^\\d]+|\\d+/g;\n\n\tconst prepQuery = (needle, capt = 0, interOR = false) => {\n\t\t// split on punct, whitespace, num-alpha, and upper-lower boundaries\n\t\tlet parts = split(needle);\n\n\t\tif (parts.length == 0)\n\t\t\treturn [];\n\n\t\t// split out any detected contractions for each term that become required suffixes\n\t\tlet contrs = Array(parts.length).fill('');\n\t\tparts = parts.map((p, pi) => p.replace(contrsRe, m => {\n\t\t\tcontrs[pi] = m;\n\t\t\treturn '';\n\t\t}));\n\n\t\t// array of regexp tpls for each term\n\t\tlet reTpl;\n\n\t\t// allows single mutations within each term\n\t\tif (intraMode == 1) {\n\t\t\treTpl = parts.map((p, pi) => {\n\t\t\t\tif (p[0] === '\"')\n\t\t\t\t\treturn escapeRegExp(p.slice(1, -1));\n\n\t\t\t\tlet reTpl = '';\n\n\t\t\t\t// split into numeric and alpha parts, so numbers are only matched as following punct or alpha boundaries, without swaps or insertions\n\t\t\t\tfor (let m of p.matchAll(NUM_OR_ALPHA_RE)) {\n\t\t\t\t\tlet p = m[0];\n\n\t\t\t\t\tlet {\n\t\t\t\t\t\tintraSlice,\n\t\t\t\t\t\tintraIns,\n\t\t\t\t\t\tintraSub,\n\t\t\t\t\t\tintraTrn,\n\t\t\t\t\t\tintraDel,\n\t\t\t\t\t} = intraRules(p);\n\n\t\t\t\t\tif (intraIns + intraSub + intraTrn + intraDel == 0)\n\t\t\t\t\t\treTpl += p + contrs[pi];\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet [lftIdx, rgtIdx] = intraSlice;\n\t\t\t\t\t\tlet lftChar = p.slice(0, lftIdx); // prefix\n\t\t\t\t\t\tlet rgtChar = p.slice(rgtIdx); // suffix\n\n\t\t\t\t\t\tlet chars = p.slice(lftIdx, rgtIdx);\n\n\t\t\t\t\t\t// neg lookahead to prefer matching 'Test' instead of 'tTest' in ManifestTest or fittest\n\t\t\t\t\t\t// but skip when search term contains leading repetition (aardvark, aaa)\n\t\t\t\t\t\tif (intraIns == 1 && lftChar.length == 1 && lftChar != chars[0])\n\t\t\t\t\t\t\tlftChar += '(?!' + lftChar + ')';\n\n\t\t\t\t\t\tlet numChars = chars.length;\n\n\t\t\t\t\t\tlet variants = [p];\n\n\t\t\t\t\t\t// variants with single char substitutions\n\t\t\t\t\t\tif (intraSub) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + intraChars + chars.slice(i + 1) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single transpositions\n\t\t\t\t\t\tif (intraTrn) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars - 1; i++) {\n\t\t\t\t\t\t\t\tif (chars[i] != chars[i+1])\n\t\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + chars[i+1] + chars[i] + chars.slice(i + 2) + rgtChar);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single char omissions\n\t\t\t\t\t\tif (intraDel) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i + 1) + '?' + chars.slice(i + 1) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single char insertions\n\t\t\t\t\t\tif (intraIns) {\n\t\t\t\t\t\t\tlet intraInsTpl = lazyRepeat(intraChars, 1);\n\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + intraInsTpl + chars.slice(i) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treTpl += '(?:' + variants.join('|') + ')' + contrs[pi];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t//\tconsole.log(reTpl);\n\n\t\t\t\treturn reTpl;\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet intraInsTpl = lazyRepeat(intraChars, intraIns);\n\n\t\t\t// capture at char level\n\t\t\tif (capt == 2 && intraIns > 0) {\n\t\t\t\t// sadly, we also have to capture the inter-term junk via parenth-wrapping .*?\n\t\t\t\t// to accum other capture groups' indices for \\b boosting during scoring\n\t\t\t\tintraInsTpl = ')(' + intraInsTpl + ')(';\n\t\t\t}\n\n\t\t\treTpl = parts.map((p, pi) => p[0] === '\"' ? escapeRegExp(p.slice(1, -1)) : p.split('').map((c, i, chars) => {\n\t\t\t\t// neg lookahead to prefer matching 'Test' instead of 'tTest' in ManifestTest or fittest\n\t\t\t\t// but skip when search term contains leading repetition (aardvark, aaa)\n\t\t\t\tif (intraIns == 1 && i == 0 && chars.length > 1 && c != chars[i+1])\n\t\t\t\t\tc += '(?!' + c + ')';\n\n\t\t\t\treturn c;\n\t\t\t}).join(intraInsTpl) + contrs[pi]);\n\t\t}\n\n\t//\tconsole.log(reTpl);\n\n\t\t// this only helps to reduce initial matches early when they can be detected\n\t\t// TODO: might want a mode 3 that excludes _\n\t\tlet preTpl = interLft == 2 ? mode2Tpl : '';\n\t\tlet sufTpl = interRgt == 2 ? mode2Tpl : '';\n\n\t\tlet interCharsTpl = sufTpl + lazyRepeat(opts.interChars, opts.interIns) + preTpl;\n\n\t\t// capture at word level\n\t\tif (capt > 0) {\n\t\t\tif (interOR) {\n\t\t\t\t// this is basically for doing .matchAll() occurence counting and highlighting without needing permuted ooo needles\n\t\t\t\treTpl = preTpl + '(' + reTpl.join(')' + sufTpl + '|' + preTpl + '(') + ')' + sufTpl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// sadly, we also have to capture the inter-term junk via parenth-wrapping .*?\n\t\t\t\t// to accum other capture groups' indices for \\b boosting during scoring\n\t\t\t\treTpl = '(' + reTpl.join(')(' + interCharsTpl + ')(') + ')';\n\t\t\t\treTpl = '(.??' + preTpl + ')' + reTpl + '(' + sufTpl + '.*)'; // nit: trailing capture here assumes interIns = Inf\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treTpl = reTpl.join(interCharsTpl);\n\t\t\treTpl = preTpl + reTpl + sufTpl;\n\t\t}\n\n\t//\tconsole.log(reTpl);\n\n\t\treturn [new RegExp(reTpl, 'i' + uFlag), parts, contrs];\n\t};\n\n\tconst filter = (haystack, needle, idxs) => {\n\n\t\tlet [query] = prepQuery(needle);\n\n\t\tif (query == null)\n\t\t\treturn null;\n\n\t\tlet out = [];\n\n\t\tif (idxs != null) {\n\t\t\tfor (let i = 0; i < idxs.length; i++) {\n\t\t\t\tlet idx = idxs[i];\n\t\t\t\tquery.test(haystack[idx]) && out.push(idx);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (let i = 0; i < haystack.length; i++)\n\t\t\t\tquery.test(haystack[i]) && out.push(i);\n\t\t}\n\n\t\treturn out;\n\t};\n\n\tlet withIntraBound = !!_intraBound;\n\n\tlet interBound = new RegExp(_interBound, uFlag);\n\tlet intraBound = new RegExp(_intraBound, uFlag);\n\n\tconst info = (idxs, haystack, needle) => {\n\n\t\tlet [query, parts, contrs] = prepQuery(needle, 1);\n\t\tlet partsCased = split(needle, true);\n\t\tlet [queryR] = prepQuery(needle, 2);\n\t\tlet partsLen = parts.length;\n\n\t\tlet _terms = Array(partsLen);\n\t\tlet _termsCased = Array(partsLen);\n\n\t\tfor (let j = 0; j < partsLen; j++) {\n\t\t\tlet part = parts[j];\n\t\t\tlet partCased = partsCased[j];\n\n\t\t\tlet term = part[0] == '\"' ? part.slice(1, -1) : part + contrs[j];\n\t\t\tlet termCased = partCased[0] == '\"' ? partCased.slice(1, -1) : partCased + contrs[j];\n\n\t\t\t_terms[j] = term;\n\t\t\t_termsCased[j] = termCased;\n\t\t}\n\n\t\tlet len = idxs.length;\n\n\t\tlet field = Array(len).fill(0);\n\n\t\tlet info = {\n\t\t\t// idx in haystack\n\t\t\tidx: Array(len),\n\n\t\t\t// start of match\n\t\t\tstart: field.slice(),\n\t\t\t// length of match\n\t\t//\tspan: field.slice(),\n\n\t\t\t// contiguous chars matched\n\t\t\tchars: field.slice(),\n\n\t\t\t// case matched in term (via term.includes(match))\n\t\t\tcases: field.slice(),\n\n\t\t\t// contiguous (no fuzz) and bounded terms (intra=0, lft2/1, rgt2/1)\n\t\t\t// excludes terms that are contiguous but have < 2 bounds (substrings)\n\t\t\tterms: field.slice(),\n\n\t\t\t// cumulative length of unmatched chars (fuzz) within span\n\t\t\tinterIns: field.slice(), // between terms\n\t\t\tintraIns: field.slice(), // within terms\n\n\t\t\t// interLft/interRgt counters\n\t\t\tinterLft2: field.slice(),\n\t\t\tinterRgt2: field.slice(),\n\t\t\tinterLft1: field.slice(),\n\t\t\tinterRgt1: field.slice(),\n\n\t\t\tranges: Array(len),\n\t\t};\n\n\t\t// might discard idxs based on bounds checks\n\t\tlet mayDiscard = interLft == 1 || interRgt == 1;\n\n\t\tlet ii = 0;\n\n\t\tfor (let i = 0; i < idxs.length; i++) {\n\t\t\tlet mhstr = haystack[idxs[i]];\n\n\t\t\t// the matched parts are [full, junk, term, junk, term, junk]\n\t\t\tlet m = mhstr.match(query);\n\n\t\t\t// leading junk\n\t\t\tlet start = m.index + m[1].length;\n\n\t\t\tlet idxAcc = start;\n\t\t//\tlet span = m[0].length;\n\n\t\t\tlet disc = false;\n\t\t\tlet lft2 = 0;\n\t\t\tlet lft1 = 0;\n\t\t\tlet rgt2 = 0;\n\t\t\tlet rgt1 = 0;\n\t\t\tlet chars = 0;\n\t\t\tlet terms = 0;\n\t\t\tlet cases = 0;\n\t\t\tlet inter = 0;\n\t\t\tlet intra = 0;\n\n\t\t\tlet refine = [];\n\n\t\t\tfor (let j = 0, k = 2; j < partsLen; j++, k+=2) {\n\t\t\t\tlet group = m[k].toLocaleLowerCase();\n\t\t\t\tlet term = _terms[j];\n\t\t\t\tlet termCased = _termsCased[j];\n\t\t\t\tlet termLen = term.length;\n\t\t\t\tlet groupLen = group.length;\n\t\t\t\tlet fullMatch = group == term;\n\n\t\t\t\tif (m[k] == termCased)\n\t\t\t\t\tcases++;\n\n\t\t\t\t// this won't handle the case when an exact match exists across the boundary of the current group and the next junk\n\t\t\t\t// e.g. blob,ob when searching for 'bob' but finding the earlier `blob` (with extra insertion)\n\t\t\t\tif (!fullMatch && m[k+1].length >= termLen) {\n\t\t\t\t\t// probe for exact match in inter junk (TODO: maybe even in this matched part?)\n\t\t\t\t\tlet idxOf = m[k+1].toLocaleLowerCase().indexOf(term);\n\n\t\t\t\t\tif (idxOf > -1) {\n\t\t\t\t\t\trefine.push(idxAcc, groupLen, idxOf, termLen);\n\t\t\t\t\t\tidxAcc += refineMatch(m, k, idxOf, termLen);\n\t\t\t\t\t\tgroup = term;\n\t\t\t\t\t\tgroupLen = termLen;\n\t\t\t\t\t\tfullMatch = true;\n\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tstart = idxAcc;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (mayDiscard || fullMatch) {\n\t\t\t\t\t// does group's left and/or right land on \\b\n\t\t\t\t\tlet lftCharIdx = idxAcc - 1;\n\t\t\t\t\tlet rgtCharIdx = idxAcc + groupLen;\n\n\t\t\t\t\tlet isPre = false;\n\t\t\t\t\tlet isSuf = false;\n\n\t\t\t\t\t// prefix info\n\t\t\t\t\tif (lftCharIdx == -1 || interBound.test(mhstr[lftCharIdx])) {\n\t\t\t\t\t\tfullMatch && lft2++;\n\t\t\t\t\t\tisPre = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (interLft == 2) {\n\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (withIntraBound && intraBound.test(mhstr[lftCharIdx] + mhstr[lftCharIdx + 1])) {\n\t\t\t\t\t\t\tfullMatch && lft1++;\n\t\t\t\t\t\t\tisPre = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (interLft == 1) {\n\t\t\t\t\t\t\t\t// regexps are eager, so try to improve the match by probing forward inter junk for exact match at a boundary\n\t\t\t\t\t\t\t\tlet junk = m[k+1];\n\t\t\t\t\t\t\t\tlet junkIdx = idxAcc + groupLen;\n\n\t\t\t\t\t\t\t\tif (junk.length >= termLen) {\n\t\t\t\t\t\t\t\t\tlet idxOf = 0;\n\t\t\t\t\t\t\t\t\tlet found = false;\n\t\t\t\t\t\t\t\t\tlet re = new RegExp(term, 'ig' + uFlag);\n\n\t\t\t\t\t\t\t\t\tlet m2;\n\t\t\t\t\t\t\t\t\twhile (m2 = re.exec(junk)) {\n\t\t\t\t\t\t\t\t\t\tidxOf = m2.index;\n\n\t\t\t\t\t\t\t\t\t\tlet charIdx = junkIdx + idxOf;\n\t\t\t\t\t\t\t\t\t\tlet lftCharIdx = charIdx - 1;\n\n\t\t\t\t\t\t\t\t\t\tif (lftCharIdx == -1 || interBound.test(mhstr[lftCharIdx])) {\n\t\t\t\t\t\t\t\t\t\t\tlft2++;\n\t\t\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse if (intraBound.test(mhstr[lftCharIdx] + mhstr[charIdx])) {\n\t\t\t\t\t\t\t\t\t\t\tlft1++;\n\t\t\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (found) {\n\t\t\t\t\t\t\t\t\t\tisPre = true;\n\n\t\t\t\t\t\t\t\t\t\t// identical to exact term refinement pass above\n\t\t\t\t\t\t\t\t\t\trefine.push(idxAcc, groupLen, idxOf, termLen);\n\t\t\t\t\t\t\t\t\t\tidxAcc += refineMatch(m, k, idxOf, termLen);\n\t\t\t\t\t\t\t\t\t\tgroup = term;\n\t\t\t\t\t\t\t\t\t\tgroupLen = termLen;\n\t\t\t\t\t\t\t\t\t\tfullMatch = true;\n\n\t\t\t\t\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\t\t\t\t\tstart = idxAcc;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (!isPre) {\n\t\t\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// suffix info\n\t\t\t\t\tif (rgtCharIdx == mhstr.length || interBound.test(mhstr[rgtCharIdx])) {\n\t\t\t\t\t\tfullMatch && rgt2++;\n\t\t\t\t\t\tisSuf = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (interRgt == 2) {\n\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (withIntraBound && intraBound.test(mhstr[rgtCharIdx - 1] + mhstr[rgtCharIdx])) {\n\t\t\t\t\t\t\tfullMatch && rgt1++;\n\t\t\t\t\t\t\tisSuf = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (interRgt == 1) {\n\t\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (fullMatch) {\n\t\t\t\t\t\tchars += termLen;\n\n\t\t\t\t\t\tif (isPre && isSuf)\n\t\t\t\t\t\t\tterms++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (groupLen > termLen)\n\t\t\t\t\tintra += groupLen - termLen; // intraFuzz\n\n\t\t\t\tif (j > 0)\n\t\t\t\t\tinter += m[k-1].length; // interFuzz\n\n\t\t\t\t// TODO: group here is lowercased, which is okay for length cmp, but not more case-sensitive filts\n\t\t\t\tif (!opts.intraFilt(term, group, idxAcc)) {\n\t\t\t\t\tdisc = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (j < partsLen - 1)\n\t\t\t\t\tidxAcc += groupLen + m[k+1].length;\n\t\t\t}\n\n\t\t\tif (!disc) {\n\t\t\t\tinfo.idx[ii] = idxs[i];\n\t\t\t\tinfo.interLft2[ii] = lft2;\n\t\t\t\tinfo.interLft1[ii] = lft1;\n\t\t\t\tinfo.interRgt2[ii] = rgt2;\n\t\t\t\tinfo.interRgt1[ii] = rgt1;\n\t\t\t\tinfo.chars[ii] = chars;\n\t\t\t\tinfo.terms[ii] = terms;\n\t\t\t\tinfo.cases[ii] = cases;\n\t\t\t\tinfo.interIns[ii] = inter;\n\t\t\t\tinfo.intraIns[ii] = intra;\n\n\t\t\t\tinfo.start[ii] = start;\n\t\t\t//\tinfo.span[ii] = span;\n\n\t\t\t\t// ranges\n\t\t\t\tlet m = mhstr.match(queryR);\n\n\t\t\t\tlet idxAcc = m.index + m[1].length;\n\n\t\t\t\tlet refLen = refine.length;\n\t\t\t\tlet ri = refLen > 0 ? 0 : Infinity;\n\t\t\t\tlet lastRi = refLen - 4;\n\n\t\t\t\tfor (let i = 2; i < m.length;) {\n\t\t\t\t\tlet len = m[i].length;\n\n\t\t\t\t\tif (ri <= lastRi && refine[ri] == idxAcc) {\n\t\t\t\t\t\tlet groupLen = refine[ri+1];\n\t\t\t\t\t\tlet idxOf = refine[ri+2];\n\t\t\t\t\t\tlet termLen = refine[ri+3];\n\n\t\t\t\t\t\t// advance to end of original (full) group match that includes intra-junk\n\t\t\t\t\t\tlet j = i;\n\t\t\t\t\t\tlet v = '';\n\t\t\t\t\t\tfor (let _len = 0; _len < groupLen; j++) {\n\t\t\t\t\t\t\tv += m[j];\n\t\t\t\t\t\t\t_len += m[j].length;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tm.splice(i, j - i, v);\n\n\t\t\t\t\t\tidxAcc += refineMatch(m, i, idxOf, termLen);\n\n\t\t\t\t\t\tri += 4;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tidxAcc += len;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tidxAcc = m.index + m[1].length;\n\n\t\t\t\tlet ranges = info.ranges[ii] = [];\n\t\t\t\tlet from = idxAcc;\n\t\t\t\tlet to = idxAcc;\n\n\t\t\t\tfor (let i = 2; i < m.length; i++) {\n\t\t\t\t\tlet len = m[i].length;\n\n\t\t\t\t\tidxAcc += len;\n\n\t\t\t\t\tif (i % 2 == 0)\n\t\t\t\t\t\tto = idxAcc;\n\t\t\t\t\telse if (len > 0) {\n\t\t\t\t\t\tranges.push(from, to);\n\t\t\t\t\t\tfrom = to = idxAcc;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (to > from)\n\t\t\t\t\tranges.push(from, to);\n\n\t\t\t\tii++;\n\t\t\t}\n\t\t}\n\n\t\t// trim arrays\n\t\tif (ii < idxs.length) {\n\t\t\tfor (let k in info)\n\t\t\t\tinfo[k] = info[k].slice(0, ii);\n\t\t}\n\n\t\treturn info;\n\t};\n\n\tconst refineMatch = (m, k, idxInNext, termLen) => {\n\t\t// shift the current group into the prior junk\n\t\tlet prepend = m[k] + m[k+1].slice(0, idxInNext);\n\t\tm[k-1] += prepend;\n\t\tm[k] = m[k+1].slice(idxInNext, idxInNext + termLen);\n\t\tm[k+1] = m[k+1].slice(idxInNext + termLen);\n\t\treturn prepend.length;\n\t};\n\n\tconst OOO_TERMS_LIMIT = 5;\n\n\t// returns [idxs, info, order]\n\tconst _search = (haystack, needle, outOfOrder, infoThresh = 1e3, preFiltered) => {\n\t\toutOfOrder = !outOfOrder ? 0 : outOfOrder === true ? OOO_TERMS_LIMIT : outOfOrder;\n\n\t\tlet needles = null;\n\t\tlet matches = null;\n\n\t\tlet negs = [];\n\n\t\tneedle = needle.replace(NEGS_RE, m => {\n\t\t\tlet neg = m.trim().slice(1);\n\n\t\t\tneg = neg[0] === '\"' ? escapeRegExp(neg.slice(1,-1)) : neg.replace(PUNCT_RE, '');\n\n\t\t\tif (neg != '')\n\t\t\t\tnegs.push(neg);\n\n\t\t\treturn '';\n\t\t});\n\n\t\tlet terms = split(needle);\n\n\t\tlet negsRe;\n\n\t\tif (negs.length > 0) {\n\t\t\tnegsRe = new RegExp(negs.join('|'), 'i' + uFlag);\n\n\t\t\tif (terms.length == 0) {\n\t\t\t\tlet idxs = [];\n\n\t\t\t\tfor (let i = 0; i < haystack.length; i++) {\n\t\t\t\t\tif (!negsRe.test(haystack[i]))\n\t\t\t\t\t\tidxs.push(i);\n\t\t\t\t}\n\n\t\t\t\treturn [idxs, null, null];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// abort search (needle is empty after pre-processing, e.g. no alpha-numeric chars)\n\t\t\tif (terms.length == 0)\n\t\t\t\treturn [null, null, null];\n\t\t}\n\n\t//\tconsole.log(negs);\n\t//\tconsole.log(needle);\n\n\t\tif (outOfOrder > 0) {\n\t\t\t// since uFuzzy is an AND-based search, we can iteratively pre-reduce the haystack by searching\n\t\t\t// for each term in isolation before running permutations on what's left.\n\t\t\t// this is a major perf win. e.g. searching \"test man ger pp a\" goes from 570ms -> 14ms\n\t\t\tlet terms = split(needle);\n\n\t\t\tif (terms.length > 1) {\n\t\t\t\t// longest -> shortest\n\t\t\t\tlet terms2 = terms.slice().sort((a, b) => b.length - a.length);\n\n\t\t\t\tfor (let ti = 0; ti < terms2.length; ti++) {\n\t\t\t\t\t// no haystack item contained all terms\n\t\t\t\t\tif (preFiltered?.length == 0)\n\t\t\t\t\t\treturn [[], null, null];\n\n\t\t\t\t\tpreFiltered = filter(haystack, terms2[ti], preFiltered);\n\t\t\t\t}\n\n\t\t\t\t// avoid combinatorial explosion by limiting outOfOrder to 5 terms (120 max searches)\n\t\t\t\t// fall back to just filter() otherwise\n\t\t\t\tif (terms.length > outOfOrder)\n\t\t\t\t\treturn [preFiltered, null, null];\n\n\t\t\t\tneedles = permute(terms).map(perm => perm.join(' '));\n\n\t\t\t\t// filtered matches for each needle excluding same matches for prior needles\n\t\t\t\tmatches = [];\n\n\t\t\t\t// keeps track of already-matched idxs to skip in follow-up permutations\n\t\t\t\tlet matchedIdxs = new Set();\n\n\t\t\t\tfor (let ni = 0; ni < needles.length; ni++) {\n\t\t\t\t\tif (matchedIdxs.size < preFiltered.length) {\n\t\t\t\t\t\t// filter further for this needle, exclude already-matched\n\t\t\t\t\t\tlet preFiltered2 = preFiltered.filter(idx => !matchedIdxs.has(idx));\n\n\t\t\t\t\t\tlet matched = filter(haystack, needles[ni], preFiltered2);\n\n\t\t\t\t\t\tfor (let j = 0; j < matched.length; j++)\n\t\t\t\t\t\t\tmatchedIdxs.add(matched[j]);\n\n\t\t\t\t\t\tmatches.push(matched);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tmatches.push([]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// interOR\n\t//\tconsole.log(prepQuery(needle, 1, null, true));\n\n\t\t// non-ooo or ooo w/single term\n\t\tif (needles == null) {\n\t\t\tneedles = [needle];\n\t\t\tmatches = [preFiltered?.length > 0 ? preFiltered : filter(haystack, needle)];\n\t\t}\n\n\t\tlet retInfo = null;\n\t\tlet retOrder = null;\n\n\t\tif (negs.length > 0)\n\t\t\tmatches = matches.map(idxs => idxs.filter(idx => !negsRe.test(haystack[idx])));\n\n\t\tlet matchCount = matches.reduce((acc, idxs) => acc + idxs.length, 0);\n\n\t\t// rank, sort, concat\n\t\tif (matchCount <= infoThresh) {\n\t\t\tretInfo = {};\n\t\t\tretOrder = [];\n\n\t\t\tfor (let ni = 0; ni < matches.length; ni++) {\n\t\t\t\tlet idxs = matches[ni];\n\n\t\t\t\tif (idxs == null || idxs.length == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tlet needle = needles[ni];\n\t\t\t\tlet _info = info(idxs, haystack, needle);\n\t\t\t\tlet order = opts.sort(_info, haystack, needle);\n\n\t\t\t\t// offset idxs for concat'ing infos\n\t\t\t\tif (ni > 0) {\n\t\t\t\t\tfor (let i = 0; i < order.length; i++)\n\t\t\t\t\t\torder[i] += retOrder.length;\n\t\t\t\t}\n\n\t\t\t\tfor (let k in _info)\n\t\t\t\t\tretInfo[k] = (retInfo[k] ?? []).concat(_info[k]);\n\n\t\t\t\tretOrder = retOrder.concat(order);\n\t\t\t}\n\t\t}\n\n\t\treturn [\n\t\t\t[].concat(...matches),\n\t\t\tretInfo,\n\t\t\tretOrder,\n\t\t];\n\t};\n\n\treturn {\n\t\tsearch: (...args) => {\n\t\t\tlet out = _search(...args);\n\t\t\treturn out;\n\t\t},\n\t\tsplit,\n\t\tfilter,\n\t\tinfo,\n\t\tsort: opts.sort,\n\t};\n}\n\nconst latinize = (() => {\n\tlet accents = {\n\t\tA: 'ÁÀÃÂÄĄ',\n\t\ta: 'áàãâäą',\n\t\tE: 'ÉÈÊËĖ',\n\t\te: 'éèêëę',\n\t\tI: 'ÍÌÎÏĮ',\n\t\ti: 'íìîïį',\n\t\tO: 'ÓÒÔÕÖ',\n\t\to: 'óòôõö',\n\t\tU: 'ÚÙÛÜŪŲ',\n\t\tu: 'úùûüūų',\n\t\tC: 'ÇČĆ',\n\t\tc: 'çčć',\n\t\tL: 'Ł',\n\t\tl: 'ł',\n\t\tN: 'ÑŃ',\n\t\tn: 'ñń',\n\t\tS: 'ŠŚ',\n\t\ts: 'šś',\n\t\tZ: 'ŻŹ',\n\t\tz: 'żź'\n\t};\n\n\tlet accentsMap = new Map();\n\tlet accentsTpl = '';\n\n\tfor (let r in accents) {\n\t\taccents[r].split('').forEach(a => {\n\t\t\taccentsTpl += a;\n\t\t\taccentsMap.set(a, r);\n\t\t});\n\t}\n\n\tlet accentsRe = new RegExp(`[${accentsTpl}]`, 'g');\n\tlet replacer = m => accentsMap.get(m);\n\n\treturn strings => {\n\t\tif (typeof strings == 'string')\n\t\t\treturn strings.replace(accentsRe, replacer);\n\n\t\tlet out = Array(strings.length);\n\t\tfor (let i = 0; i < strings.length; i++)\n\t\t\tout[i] = strings[i].replace(accentsRe, replacer);\n\t\treturn out;\n\t};\n})();\n\n// https://stackoverflow.com/questions/9960908/permutations-in-javascript/37580979#37580979\nfunction permute(arr) {\n\tarr = arr.slice();\n\n\tlet length = arr.length,\n\t\tresult = [arr.slice()],\n\t\tc = new Array(length).fill(0),\n\t\ti = 1, k, p;\n\n\twhile (i < length) {\n\t\tif (c[i] < i) {\n\t\t\tk = i % 2 && c[i];\n\t\t\tp = arr[i];\n\t\t\tarr[i] = arr[k];\n\t\t\tarr[k] = p;\n\t\t\t++c[i];\n\t\t\ti = 1;\n\t\t\tresult.push(arr.slice());\n\t\t} else {\n\t\t\tc[i] = 0;\n\t\t\t++i;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nconst _mark = (part, matched) => matched ? `
${part}` : part;\nconst _append = (acc, part) => acc + part;\n\nfunction highlight(str, ranges, mark = _mark, accum = '', append = _append) {\n\taccum = append(accum, mark(str.substring(0, ranges[0]), false)) ?? accum;\n\n\tfor (let i = 0; i < ranges.length; i+=2) {\n\t\tlet fr = ranges[i];\n\t\tlet to = ranges[i+1];\n\n\t\taccum = append(accum, mark(str.substring(fr, to), true)) ?? accum;\n\n\t\tif (i < ranges.length - 3)\n\t\t\taccum = append(accum, mark(str.substring(ranges[i+1], ranges[i+2]), false)) ?? accum;\n\t}\n\n\taccum = append(accum, mark(str.substring(ranges[ranges.length - 1]), false)) ?? accum;\n\n\treturn accum;\n}\n\nuFuzzy.latinize = latinize;\nuFuzzy.permute = arr => {\n\tlet idxs = permute([...Array(arr.length).keys()]).sort((a,b) => {\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (a[i] != b[i])\n\t\t\t\treturn a[i] - b[i];\n\t\t}\n\t\treturn 0;\n\t});\n\n\treturn idxs.map(pi => pi.map(i => arr[i]));\n};\nuFuzzy.highlight = highlight;\n\nexport { uFuzzy as default };\n","import { isEqual } from 'lodash';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { SceneQueryRunner } from '../querying/SceneQueryRunner.js';\nimport uFuzzy from '@leeoniya/ufuzzy';\n\nfunction isVariableValueEqual(a, b) {\n if (a === b) {\n return true;\n }\n return isEqual(a, b);\n}\nfunction safeStringifyValue(value) {\n const getCircularReplacer = () => {\n const seen = /* @__PURE__ */ new WeakSet();\n return (_, value2) => {\n if (typeof value2 === \"object\" && value2 !== null) {\n if (seen.has(value2)) {\n return;\n }\n seen.add(value2);\n }\n return value2;\n };\n };\n try {\n return JSON.stringify(value, getCircularReplacer());\n } catch (error) {\n console.error(error);\n }\n return \"\";\n}\nfunction renderPrometheusLabelFilters(filters) {\n return filters.map((filter) => renderFilter(filter)).join(\",\");\n}\nfunction renderFilter(filter) {\n var _a, _b;\n let value = \"\";\n let operator = filter.operator;\n if (operator === \"=|\") {\n operator = \"=~\";\n value = (_a = filter.values) == null ? void 0 : _a.map(escapeLabelValueInRegexSelector).join(\"|\");\n } else if (operator === \"!=|\") {\n operator = \"!~\";\n value = (_b = filter.values) == null ? void 0 : _b.map(escapeLabelValueInRegexSelector).join(\"|\");\n } else if (operator === \"=~\" || operator === \"!~\") {\n value = escapeLabelValueInRegexSelector(filter.value);\n } else {\n value = escapeLabelValueInExactSelector(filter.value);\n }\n return `${filter.key}${operator}\"${value}\"`;\n}\nfunction escapeLabelValueInExactSelector(labelValue) {\n return labelValue.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\n/g, \"\\\\n\").replace(/\"/g, '\\\\\"');\n}\nfunction escapeLabelValueInRegexSelector(labelValue) {\n return escapeLabelValueInExactSelector(escapeLokiRegexp(labelValue));\n}\nconst RE2_METACHARACTERS = /[*+?()|\\\\.\\[\\]{}^$]/g;\nfunction escapeLokiRegexp(value) {\n return value.replace(RE2_METACHARACTERS, \"\\\\$&\");\n}\nfunction getQueriesForVariables(sourceObject) {\n var _a;\n const runners = sceneGraph.findAllObjects(\n sourceObject.getRoot(),\n (o) => o instanceof SceneQueryRunner\n );\n const interpolatedDsUuid = sceneGraph.interpolate(sourceObject, (_a = sourceObject.state.datasource) == null ? void 0 : _a.uid);\n const applicableRunners = filterOutInactiveRunnerDuplicates(runners).filter((r) => {\n var _a2;\n const interpolatedQueryDsUuid = sceneGraph.interpolate(sourceObject, (_a2 = r.state.datasource) == null ? void 0 : _a2.uid);\n return interpolatedQueryDsUuid === interpolatedDsUuid;\n });\n if (applicableRunners.length === 0) {\n return [];\n }\n const result = [];\n applicableRunners.forEach((r) => {\n result.push(...r.state.queries);\n });\n return result;\n}\nfunction filterOutInactiveRunnerDuplicates(runners) {\n const groupedItems = {};\n for (const item of runners) {\n if (item.state.key) {\n if (!(item.state.key in groupedItems)) {\n groupedItems[item.state.key] = [];\n }\n groupedItems[item.state.key].push(item);\n }\n }\n return Object.values(groupedItems).flatMap((group) => {\n const activeItems = group.filter((item) => item.isActive);\n if (activeItems.length === 0 && group.length === 1) {\n return group;\n }\n return activeItems;\n });\n}\nfunction escapeUrlPipeDelimiters(value) {\n if (value === null || value === void 0) {\n return \"\";\n }\n return value = /\\|/g[Symbol.replace](value, \"__gfp__\");\n}\nfunction escapeUrlCommaDelimiters(value) {\n if (value === null || value === void 0) {\n return \"\";\n }\n return /,/g[Symbol.replace](value, \"__gfc__\");\n}\nfunction escapeURLDelimiters(value) {\n return escapeUrlCommaDelimiters(escapeUrlPipeDelimiters(value));\n}\nfunction unescapeUrlDelimiters(value) {\n if (value === null || value === void 0) {\n return \"\";\n }\n value = /__gfp__/g[Symbol.replace](value, \"|\");\n value = /__gfc__/g[Symbol.replace](value, \",\");\n return value;\n}\nfunction toUrlCommaDelimitedString(key, label) {\n if (!label || key === label) {\n return escapeUrlCommaDelimiters(key);\n }\n return [key, label].map(escapeUrlCommaDelimiters).join(\",\");\n}\nfunction dataFromResponse(response) {\n return Array.isArray(response) ? response : response.data;\n}\nfunction responseHasError(response) {\n return !Array.isArray(response) && Boolean(response.error);\n}\nfunction handleOptionGroups(values) {\n const result = [];\n const groupedResults = /* @__PURE__ */ new Map();\n for (const value of values) {\n const groupLabel = value.group;\n if (groupLabel) {\n let group = groupedResults.get(groupLabel);\n if (!group) {\n group = [];\n groupedResults.set(groupLabel, group);\n result.push({ label: groupLabel, options: group });\n }\n group.push(value);\n } else {\n result.push(value);\n }\n }\n return result;\n}\nfunction getFuzzySearcher(haystack, limit = 1e4) {\n const ufuzzy = new uFuzzy();\n const FIRST = Array.from({ length: Math.min(limit, haystack.length) }, (_, i) => i);\n return (search) => {\n if (search === \"\") {\n return FIRST;\n }\n const [idxs, info, order] = ufuzzy.search(haystack, search);\n if (idxs) {\n if (info && order) {\n const outIdxs = Array(Math.min(order.length, limit));\n for (let i = 0; i < outIdxs.length; i++) {\n outIdxs[i] = info.idx[order[i]];\n }\n return outIdxs;\n }\n return idxs.slice(0, limit);\n }\n return [];\n };\n}\n\nexport { dataFromResponse, escapeLabelValueInExactSelector, escapeLabelValueInRegexSelector, escapeURLDelimiters, escapeUrlCommaDelimiters, escapeUrlPipeDelimiters, getFuzzySearcher, getQueriesForVariables, handleOptionGroups, isVariableValueEqual, renderPrometheusLabelFilters, responseHasError, safeStringifyValue, toUrlCommaDelimitedString, unescapeUrlDelimiters };\n//# sourceMappingURL=utils.js.map\n","import { SceneObjectBase } from '../../core/SceneObjectBase.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass ConstantVariable extends SceneObjectBase {\n constructor(initialState) {\n super(__spreadProps(__spreadValues({\n type: \"constant\",\n value: \"\",\n name: \"\"\n }, initialState), {\n skipUrlSync: true\n }));\n }\n getValue() {\n return this.state.value;\n }\n}\n\nexport { ConstantVariable };\n//# sourceMappingURL=ConstantVariable.js.map\n","import { DataLinkBuiltInVars } from '@grafana/data';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { writeSceneLog } from '../utils/writeSceneLog.js';\nimport { VARIABLE_REGEX } from './constants.js';\nimport { safeStringifyValue } from './utils.js';\nimport { ConstantVariable } from './variants/ConstantVariable.js';\n\nclass VariableDependencyConfig {\n constructor(_sceneObject, _options) {\n this._sceneObject = _sceneObject;\n this._options = _options;\n this._dependencies = /* @__PURE__ */ new Set();\n this._isWaitingForVariables = false;\n this.scanCount = 0;\n this._statePaths = _options.statePaths;\n if (this._options.handleTimeMacros) {\n this.handleTimeMacros();\n }\n }\n hasDependencyOn(name) {\n return this.getNames().has(name);\n }\n variableUpdateCompleted(variable, hasChanged) {\n const deps = this.getNames();\n let dependencyChanged = false;\n if ((deps.has(variable.state.name) || deps.has(DataLinkBuiltInVars.includeVars)) && hasChanged) {\n dependencyChanged = true;\n }\n writeSceneLog(\n \"VariableDependencyConfig\",\n \"variableUpdateCompleted\",\n variable.state.name,\n dependencyChanged,\n this._isWaitingForVariables\n );\n if (this._options.onAnyVariableChanged) {\n this._options.onAnyVariableChanged(variable);\n }\n if (this._options.onVariableUpdateCompleted && (this._isWaitingForVariables || dependencyChanged)) {\n this._options.onVariableUpdateCompleted();\n }\n if (dependencyChanged) {\n if (this._options.onReferencedVariableValueChanged) {\n this._options.onReferencedVariableValueChanged(variable);\n }\n if (!this._options.onReferencedVariableValueChanged && !this._options.onVariableUpdateCompleted) {\n this._sceneObject.forceRender();\n }\n }\n }\n hasDependencyInLoadingState() {\n if (sceneGraph.hasVariableDependencyInLoadingState(this._sceneObject)) {\n this._isWaitingForVariables = true;\n return true;\n }\n this._isWaitingForVariables = false;\n return false;\n }\n getNames() {\n const prevState = this._state;\n const newState = this._state = this._sceneObject.state;\n if (!prevState) {\n this.scanStateForDependencies(this._state);\n return this._dependencies;\n }\n if (newState !== prevState) {\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === \"*\" || newState[path] !== prevState[path]) {\n this.scanStateForDependencies(newState);\n break;\n }\n }\n } else {\n this.scanStateForDependencies(newState);\n }\n }\n return this._dependencies;\n }\n setVariableNames(varNames) {\n this._options.variableNames = varNames;\n this.scanStateForDependencies(this._state);\n }\n setPaths(paths) {\n this._statePaths = paths;\n }\n scanStateForDependencies(state) {\n this._dependencies.clear();\n this.scanCount += 1;\n if (this._options.variableNames) {\n for (const name of this._options.variableNames) {\n this._dependencies.add(name);\n }\n }\n if (this._statePaths) {\n for (const path of this._statePaths) {\n if (path === \"*\") {\n this.extractVariablesFrom(state);\n break;\n } else {\n const value = state[path];\n if (value) {\n this.extractVariablesFrom(value);\n }\n }\n }\n }\n }\n extractVariablesFrom(value) {\n VARIABLE_REGEX.lastIndex = 0;\n const stringToCheck = typeof value !== \"string\" ? safeStringifyValue(value) : value;\n const matches = stringToCheck.matchAll(VARIABLE_REGEX);\n if (!matches) {\n return;\n }\n for (const match of matches) {\n const [, var1, var2, , var3] = match;\n const variableName = var1 || var2 || var3;\n this._dependencies.add(variableName);\n }\n }\n handleTimeMacros() {\n this._sceneObject.addActivationHandler(() => {\n const timeRange = sceneGraph.getTimeRange(this._sceneObject);\n const sub = timeRange.subscribeToState((newState, oldState) => {\n const deps = this.getNames();\n const hasFromDep = deps.has(\"__from\");\n const hasToDep = deps.has(\"__to\");\n const hasTimeZone = deps.has(\"__timezone\");\n if (newState.value !== oldState.value) {\n if (hasFromDep) {\n const variable = new ConstantVariable({ name: \"__from\", value: newState.from });\n this.variableUpdateCompleted(variable, true);\n } else if (hasToDep) {\n const variable = new ConstantVariable({ name: \"__to\", value: newState.to });\n this.variableUpdateCompleted(variable, true);\n }\n }\n if (newState.timeZone !== oldState.timeZone && hasTimeZone) {\n const variable = new ConstantVariable({ name: \"__timezone\", value: newState.timeZone });\n this.variableUpdateCompleted(variable, true);\n }\n });\n return () => sub.unsubscribe();\n });\n }\n}\n\nexport { VariableDependencyConfig };\n//# sourceMappingURL=VariableDependencyConfig.js.map\n","import { VariableSupportType } from '@grafana/data';\n\nconst hasLegacyVariableSupport = (datasource) => {\n return Boolean(datasource.metricFindQuery) && !Boolean(datasource.variables);\n};\nconst hasStandardVariableSupport = (datasource) => {\n if (!datasource.variables) {\n return false;\n }\n if (datasource.variables.getType() !== VariableSupportType.Standard) {\n return false;\n }\n const variableSupport = datasource.variables;\n return \"toDataQuery\" in variableSupport && Boolean(variableSupport.toDataQuery);\n};\nconst hasCustomVariableSupport = (datasource) => {\n if (!datasource.variables) {\n return false;\n }\n if (datasource.variables.getType() !== VariableSupportType.Custom) {\n return false;\n }\n const variableSupport = datasource.variables;\n return \"query\" in variableSupport && \"editor\" in variableSupport && Boolean(variableSupport.query) && Boolean(variableSupport.editor);\n};\nconst hasDataSourceVariableSupport = (datasource) => {\n if (!datasource.variables) {\n return false;\n }\n return datasource.variables.getType() === VariableSupportType.Datasource;\n};\n\nexport { hasCustomVariableSupport, hasDataSourceVariableSupport, hasLegacyVariableSupport, hasStandardVariableSupport };\n//# sourceMappingURL=guards.js.map\n","import { from, mergeMap, of } from 'rxjs';\nimport { LoadingState, getDefaultTimeRange } from '@grafana/data';\nimport { getRunRequest } from '@grafana/runtime';\nimport { hasStandardVariableSupport, hasLegacyVariableSupport, hasCustomVariableSupport, hasDataSourceVariableSupport } from './guards.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass StandardQueryRunner {\n constructor(datasource, _runRequest = getRunRequest()) {\n this.datasource = datasource;\n this._runRequest = _runRequest;\n }\n getTarget(variable) {\n if (hasStandardVariableSupport(this.datasource)) {\n return this.datasource.variables.toDataQuery(ensureVariableQueryModelIsADataQuery(variable));\n }\n throw new Error(\"Couldn't create a target with supplied arguments.\");\n }\n runRequest(_, request) {\n if (!hasStandardVariableSupport(this.datasource)) {\n return getEmptyMetricFindValueObservable();\n }\n if (!this.datasource.variables.query) {\n return this._runRequest(this.datasource, request);\n }\n return this._runRequest(this.datasource, request, this.datasource.variables.query.bind(this.datasource.variables));\n }\n}\nclass LegacyQueryRunner {\n constructor(datasource) {\n this.datasource = datasource;\n }\n getTarget(variable) {\n if (hasLegacyVariableSupport(this.datasource)) {\n return variable.state.query;\n }\n throw new Error(\"Couldn't create a target with supplied arguments.\");\n }\n runRequest({ variable, searchFilter }, request) {\n if (!hasLegacyVariableSupport(this.datasource)) {\n return getEmptyMetricFindValueObservable();\n }\n return from(\n this.datasource.metricFindQuery(variable.state.query, __spreadProps(__spreadValues({}, request), {\n variable: {\n name: variable.state.name,\n type: variable.state.type\n },\n searchFilter\n }))\n ).pipe(\n mergeMap((values) => {\n if (!values || !values.length) {\n return getEmptyMetricFindValueObservable();\n }\n const series = values;\n return of({ series, state: LoadingState.Done, timeRange: request.range });\n })\n );\n }\n}\nclass CustomQueryRunner {\n constructor(datasource, _runRequest = getRunRequest()) {\n this.datasource = datasource;\n this._runRequest = _runRequest;\n }\n getTarget(variable) {\n if (hasCustomVariableSupport(this.datasource)) {\n return variable.state.query;\n }\n throw new Error(\"Couldn't create a target with supplied arguments.\");\n }\n runRequest(_, request) {\n if (!hasCustomVariableSupport(this.datasource)) {\n return getEmptyMetricFindValueObservable();\n }\n if (!this.datasource.variables.query) {\n return this._runRequest(this.datasource, request);\n }\n return this._runRequest(this.datasource, request, this.datasource.variables.query.bind(this.datasource.variables));\n }\n}\nconst variableDummyRefId = \"variable-query\";\nclass DatasourceQueryRunner {\n constructor(datasource, _runRequest = getRunRequest()) {\n this.datasource = datasource;\n this._runRequest = _runRequest;\n }\n getTarget(variable) {\n var _a;\n if (hasDataSourceVariableSupport(this.datasource)) {\n if (typeof variable.state.query === \"string\") {\n return variable.state.query;\n }\n return __spreadProps(__spreadValues({}, variable.state.query), { refId: (_a = variable.state.query.refId) != null ? _a : variableDummyRefId });\n }\n throw new Error(\"Couldn't create a target with supplied arguments.\");\n }\n runRequest(_, request) {\n if (!hasDataSourceVariableSupport(this.datasource)) {\n return getEmptyMetricFindValueObservable();\n }\n return this._runRequest(this.datasource, request, this.datasource.query);\n }\n}\nfunction getEmptyMetricFindValueObservable() {\n return of({ state: LoadingState.Done, series: [], timeRange: getDefaultTimeRange() });\n}\nfunction createQueryVariableRunnerFactory(datasource) {\n if (hasStandardVariableSupport(datasource)) {\n return new StandardQueryRunner(datasource, getRunRequest());\n }\n if (hasLegacyVariableSupport(datasource)) {\n return new LegacyQueryRunner(datasource);\n }\n if (hasCustomVariableSupport(datasource)) {\n return new CustomQueryRunner(datasource);\n }\n if (hasDataSourceVariableSupport(datasource)) {\n return new DatasourceQueryRunner(datasource);\n }\n throw new Error(`Couldn't create a query runner for datasource ${datasource.type}`);\n}\nlet createQueryVariableRunner = createQueryVariableRunnerFactory;\nfunction ensureVariableQueryModelIsADataQuery(variable) {\n var _a;\n const query = (_a = variable.state.query) != null ? _a : \"\";\n if (typeof query === \"string\") {\n return { query, refId: `variable-${variable.state.name}` };\n }\n if (query.refId == null) {\n return __spreadProps(__spreadValues({}, query), { refId: `variable-${variable.state.name}` });\n }\n return variable.state.query;\n}\n\nexport { createQueryVariableRunner };\n//# sourceMappingURL=createQueryVariableRunner.js.map\n","import { isNumber, uniqBy, sortBy, toLower } from 'lodash';\nimport { stringToJsRegex, VariableSort } from '@grafana/data';\n\nfunction metricNamesToVariableValues(variableRegEx, sort, metricNames) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n let regex;\n let options = [];\n if (variableRegEx) {\n regex = stringToJsRegex(variableRegEx);\n }\n for (let i = 0; i < metricNames.length; i++) {\n const item = metricNames[i];\n let text = (_b = (_a = item.text) != null ? _a : item.value) != null ? _b : \"\";\n let value = (_d = (_c = item.value) != null ? _c : item.text) != null ? _d : \"\";\n if (isNumber(value)) {\n value = value.toString();\n }\n if (isNumber(text)) {\n text = text.toString();\n }\n if (regex) {\n const matches = getAllMatches(value, regex);\n if (!matches.length) {\n continue;\n }\n const valueGroup = matches.find((m) => m.groups && m.groups.value);\n const textGroup = matches.find((m) => m.groups && m.groups.text);\n const firstMatch = matches.find((m) => m.length > 1);\n const manyMatches = matches.length > 1 && firstMatch;\n if (valueGroup || textGroup) {\n value = (_g = (_e = valueGroup == null ? void 0 : valueGroup.groups) == null ? void 0 : _e.value) != null ? _g : (_f = textGroup == null ? void 0 : textGroup.groups) == null ? void 0 : _f.text;\n text = (_j = (_h = textGroup == null ? void 0 : textGroup.groups) == null ? void 0 : _h.text) != null ? _j : (_i = valueGroup == null ? void 0 : valueGroup.groups) == null ? void 0 : _i.value;\n } else if (manyMatches) {\n for (let j = 0; j < matches.length; j++) {\n const match = matches[j];\n options.push({ label: match[1], value: match[1] });\n }\n continue;\n } else if (firstMatch) {\n text = firstMatch[1];\n value = firstMatch[1];\n }\n }\n options.push({ label: text, value });\n }\n options = uniqBy(options, \"value\");\n return sortVariableValues(options, sort);\n}\nconst getAllMatches = (str, regex) => {\n const results = [];\n let matches = null;\n regex.lastIndex = 0;\n do {\n matches = regex.exec(str);\n if (matches) {\n results.push(matches);\n }\n } while (regex.global && matches && matches[0] !== \"\" && matches[0] !== void 0);\n return results;\n};\nconst sortVariableValues = (options, sortOrder) => {\n if (sortOrder === VariableSort.disabled) {\n return options;\n }\n switch (sortOrder) {\n case VariableSort.alphabeticalAsc:\n options = sortBy(options, \"label\");\n break;\n case VariableSort.alphabeticalDesc:\n options = sortBy(options, \"label\").reverse();\n break;\n case VariableSort.numericalAsc:\n options = sortBy(options, sortByNumeric);\n break;\n case VariableSort.numericalDesc:\n options = sortBy(options, sortByNumeric);\n options = options.reverse();\n break;\n case VariableSort.alphabeticalCaseInsensitiveAsc:\n options = sortBy(options, (opt) => {\n return toLower(opt.label);\n });\n break;\n case VariableSort.alphabeticalCaseInsensitiveDesc:\n options = sortBy(options, (opt) => {\n return toLower(opt.label);\n });\n options = options.reverse();\n break;\n case (VariableSort.naturalAsc || 7):\n options = sortByNaturalSort(options);\n break;\n case (VariableSort.naturalDesc || 8):\n options = sortByNaturalSort(options);\n options = options.reverse();\n break;\n }\n return options;\n};\nfunction sortByNumeric(opt) {\n if (!opt.label) {\n return -1;\n }\n const matches = opt.label.match(/.*?(\\d+).*/);\n if (!matches || matches.length < 2) {\n return -1;\n } else {\n return parseInt(matches[1], 10);\n }\n}\nconst collator = new Intl.Collator(void 0, { sensitivity: \"accent\", numeric: true });\nfunction sortByNaturalSort(options) {\n return options.slice().sort((a, b) => {\n return collator.compare(a.label, b.label);\n });\n}\n\nexport { metricNamesToVariableValues, sortVariableValues };\n//# sourceMappingURL=utils.js.map\n","import { lastValueFrom, of, from, mergeMap, filter, take, throwError, catchError } from 'rxjs';\nimport { v4 } from 'uuid';\nimport { VariableRefresh, VariableSort, LoadingState, CoreApp } from '@grafana/data';\nimport { sceneGraph } from '../../../core/sceneGraph/index.js';\nimport { VariableDependencyConfig } from '../../VariableDependencyConfig.js';\nimport { renderSelectForVariable } from '../../components/VariableValueSelect.js';\nimport { MultiValueVariable } from '../MultiValueVariable.js';\nimport { createQueryVariableRunner } from './createQueryVariableRunner.js';\nimport { metricNamesToVariableValues } from './utils.js';\nimport { toMetricFindValues } from './toMetricFindValues.js';\nimport { getDataSource } from '../../../utils/getDataSource.js';\nimport { safeStringifyValue } from '../../utils.js';\nimport { SEARCH_FILTER_VARIABLE } from '../../constants.js';\nimport { debounce } from 'lodash';\nimport { registerQueryWithController } from '../../../querying/registerQueryWithController.js';\nimport { wrapInSafeSerializableSceneObject } from '../../../utils/wrapInSafeSerializableSceneObject.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass QueryVariable extends MultiValueVariable {\n constructor(initialState) {\n super(__spreadValues({\n type: \"query\",\n name: \"\",\n value: \"\",\n text: \"\",\n options: [],\n datasource: null,\n regex: \"\",\n query: \"\",\n refresh: VariableRefresh.onDashboardLoad,\n sort: VariableSort.disabled\n }, initialState));\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"regex\", \"query\", \"datasource\"]\n });\n this.onSearchChange = (searchFilter) => {\n if (!containsSearchFilter(this.state.query)) {\n return;\n }\n this._updateOptionsBasedOnSearchFilter(searchFilter);\n };\n this._updateOptionsBasedOnSearchFilter = debounce(async (searchFilter) => {\n const result = await lastValueFrom(this.getValueOptions({ searchFilter }));\n this.setState({ options: result, loading: false });\n }, 400);\n }\n getValueOptions(args) {\n if (!this.state.query) {\n return of([]);\n }\n this.setState({ loading: true, error: null });\n return from(\n getDataSource(this.state.datasource, {\n __sceneObject: wrapInSafeSerializableSceneObject(this)\n })\n ).pipe(\n mergeMap((ds) => {\n const runner = createQueryVariableRunner(ds);\n const target = runner.getTarget(this);\n const request = this.getRequest(target, args.searchFilter);\n return runner.runRequest({ variable: this, searchFilter: args.searchFilter }, request).pipe(\n registerQueryWithController({\n type: \"variable\",\n request,\n origin: this\n }),\n filter((data) => data.state === LoadingState.Done || data.state === LoadingState.Error),\n take(1),\n mergeMap((data) => {\n if (data.state === LoadingState.Error) {\n return throwError(() => data.error);\n }\n return of(data);\n }),\n toMetricFindValues(),\n mergeMap((values) => {\n let regex = \"\";\n if (this.state.regex) {\n regex = sceneGraph.interpolate(this, this.state.regex, void 0, \"regex\");\n }\n return of(metricNamesToVariableValues(regex, this.state.sort, values));\n }),\n catchError((error) => {\n if (error.cancelled) {\n return of([]);\n }\n return throwError(() => error);\n })\n );\n })\n );\n }\n getRequest(target, searchFilter) {\n const scopedVars = {\n __sceneObject: wrapInSafeSerializableSceneObject(this)\n };\n if (searchFilter) {\n scopedVars.__searchFilter = { value: searchFilter, text: searchFilter };\n }\n const range = sceneGraph.getTimeRange(this).state.value;\n const request = {\n app: CoreApp.Dashboard,\n requestId: v4(),\n timezone: \"\",\n range,\n interval: \"\",\n intervalMs: 0,\n targets: [target],\n scopedVars,\n startTime: Date.now()\n };\n return request;\n }\n}\nQueryVariable.Component = ({ model }) => {\n return renderSelectForVariable(model);\n};\nfunction containsSearchFilter(query) {\n const str = safeStringifyValue(query);\n return str.indexOf(SEARCH_FILTER_VARIABLE) > -1;\n}\n\nexport { QueryVariable };\n//# sourceMappingURL=QueryVariable.js.map\n","import { getProcessedDataFrames, getFieldDisplayName, FieldType, isDataFrame } from '@grafana/data';\nimport { map } from 'rxjs';\n\nfunction toMetricFindValues() {\n return (source) => source.pipe(\n map((panelData) => {\n const frames = panelData.series;\n if (!frames || !frames.length) {\n return [];\n }\n if (areMetricFindValues(frames)) {\n return frames;\n }\n if (frames[0].fields.length === 0) {\n return [];\n }\n const processedDataFrames = getProcessedDataFrames(frames);\n const metrics = [];\n let valueIndex = -1;\n let textIndex = -1;\n let stringIndex = -1;\n let expandableIndex = -1;\n for (const frame of processedDataFrames) {\n for (let index = 0; index < frame.fields.length; index++) {\n const field = frame.fields[index];\n const fieldName = getFieldDisplayName(field, frame, frames).toLowerCase();\n if (field.type === FieldType.string && stringIndex === -1) {\n stringIndex = index;\n }\n if (fieldName === \"text\" && field.type === FieldType.string && textIndex === -1) {\n textIndex = index;\n }\n if (fieldName === \"value\" && field.type === FieldType.string && valueIndex === -1) {\n valueIndex = index;\n }\n if (fieldName === \"expandable\" && (field.type === FieldType.boolean || field.type === FieldType.number) && expandableIndex === -1) {\n expandableIndex = index;\n }\n }\n }\n if (stringIndex === -1) {\n throw new Error(\"Couldn't find any field of type string in the results.\");\n }\n for (const frame of frames) {\n for (let index = 0; index < frame.length; index++) {\n const expandable = expandableIndex !== -1 ? frame.fields[expandableIndex].values.get(index) : void 0;\n const string = frame.fields[stringIndex].values.get(index);\n const text = textIndex !== -1 ? frame.fields[textIndex].values.get(index) : \"\";\n const value = valueIndex !== -1 ? frame.fields[valueIndex].values.get(index) : \"\";\n if (valueIndex === -1 && textIndex === -1) {\n metrics.push({ text: string, value: string, expandable });\n continue;\n }\n if (valueIndex === -1 && textIndex !== -1) {\n metrics.push({ text, value: text, expandable });\n continue;\n }\n if (valueIndex !== -1 && textIndex === -1) {\n metrics.push({ text: value, value, expandable });\n continue;\n }\n metrics.push({ text, value, expandable });\n }\n }\n return metrics;\n })\n );\n}\nfunction areMetricFindValues(data) {\n if (!data) {\n return false;\n }\n if (!data.length) {\n return true;\n }\n const firstValue = data[0];\n if (isDataFrame(firstValue)) {\n return false;\n }\n for (const firstValueKey in firstValue) {\n if (!firstValue.hasOwnProperty(firstValueKey)) {\n continue;\n }\n if (firstValue[firstValueKey] !== null && typeof firstValue[firstValueKey] !== \"string\" && typeof firstValue[firstValueKey] !== \"number\") {\n continue;\n }\n const key = firstValueKey.toLowerCase();\n if (key === \"text\" || key === \"value\") {\n return true;\n }\n }\n return false;\n}\n\nexport { toMetricFindValues };\n//# sourceMappingURL=toMetricFindValues.js.map\n","import { EmptyDataNode, EmptyVariableSet } from '../../variables/interpolation/defaults.js';\nimport { sceneInterpolator } from '../../variables/interpolation/sceneInterpolator.js';\nimport { isDataLayer } from '../types.js';\nimport { lookupVariable } from '../../variables/lookupVariable.js';\nimport { getClosest } from './utils.js';\nimport { QueryVariable } from '../../variables/variants/query/QueryVariable.js';\n\nfunction getVariables(sceneObject) {\n var _a;\n return (_a = getClosest(sceneObject, (s) => s.state.$variables)) != null ? _a : EmptyVariableSet;\n}\nfunction getData(sceneObject) {\n var _a;\n return (_a = getClosest(sceneObject, (s) => s.state.$data)) != null ? _a : EmptyDataNode;\n}\nfunction isSceneLayout(s) {\n return \"isDraggable\" in s;\n}\nfunction getLayout(scene) {\n const parent = getClosest(scene, (s) => isSceneLayout(s) ? s : void 0);\n if (parent) {\n return parent;\n }\n return null;\n}\nfunction interpolate(sceneObject, value, scopedVars, format, interpolations) {\n if (value === \"\" || value == null) {\n return \"\";\n }\n return sceneInterpolator(sceneObject, value, scopedVars, format, interpolations);\n}\nfunction hasVariableDependencyInLoadingState(sceneObject) {\n if (!sceneObject.variableDependency) {\n return false;\n }\n for (const name of sceneObject.variableDependency.getNames()) {\n if (sceneObject instanceof QueryVariable && sceneObject.state.name === name) {\n console.warn(\"Query variable is referencing itself\");\n continue;\n }\n const variable = lookupVariable(name, sceneObject);\n if (!variable) {\n continue;\n }\n const set = variable.parent;\n if (set.isVariableLoadingOrWaitingToUpdate(variable)) {\n return true;\n }\n }\n return false;\n}\nfunction findObjectInternal(scene, check, alreadySearchedChild, shouldSearchUp) {\n if (check(scene)) {\n return scene;\n }\n let found = null;\n scene.forEachChild((child) => {\n if (child === alreadySearchedChild) {\n return;\n }\n let maybe = findObjectInternal(child, check);\n if (maybe) {\n found = maybe;\n }\n });\n if (found) {\n return found;\n }\n if (shouldSearchUp && scene.parent) {\n return findObjectInternal(scene.parent, check, scene, true);\n }\n return null;\n}\nfunction findByKey(sceneObject, key) {\n const found = findObject(sceneObject, (sceneToCheck) => {\n return sceneToCheck.state.key === key;\n });\n if (!found) {\n throw new Error(\"Unable to find scene with key \" + key);\n }\n return found;\n}\nfunction findByKeyAndType(sceneObject, key, targetType) {\n const found = findObject(sceneObject, (sceneToCheck) => {\n return sceneToCheck.state.key === key;\n });\n if (!found) {\n throw new Error(\"Unable to find scene with key \" + key);\n }\n if (!(found instanceof targetType)) {\n throw new Error(`Found scene object with key ${key} does not match type ${targetType.name}`);\n }\n return found;\n}\nfunction findObject(scene, check) {\n return findObjectInternal(scene, check, void 0, true);\n}\nfunction findAllObjects(scene, check) {\n const found = [];\n scene.forEachChild((child) => {\n if (check(child)) {\n found.push(child);\n }\n found.push(...findAllObjects(child, check));\n });\n return found;\n}\nfunction getDataLayers(sceneObject, localOnly = false) {\n let currentLevel = sceneObject;\n let collected = [];\n while (currentLevel) {\n const dataProvider = currentLevel.state.$data;\n if (!dataProvider) {\n currentLevel = currentLevel.parent;\n continue;\n }\n if (isDataLayer(dataProvider)) {\n collected = collected.concat(dataProvider);\n } else {\n if (dataProvider.state.$data && isDataLayer(dataProvider.state.$data)) {\n collected = collected.concat(dataProvider.state.$data);\n }\n }\n if (localOnly && collected.length > 0) {\n break;\n }\n currentLevel = currentLevel.parent;\n }\n return collected;\n}\nfunction getAncestor(sceneObject, ancestorType) {\n let parent = sceneObject;\n while (parent) {\n if (parent instanceof ancestorType) {\n return parent;\n }\n parent = parent.parent;\n }\n if (!parent) {\n throw new Error(\"Unable to find parent of type \" + ancestorType.name);\n }\n return parent;\n}\nfunction findDescendents(scene, descendentType) {\n function isDescendentType(scene2) {\n return scene2 instanceof descendentType;\n }\n const targetScenes = findAllObjects(scene, isDescendentType);\n return targetScenes.filter(isDescendentType);\n}\n\nexport { findAllObjects, findByKey, findByKeyAndType, findDescendents, findObject, getAncestor, getData, getDataLayers, getLayout, getVariables, hasVariableDependencyInLoadingState, interpolate };\n//# sourceMappingURL=sceneGraph.js.map\n","import { lookupVariable } from '../../variables/lookupVariable.js';\nimport { getQueryController } from './getQueryController.js';\nimport { getTimeRange } from './getTimeRange.js';\nimport { getVariables, getData, getLayout, getDataLayers, interpolate, hasVariableDependencyInLoadingState, findByKey, findByKeyAndType, findObject, findAllObjects, getAncestor, findDescendents } from './sceneGraph.js';\n\nconst sceneGraph = {\n getVariables,\n getData,\n getTimeRange,\n getLayout,\n getDataLayers,\n interpolate,\n lookupVariable,\n hasVariableDependencyInLoadingState,\n findByKey,\n findByKeyAndType,\n findObject,\n findAllObjects,\n getAncestor,\n getQueryController,\n findDescendents\n};\n\nexport { sceneGraph };\n//# sourceMappingURL=index.js.map\n","import { sceneGraph } from '../core/sceneGraph/index.js';\n\nclass UniqueUrlKeyMapper {\n constructor() {\n this.index = /* @__PURE__ */ new Map();\n }\n getUniqueKey(key, obj) {\n const objectsWithKey = this.index.get(key);\n if (!objectsWithKey) {\n this.index.set(key, [obj]);\n return key;\n }\n let address = objectsWithKey.findIndex((o) => o === obj);\n if (address === -1) {\n filterOutOrphanedObjects(objectsWithKey);\n objectsWithKey.push(obj);\n address = objectsWithKey.length - 1;\n }\n if (address > 0) {\n return `${key}-${address + 1}`;\n }\n return key;\n }\n clear() {\n this.index.clear();\n }\n}\nfunction filterOutOrphanedObjects(sceneObjects) {\n for (const obj of sceneObjects) {\n if (isOrphanOrInActive(obj)) {\n const index = sceneObjects.indexOf(obj);\n sceneObjects.splice(index, 1);\n }\n }\n}\nfunction isOrphanOrInActive(obj) {\n const root = obj.getRoot();\n if (!sceneGraph.findObject(root, (child) => child === obj)) {\n return true;\n }\n return false;\n}\n\nexport { UniqueUrlKeyMapper };\n//# sourceMappingURL=UniqueUrlKeyMapper.js.map\n","import { isEqual } from 'lodash';\nimport { UniqueUrlKeyMapper } from './UniqueUrlKeyMapper.js';\n\nfunction getUrlState(root) {\n const urlKeyMapper = new UniqueUrlKeyMapper();\n const result = {};\n const visitNode = (obj) => {\n if (obj.urlSync) {\n const newUrlState = obj.urlSync.getUrlState();\n for (const [key, value] of Object.entries(newUrlState)) {\n if (value != null) {\n const uniqueKey = urlKeyMapper.getUniqueKey(key, obj);\n result[uniqueKey] = value;\n }\n }\n }\n obj.forEachChild(visitNode);\n };\n visitNode(root);\n return result;\n}\nfunction syncStateFromSearchParams(root, urlParams) {\n const urlKeyMapper = new UniqueUrlKeyMapper();\n syncStateFromUrl(root, urlParams, urlKeyMapper);\n}\nfunction syncStateFromUrl(root, urlParams, urlKeyMapper, onlyChildren) {\n if (!onlyChildren) {\n syncUrlStateToObject(root, urlParams, urlKeyMapper);\n }\n root.forEachChild((child) => {\n syncUrlStateToObject(child, urlParams, urlKeyMapper);\n });\n root.forEachChild((child) => syncStateFromUrl(child, urlParams, urlKeyMapper, true));\n}\nfunction syncUrlStateToObject(sceneObject, urlParams, urlKeyMapper) {\n if (sceneObject.urlSync) {\n const urlState = {};\n const currentState = sceneObject.urlSync.getUrlState();\n for (const key of sceneObject.urlSync.getKeys()) {\n const uniqueKey = urlKeyMapper.getUniqueKey(key, sceneObject);\n const newValue = urlParams.getAll(uniqueKey);\n const currentValue = currentState[key];\n if (isUrlValueEqual(newValue, currentValue)) {\n continue;\n }\n if (newValue.length > 0) {\n if (Array.isArray(currentValue)) {\n urlState[key] = newValue;\n } else {\n urlState[key] = newValue[0];\n }\n } else {\n urlState[key] = null;\n }\n }\n if (Object.keys(urlState).length > 0) {\n sceneObject.urlSync.updateFromUrl(urlState);\n }\n }\n}\nfunction isUrlValueEqual(currentUrlValue, newUrlValue) {\n if (currentUrlValue.length === 0 && newUrlValue == null) {\n return true;\n }\n if (!Array.isArray(newUrlValue) && (currentUrlValue == null ? void 0 : currentUrlValue.length) === 1) {\n return newUrlValue === currentUrlValue[0];\n }\n if ((newUrlValue == null ? void 0 : newUrlValue.length) === 0 && currentUrlValue === null) {\n return true;\n }\n return isEqual(currentUrlValue, newUrlValue);\n}\n\nexport { getUrlState, isUrlValueEqual, syncStateFromSearchParams, syncStateFromUrl };\n//# sourceMappingURL=utils.js.map\n","import { DashboardCursorSync } from '@grafana/schema';\nimport { Observable } from 'rxjs';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass CursorSync extends SceneObjectBase {\n constructor(state) {\n super(__spreadProps(__spreadValues({}, state), {\n sync: state.sync || DashboardCursorSync.Off\n }));\n this.getEventsBus = (panel) => {\n if (!this.parent) {\n throw new Error(\"EnableCursorSync cannot be used as a standalone scene object\");\n }\n return new PanelContextEventBus(this.parent, panel);\n };\n }\n getEventsScope() {\n if (!this.parent) {\n throw new Error(\"EnableCursorSync cannot be used as a standalone scene object\");\n }\n return this.state.key;\n }\n}\nclass PanelContextEventBus {\n constructor(_source, _eventsOrigin) {\n this._source = _source;\n this._eventsOrigin = _eventsOrigin;\n }\n publish(event) {\n event.origin = this;\n this._eventsOrigin.publishEvent(event, true);\n }\n getStream(eventType) {\n return new Observable((observer) => {\n const handler = (event) => {\n observer.next(event);\n };\n const sub = this._source.subscribeToEvent(eventType, handler);\n return () => sub.unsubscribe();\n });\n }\n subscribe(eventType, handler) {\n return this.getStream(eventType).pipe().subscribe(handler);\n }\n removeAllListeners() {\n }\n newScopedBus(key, filter) {\n throw new Error(\"For internal use only\");\n }\n}\nfunction getCursorSyncScope(sceneObject) {\n return sceneGraph.findObject(sceneObject, (o) => o instanceof CursorSync);\n}\n\nexport { CursorSync, getCursorSyncScope };\n//# sourceMappingURL=CursorSync.js.map\n","export var noop = function () { };\nexport function on(obj) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (obj && obj.addEventListener) {\n obj.addEventListener.apply(obj, args);\n }\n}\nexport function off(obj) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n if (obj && obj.removeEventListener) {\n obj.removeEventListener.apply(obj, args);\n }\n}\nexport var isBrowser = typeof window !== 'undefined';\nexport var isNavigator = typeof navigator !== 'undefined';\n","import { useEffect, useLayoutEffect } from 'react';\nimport { isBrowser } from './misc/util';\nvar useIsomorphicLayoutEffect = isBrowser ? useLayoutEffect : useEffect;\nexport default useIsomorphicLayoutEffect;\n","import { useMemo, useState } from 'react';\nimport useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect';\nimport { isBrowser, noop } from './misc/util';\nvar defaultState = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n bottom: 0,\n right: 0,\n};\nfunction useMeasure() {\n var _a = useState(null), element = _a[0], ref = _a[1];\n var _b = useState(defaultState), rect = _b[0], setRect = _b[1];\n var observer = useMemo(function () {\n return new window.ResizeObserver(function (entries) {\n if (entries[0]) {\n var _a = entries[0].contentRect, x = _a.x, y = _a.y, width = _a.width, height = _a.height, top_1 = _a.top, left = _a.left, bottom = _a.bottom, right = _a.right;\n setRect({ x: x, y: y, width: width, height: height, top: top_1, left: left, bottom: bottom, right: right });\n }\n });\n }, []);\n useIsomorphicLayoutEffect(function () {\n if (!element)\n return;\n observer.observe(element);\n return function () {\n observer.disconnect();\n };\n }, [element]);\n return [ref, rect];\n}\nexport default isBrowser && typeof window.ResizeObserver !== 'undefined'\n ? useMeasure\n : (function () { return [noop, defaultState]; });\n","import { css } from '@emotion/css';\nimport { useStyles2, Icon, Tooltip, Button } from '@grafana/ui';\nimport React from 'react';\n\nfunction VizPanelSeriesLimit({ data, showAll, seriesLimit, onShowAllSeries }) {\n const styles = useStyles2(getStyles);\n const seriesCount = data == null ? void 0 : data.series.length;\n if (seriesCount === void 0 || seriesCount < seriesLimit) {\n return null;\n }\n const buttonText = showAll ? \"Restore limit\" : `Show all ${seriesCount}`;\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.timeSeriesDisclaimer\n }, !showAll && /* @__PURE__ */ React.createElement(\"span\", {\n className: styles.warningMessage\n }, /* @__PURE__ */ React.createElement(Icon, {\n title: `Showing only ${seriesLimit} series`,\n name: \"exclamation-triangle\",\n \"aria-hidden\": \"true\"\n })), /* @__PURE__ */ React.createElement(Tooltip, {\n content: \"Rendering too many series in a single panel may impact performance and make data harder to read.\"\n }, /* @__PURE__ */ React.createElement(Button, {\n variant: \"secondary\",\n size: \"sm\",\n onClick: onShowAllSeries\n }, buttonText)));\n}\nconst getStyles = (theme) => ({\n timeSeriesDisclaimer: css({\n label: \"time-series-disclaimer\",\n display: \"flex\",\n alignItems: \"center\",\n gap: theme.spacing(1)\n }),\n warningMessage: css({\n display: \"flex\",\n alignItems: \"center\",\n gap: theme.spacing(0.5),\n color: theme.colors.warning.main,\n fontSize: theme.typography.bodySmall.fontSize\n })\n});\n\nexport { VizPanelSeriesLimit };\n//# sourceMappingURL=VizPanelSeriesLimit.js.map\n","import React, { useMemo, useCallback } from 'react';\nimport { useMeasure } from 'react-use';\nimport { SetPanelAttentionEvent, AlertState, PluginContextProvider } from '@grafana/data';\nimport { getAppEvents } from '@grafana/runtime';\nimport { useStyles2, Tooltip, PanelChrome, Icon, ErrorBoundaryAlert, PanelContextProvider } from '@grafana/ui';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { isSceneObject } from '../../core/types.js';\nimport { css, cx } from '@emotion/css';\nimport { debounce } from 'lodash';\nimport { VizPanelSeriesLimit } from './VizPanelSeriesLimit.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nfunction VizPanelRenderer({ model }) {\n var _a;\n const {\n title,\n options,\n fieldConfig,\n _pluginLoadError,\n displayMode,\n hoverHeader,\n showMenuAlways,\n hoverHeaderOffset,\n menu,\n headerActions,\n titleItems,\n seriesLimit,\n seriesLimitShowAll,\n description,\n collapsible,\n collapsed,\n _renderCounter = 0\n } = model.useState();\n const [ref, { width, height }] = useMeasure();\n const appEvents = useMemo(() => getAppEvents(), []);\n const setPanelAttention = useCallback(() => {\n if (model.state.key) {\n appEvents.publish(new SetPanelAttentionEvent({ panelId: model.state.key }));\n }\n }, [model.state.key, appEvents]);\n const debouncedMouseMove = useMemo(\n () => debounce(setPanelAttention, 100, { leading: true, trailing: false }),\n [setPanelAttention]\n );\n const plugin = model.getPlugin();\n const { dragClass, dragClassCancel } = getDragClasses(model);\n const dragHooks = getDragHooks(model);\n const dataObject = sceneGraph.getData(model);\n const rawData = dataObject.useState();\n const dataWithSeriesLimit = useDataWithSeriesLimit(rawData.data, seriesLimit, seriesLimitShowAll);\n const dataWithFieldConfig = model.applyFieldConfig(dataWithSeriesLimit);\n const sceneTimeRange = sceneGraph.getTimeRange(model);\n const timeZone = sceneTimeRange.getTimeZone();\n const timeRange = model.getTimeRange(dataWithFieldConfig);\n const titleInterpolated = model.interpolate(title, void 0, \"text\");\n const alertStateStyles = useStyles2(getAlertStateStyles);\n if (!plugin) {\n return /* @__PURE__ */ React.createElement(\"div\", null, \"Loading plugin panel...\");\n }\n if (!plugin.panel) {\n return /* @__PURE__ */ React.createElement(\"div\", null, \"Panel plugin has no panel component\");\n }\n const PanelComponent = plugin.panel;\n if (dataObject && dataObject.setContainerWidth) {\n dataObject.setContainerWidth(Math.round(width));\n }\n let titleItemsElement = [];\n if (titleItems) {\n if (Array.isArray(titleItems)) {\n titleItemsElement = titleItemsElement.concat(\n titleItems.map((titleItem) => {\n return /* @__PURE__ */ React.createElement(titleItem.Component, {\n model: titleItem,\n key: `${titleItem.state.key}`\n });\n })\n );\n } else if (isSceneObject(titleItems)) {\n titleItemsElement.push(/* @__PURE__ */ React.createElement(titleItems.Component, {\n model: titleItems\n }));\n } else {\n titleItemsElement.push(titleItems);\n }\n }\n if (seriesLimit) {\n titleItemsElement.push(\n /* @__PURE__ */ React.createElement(VizPanelSeriesLimit, {\n key: \"series-limit\",\n data: rawData.data,\n seriesLimit,\n showAll: seriesLimitShowAll,\n onShowAllSeries: () => model.setState({ seriesLimitShowAll: !seriesLimitShowAll })\n })\n );\n }\n if (model.state.$timeRange) {\n titleItemsElement.push(/* @__PURE__ */ React.createElement(model.state.$timeRange.Component, {\n model: model.state.$timeRange,\n key: model.state.key\n }));\n }\n if (dataWithFieldConfig.alertState) {\n titleItemsElement.push(\n /* @__PURE__ */ React.createElement(Tooltip, {\n content: (_a = dataWithFieldConfig.alertState.state) != null ? _a : \"unknown\",\n key: `alert-states-icon-${model.state.key}`\n }, /* @__PURE__ */ React.createElement(PanelChrome.TitleItem, {\n className: cx({\n [alertStateStyles.ok]: dataWithFieldConfig.alertState.state === AlertState.OK,\n [alertStateStyles.pending]: dataWithFieldConfig.alertState.state === AlertState.Pending,\n [alertStateStyles.alerting]: dataWithFieldConfig.alertState.state === AlertState.Alerting\n })\n }, /* @__PURE__ */ React.createElement(Icon, {\n name: dataWithFieldConfig.alertState.state === \"alerting\" ? \"heart-break\" : \"heart\",\n className: \"panel-alert-icon\",\n size: \"md\"\n })))\n );\n }\n let panelMenu;\n if (menu) {\n panelMenu = /* @__PURE__ */ React.createElement(menu.Component, {\n model: menu\n });\n }\n let actionsElement;\n if (headerActions) {\n if (Array.isArray(headerActions)) {\n actionsElement = /* @__PURE__ */ React.createElement(React.Fragment, null, headerActions.map((action) => {\n return /* @__PURE__ */ React.createElement(action.Component, {\n model: action,\n key: `${action.state.key}`\n });\n }));\n } else if (isSceneObject(headerActions)) {\n actionsElement = /* @__PURE__ */ React.createElement(headerActions.Component, {\n model: headerActions\n });\n } else {\n actionsElement = headerActions;\n }\n }\n const data = dataWithFieldConfig;\n const isReadyToRender = dataObject.isDataReadyToDisplay ? dataObject.isDataReadyToDisplay() : true;\n const context = model.getPanelContext();\n const panelId = model.getLegacyPanelId();\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: relativeWrapper\n }, /* @__PURE__ */ React.createElement(\"div\", {\n ref,\n className: absoluteWrapper,\n \"data-viz-panel-key\": model.state.key\n }, width > 0 && height > 0 && /* @__PURE__ */ React.createElement(PanelChrome, {\n title: titleInterpolated,\n description: (description == null ? void 0 : description.trim()) ? model.getDescription : void 0,\n loadingState: data.state,\n statusMessage: getChromeStatusMessage(data, _pluginLoadError),\n statusMessageOnClick: model.onStatusMessageClick,\n width,\n height,\n selectionId: model.state.key,\n displayMode,\n showMenuAlways,\n hoverHeader,\n hoverHeaderOffset,\n titleItems: titleItemsElement,\n dragClass,\n actions: actionsElement,\n dragClassCancel,\n padding: plugin.noPadding ? \"none\" : \"md\",\n menu: panelMenu,\n onCancelQuery: model.onCancelQuery,\n onFocus: setPanelAttention,\n onMouseEnter: setPanelAttention,\n onMouseMove: debouncedMouseMove,\n collapsible,\n collapsed,\n onToggleCollapse: model.onToggleCollapse,\n onDragStart: (e) => {\n var _a2;\n (_a2 = dragHooks.onDragStart) == null ? void 0 : _a2.call(dragHooks, e, model);\n }\n }, (innerWidth, innerHeight) => /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ErrorBoundaryAlert, {\n dependencies: [plugin, data]\n }, /* @__PURE__ */ React.createElement(PluginContextProvider, {\n meta: plugin.meta\n }, /* @__PURE__ */ React.createElement(PanelContextProvider, {\n value: context\n }, isReadyToRender && /* @__PURE__ */ React.createElement(PanelComponent, {\n id: panelId,\n data,\n title,\n timeRange,\n timeZone,\n options,\n fieldConfig,\n transparent: false,\n width: innerWidth,\n height: innerHeight,\n renderCounter: _renderCounter,\n replaceVariables: model.interpolate,\n onOptionsChange: model.onOptionsChange,\n onFieldConfigChange: model.onFieldConfigChange,\n onChangeTimeRange: model.onTimeRangeChange,\n eventBus: context.eventBus\n }))))))));\n}\nfunction useDataWithSeriesLimit(data, seriesLimit, showAllSeries) {\n return useMemo(() => {\n if (!(data == null ? void 0 : data.series) || !seriesLimit || showAllSeries) {\n return data;\n }\n return __spreadProps(__spreadValues({}, data), {\n series: data.series.slice(0, seriesLimit)\n });\n }, [data, seriesLimit, showAllSeries]);\n}\nfunction getDragClasses(panel) {\n var _a, _b;\n const parentLayout = sceneGraph.getLayout(panel);\n const isDraggable = parentLayout == null ? void 0 : parentLayout.isDraggable();\n if (!parentLayout || !isDraggable || itemDraggingDisabled(panel, parentLayout)) {\n return { dragClass: \"\", dragClassCancel: \"\" };\n }\n return { dragClass: (_a = parentLayout.getDragClass) == null ? void 0 : _a.call(parentLayout), dragClassCancel: (_b = parentLayout == null ? void 0 : parentLayout.getDragClassCancel) == null ? void 0 : _b.call(parentLayout) };\n}\nfunction getDragHooks(panel) {\n var _a, _b;\n const parentLayout = sceneGraph.getLayout(panel);\n return (_b = (_a = parentLayout == null ? void 0 : parentLayout.getDragHooks) == null ? void 0 : _a.call(parentLayout)) != null ? _b : {};\n}\nfunction itemDraggingDisabled(item, layout) {\n let ancestor = item.parent;\n while (ancestor && ancestor !== layout) {\n if (\"isDraggable\" in ancestor.state && ancestor.state.isDraggable === false) {\n return true;\n }\n ancestor = ancestor.parent;\n }\n return false;\n}\nfunction getChromeStatusMessage(data, pluginLoadingError) {\n if (pluginLoadingError) {\n return pluginLoadingError;\n }\n let message = data.error ? data.error.message : void 0;\n if (data.errors) {\n message = data.errors.map((e) => e.message).join(\", \");\n }\n return message;\n}\nconst relativeWrapper = css({\n position: \"relative\",\n width: \"100%\",\n height: \"100%\"\n});\nconst absoluteWrapper = css({\n position: \"absolute\",\n width: \"100%\",\n height: \"100%\"\n});\nconst getAlertStateStyles = (theme) => {\n return {\n ok: css({\n color: theme.colors.success.text\n }),\n pending: css({\n color: theme.colors.warning.text\n }),\n alerting: css({\n color: theme.colors.error.text\n })\n };\n};\n\nexport { VizPanelRenderer };\n//# sourceMappingURL=VizPanelRenderer.js.map\n","import { isSystemOverrideWithRef, FieldMatcherID, ByNamesMatcherMode, FieldType, getFieldDisplayName, fieldMatchers } from '@grafana/data';\nimport { SeriesVisibilityChangeMode } from '@grafana/ui';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst displayOverrideRef = \"hideSeriesFrom\";\nconst isHideSeriesOverride = isSystemOverrideWithRef(displayOverrideRef);\nfunction seriesVisibilityConfigFactory(label, mode, fieldConfig, data) {\n const { overrides } = fieldConfig;\n const displayName = label;\n const currentIndex = overrides.findIndex(isHideSeriesOverride);\n if (currentIndex < 0) {\n if (mode === SeriesVisibilityChangeMode.ToggleSelection) {\n const override3 = createOverride([displayName, ...getNamesOfHiddenFields(overrides, data)]);\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: [...fieldConfig.overrides, override3]\n });\n }\n const displayNames = getDisplayNames(data, displayName);\n const override2 = createOverride(displayNames);\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: [...fieldConfig.overrides, override2]\n });\n }\n const overridesCopy = Array.from(overrides);\n const [current] = overridesCopy.splice(currentIndex, 1);\n if (mode === SeriesVisibilityChangeMode.ToggleSelection) {\n let existing = getExistingDisplayNames(current);\n const nameOfHiddenFields = getNamesOfHiddenFields(overridesCopy, data);\n if (nameOfHiddenFields.length > 0) {\n existing = existing.filter((el) => nameOfHiddenFields.indexOf(el) < 0);\n }\n if (existing[0] === displayName && existing.length === 1) {\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: overridesCopy\n });\n }\n const override2 = createOverride([displayName, ...nameOfHiddenFields]);\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: [...overridesCopy, override2]\n });\n }\n const override = createExtendedOverride(current, displayName);\n if (allFieldsAreExcluded(override, data)) {\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: overridesCopy\n });\n }\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: [...overridesCopy, override]\n });\n}\nfunction createOverride(names, mode = ByNamesMatcherMode.exclude, property) {\n property = property != null ? property : {\n id: \"custom.hideFrom\",\n value: {\n viz: true,\n legend: false,\n tooltip: false\n }\n };\n return {\n __systemRef: displayOverrideRef,\n matcher: {\n id: FieldMatcherID.byNames,\n options: {\n mode,\n names,\n prefix: mode === ByNamesMatcherMode.exclude ? \"All except:\" : void 0,\n readOnly: true\n }\n },\n properties: [\n __spreadProps(__spreadValues({}, property), {\n value: {\n viz: true,\n legend: false,\n tooltip: false\n }\n })\n ]\n };\n}\nconst createExtendedOverride = (current, displayName, mode = ByNamesMatcherMode.exclude) => {\n const property = current.properties.find((p) => p.id === \"custom.hideFrom\");\n const existing = getExistingDisplayNames(current);\n const index = existing.findIndex((name) => name === displayName);\n if (index < 0) {\n existing.push(displayName);\n } else {\n existing.splice(index, 1);\n }\n return createOverride(existing, mode, property);\n};\nconst getExistingDisplayNames = (rule) => {\n var _a;\n const names = (_a = rule.matcher.options) == null ? void 0 : _a.names;\n if (!Array.isArray(names)) {\n return [];\n }\n return [...names];\n};\nconst allFieldsAreExcluded = (override, data) => {\n return getExistingDisplayNames(override).length === getDisplayNames(data).length;\n};\nconst getDisplayNames = (data, excludeName) => {\n const unique = /* @__PURE__ */ new Set();\n for (const frame of data) {\n for (const field of frame.fields) {\n if (field.type !== FieldType.number) {\n continue;\n }\n const name = getFieldDisplayName(field, frame, data);\n if (name === excludeName) {\n continue;\n }\n unique.add(name);\n }\n }\n return Array.from(unique);\n};\nconst getNamesOfHiddenFields = (overrides, data) => {\n var _a;\n let names = [];\n for (const override of overrides) {\n const property = override.properties.find((p) => p.id === \"custom.hideFrom\");\n if (property !== void 0 && ((_a = property.value) == null ? void 0 : _a.legend) === true) {\n const info = fieldMatchers.get(override.matcher.id);\n const matcher = info.get(override.matcher.options);\n for (const frame of data) {\n for (const field of frame.fields) {\n if (field.type !== FieldType.number) {\n continue;\n }\n const name = getFieldDisplayName(field, frame, data);\n if (matcher(field, frame, data)) {\n names.push(name);\n }\n }\n }\n }\n }\n return names;\n};\n\nexport { seriesVisibilityConfigFactory };\n//# sourceMappingURL=seriesVisibilityConfigFactory.js.map\n","import { FieldMatcherID, FieldColorModeId } from '@grafana/data';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst changeSeriesColorConfigFactory = (label, color, fieldConfig) => {\n const { overrides } = fieldConfig;\n const currentIndex = fieldConfig.overrides.findIndex((override) => {\n return override.matcher.id === FieldMatcherID.byName && override.matcher.options === label;\n });\n if (currentIndex < 0) {\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: [...fieldConfig.overrides, createOverride(label, color)]\n });\n }\n const overridesCopy = Array.from(overrides);\n const existing = overridesCopy[currentIndex];\n const propertyIndex = existing.properties.findIndex((p) => p.id === \"color\");\n if (propertyIndex < 0) {\n overridesCopy[currentIndex] = __spreadProps(__spreadValues({}, existing), {\n properties: [...existing.properties, createProperty(color)]\n });\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: overridesCopy\n });\n }\n const propertiesCopy = Array.from(existing.properties);\n propertiesCopy[propertyIndex] = createProperty(color);\n overridesCopy[currentIndex] = __spreadProps(__spreadValues({}, existing), {\n properties: propertiesCopy\n });\n return __spreadProps(__spreadValues({}, fieldConfig), {\n overrides: overridesCopy\n });\n};\nconst createOverride = (label, color) => {\n return {\n matcher: {\n id: FieldMatcherID.byName,\n options: label\n },\n properties: [createProperty(color)]\n };\n};\nconst createProperty = (color) => {\n return {\n id: \"color\",\n value: {\n mode: FieldColorModeId.Fixed,\n fixedColor: color\n }\n };\n};\n\nexport { changeSeriesColorConfigFactory };\n//# sourceMappingURL=colorSeriesConfigFactory.js.map\n","import { toUtc, getPanelOptionsWithDefaults, renderMarkdown, applyFieldOverrides, compareArrayValues, compareDataFrameStructures, CoreApp, DashboardCursorSync, PanelPlugin, PluginType } from '@grafana/data';\nimport { getPluginImportUtils, config, getAppEvents } from '@grafana/runtime';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { VizPanelRenderer } from './VizPanelRenderer.js';\nimport { VariableDependencyConfig } from '../../variables/VariableDependencyConfig.js';\nimport { seriesVisibilityConfigFactory } from './seriesVisibilityConfigFactory.js';\nimport { emptyPanelData } from '../../core/SceneDataNode.js';\nimport { changeSeriesColorConfigFactory } from './colorSeriesConfigFactory.js';\nimport { loadPanelPluginSync } from './registerRuntimePanelPlugin.js';\nimport { getCursorSyncScope } from '../../behaviors/CursorSync.js';\nimport { mergeWith, cloneDeep, isArray, merge, isEmpty } from 'lodash';\nimport { UserActionEvent } from '../../core/events.js';\nimport { evaluateTimeRange } from '../../utils/evaluateTimeRange.js';\nimport { LiveNowTimer } from '../../behaviors/LiveNowTimer.js';\nimport { wrapPromiseInStateObservable, registerQueryWithController } from '../../querying/registerQueryWithController.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass VizPanel extends SceneObjectBase {\n constructor(state) {\n var _a;\n super(__spreadValues({\n options: {},\n fieldConfig: { defaults: {}, overrides: [] },\n title: \"Title\",\n pluginId: \"timeseries\",\n _renderCounter: 0\n }, state));\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"title\", \"options\", \"fieldConfig\"]\n });\n this._structureRev = 0;\n this.onTimeRangeChange = (timeRange) => {\n const sceneTimeRange = sceneGraph.getTimeRange(this);\n sceneTimeRange.onTimeRangeChange({\n raw: {\n from: toUtc(timeRange.from),\n to: toUtc(timeRange.to)\n },\n from: toUtc(timeRange.from),\n to: toUtc(timeRange.to)\n });\n };\n this.getTimeRange = (data) => {\n const liveNowTimer = sceneGraph.findObject(this, (o) => o instanceof LiveNowTimer);\n const sceneTimeRange = sceneGraph.getTimeRange(this);\n if (liveNowTimer instanceof LiveNowTimer && liveNowTimer.isEnabled) {\n return evaluateTimeRange(\n sceneTimeRange.state.from,\n sceneTimeRange.state.to,\n sceneTimeRange.getTimeZone(),\n sceneTimeRange.state.fiscalYearStartMonth,\n sceneTimeRange.state.UNSAFE_nowDelay,\n sceneTimeRange.state.weekStart\n );\n }\n const plugin = this.getPlugin();\n if (plugin && !plugin.meta.skipDataQuery && data && data.timeRange) {\n return data.timeRange;\n }\n return sceneTimeRange.state.value;\n };\n this.onTitleChange = (title) => {\n this.setState({ title });\n };\n this.onDescriptionChange = (description) => {\n this.setState({ description });\n };\n this.onDisplayModeChange = (displayMode) => {\n this.setState({ displayMode });\n };\n this.onToggleCollapse = (collapsed) => {\n this.setState({\n collapsed\n });\n };\n this.onOptionsChange = (optionsUpdate, replace = false, isAfterPluginChange = false) => {\n var _a;\n const { fieldConfig, options } = this.state;\n const nextOptions = replace ? optionsUpdate : mergeWith(cloneDeep(options), optionsUpdate, (objValue, srcValue, key, obj) => {\n if (isArray(srcValue)) {\n return srcValue;\n }\n if (objValue !== srcValue && typeof srcValue === \"undefined\") {\n obj[key] = srcValue;\n return;\n }\n return;\n });\n const withDefaults = getPanelOptionsWithDefaults({\n plugin: this._plugin,\n currentOptions: nextOptions,\n currentFieldConfig: fieldConfig,\n isAfterPluginChange\n });\n this.setState({\n options: withDefaults.options,\n _renderCounter: ((_a = this.state._renderCounter) != null ? _a : 0) + 1\n });\n };\n this.onFieldConfigChange = (fieldConfigUpdate, replace) => {\n const { fieldConfig, options } = this.state;\n const nextFieldConfig = replace ? fieldConfigUpdate : merge(cloneDeep(fieldConfig), fieldConfigUpdate);\n const withDefaults = getPanelOptionsWithDefaults({\n plugin: this._plugin,\n currentOptions: options,\n currentFieldConfig: nextFieldConfig,\n isAfterPluginChange: false\n });\n this._dataWithFieldConfig = void 0;\n this.setState({ fieldConfig: withDefaults.fieldConfig });\n };\n this.interpolate = (value, scoped, format) => {\n return sceneGraph.interpolate(this, value, scoped, format);\n };\n this.getDescription = () => {\n this.publishEvent(new UserActionEvent({ origin: this, interaction: \"panel-description-shown\" }), true);\n const { description } = this.state;\n if (description) {\n const markdown = this.interpolate(description);\n return renderMarkdown(markdown);\n }\n return \"\";\n };\n this.onCancelQuery = () => {\n var _a;\n this.publishEvent(new UserActionEvent({ origin: this, interaction: \"panel-cancel-query-clicked\" }), true);\n const data = sceneGraph.getData(this);\n (_a = data.cancelQuery) == null ? void 0 : _a.call(data);\n };\n this.onStatusMessageClick = () => {\n this.publishEvent(new UserActionEvent({ origin: this, interaction: \"panel-status-message-clicked\" }), true);\n };\n this._onSeriesColorChange = (label, color) => {\n this.onFieldConfigChange(changeSeriesColorConfigFactory(label, color, this.state.fieldConfig));\n };\n this._onSeriesVisibilityChange = (label, mode) => {\n if (!this._dataWithFieldConfig) {\n return;\n }\n this.onFieldConfigChange(\n seriesVisibilityConfigFactory(label, mode, this.state.fieldConfig, this._dataWithFieldConfig.series),\n true\n );\n };\n this._onInstanceStateChange = (state) => {\n if (this._panelContext) {\n this._panelContext = __spreadProps(__spreadValues({}, this._panelContext), {\n instanceState: state\n });\n }\n this.setState({ _pluginInstanceState: state });\n };\n this._onToggleLegendSort = (sortKey) => {\n const legendOptions = this.state.options.legend;\n if (!legendOptions) {\n return;\n }\n let sortDesc = legendOptions.sortDesc;\n let sortBy = legendOptions.sortBy;\n if (sortKey !== sortBy) {\n sortDesc = void 0;\n }\n if (sortDesc === false) {\n sortBy = void 0;\n sortDesc = void 0;\n } else {\n sortDesc = !sortDesc;\n sortBy = sortKey;\n }\n this.onOptionsChange(\n __spreadProps(__spreadValues({}, this.state.options), {\n legend: __spreadProps(__spreadValues({}, legendOptions), { sortBy, sortDesc })\n }),\n true\n );\n };\n this.addActivationHandler(() => {\n this._onActivate();\n });\n (_a = state.menu) == null ? void 0 : _a.addActivationHandler(() => {\n this.publishEvent(new UserActionEvent({ origin: this, interaction: \"panel-menu-shown\" }), true);\n });\n }\n _onActivate() {\n if (!this._plugin) {\n this._loadPlugin(this.state.pluginId);\n }\n }\n forceRender() {\n var _a;\n this.setState({ _renderCounter: ((_a = this.state._renderCounter) != null ? _a : 0) + 1 });\n }\n async _loadPlugin(pluginId, overwriteOptions, overwriteFieldConfig, isAfterPluginChange) {\n const plugin = loadPanelPluginSync(pluginId);\n if (plugin) {\n this._pluginLoaded(plugin, overwriteOptions, overwriteFieldConfig, isAfterPluginChange);\n } else {\n const { importPanelPlugin } = getPluginImportUtils();\n try {\n const panelPromise = importPanelPlugin(pluginId);\n const queryControler = sceneGraph.getQueryController(this);\n if (queryControler && queryControler.state.enableProfiling) {\n wrapPromiseInStateObservable(panelPromise).pipe(registerQueryWithController({ type: \"plugin\", origin: this })).subscribe(() => {\n });\n }\n const result = await panelPromise;\n this._pluginLoaded(result, overwriteOptions, overwriteFieldConfig, isAfterPluginChange);\n } catch (err) {\n this._pluginLoaded(getPanelPluginNotFound(pluginId));\n if (err instanceof Error) {\n this.setState({ _pluginLoadError: err.message });\n }\n }\n }\n }\n getLegacyPanelId() {\n const panelId = parseInt(this.state.key.replace(\"panel-\", \"\"), 10);\n if (isNaN(panelId)) {\n return 0;\n }\n return panelId;\n }\n async _pluginLoaded(plugin, overwriteOptions, overwriteFieldConfig, isAfterPluginChange) {\n const { options, fieldConfig, title, pluginVersion, _UNSAFE_customMigrationHandler } = this.state;\n const panel = {\n title,\n options,\n fieldConfig,\n id: this.getLegacyPanelId(),\n type: plugin.meta.id,\n pluginVersion\n };\n if (overwriteOptions) {\n panel.options = overwriteOptions;\n }\n if (overwriteFieldConfig) {\n panel.fieldConfig = overwriteFieldConfig;\n }\n const currentVersion = this._getPluginVersion(plugin);\n _UNSAFE_customMigrationHandler == null ? void 0 : _UNSAFE_customMigrationHandler(panel, plugin);\n if (plugin.onPanelMigration && currentVersion !== pluginVersion && !isAfterPluginChange) {\n panel.options = await plugin.onPanelMigration(panel);\n }\n const withDefaults = getPanelOptionsWithDefaults({\n plugin,\n currentOptions: panel.options,\n currentFieldConfig: panel.fieldConfig,\n isAfterPluginChange: isAfterPluginChange != null ? isAfterPluginChange : false\n });\n this._plugin = plugin;\n this.setState({\n options: withDefaults.options,\n fieldConfig: withDefaults.fieldConfig,\n pluginVersion: currentVersion,\n pluginId: plugin.meta.id\n });\n if (plugin.meta.skipDataQuery) {\n const sceneTimeRange = sceneGraph.getTimeRange(this);\n this._subs.add(sceneTimeRange.subscribeToState(() => this.forceRender()));\n }\n }\n _getPluginVersion(plugin) {\n return plugin && plugin.meta.info.version ? plugin.meta.info.version : config.buildInfo.version;\n }\n getPlugin() {\n return this._plugin;\n }\n getPanelContext() {\n var _a;\n (_a = this._panelContext) != null ? _a : this._panelContext = this.buildPanelContext();\n return this._panelContext;\n }\n async changePluginType(pluginId, newOptions, newFieldConfig) {\n var _a, _b;\n const { options: prevOptions, fieldConfig: prevFieldConfig, pluginId: prevPluginId } = this.state;\n this._dataWithFieldConfig = void 0;\n const isAfterPluginChange = this.state.pluginId !== pluginId;\n await this._loadPlugin(pluginId, newOptions != null ? newOptions : {}, newFieldConfig, isAfterPluginChange);\n const panel = {\n title: this.state.title,\n options: this.state.options,\n fieldConfig: this.state.fieldConfig,\n id: 1,\n type: pluginId\n };\n const updatedOptions = (_b = (_a = this._plugin) == null ? void 0 : _a.onPanelTypeChanged) == null ? void 0 : _b.call(_a, panel, prevPluginId, prevOptions, prevFieldConfig);\n if (updatedOptions && !isEmpty(updatedOptions)) {\n this.onOptionsChange(updatedOptions, true, true);\n }\n }\n clearFieldConfigCache() {\n this._dataWithFieldConfig = void 0;\n }\n applyFieldConfig(rawData) {\n var _a, _b, _c, _d;\n const plugin = this._plugin;\n if (!plugin || plugin.meta.skipDataQuery || !rawData) {\n return emptyPanelData;\n }\n if (this._prevData === rawData && this._dataWithFieldConfig) {\n return this._dataWithFieldConfig;\n }\n const pluginDataSupport = plugin.dataSupport || { alertStates: false, annotations: false };\n const fieldConfigRegistry = plugin.fieldConfigRegistry;\n const prevFrames = (_b = (_a = this._dataWithFieldConfig) == null ? void 0 : _a.series) != null ? _b : [];\n const newFrames = applyFieldOverrides({\n data: rawData.series,\n fieldConfig: this.state.fieldConfig,\n fieldConfigRegistry,\n replaceVariables: this.interpolate,\n theme: config.theme2,\n timeZone: (_c = rawData.request) == null ? void 0 : _c.timezone\n });\n if (!compareArrayValues(newFrames, prevFrames, compareDataFrameStructures)) {\n this._structureRev++;\n }\n this._dataWithFieldConfig = __spreadProps(__spreadValues({}, rawData), {\n structureRev: this._structureRev,\n series: newFrames\n });\n if (this._dataWithFieldConfig.annotations) {\n this._dataWithFieldConfig.annotations = applyFieldOverrides({\n data: this._dataWithFieldConfig.annotations,\n fieldConfig: {\n defaults: {},\n overrides: []\n },\n fieldConfigRegistry,\n replaceVariables: this.interpolate,\n theme: config.theme2,\n timeZone: (_d = rawData.request) == null ? void 0 : _d.timezone\n });\n }\n if (!pluginDataSupport.alertStates) {\n this._dataWithFieldConfig.alertState = void 0;\n }\n if (!pluginDataSupport.annotations) {\n this._dataWithFieldConfig.annotations = void 0;\n }\n this._prevData = rawData;\n return this._dataWithFieldConfig;\n }\n buildPanelContext() {\n const sync = getCursorSyncScope(this);\n const context = {\n eventsScope: sync ? sync.getEventsScope() : \"__global_\",\n eventBus: sync ? sync.getEventsBus(this) : getAppEvents(),\n app: CoreApp.Unknown,\n sync: () => {\n if (sync) {\n return sync.state.sync;\n }\n return DashboardCursorSync.Off;\n },\n onSeriesColorChange: this._onSeriesColorChange,\n onToggleSeriesVisibility: this._onSeriesVisibilityChange,\n onToggleLegendSort: this._onToggleLegendSort,\n onInstanceStateChange: this._onInstanceStateChange\n };\n if (this.state.extendPanelContext) {\n this.state.extendPanelContext(this, context);\n }\n return context;\n }\n}\nVizPanel.Component = VizPanelRenderer;\nfunction getPanelPluginNotFound(id) {\n const plugin = new PanelPlugin(() => null);\n plugin.meta = {\n id,\n name: id,\n sort: 100,\n type: PluginType.panel,\n module: \"\",\n baseUrl: \"\",\n info: {\n author: {\n name: \"\"\n },\n description: \"\",\n links: [],\n logos: {\n large: \"\",\n small: \"public/img/grafana_icon.svg\"\n },\n screenshots: [],\n updated: \"\",\n version: \"\"\n }\n };\n return plugin;\n}\n\nexport { VizPanel };\n//# sourceMappingURL=VizPanel.js.map\n","import { VizPanel } from '../components/VizPanel/VizPanel.js';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\n\nconst _LiveNowTimer = class extends SceneObjectBase {\n constructor({ enabled = false }) {\n super({ enabled });\n this.timerId = void 0;\n this._activationHandler = () => {\n if (this.state.enabled) {\n this.enable();\n }\n return () => {\n window.clearInterval(this.timerId);\n this.timerId = void 0;\n };\n };\n this.addActivationHandler(this._activationHandler);\n }\n enable() {\n window.clearInterval(this.timerId);\n this.timerId = void 0;\n this.timerId = window.setInterval(() => {\n const panels = sceneGraph.findAllObjects(this.getRoot(), (obj) => obj instanceof VizPanel);\n for (const panel of panels) {\n panel.forceRender();\n }\n }, _LiveNowTimer.REFRESH_RATE);\n this.setState({ enabled: true });\n }\n disable() {\n window.clearInterval(this.timerId);\n this.timerId = void 0;\n this.setState({ enabled: false });\n }\n get isEnabled() {\n return this.state.enabled;\n }\n};\nlet LiveNowTimer = _LiveNowTimer;\nLiveNowTimer.REFRESH_RATE = 100;\n\nexport { LiveNowTimer };\n//# sourceMappingURL=LiveNowTimer.js.map\n","import { isFetchError } from '@grafana/runtime';\n\nfunction getMessageFromError(err) {\n if (typeof err === \"string\") {\n return err;\n }\n if (err) {\n if (err instanceof Error) {\n return err.message;\n } else if (isFetchError(err)) {\n if (err.data && err.data.message) {\n return err.data.message;\n } else if (err.statusText) {\n return err.statusText;\n }\n } else if (err.hasOwnProperty(\"message\")) {\n return err.message;\n }\n }\n return JSON.stringify(err);\n}\n\nexport { getMessageFromError };\n//# sourceMappingURL=getMessageFromError.js.map\n","import { ReplaySubject } from 'rxjs';\nimport { emptyPanelData } from '../../core/SceneDataNode.js';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { setBaseClassState } from '../../utils/utils.js';\nimport { writeSceneLog } from '../../utils/writeSceneLog.js';\nimport { VariableDependencyConfig } from '../../variables/VariableDependencyConfig.js';\nimport { VariableValueRecorder } from '../../variables/VariableValueRecorder.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass SceneDataLayerBase extends SceneObjectBase {\n constructor(initialState, variableDependencyStatePaths = []) {\n super(__spreadValues({\n isEnabled: true\n }, initialState));\n this._results = new ReplaySubject(1);\n this.isDataLayer = true;\n this._variableValueRecorder = new VariableValueRecorder();\n this._variableDependency = new VariableDependencyConfig(this, {\n onVariableUpdateCompleted: this.onVariableUpdateCompleted.bind(this)\n });\n this._variableDependency.setPaths(variableDependencyStatePaths);\n this.addActivationHandler(() => this.onActivate());\n }\n onActivate() {\n if (this.state.isEnabled) {\n this.onEnable();\n }\n if (this.shouldRunLayerOnActivate()) {\n this.runLayer();\n }\n this.subscribeToState((n, p) => {\n if (!n.isEnabled && this.querySub) {\n this.querySub.unsubscribe();\n this.querySub = void 0;\n this.onDisable();\n this._results.next({ origin: this, data: emptyPanelData });\n this.setStateHelper({ data: emptyPanelData });\n }\n if (n.isEnabled && !p.isEnabled) {\n this.onEnable();\n this.runLayer();\n }\n });\n return () => {\n this.onDeactivate();\n };\n }\n onDeactivate() {\n if (this.querySub) {\n this.querySub.unsubscribe();\n this.querySub = void 0;\n }\n this.onDisable();\n this._variableValueRecorder.recordCurrentDependencyValuesForSceneObject(this);\n }\n onVariableUpdateCompleted() {\n this.runLayer();\n }\n cancelQuery() {\n if (this.querySub) {\n this.querySub.unsubscribe();\n this.querySub = void 0;\n this.publishResults(emptyPanelData);\n }\n }\n publishResults(data) {\n if (this.state.isEnabled) {\n this._results.next({ origin: this, data });\n this.setStateHelper({ data });\n }\n }\n getResultsStream() {\n return this._results;\n }\n shouldRunLayerOnActivate() {\n if (!this.state.isEnabled) {\n return false;\n }\n if (this._variableValueRecorder.hasDependenciesChanged(this)) {\n writeSceneLog(\n \"SceneDataLayerBase\",\n \"Variable dependency changed while inactive, shouldRunLayerOnActivate returns true\"\n );\n return true;\n }\n if (!this.state.data) {\n return true;\n }\n return false;\n }\n setStateHelper(state) {\n setBaseClassState(this, state);\n }\n}\n\nexport { SceneDataLayerBase };\n//# sourceMappingURL=SceneDataLayerBase.js.map\n","import { css } from '@emotion/css';\nimport { LoadingState } from '@grafana/schema';\nimport { InlineSwitch } from '@grafana/ui';\nimport React from 'react';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { ControlsLabel } from '../../utils/ControlsLabel.js';\n\nclass SceneDataLayerControls extends SceneObjectBase {\n constructor() {\n super({});\n }\n}\nSceneDataLayerControls.Component = SceneDataLayerControlsRenderer;\nfunction SceneDataLayerControlsRenderer({ model }) {\n const layers = sceneGraph.getDataLayers(model, true);\n if (layers.length === 0) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(React.Fragment, null, layers.map((layer) => /* @__PURE__ */ React.createElement(layer.Component, {\n model: layer,\n key: layer.state.key\n })));\n}\nfunction DataLayerControlSwitch({ layer }) {\n var _a, _b;\n const elementId = `data-layer-${layer.state.key}`;\n const { data, isEnabled } = layer.useState();\n const showLoading = Boolean(data && data.state === LoadingState.Loading);\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: containerStyle\n }, /* @__PURE__ */ React.createElement(ControlsLabel, {\n htmlFor: elementId,\n isLoading: showLoading,\n onCancel: () => {\n var _a2;\n return (_a2 = layer.cancelQuery) == null ? void 0 : _a2.call(layer);\n },\n label: layer.state.name,\n description: layer.state.description,\n error: (_b = (_a = layer.state.data) == null ? void 0 : _a.errors) == null ? void 0 : _b[0].message\n }), /* @__PURE__ */ React.createElement(InlineSwitch, {\n id: elementId,\n value: isEnabled,\n onChange: () => layer.setState({ isEnabled: !isEnabled })\n }));\n}\nconst containerStyle = css({ display: \"flex\" });\n\nexport { DataLayerControlSwitch, SceneDataLayerControls };\n//# sourceMappingURL=SceneDataLayerControls.js.map\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n//# sourceMappingURL=isFunction.js.map","import { isFunction } from './isFunction';\nexport function hasLift(source) {\n return isFunction(source === null || source === void 0 ? void 0 : source.lift);\n}\nexport function operate(init) {\n return function (source) {\n if (hasLift(source)) {\n return source.lift(function (liftedSource) {\n try {\n return init(liftedSource, this);\n }\n catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n//# sourceMappingURL=lift.js.map","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import { createErrorClass } from './createErrorClass';\nexport var UnsubscriptionError = createErrorClass(function (_super) {\n return function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ')\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n };\n});\n//# sourceMappingURL=UnsubscriptionError.js.map","export function createErrorClass(createImpl) {\n var _super = function (instance) {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n var ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n//# sourceMappingURL=createErrorClass.js.map","export function arrRemove(arr, item) {\n if (arr) {\n var index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrRemove.js.map","import { __read, __spreadArray, __values } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nvar Subscription = (function () {\n function Subscription(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n Subscription.prototype.unsubscribe = function () {\n var e_1, _a, e_2, _b;\n var errors;\n if (!this.closed) {\n this.closed = true;\n var _parentage = this._parentage;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n try {\n for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {\n var parent_1 = _parentage_1_1.value;\n parent_1.remove(this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n var initialFinalizer = this.initialTeardown;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n var _finalizers = this._finalizers;\n if (_finalizers) {\n this._finalizers = null;\n try {\n for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {\n var finalizer = _finalizers_1_1.value;\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n };\n Subscription.prototype.add = function (teardown) {\n var _a;\n if (teardown && teardown !== this) {\n if (this.closed) {\n execFinalizer(teardown);\n }\n else {\n if (teardown instanceof Subscription) {\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);\n }\n }\n };\n Subscription.prototype._hasParent = function (parent) {\n var _parentage = this._parentage;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n };\n Subscription.prototype._addParent = function (parent) {\n var _parentage = this._parentage;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n };\n Subscription.prototype._removeParent = function (parent) {\n var _parentage = this._parentage;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n };\n Subscription.prototype.remove = function (teardown) {\n var _finalizers = this._finalizers;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n };\n Subscription.EMPTY = (function () {\n var empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n return Subscription;\n}());\nexport { Subscription };\nexport var EMPTY_SUBSCRIPTION = Subscription.EMPTY;\nexport function isSubscription(value) {\n return (value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));\n}\nfunction execFinalizer(finalizer) {\n if (isFunction(finalizer)) {\n finalizer();\n }\n else {\n finalizer.unsubscribe();\n }\n}\n//# sourceMappingURL=Subscription.js.map","export var config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n//# sourceMappingURL=config.js.map","import { __read, __spreadArray } from \"tslib\";\nexport var timeoutProvider = {\n setTimeout: function (handler, timeout) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var delegate = timeoutProvider.delegate;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));\n }\n return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));\n },\n clearTimeout: function (handle) {\n var delegate = timeoutProvider.delegate;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n//# sourceMappingURL=timeoutProvider.js.map","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(function () {\n var onUnhandledError = config.onUnhandledError;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n//# sourceMappingURL=reportUnhandledError.js.map","export function noop() { }\n//# sourceMappingURL=noop.js.map","export var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();\nexport function errorNotification(error) {\n return createNotification('E', undefined, error);\n}\nexport function nextNotification(value) {\n return createNotification('N', value, undefined);\n}\nexport function createNotification(kind, value, error) {\n return {\n kind: kind,\n value: value,\n error: error,\n };\n}\n//# sourceMappingURL=NotificationFactories.js.map","import { config } from '../config';\nvar context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n var isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n var _a = context, errorThrown = _a.errorThrown, error = _a.error;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n }\n else {\n cb();\n }\n}\nexport function captureError(err) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n//# sourceMappingURL=errorContext.js.map","import { __extends } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\nvar Subscriber = (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destination) {\n var _this = _super.call(this) || this;\n _this.isStopped = false;\n if (destination) {\n _this.destination = destination;\n if (isSubscription(destination)) {\n destination.add(_this);\n }\n }\n else {\n _this.destination = EMPTY_OBSERVER;\n }\n return _this;\n }\n Subscriber.create = function (next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n };\n Subscriber.prototype.next = function (value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (!this.closed) {\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n this.destination = null;\n }\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n };\n Subscriber.prototype._complete = function () {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nvar ConsumerObserver = (function () {\n function ConsumerObserver(partialObserver) {\n this.partialObserver = partialObserver;\n }\n ConsumerObserver.prototype.next = function (value) {\n var partialObserver = this.partialObserver;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n ConsumerObserver.prototype.error = function (err) {\n var partialObserver = this.partialObserver;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n else {\n handleUnhandledError(err);\n }\n };\n ConsumerObserver.prototype.complete = function () {\n var partialObserver = this.partialObserver;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n return ConsumerObserver;\n}());\nvar SafeSubscriber = (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n var partialObserver;\n if (isFunction(observerOrNext) || !observerOrNext) {\n partialObserver = {\n next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),\n error: error !== null && error !== void 0 ? error : undefined,\n complete: complete !== null && complete !== void 0 ? complete : undefined,\n };\n }\n else {\n var context_1;\n if (_this && config.useDeprecatedNextContext) {\n context_1 = Object.create(observerOrNext);\n context_1.unsubscribe = function () { return _this.unsubscribe(); };\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context_1),\n error: observerOrNext.error && bind(observerOrNext.error, context_1),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n _this.destination = new ConsumerObserver(partialObserver);\n return _this;\n }\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\nfunction handleUnhandledError(error) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n }\n else {\n reportUnhandledError(error);\n }\n}\nfunction defaultErrorHandler(err) {\n throw err;\n}\nfunction handleStoppedNotification(notification, subscriber) {\n var onStoppedNotification = config.onStoppedNotification;\n onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });\n}\nexport var EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n//# sourceMappingURL=Subscriber.js.map","import { __extends } from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\nvar OperatorSubscriber = (function (_super) {\n __extends(OperatorSubscriber, _super);\n function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {\n var _this = _super.call(this, destination) || this;\n _this.onFinalize = onFinalize;\n _this.shouldUnsubscribe = shouldUnsubscribe;\n _this._next = onNext\n ? function (value) {\n try {\n onNext(value);\n }\n catch (err) {\n destination.error(err);\n }\n }\n : _super.prototype._next;\n _this._error = onError\n ? function (err) {\n try {\n onError(err);\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._error;\n _this._complete = onComplete\n ? function () {\n try {\n onComplete();\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._complete;\n return _this;\n }\n OperatorSubscriber.prototype.unsubscribe = function () {\n var _a;\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n var closed_1 = this.closed;\n _super.prototype.unsubscribe.call(this);\n !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));\n }\n };\n return OperatorSubscriber;\n}(Subscriber));\nexport { OperatorSubscriber };\n//# sourceMappingURL=OperatorSubscriber.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function map(project, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n subscriber.next(project.call(thisArg, value, index++));\n }));\n });\n}\n//# sourceMappingURL=map.js.map","export var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();\n//# sourceMappingURL=observable.js.map","export function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map","import { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription } from './Subscription';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\nvar Observable = (function () {\n function Observable(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var _this = this;\n var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(function () {\n var _a = _this, operator = _a.operator, source = _a.source;\n subscriber.add(operator\n ?\n operator.call(subscriber, source)\n : source\n ?\n _this._subscribe(subscriber)\n :\n _this._trySubscribe(subscriber));\n });\n return subscriber;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscriber = new SafeSubscriber({\n next: function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n _this.subscribe(subscriber);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n var _a;\n return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;\n}\nfunction isObserver(value) {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\nfunction isSubscriber(value) {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n//# sourceMappingURL=Observable.js.map","import { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport var iterator = getSymbolIterator();\n//# sourceMappingURL=iterator.js.map","import { __asyncValues, __awaiter, __generator, __values } from \"tslib\";\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function innerFrom(input) {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\nexport function fromInteropObservable(obj) {\n return new Observable(function (subscriber) {\n var obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\nexport function fromArrayLike(array) {\n return new Observable(function (subscriber) {\n for (var i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\nexport function fromPromise(promise) {\n return new Observable(function (subscriber) {\n promise\n .then(function (value) {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, function (err) { return subscriber.error(err); })\n .then(null, reportUnhandledError);\n });\n}\nexport function fromIterable(iterable) {\n return new Observable(function (subscriber) {\n var e_1, _a;\n try {\n for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {\n var value = iterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n subscriber.complete();\n });\n}\nexport function fromAsyncIterable(asyncIterable) {\n return new Observable(function (subscriber) {\n process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });\n });\n}\nexport function fromReadableStreamLike(readableStream) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\nfunction process(asyncIterable, subscriber) {\n var asyncIterable_1, asyncIterable_1_1;\n var e_2, _a;\n return __awaiter(this, void 0, void 0, function () {\n var value, e_2_1;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, 6, 11]);\n asyncIterable_1 = __asyncValues(asyncIterable);\n _b.label = 1;\n case 1: return [4, asyncIterable_1.next()];\n case 2:\n if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];\n value = asyncIterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return [2];\n }\n _b.label = 3;\n case 3: return [3, 1];\n case 4: return [3, 11];\n case 5:\n e_2_1 = _b.sent();\n e_2 = { error: e_2_1 };\n return [3, 11];\n case 6:\n _b.trys.push([6, , 9, 10]);\n if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];\n return [4, _a.call(asyncIterable_1)];\n case 7:\n _b.sent();\n _b.label = 8;\n case 8: return [3, 10];\n case 9:\n if (e_2) throw e_2.error;\n return [7];\n case 10: return [7];\n case 11:\n subscriber.complete();\n return [2];\n }\n });\n });\n}\n//# sourceMappingURL=innerFrom.js.map","import { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\nexport function isInteropObservable(input) {\n return isFunction(input[Symbol_observable]);\n}\n//# sourceMappingURL=isInteropObservable.js.map","export var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n//# sourceMappingURL=isArrayLike.js.map","import { isFunction } from \"./isFunction\";\nexport function isPromise(value) {\n return isFunction(value === null || value === void 0 ? void 0 : value.then);\n}\n//# sourceMappingURL=isPromise.js.map","import { isFunction } from './isFunction';\nexport function isAsyncIterable(obj) {\n return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);\n}\n//# sourceMappingURL=isAsyncIterable.js.map","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\nexport function isIterable(input) {\n return isFunction(input === null || input === void 0 ? void 0 : input[Symbol_iterator]);\n}\n//# sourceMappingURL=isIterable.js.map","import { __asyncGenerator, __await, __generator } from \"tslib\";\nimport { isFunction } from './isFunction';\nexport function readableStreamLikeToAsyncGenerator(readableStream) {\n return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {\n var reader, _a, value, done;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n reader = readableStream.getReader();\n _b.label = 1;\n case 1:\n _b.trys.push([1, , 9, 10]);\n _b.label = 2;\n case 2:\n if (!true) return [3, 8];\n return [4, __await(reader.read())];\n case 3:\n _a = _b.sent(), value = _a.value, done = _a.done;\n if (!done) return [3, 5];\n return [4, __await(void 0)];\n case 4: return [2, _b.sent()];\n case 5: return [4, __await(value)];\n case 6: return [4, _b.sent()];\n case 7:\n _b.sent();\n return [3, 2];\n case 8: return [3, 10];\n case 9:\n reader.releaseLock();\n return [7];\n case 10: return [2];\n }\n });\n });\n}\nexport function isReadableStreamLike(obj) {\n return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);\n}\n//# sourceMappingURL=isReadableStreamLike.js.map","export function createInvalidObservableTypeError(input) {\n return new TypeError(\"You provided \" + (input !== null && typeof input === 'object' ? 'an invalid object' : \"'\" + input + \"'\") + \" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.\");\n}\n//# sourceMappingURL=throwUnobservableError.js.map","import { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\nexport function mergeMap(project, resultSelector, concurrent) {\n if (concurrent === void 0) { concurrent = Infinity; }\n if (isFunction(resultSelector)) {\n return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);\n }\n else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });\n}\n//# sourceMappingURL=mergeMap.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {\n var buffer = [];\n var active = 0;\n var index = 0;\n var isComplete = false;\n var checkComplete = function () {\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };\n var doInnerSub = function (value) {\n expand && subscriber.next(value);\n active++;\n var innerComplete = false;\n innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {\n onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);\n if (expand) {\n outerNext(innerValue);\n }\n else {\n subscriber.next(innerValue);\n }\n }, function () {\n innerComplete = true;\n }, undefined, function () {\n if (innerComplete) {\n try {\n active--;\n var _loop_1 = function () {\n var bufferedValue = buffer.shift();\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });\n }\n else {\n doInnerSub(bufferedValue);\n }\n };\n while (buffer.length && active < concurrent) {\n _loop_1();\n }\n checkComplete();\n }\n catch (err) {\n subscriber.error(err);\n }\n }\n }));\n };\n source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {\n isComplete = true;\n checkComplete();\n }));\n return function () {\n additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();\n };\n}\n//# sourceMappingURL=mergeInternals.js.map","import { isString } from 'lodash';\nimport { of } from 'rxjs';\nimport { map, mergeMap } from 'rxjs/operators';\nimport { FieldType, getFieldDisplayName, AnnotationEventFieldSource, standardTransformers } from '@grafana/data';\nimport { config } from '@grafana/runtime';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nconst standardAnnotationSupport = {\n prepareAnnotation: (json) => {\n if (isString(json == null ? void 0 : json.query)) {\n const _a = json, { query } = _a, rest = __objRest(_a, [\"query\"]);\n return __spreadProps(__spreadValues({}, rest), {\n target: {\n refId: \"annotation_query\",\n query\n },\n mappings: {}\n });\n }\n return json;\n },\n prepareQuery: (anno) => anno.target,\n processEvents: (anno, data) => {\n return getAnnotationsFromData(data, anno.mappings);\n }\n};\nfunction singleFrameFromPanelData() {\n return (source) => source.pipe(\n mergeMap((data) => {\n if (!(data == null ? void 0 : data.length)) {\n return of(void 0);\n }\n if (data.length === 1) {\n return of(data[0]);\n }\n const ctx = {\n interpolate: (v) => v\n };\n return of(data).pipe(\n standardTransformers.mergeTransformer.operator({}, ctx),\n map((d) => d[0])\n );\n })\n );\n}\nconst annotationEventNames = [\n {\n key: \"time\",\n field: (frame) => frame.fields.find((f) => f.type === FieldType.time),\n placeholder: \"time, or the first time field\"\n },\n { key: \"timeEnd\", help: \"When this field is defined, the annotation will be treated as a range\" },\n {\n key: \"title\"\n },\n {\n key: \"text\",\n field: (frame) => frame.fields.find((f) => f.type === FieldType.string),\n placeholder: \"text, or the first text field\"\n },\n { key: \"tags\", split: \",\", help: \"The results will be split on comma (,)\" },\n {\n key: \"id\"\n }\n];\nconst publicDashboardEventNames = [\n {\n key: \"color\"\n },\n {\n key: \"isRegion\"\n },\n {\n key: \"source\"\n }\n];\nconst alertEventAndAnnotationFields = [\n ...config.publicDashboardAccessToken ? publicDashboardEventNames : [],\n ...annotationEventNames,\n { key: \"userId\" },\n { key: \"login\" },\n { key: \"email\" },\n { key: \"prevState\" },\n { key: \"newState\" },\n { key: \"data\" },\n { key: \"panelId\" },\n { key: \"alertId\" },\n { key: \"dashboardId\" },\n { key: \"dashboardUID\" }\n];\nfunction getAnnotationsFromData(data, options) {\n return of(data).pipe(\n singleFrameFromPanelData(),\n map((frame) => {\n if (!(frame == null ? void 0 : frame.length)) {\n return [];\n }\n let hasTime = false;\n let hasText = false;\n const byName = {};\n for (const f of frame.fields) {\n const name = getFieldDisplayName(f, frame);\n byName[name.toLowerCase()] = f;\n }\n if (!options) {\n options = {};\n }\n const fields = [];\n for (const evts of alertEventAndAnnotationFields) {\n const opt = options[evts.key] || {};\n if (opt.source === AnnotationEventFieldSource.Skip) {\n continue;\n }\n const setter = { key: evts.key, split: evts.split };\n if (opt.source === AnnotationEventFieldSource.Text) {\n setter.text = opt.value;\n } else {\n const lower = (opt.value || evts.key).toLowerCase();\n setter.field = byName[lower];\n if (!setter.field && evts.field) {\n setter.field = evts.field(frame);\n }\n }\n if (setter.field || setter.text) {\n fields.push(setter);\n if (setter.key === \"time\") {\n hasTime = true;\n } else if (setter.key === \"text\") {\n hasText = true;\n }\n }\n }\n if (!hasTime || !hasText) {\n console.error(\"Cannot process annotation fields. No time or text present.\");\n return [];\n }\n const events = [];\n for (let i = 0; i < frame.length; i++) {\n const anno = {\n type: \"default\",\n color: \"red\"\n };\n for (const f of fields) {\n let v = void 0;\n if (f.text) {\n v = f.text;\n } else if (f.field) {\n v = f.field.values.get(i);\n if (v !== void 0 && f.regex) {\n const match = f.regex.exec(v);\n if (match) {\n v = match[1] ? match[1] : match[0];\n }\n }\n }\n if (v !== null && v !== void 0) {\n if (f.split && typeof v === \"string\") {\n v = v.split(\",\");\n }\n anno[f.key] = v;\n }\n }\n events.push(anno);\n }\n return events;\n })\n );\n}\nconst legacyRunner = [\n \"prometheus\",\n \"loki\",\n \"elasticsearch\",\n \"grafana-opensearch-datasource\"\n];\nfunction shouldUseLegacyRunner(datasource) {\n const { type } = datasource;\n return !datasource.annotations || legacyRunner.includes(type);\n}\n\nexport { annotationEventNames, getAnnotationsFromData, publicDashboardEventNames, shouldUseLegacyRunner, singleFrameFromPanelData, standardAnnotationSupport };\n//# sourceMappingURL=standardAnnotationsSupport.js.map\n","import { from, of } from 'rxjs';\nimport { map, mergeMap } from 'rxjs/operators';\nimport { rangeUtil, CoreApp, DataTopic } from '@grafana/data';\nimport { getTemplateSrv, getRunRequest } from '@grafana/runtime';\nimport { shouldUseLegacyRunner, standardAnnotationSupport } from './standardAnnotationsSupport.js';\nimport { LoadingState } from '@grafana/schema';\nimport { getEnrichedDataRequest } from '../../getEnrichedDataRequest.js';\nimport { wrapInSafeSerializableSceneObject } from '../../../utils/wrapInSafeSerializableSceneObject.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nlet counter = 100;\nfunction getNextRequestId() {\n return \"AQ\" + counter++;\n}\nfunction executeAnnotationQuery(datasource, timeRange, query, layer) {\n var _a;\n if (datasource.annotationQuery && shouldUseLegacyRunner(datasource)) {\n console.warn(\"Using deprecated annotationQuery method, please upgrade your datasource\");\n return from(\n datasource.annotationQuery({\n range: timeRange.state.value,\n rangeRaw: timeRange.state.value.raw,\n annotation: query,\n dashboard: {\n getVariables: getTemplateSrv().getVariables\n }\n })\n ).pipe(\n map((events) => ({\n state: LoadingState.Done,\n events\n }))\n );\n }\n const processor = __spreadValues(__spreadValues({}, standardAnnotationSupport), datasource.annotations);\n const annotationWithDefaults = __spreadValues(__spreadValues({}, (_a = processor.getDefaultQuery) == null ? void 0 : _a.call(processor)), query);\n const annotation = processor.prepareAnnotation(annotationWithDefaults);\n if (!annotation) {\n return of({\n state: LoadingState.Done,\n events: []\n });\n }\n const processedQuery = processor.prepareQuery(annotation);\n if (!processedQuery) {\n return of({\n state: LoadingState.Done,\n events: []\n });\n }\n const maxDataPoints = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\n const interval = rangeUtil.calculateInterval(timeRange.state.value, maxDataPoints, datasource.interval);\n const scopedVars = {\n __interval: { text: interval.interval, value: interval.interval },\n __interval_ms: { text: interval.intervalMs.toString(), value: interval.intervalMs },\n __annotation: { text: annotation.name, value: annotation },\n __sceneObject: wrapInSafeSerializableSceneObject(layer)\n };\n const queryRequest = __spreadValues(__spreadProps(__spreadValues({\n startTime: Date.now(),\n requestId: getNextRequestId(),\n range: timeRange.state.value,\n maxDataPoints,\n scopedVars\n }, interval), {\n app: CoreApp.Dashboard,\n timezone: timeRange.getTimeZone(),\n targets: [\n __spreadProps(__spreadValues({}, processedQuery), {\n refId: \"Anno\"\n })\n ]\n }), getEnrichedDataRequest(layer));\n const runRequest = getRunRequest();\n return runRequest(datasource, queryRequest).pipe(\n mergeMap((panelData) => {\n const data = (panelData == null ? void 0 : panelData.series.length) ? panelData.series : panelData.annotations;\n if (!(data == null ? void 0 : data.length)) {\n return of({\n state: panelData.state,\n events: []\n });\n }\n data.forEach((frame) => {\n var _a2;\n if (!((_a2 = frame.meta) == null ? void 0 : _a2.dataTopic)) {\n frame.meta = __spreadProps(__spreadValues({}, frame.meta || {}), { dataTopic: DataTopic.Annotations });\n }\n });\n return processor.processEvents(annotation, data).pipe(\n map((events) => {\n return {\n state: panelData.state,\n events: events || []\n };\n })\n );\n })\n );\n}\n\nexport { executeAnnotationQuery };\n//# sourceMappingURL=standardAnnotationQuery.js.map\n","import { config } from '@grafana/runtime';\nimport { cloneDeep, partition, groupBy, map, every, find, head, concat } from 'lodash';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nfunction postProcessQueryResult(annotation, results) {\n if (annotation.snapshotData) {\n annotation = cloneDeep(annotation);\n delete annotation.snapshotData;\n }\n const processed = results.map((item) => {\n var _a;\n const processedItem = __spreadValues({}, item);\n processedItem.source = annotation;\n processedItem.color = config.theme2.visualization.getColorByName(annotation.iconColor);\n processedItem.type = annotation.name;\n processedItem.isRegion = Boolean(processedItem.timeEnd && processedItem.time !== processedItem.timeEnd);\n switch ((_a = processedItem.newState) == null ? void 0 : _a.toLowerCase()) {\n case \"pending\":\n processedItem.color = \"yellow\";\n break;\n case \"alerting\":\n processedItem.color = \"red\";\n break;\n case \"ok\":\n processedItem.color = \"green\";\n break;\n case \"normal\":\n processedItem.color = \"green\";\n break;\n case \"no_data\":\n processedItem.color = \"gray\";\n break;\n case \"nodata\":\n processedItem.color = \"gray\";\n break;\n }\n return processedItem;\n });\n return processed;\n}\nfunction dedupAnnotations(annotations) {\n let dedup = [];\n const events = partition(annotations, \"id\");\n const eventsById = groupBy(events[0], \"id\");\n dedup = map(eventsById, (eventGroup) => {\n if (eventGroup.length > 1 && !every(eventGroup, isPanelAlert)) {\n return find(eventGroup, (event) => {\n return event.eventType !== \"panel-alert\";\n });\n } else {\n return head(eventGroup);\n }\n });\n dedup = concat(dedup, events[1]);\n return dedup;\n}\nfunction isPanelAlert(event) {\n return event.eventType === \"panel-alert\";\n}\n\nexport { dedupAnnotations, postProcessQueryResult };\n//# sourceMappingURL=utils.js.map\n","import { arrayToDataFrame, DataTopic } from '@grafana/data';\nimport { LoadingState } from '@grafana/schema';\nimport React from 'react';\nimport { map } from 'rxjs';\nimport { emptyPanelData } from '../../../core/SceneDataNode.js';\nimport { sceneGraph } from '../../../core/sceneGraph/index.js';\nimport { getDataSource } from '../../../utils/getDataSource.js';\nimport { getMessageFromError } from '../../../utils/getMessageFromError.js';\nimport { writeSceneLog } from '../../../utils/writeSceneLog.js';\nimport { registerQueryWithController } from '../../registerQueryWithController.js';\nimport { SceneDataLayerBase } from '../SceneDataLayerBase.js';\nimport { DataLayerControlSwitch } from '../SceneDataLayerControls.js';\nimport { executeAnnotationQuery } from './standardAnnotationQuery.js';\nimport { postProcessQueryResult, dedupAnnotations } from './utils.js';\nimport { wrapInSafeSerializableSceneObject } from '../../../utils/wrapInSafeSerializableSceneObject.js';\nimport { RefreshEvent } from '@grafana/runtime';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass AnnotationsDataLayer extends SceneDataLayerBase {\n constructor(initialState) {\n super(\n __spreadValues({\n isEnabled: true\n }, initialState),\n [\"query\"]\n );\n this._scopedVars = {\n __sceneObject: wrapInSafeSerializableSceneObject(this)\n };\n }\n onEnable() {\n this.publishEvent(new RefreshEvent(), true);\n const timeRange = sceneGraph.getTimeRange(this);\n this._timeRangeSub = timeRange.subscribeToState(() => {\n this.runWithTimeRange(timeRange);\n });\n }\n onDisable() {\n var _a;\n this.publishEvent(new RefreshEvent(), true);\n (_a = this._timeRangeSub) == null ? void 0 : _a.unsubscribe();\n }\n runLayer() {\n writeSceneLog(\"AnnotationsDataLayer\", \"run layer\");\n const timeRange = sceneGraph.getTimeRange(this);\n this.runWithTimeRange(timeRange);\n }\n async runWithTimeRange(timeRange) {\n const { query } = this.state;\n if (this.querySub) {\n this.querySub.unsubscribe();\n }\n if (this._variableDependency.hasDependencyInLoadingState()) {\n writeSceneLog(\"AnnotationsDataLayer\", \"Variable dependency is in loading state, skipping query execution\");\n return;\n }\n try {\n const ds = await this.resolveDataSource(query);\n let stream = executeAnnotationQuery(ds, timeRange, query, this).pipe(\n registerQueryWithController({\n type: \"annotations\",\n origin: this,\n cancel: () => this.cancelQuery()\n }),\n map((events) => {\n const stateUpdate = this.processEvents(query, events);\n return stateUpdate;\n })\n );\n this.querySub = stream.subscribe((stateUpdate) => {\n this.publishResults(stateUpdate);\n });\n } catch (e) {\n this.publishResults(__spreadProps(__spreadValues({}, emptyPanelData), {\n state: LoadingState.Error,\n errors: [\n {\n message: getMessageFromError(e)\n }\n ]\n }));\n console.error(\"AnnotationsDataLayer error\", e);\n }\n }\n async resolveDataSource(query) {\n return await getDataSource(query.datasource || void 0, this._scopedVars);\n }\n processEvents(query, events) {\n let processedEvents = postProcessQueryResult(query, events.events || []);\n processedEvents = dedupAnnotations(processedEvents);\n const stateUpdate = __spreadProps(__spreadValues({}, emptyPanelData), { state: events.state });\n const df = arrayToDataFrame(processedEvents);\n df.meta = __spreadProps(__spreadValues({}, df.meta), {\n dataTopic: DataTopic.Annotations\n });\n stateUpdate.series = [df];\n return stateUpdate;\n }\n}\nAnnotationsDataLayer.Component = AnnotationsDataLayerRenderer;\nfunction AnnotationsDataLayerRenderer({ model }) {\n const { isHidden } = model.useState();\n if (isHidden) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(DataLayerControlSwitch, {\n layer: model\n });\n}\n\nexport { AnnotationsDataLayer };\n//# sourceMappingURL=AnnotationsDataLayer.js.map\n","import { SceneTimeRangeTransformerBase } from './SceneTimeRangeTransformerBase.js';\nimport { getDefaultTimeRange } from '@grafana/data';\nimport { evaluateTimeRange } from '../utils/evaluateTimeRange.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass SceneTimeZoneOverride extends SceneTimeRangeTransformerBase {\n constructor(state) {\n super(__spreadProps(__spreadValues({}, state), {\n timeZone: state.timeZone,\n from: \"now-6h\",\n to: \"now\",\n value: getDefaultTimeRange()\n }));\n }\n ancestorTimeRangeChanged(timeRange) {\n this.setState(__spreadProps(__spreadValues({}, timeRange), {\n timeZone: this.state.timeZone,\n value: evaluateTimeRange(\n timeRange.from,\n timeRange.to,\n this.state.timeZone,\n timeRange.fiscalYearStartMonth,\n timeRange.UNSAFE_nowDelay,\n timeRange.weekStart\n )\n }));\n }\n getTimeZone() {\n return this.state.timeZone;\n }\n onTimeZoneChange(timeZone) {\n const parentTimeRange = this.getAncestorTimeRange();\n this.setState({\n timeZone,\n value: evaluateTimeRange(\n parentTimeRange.state.from,\n parentTimeRange.state.to,\n timeZone,\n parentTimeRange.state.fiscalYearStartMonth,\n parentTimeRange.state.UNSAFE_nowDelay,\n parentTimeRange.state.weekStart\n )\n });\n }\n}\n\nexport { SceneTimeZoneOverride };\n//# sourceMappingURL=SceneTimeZoneOverride.js.map\n","import React from 'react';\nimport { ReplaySubject } from 'rxjs';\nimport { emptyPanelData } from '../core/SceneDataNode.js';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { DataLayersMerger } from './DataLayersMerger.js';\nimport { setBaseClassState } from '../utils/utils.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass SceneDataLayerSetBase extends SceneObjectBase {\n constructor() {\n super(...arguments);\n this.isDataLayer = true;\n this._results = new ReplaySubject(1);\n this._dataLayersMerger = new DataLayersMerger();\n }\n subscribeToAllLayers(layers) {\n if (layers.length > 0) {\n this.querySub = this._dataLayersMerger.getMergedStream(layers).subscribe(this._onLayerUpdateReceived.bind(this));\n } else {\n this._results.next({ origin: this, data: emptyPanelData });\n this.setStateHelper({ data: emptyPanelData });\n }\n }\n _onLayerUpdateReceived(results) {\n var _a;\n let series = [];\n for (const result of results) {\n if ((_a = result.data) == null ? void 0 : _a.series) {\n series = series.concat(result.data.series);\n }\n }\n const combinedData = __spreadProps(__spreadValues({}, emptyPanelData), { series });\n this._results.next({ origin: this, data: combinedData });\n this.setStateHelper({ data: combinedData });\n }\n getResultsStream() {\n return this._results;\n }\n cancelQuery() {\n var _a;\n (_a = this.querySub) == null ? void 0 : _a.unsubscribe();\n }\n setStateHelper(state) {\n setBaseClassState(this, state);\n }\n}\nclass SceneDataLayerSet extends SceneDataLayerSetBase {\n constructor(state) {\n var _a, _b;\n super({\n name: (_a = state.name) != null ? _a : \"Data layers\",\n layers: (_b = state.layers) != null ? _b : []\n });\n this.addActivationHandler(() => this._onActivate());\n }\n _onActivate() {\n this._subs.add(\n this.subscribeToState((newState, oldState) => {\n var _a;\n if (newState.layers !== oldState.layers) {\n (_a = this.querySub) == null ? void 0 : _a.unsubscribe();\n this.subscribeToAllLayers(newState.layers);\n }\n })\n );\n this.subscribeToAllLayers(this.state.layers);\n return () => {\n var _a;\n (_a = this.querySub) == null ? void 0 : _a.unsubscribe();\n };\n }\n}\nSceneDataLayerSet.Component = ({ model }) => {\n const { layers } = model.useState();\n return /* @__PURE__ */ React.createElement(React.Fragment, null, layers.map((layer) => /* @__PURE__ */ React.createElement(layer.Component, {\n model: layer,\n key: layer.state.key\n })));\n};\n\nexport { SceneDataLayerSet, SceneDataLayerSetBase };\n//# sourceMappingURL=SceneDataLayerSet.js.map\n","import { DataTopic, transformDataFrame, LoadingState } from '@grafana/data';\nimport { toDataQueryError } from '@grafana/runtime';\nimport { ReplaySubject, forkJoin, map, catchError, of } from 'rxjs';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig.js';\nimport { SceneDataLayerSet } from './SceneDataLayerSet.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass SceneDataTransformer extends SceneObjectBase {\n constructor(state) {\n super(state);\n this._results = new ReplaySubject(1);\n this._variableDependency = new VariableDependencyConfig(\n this,\n {\n statePaths: [\"transformations\"],\n onReferencedVariableValueChanged: () => this.reprocessTransformations()\n }\n );\n this.addActivationHandler(() => this.activationHandler());\n }\n activationHandler() {\n const sourceData = this.getSourceData();\n this._subs.add(sourceData.subscribeToState((state) => this.transform(state.data)));\n if (sourceData.state.data) {\n this.transform(sourceData.state.data);\n }\n return () => {\n if (this._transformSub) {\n this._transformSub.unsubscribe();\n }\n };\n }\n getSourceData() {\n if (this.state.$data) {\n if (this.state.$data instanceof SceneDataLayerSet) {\n throw new Error(\"SceneDataLayerSet can not be used as data provider for SceneDataTransformer.\");\n }\n return this.state.$data;\n }\n if (!this.parent || !this.parent.parent) {\n throw new Error(\"SceneDataTransformer must either have $data set on it or have a parent.parent with $data\");\n }\n return sceneGraph.getData(this.parent.parent);\n }\n setContainerWidth(width) {\n if (this.state.$data && this.state.$data.setContainerWidth) {\n this.state.$data.setContainerWidth(width);\n }\n }\n isDataReadyToDisplay() {\n const dataObject = this.getSourceData();\n if (dataObject.isDataReadyToDisplay) {\n return dataObject.isDataReadyToDisplay();\n }\n return true;\n }\n reprocessTransformations() {\n this.transform(this.getSourceData().state.data, true);\n }\n cancelQuery() {\n var _a, _b;\n (_b = (_a = this.getSourceData()).cancelQuery) == null ? void 0 : _b.call(_a);\n }\n getResultsStream() {\n return this._results;\n }\n clone(withState) {\n const clone = super.clone(withState);\n if (this._prevDataFromSource) {\n clone[\"_prevDataFromSource\"] = this._prevDataFromSource;\n }\n return clone;\n }\n haveAlreadyTransformedData(data) {\n if (!this._prevDataFromSource) {\n return false;\n }\n if (data === this._prevDataFromSource) {\n return true;\n }\n const { series, annotations } = this._prevDataFromSource;\n if (data.series === series && data.annotations === annotations) {\n if (this.state.data && data.state !== this.state.data.state) {\n this.setState({ data: __spreadProps(__spreadValues({}, this.state.data), { state: data.state }) });\n }\n return true;\n }\n return false;\n }\n transform(data, force = false) {\n var _a;\n if (this.state.transformations.length === 0 || !data) {\n this._prevDataFromSource = data;\n this.setState({ data });\n if (data) {\n this._results.next({ origin: this, data });\n }\n return;\n }\n if (!force && this.haveAlreadyTransformedData(data)) {\n return;\n }\n const seriesTransformations = this.state.transformations.filter((transformation) => {\n if (\"options\" in transformation || \"topic\" in transformation) {\n return transformation.topic == null || transformation.topic === DataTopic.Series;\n }\n return true;\n }).map((transformation) => \"operator\" in transformation ? transformation.operator : transformation);\n const annotationsTransformations = this.state.transformations.filter((transformation) => {\n if (\"options\" in transformation || \"topic\" in transformation) {\n return transformation.topic === DataTopic.Annotations;\n }\n return false;\n }).map((transformation) => \"operator\" in transformation ? transformation.operator : transformation);\n if (this._transformSub) {\n this._transformSub.unsubscribe();\n }\n const ctx = {\n interpolate: (value) => {\n var _a2;\n return sceneGraph.interpolate(this, value, (_a2 = data.request) == null ? void 0 : _a2.scopedVars);\n }\n };\n let streams = [transformDataFrame(seriesTransformations, data.series, ctx)];\n if (data.annotations && data.annotations.length > 0 && annotationsTransformations.length > 0) {\n streams.push(transformDataFrame(annotationsTransformations, (_a = data.annotations) != null ? _a : []));\n }\n this._transformSub = forkJoin(streams).pipe(\n map((values) => {\n const transformedSeries = values[0];\n const transformedAnnotations = values[1];\n return __spreadProps(__spreadValues({}, data), {\n series: transformedSeries,\n annotations: transformedAnnotations != null ? transformedAnnotations : data.annotations\n });\n }),\n catchError((err) => {\n var _a2;\n console.error(\"Error transforming data: \", err);\n const sourceErr = ((_a2 = this.getSourceData().state.data) == null ? void 0 : _a2.errors) || [];\n const transformationError = toDataQueryError(err);\n transformationError.message = `Error transforming data: ${transformationError.message}`;\n const result = __spreadProps(__spreadValues({}, data), {\n state: LoadingState.Error,\n errors: [...sourceErr, transformationError]\n });\n return of(result);\n })\n ).subscribe((transformedData) => {\n this.setState({ data: transformedData });\n this._results.next({ origin: this, data: transformedData });\n this._prevDataFromSource = data;\n });\n }\n}\n\nexport { SceneDataTransformer };\n//# sourceMappingURL=SceneDataTransformer.js.map\n","import React from 'react';\nimport { VariableHide } from '@grafana/data';\nimport { SceneObjectBase, useSceneObjectState } from '../../core/SceneObjectBase.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { ControlsLabel } from '../../utils/ControlsLabel.js';\nimport { css } from '@emotion/css';\nimport { selectors } from '@grafana/e2e-selectors';\n\nclass VariableValueSelectors extends SceneObjectBase {\n}\nVariableValueSelectors.Component = VariableValueSelectorsRenderer;\nfunction VariableValueSelectorsRenderer({ model }) {\n const variables = sceneGraph.getVariables(model).useState();\n return /* @__PURE__ */ React.createElement(React.Fragment, null, variables.variables.map((variable) => /* @__PURE__ */ React.createElement(VariableValueSelectWrapper, {\n key: variable.state.key,\n variable,\n layout: model.state.layout\n })));\n}\nfunction VariableValueSelectWrapper({ variable, layout, showAlways, hideLabel }) {\n const state = useSceneObjectState(variable, { shouldActivateOrKeepAlive: true });\n if (state.hide === VariableHide.hideVariable && !showAlways) {\n return null;\n }\n if (layout === \"vertical\") {\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: verticalContainer,\n \"data-testid\": selectors.pages.Dashboard.SubMenu.submenuItem\n }, /* @__PURE__ */ React.createElement(VariableLabel, {\n variable,\n layout,\n hideLabel\n }), /* @__PURE__ */ React.createElement(variable.Component, {\n model: variable\n }));\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: containerStyle,\n \"data-testid\": selectors.pages.Dashboard.SubMenu.submenuItem\n }, /* @__PURE__ */ React.createElement(VariableLabel, {\n variable,\n hideLabel\n }), /* @__PURE__ */ React.createElement(variable.Component, {\n model: variable\n }));\n}\nfunction VariableLabel({ variable, layout, hideLabel }) {\n var _a;\n const { state } = variable;\n if (variable.state.hide === VariableHide.hideLabel || hideLabel) {\n return null;\n }\n const elementId = `var-${state.key}`;\n const labelOrName = state.label || state.name;\n return /* @__PURE__ */ React.createElement(ControlsLabel, {\n htmlFor: elementId,\n isLoading: state.loading,\n onCancel: () => {\n var _a2;\n return (_a2 = variable.onCancel) == null ? void 0 : _a2.call(variable);\n },\n label: labelOrName,\n error: state.error,\n layout,\n description: (_a = state.description) != null ? _a : void 0\n });\n}\nconst containerStyle = css({ display: \"flex\" });\nconst verticalContainer = css({ display: \"flex\", flexDirection: \"column\" });\n\nexport { VariableValueSelectWrapper, VariableValueSelectors };\n//# sourceMappingURL=VariableValueSelectors.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { VariableValueSelectWrapper } from './VariableValueSelectors.js';\n\nclass VariableValueControl extends SceneObjectBase {\n}\nVariableValueControl.Component = VariableValueControlRenderer;\nfunction VariableValueControlRenderer({ model }) {\n const variable = sceneGraph.lookupVariable(model.state.variableName, model);\n if (!variable) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(VariableValueSelectWrapper, {\n key: variable.state.key,\n variable,\n layout: model.state.layout,\n showAlways: true\n });\n}\n\nexport { VariableValueControl };\n//# sourceMappingURL=VariableValueControl.js.map\n","import { VariableRefresh } from '@grafana/data';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { writeSceneLog } from '../../utils/writeSceneLog.js';\nimport { SceneVariableValueChangedEvent } from '../types.js';\nimport { VariableValueRecorder } from '../VariableValueRecorder.js';\n\nclass SceneVariableSet extends SceneObjectBase {\n constructor(state) {\n super(state);\n this._variablesThatHaveChanged = /* @__PURE__ */ new Set();\n this._variablesToUpdate = /* @__PURE__ */ new Set();\n this._updating = /* @__PURE__ */ new Map();\n this._variableValueRecorder = new VariableValueRecorder();\n this._variableDependency = new SceneVariableSetVariableDependencyHandler(\n this._handleParentVariableUpdatesCompleted.bind(this)\n );\n this._onActivate = () => {\n const timeRange = sceneGraph.getTimeRange(this);\n this._subs.add(\n this.subscribeToEvent(SceneVariableValueChangedEvent, (event) => this._handleVariableValueChanged(event.payload))\n );\n this._subs.add(\n timeRange.subscribeToState(() => {\n this._refreshTimeRangeBasedVariables();\n })\n );\n this._subs.add(this.subscribeToState(this._onStateChanged));\n this._checkForVariablesThatChangedWhileInactive();\n for (const variable of this.state.variables) {\n if (this._variableNeedsUpdate(variable)) {\n this._variablesToUpdate.add(variable);\n }\n }\n this._updateNextBatch();\n return this._onDeactivate;\n };\n this._onDeactivate = () => {\n var _a;\n for (const update of this._updating.values()) {\n (_a = update.subscription) == null ? void 0 : _a.unsubscribe();\n }\n for (const variable of this.state.variables) {\n if (!this._variablesToUpdate.has(variable) && !this._updating.has(variable)) {\n this._variableValueRecorder.recordCurrentValue(variable);\n }\n }\n this._variablesToUpdate.clear();\n this._updating.clear();\n };\n this._onStateChanged = (newState, oldState) => {\n const variablesToUpdateCountStart = this._variablesToUpdate.size;\n for (const variable of oldState.variables) {\n if (!newState.variables.includes(variable)) {\n const updating = this._updating.get(variable);\n if (updating == null ? void 0 : updating.subscription) {\n updating.subscription.unsubscribe();\n }\n this._updating.delete(variable);\n this._variablesToUpdate.delete(variable);\n }\n }\n for (const variable of newState.variables) {\n if (!oldState.variables.includes(variable)) {\n if (this._variableNeedsUpdate(variable)) {\n this._variablesToUpdate.add(variable);\n }\n }\n }\n if (variablesToUpdateCountStart === 0 && this._variablesToUpdate.size > 0) {\n this._updateNextBatch();\n }\n };\n this.addActivationHandler(this._onActivate);\n }\n getByName(name) {\n return this.state.variables.find((x) => x.state.name === name);\n }\n _refreshTimeRangeBasedVariables() {\n for (const variable of this.state.variables) {\n if (\"refresh\" in variable.state && variable.state.refresh === VariableRefresh.onTimeRangeChanged) {\n this._variablesToUpdate.add(variable);\n }\n }\n this._updateNextBatch();\n }\n _checkForVariablesThatChangedWhileInactive() {\n if (!this._variableValueRecorder.hasValues()) {\n return;\n }\n for (const variable of this.state.variables) {\n if (this._variableValueRecorder.hasValueChanged(variable)) {\n writeVariableTraceLog(variable, \"Changed while in-active\");\n this._addDependentVariablesToUpdateQueue(variable);\n }\n }\n }\n _variableNeedsUpdate(variable) {\n if (variable.isLazy) {\n return false;\n }\n if (!variable.validateAndUpdate) {\n return false;\n }\n if (this._variableValueRecorder.hasRecordedValue(variable)) {\n writeVariableTraceLog(variable, \"Skipping updateAndValidate current value valid\");\n return false;\n }\n return true;\n }\n _updateNextBatch() {\n for (const variable of this._variablesToUpdate) {\n if (!variable.validateAndUpdate) {\n throw new Error(\"Variable added to variablesToUpdate but does not have validateAndUpdate\");\n }\n if (this._updating.has(variable)) {\n continue;\n }\n if (sceneGraph.hasVariableDependencyInLoadingState(variable)) {\n continue;\n }\n const variableToUpdate = {\n variable\n };\n this._updating.set(variable, variableToUpdate);\n writeVariableTraceLog(variable, \"updateAndValidate started\");\n variableToUpdate.subscription = variable.validateAndUpdate().subscribe({\n next: () => this._validateAndUpdateCompleted(variable),\n complete: () => this._validateAndUpdateCompleted(variable),\n error: (err) => this._handleVariableError(variable, err)\n });\n }\n }\n _validateAndUpdateCompleted(variable) {\n var _a;\n if (!this._updating.has(variable)) {\n return;\n }\n const update = this._updating.get(variable);\n (_a = update == null ? void 0 : update.subscription) == null ? void 0 : _a.unsubscribe();\n this._updating.delete(variable);\n this._variablesToUpdate.delete(variable);\n writeVariableTraceLog(variable, \"updateAndValidate completed\");\n this._notifyDependentSceneObjects(variable);\n this._updateNextBatch();\n }\n cancel(variable) {\n var _a;\n const update = this._updating.get(variable);\n (_a = update == null ? void 0 : update.subscription) == null ? void 0 : _a.unsubscribe();\n this._updating.delete(variable);\n this._variablesToUpdate.delete(variable);\n }\n _handleVariableError(variable, err) {\n var _a;\n const update = this._updating.get(variable);\n (_a = update == null ? void 0 : update.subscription) == null ? void 0 : _a.unsubscribe();\n this._updating.delete(variable);\n this._variablesToUpdate.delete(variable);\n variable.setState({ loading: false, error: err.message });\n console.error(\"SceneVariableSet updateAndValidate error\", err);\n writeVariableTraceLog(variable, \"updateAndValidate error\", err);\n this._notifyDependentSceneObjects(variable);\n this._updateNextBatch();\n }\n _handleVariableValueChanged(variableThatChanged) {\n this._variablesThatHaveChanged.add(variableThatChanged);\n this._addDependentVariablesToUpdateQueue(variableThatChanged);\n if (!this._updating.has(variableThatChanged)) {\n this._updateNextBatch();\n this._notifyDependentSceneObjects(variableThatChanged);\n }\n }\n _handleParentVariableUpdatesCompleted(variable, hasChanged) {\n if (hasChanged) {\n this._addDependentVariablesToUpdateQueue(variable);\n }\n if (this._variablesToUpdate.size > 0 && this._updating.size === 0) {\n this._updateNextBatch();\n }\n }\n _addDependentVariablesToUpdateQueue(variableThatChanged) {\n for (const otherVariable of this.state.variables) {\n if (otherVariable.variableDependency) {\n if (otherVariable.variableDependency.hasDependencyOn(variableThatChanged.state.name)) {\n writeVariableTraceLog(otherVariable, \"Added to update queue, dependant variable value changed\");\n if (this._updating.has(otherVariable) && otherVariable.onCancel) {\n otherVariable.onCancel();\n }\n this._variablesToUpdate.add(otherVariable);\n }\n }\n }\n }\n _notifyDependentSceneObjects(variable) {\n if (!this.parent) {\n return;\n }\n this._traverseSceneAndNotify(this.parent, variable, this._variablesThatHaveChanged.has(variable));\n this._variablesThatHaveChanged.delete(variable);\n }\n _traverseSceneAndNotify(sceneObject, variable, hasChanged) {\n if (this === sceneObject) {\n return;\n }\n if (!sceneObject.isActive) {\n return;\n }\n if (sceneObject.state.$variables && sceneObject.state.$variables !== this) {\n const localVar = sceneObject.state.$variables.getByName(variable.state.name);\n if (localVar == null ? void 0 : localVar.isAncestorLoading) {\n variable = localVar;\n } else if (localVar) {\n return;\n }\n }\n if (sceneObject.variableDependency) {\n sceneObject.variableDependency.variableUpdateCompleted(variable, hasChanged);\n }\n sceneObject.forEachChild((child) => this._traverseSceneAndNotify(child, variable, hasChanged));\n }\n isVariableLoadingOrWaitingToUpdate(variable) {\n if (variable.isAncestorLoading && variable.isAncestorLoading()) {\n return true;\n }\n if (this._variablesToUpdate.has(variable) || this._updating.has(variable)) {\n return true;\n }\n return sceneGraph.hasVariableDependencyInLoadingState(variable);\n }\n}\nfunction writeVariableTraceLog(variable, message, err) {\n if (err) {\n writeSceneLog(\"SceneVariableSet\", `Variable[${variable.state.name}]: ${message}`, err);\n } else {\n writeSceneLog(\"SceneVariableSet\", `Variable[${variable.state.name}]: ${message}`);\n }\n}\nclass SceneVariableSetVariableDependencyHandler {\n constructor(_variableUpdatesCompleted) {\n this._variableUpdatesCompleted = _variableUpdatesCompleted;\n this._emptySet = /* @__PURE__ */ new Set();\n }\n getNames() {\n return this._emptySet;\n }\n hasDependencyOn(name) {\n return false;\n }\n variableUpdateCompleted(variable, hasChanged) {\n this._variableUpdatesCompleted(variable, hasChanged);\n }\n}\n\nexport { SceneVariableSet };\n//# sourceMappingURL=SceneVariableSet.js.map\n","import { of } from 'rxjs';\nimport { VariableDependencyConfig } from '../VariableDependencyConfig.js';\nimport { renderSelectForVariable } from '../components/VariableValueSelect.js';\nimport { MultiValueVariable } from './MultiValueVariable.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass CustomVariable extends MultiValueVariable {\n constructor(initialState) {\n super(__spreadValues({\n type: \"custom\",\n query: \"\",\n value: \"\",\n text: \"\",\n options: [],\n name: \"\"\n }, initialState));\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"query\"]\n });\n }\n getValueOptions(args) {\n var _a;\n const interpolated = sceneGraph.interpolate(this, this.state.query);\n const match = (_a = interpolated.match(/(?:\\\\,|[^,])+/g)) != null ? _a : [];\n const options = match.map((text) => {\n var _a2;\n text = text.replace(/\\\\,/g, \",\");\n const textMatch = (_a2 = /^(.+)\\s:\\s(.+)$/g.exec(text)) != null ? _a2 : [];\n if (textMatch.length === 3) {\n const [, key, value] = textMatch;\n return { label: key.trim(), value: value.trim() };\n } else {\n return { label: text.trim(), value: text.trim() };\n }\n });\n if (!options.length) {\n this.skipNextValidation = true;\n }\n return of(options);\n }\n}\nCustomVariable.Component = ({ model }) => {\n return renderSelectForVariable(model);\n};\n\nexport { CustomVariable };\n//# sourceMappingURL=CustomVariable.js.map\n","import { of } from 'rxjs';\nimport { stringToJsRegex } from '@grafana/data';\nimport { getDataSourceSrv } from '@grafana/runtime';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { VariableDependencyConfig } from '../VariableDependencyConfig.js';\nimport { renderSelectForVariable } from '../components/VariableValueSelect.js';\nimport { MultiValueVariable } from './MultiValueVariable.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass DataSourceVariable extends MultiValueVariable {\n constructor(initialState) {\n super(__spreadValues({\n type: \"datasource\",\n value: \"\",\n text: \"\",\n options: [],\n name: \"\",\n regex: \"\",\n pluginId: \"\"\n }, initialState));\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"regex\"]\n });\n }\n getValueOptions(args) {\n if (!this.state.pluginId) {\n return of([]);\n }\n const dataSources = getDataSourceSrv().getList({ metrics: true, variables: false, pluginId: this.state.pluginId });\n let regex;\n if (this.state.regex) {\n const interpolated = sceneGraph.interpolate(this, this.state.regex, void 0, \"regex\");\n regex = stringToJsRegex(interpolated);\n }\n const options = [];\n for (let i = 0; i < dataSources.length; i++) {\n const source = dataSources[i];\n if (isValid(source, regex)) {\n options.push({ label: source.name, value: source.uid });\n }\n if (this.state.defaultOptionEnabled && isDefault(source, regex)) {\n options.push({ label: \"default\", value: \"default\" });\n }\n }\n if (options.length === 0) {\n this.setState({ error: \"No data sources found\" });\n } else if (this.state.error) {\n this.setState({ error: null });\n }\n return of(options);\n }\n}\nDataSourceVariable.Component = ({ model }) => {\n return renderSelectForVariable(model);\n};\nfunction isValid(source, regex) {\n if (!regex) {\n return true;\n }\n return regex.exec(source.name);\n}\nfunction isDefault(source, regex) {\n if (!source.isDefault) {\n return false;\n }\n if (!regex) {\n return true;\n }\n return regex.exec(\"default\");\n}\n\nexport { DataSourceVariable };\n//# sourceMappingURL=DataSourceVariable.js.map\n","function buildMetricTree(parent, depth) {\n const chars = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"];\n const children = [];\n if (depth > 5) {\n return [];\n }\n for (const letter of chars) {\n const nodeName = `${parent}${letter}`;\n children.push({\n name: nodeName,\n children: buildMetricTree(nodeName, depth + 1)\n });\n }\n return children;\n}\nfunction queryTree(children, query, queryIndex) {\n if (queryIndex >= query.length) {\n return children;\n }\n if (query[queryIndex] === \"*\") {\n return children;\n }\n const nodeQuery = query[queryIndex];\n let result = [];\n let namesToMatch = [nodeQuery];\n if (nodeQuery.startsWith(\"{\")) {\n namesToMatch = nodeQuery.replace(/\\{|\\}/g, \"\").split(\",\");\n }\n for (const node of children) {\n for (const nameToMatch of namesToMatch) {\n if (nameToMatch.indexOf(\"*\") !== -1) {\n const pattern = nameToMatch.replace(\"*\", \"\");\n const regex = new RegExp(`^${pattern}.*`, \"gi\");\n if (regex.test(node.name)) {\n result = result.concat(queryTree([node], query, queryIndex + 1));\n }\n } else if (node.name === nameToMatch) {\n result = result.concat(queryTree(node.children, query, queryIndex + 1));\n }\n }\n }\n return result;\n}\nfunction queryMetricTree(query) {\n if (query.indexOf(\"value\") === 0) {\n return [{ name: query, children: [] }];\n }\n const children = buildMetricTree(\"\", 0);\n return queryTree(children, query.split(\".\"), 0);\n}\n\nexport { queryMetricTree };\n//# sourceMappingURL=metricTree.js.map\n","import { Subject, Observable } from 'rxjs';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { queryMetricTree } from '../../utils/metricTree.js';\nimport { VariableDependencyConfig } from '../VariableDependencyConfig.js';\nimport { renderSelectForVariable } from '../components/VariableValueSelect.js';\nimport { MultiValueVariable } from './MultiValueVariable.js';\nimport { VariableRefresh } from '@grafana/data';\nimport { getClosest } from '../../core/sceneGraph/utils.js';\nimport { SceneVariableSet } from '../sets/SceneVariableSet.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass TestVariable extends MultiValueVariable {\n constructor(initialState, isLazy = false) {\n super(__spreadValues({\n type: \"custom\",\n name: \"Test\",\n value: \"Value\",\n text: \"Text\",\n query: \"Query\",\n options: [],\n refresh: VariableRefresh.onDashboardLoad,\n updateOptions: true\n }, initialState));\n this.completeUpdate = new Subject();\n this.isGettingValues = true;\n this.getValueOptionsCount = 0;\n this.isLazy = false;\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"query\"]\n });\n this.isLazy = isLazy;\n }\n getValueOptions(args) {\n const { delayMs } = this.state;\n this.getValueOptionsCount += 1;\n const queryController = sceneGraph.getQueryController(this);\n return new Observable((observer) => {\n const queryEntry = {\n type: \"variable\",\n origin: this,\n cancel: () => observer.complete()\n };\n if (queryController) {\n queryController.queryStarted(queryEntry);\n }\n this.setState({ loading: true });\n if (this.state.throwError) {\n throw new Error(this.state.throwError);\n }\n const interpolatedQuery = sceneGraph.interpolate(this, this.state.query);\n const options = this.getOptions(interpolatedQuery);\n const sub = this.completeUpdate.subscribe({\n next: () => {\n const newState = { issuedQuery: interpolatedQuery, loading: false };\n if (this.state.updateOptions) {\n newState.options = options;\n }\n this.setState(newState);\n observer.next(options);\n observer.complete();\n }\n });\n let timeout;\n if (delayMs) {\n timeout = window.setTimeout(() => this.signalUpdateCompleted(), delayMs);\n } else if (delayMs === 0) {\n this.signalUpdateCompleted();\n }\n this.isGettingValues = true;\n return () => {\n sub.unsubscribe();\n window.clearTimeout(timeout);\n this.isGettingValues = false;\n if (this.state.loading) {\n this.setState({ loading: false });\n }\n if (queryController) {\n queryController.queryCompleted(queryEntry);\n }\n };\n });\n }\n cancel() {\n const sceneVarSet = getClosest(this, (s) => s instanceof SceneVariableSet ? s : void 0);\n sceneVarSet == null ? void 0 : sceneVarSet.cancel(this);\n }\n getOptions(interpolatedQuery) {\n if (this.state.optionsToReturn) {\n return this.state.optionsToReturn;\n }\n return queryMetricTree(interpolatedQuery).map((x) => ({ label: x.name, value: x.name }));\n }\n signalUpdateCompleted() {\n this.completeUpdate.next(1);\n }\n}\nTestVariable.Component = ({ model }) => {\n return renderSelectForVariable(model);\n};\n\nexport { TestVariable };\n//# sourceMappingURL=TestVariable.js.map\n","import React, { useCallback } from 'react';\nimport { AutoSizeInput } from '@grafana/ui';\n\nfunction VariableValueInput({ model }) {\n const { value, key, loading } = model.useState();\n const onBlur = useCallback(\n (e) => {\n model.setValue(e.currentTarget.value);\n },\n [model]\n );\n const onKeyDown = useCallback(\n (e) => {\n if (e.key === \"Enter\") {\n model.setValue(e.currentTarget.value);\n }\n },\n [model]\n );\n return /* @__PURE__ */ React.createElement(AutoSizeInput, {\n id: key,\n placeholder: \"Enter value\",\n minWidth: 15,\n maxWidth: 30,\n value,\n loading,\n onBlur,\n onKeyDown\n });\n}\n\nexport { VariableValueInput };\n//# sourceMappingURL=VariableValueInput.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { SceneObjectUrlSyncConfig } from '../../services/SceneObjectUrlSyncConfig.js';\nimport { VariableValueInput } from '../components/VariableValueInput.js';\nimport { SceneVariableValueChangedEvent } from '../types.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass TextBoxVariable extends SceneObjectBase {\n constructor(initialState) {\n super(__spreadValues({\n type: \"textbox\",\n value: \"\",\n name: \"\"\n }, initialState));\n this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: () => [this.getKey()] });\n }\n getValue() {\n return this.state.value;\n }\n setValue(newValue) {\n if (newValue !== this.state.value) {\n this.setState({ value: newValue });\n this.publishEvent(new SceneVariableValueChangedEvent(this), true);\n }\n }\n getKey() {\n return `var-${this.state.name}`;\n }\n getUrlState() {\n return { [this.getKey()]: this.state.value };\n }\n updateFromUrl(values) {\n const val = values[this.getKey()];\n if (typeof val === \"string\") {\n this.setValue(val);\n }\n }\n}\nTextBoxVariable.Component = ({ model }) => {\n return /* @__PURE__ */ React.createElement(VariableValueInput, {\n model\n });\n};\n\nexport { TextBoxVariable };\n//# sourceMappingURL=TextBoxVariable.js.map\n","import { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass LocalValueVariable extends SceneObjectBase {\n constructor(initialState) {\n super(__spreadProps(__spreadValues({\n type: \"system\",\n value: \"\",\n text: \"\",\n name: \"\"\n }, initialState), {\n skipUrlSync: true\n }));\n }\n getValue() {\n return this.state.value;\n }\n getValueText() {\n return this.state.text.toString();\n }\n isAncestorLoading() {\n var _a, _b;\n const ancestorScope = (_b = (_a = this.parent) == null ? void 0 : _a.parent) == null ? void 0 : _b.parent;\n if (!ancestorScope) {\n throw new Error(\"LocalValueVariable requires a parent SceneVariableSet that has an ancestor SceneVariableSet\");\n }\n const set = sceneGraph.getVariables(ancestorScope);\n const parentVar = sceneGraph.lookupVariable(this.state.name, ancestorScope);\n if (set && parentVar) {\n return set.isVariableLoadingOrWaitingToUpdate(parentVar);\n }\n return false;\n }\n}\n\nexport { LocalValueVariable };\n//# sourceMappingURL=LocalValueVariable.js.map\n","import { rangeUtil } from '@grafana/data';\nimport { VariableRefresh } from '@grafana/schema';\nimport { Select } from '@grafana/ui';\nimport React from 'react';\nimport { of } from 'rxjs';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { SceneObjectUrlSyncConfig } from '../../services/SceneObjectUrlSyncConfig.js';\nimport { AUTO_VARIABLE_VALUE, AUTO_VARIABLE_TEXT } from '../constants.js';\nimport { SceneVariableValueChangedEvent } from '../types.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass IntervalVariable extends SceneObjectBase {\n constructor(initialState) {\n super(__spreadValues({\n type: \"interval\",\n value: \"\",\n intervals: [\"1m\", \"10m\", \"30m\", \"1h\", \"6h\", \"12h\", \"1d\", \"7d\", \"14d\", \"30d\"],\n name: \"\",\n autoStepCount: 30,\n autoMinInterval: \"10s\",\n autoEnabled: false,\n refresh: VariableRefresh.onTimeRangeChanged\n }, initialState));\n this._onChange = (value) => {\n this.setState({ value: value.value });\n this.publishEvent(new SceneVariableValueChangedEvent(this), true);\n };\n this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: () => [this.getKey()] });\n }\n getKey() {\n return `var-${this.state.name}`;\n }\n getUrlState() {\n return { [this.getKey()]: this.state.value };\n }\n updateFromUrl(values) {\n const update = {};\n const val = values[this.getKey()];\n if (typeof val === \"string\") {\n if (val.startsWith(\"$__auto_interval_\")) {\n update.value = AUTO_VARIABLE_VALUE;\n } else {\n update.value = val;\n }\n }\n this.setState(update);\n }\n getOptionsForSelect() {\n const { value: currentValue, intervals, autoEnabled } = this.state;\n let options = intervals.map((interval) => ({ value: interval, label: interval }));\n if (autoEnabled) {\n options = [{ value: AUTO_VARIABLE_VALUE, label: AUTO_VARIABLE_TEXT }, ...options];\n }\n if (currentValue && !options.some((option) => option.value === currentValue)) {\n options.push({ value: currentValue, label: currentValue });\n }\n return options;\n }\n getValue() {\n const { value, autoStepCount, autoMinInterval } = this.state;\n if (value === AUTO_VARIABLE_VALUE) {\n return this.getAutoRefreshInteval(autoStepCount, autoMinInterval);\n }\n return value;\n }\n getAutoRefreshInteval(autoStepCount, minRefreshInterval) {\n const timeRange = sceneGraph.getTimeRange(this).state.value;\n const intervalObject = rangeUtil.calculateInterval(timeRange, autoStepCount, minRefreshInterval);\n return intervalObject.interval;\n }\n validateAndUpdate() {\n const { value, intervals } = this.state;\n let shouldPublish = false;\n if (value === AUTO_VARIABLE_VALUE) {\n shouldPublish = true;\n } else if (!value && intervals.length > 0) {\n const firstOption = intervals[0];\n this.setState({ value: firstOption });\n shouldPublish = true;\n }\n if (shouldPublish) {\n this.publishEvent(new SceneVariableValueChangedEvent(this), true);\n }\n return of({});\n }\n}\nIntervalVariable.Component = ({ model }) => {\n const { key, value } = model.useState();\n return /* @__PURE__ */ React.createElement(Select, {\n id: key,\n placeholder: \"Select value\",\n width: \"auto\",\n value,\n tabSelectsValue: false,\n options: model.getOptionsForSelect(),\n onChange: model._onChange\n });\n};\n\nexport { IntervalVariable };\n//# sourceMappingURL=IntervalVariable.js.map\n","import { locationService } from '@grafana/runtime';\nimport { SceneObjectStateChangedEvent } from '../core/events.js';\nimport { writeSceneLog } from '../utils/writeSceneLog.js';\nimport { Subscription } from 'rxjs';\nimport { UniqueUrlKeyMapper } from './UniqueUrlKeyMapper.js';\nimport { getUrlState, syncStateFromUrl, isUrlValueEqual } from './utils.js';\nimport { BusEventWithPayload } from '@grafana/data';\nimport { useMemo } from 'react';\n\nvar __accessCheck = (obj, member, msg) => {\n if (!member.has(obj))\n throw TypeError(\"Cannot \" + msg);\n};\nvar __privateGet = (obj, member, getter) => {\n __accessCheck(obj, member, \"read from private field\");\n return getter ? getter.call(obj) : member.get(obj);\n};\nvar __privateAdd = (obj, member, value) => {\n if (member.has(obj))\n throw TypeError(\"Cannot add the same private member more than once\");\n member instanceof WeakSet ? member.add(obj) : member.set(obj, value);\n};\nvar __privateSet = (obj, member, value, setter) => {\n __accessCheck(obj, member, \"write to private field\");\n setter ? setter.call(obj, value) : member.set(obj, value);\n return value;\n};\nvar _cache, _location;\nclass NewSceneObjectAddedEvent extends BusEventWithPayload {\n}\nNewSceneObjectAddedEvent.type = \"new-scene-object-added\";\nclass UrlSyncManager {\n constructor(_options = {}, locationService$1 = locationService) {\n this._urlKeyMapper = new UniqueUrlKeyMapper();\n this._options = _options;\n this._locationService = locationService$1;\n this._paramsCache = new UrlParamsCache(locationService$1);\n }\n initSync(root) {\n var _a;\n if (this._subs) {\n writeSceneLog(\"UrlSyncManager\", \"Unregister previous scene state subscription\", (_a = this._sceneRoot) == null ? void 0 : _a.state.key);\n this._subs.unsubscribe();\n }\n writeSceneLog(\"UrlSyncManager\", \"init\", root.state.key);\n this._sceneRoot = root;\n this._subs = new Subscription();\n this._subs.add(\n root.subscribeToEvent(SceneObjectStateChangedEvent, (evt) => {\n this.handleSceneObjectStateChanged(evt.payload.changedObject);\n })\n );\n this._subs.add(\n root.subscribeToEvent(NewSceneObjectAddedEvent, (evt) => {\n this.handleNewObject(evt.payload);\n })\n );\n this._urlKeyMapper.clear();\n this._lastLocation = this._locationService.getLocation();\n this.handleNewObject(this._sceneRoot);\n if (this._options.updateUrlOnInit) {\n const urlState = getUrlState(root);\n if (isUrlStateDifferent(urlState, this._paramsCache.getParams())) {\n this._locationService.partial(urlState, true);\n }\n }\n }\n cleanUp(root) {\n if (this._sceneRoot !== root) {\n return;\n }\n writeSceneLog(\"UrlSyncManager\", \"Clean up\");\n if (this._subs) {\n this._subs.unsubscribe();\n this._subs = void 0;\n writeSceneLog(\n \"UrlSyncManager\",\n \"Root deactived, unsub to state\",\n \"same key\",\n this._sceneRoot.state.key === root.state.key\n );\n }\n this._sceneRoot = void 0;\n this._lastLocation = void 0;\n }\n handleNewLocation(location) {\n if (!this._sceneRoot || this._lastLocation === location) {\n return;\n }\n writeSceneLog(\"UrlSyncManager\", \"handleNewLocation\");\n this._lastLocation = location;\n syncStateFromUrl(this._sceneRoot, this._paramsCache.getParams(), this._urlKeyMapper);\n }\n handleNewObject(sceneObj) {\n if (!this._sceneRoot) {\n return;\n }\n syncStateFromUrl(sceneObj, this._paramsCache.getParams(), this._urlKeyMapper);\n }\n handleSceneObjectStateChanged(changedObject) {\n var _a, _b;\n if (!changedObject.urlSync) {\n return;\n }\n const newUrlState = changedObject.urlSync.getUrlState();\n const searchParams = this._locationService.getSearch();\n const mappedUpdated = {};\n for (const [key, newUrlValue] of Object.entries(newUrlState)) {\n const uniqueKey = this._urlKeyMapper.getUniqueKey(key, changedObject);\n const currentUrlValue = searchParams.getAll(uniqueKey);\n if (!isUrlValueEqual(currentUrlValue, newUrlValue)) {\n mappedUpdated[uniqueKey] = newUrlValue;\n }\n }\n if (Object.keys(mappedUpdated).length > 0) {\n const shouldCreateHistoryEntry = (_b = (_a = changedObject.urlSync).shouldCreateHistoryStep) == null ? void 0 : _b.call(_a, newUrlState);\n const shouldReplace = shouldCreateHistoryEntry !== true;\n writeSceneLog(\"UrlSyncManager\", \"onStateChange updating URL\");\n this._locationService.partial(mappedUpdated, shouldReplace);\n this._lastLocation = this._locationService.getLocation();\n }\n }\n getUrlState(root) {\n return getUrlState(root);\n }\n}\nclass UrlParamsCache {\n constructor(locationService) {\n this.locationService = locationService;\n __privateAdd(this, _cache, void 0);\n __privateAdd(this, _location, void 0);\n }\n getParams() {\n const location = this.locationService.getLocation();\n if (__privateGet(this, _location) === location) {\n return __privateGet(this, _cache);\n }\n __privateSet(this, _location, location);\n __privateSet(this, _cache, new URLSearchParams(location.search));\n return __privateGet(this, _cache);\n }\n}\n_cache = new WeakMap();\n_location = new WeakMap();\nfunction isUrlStateDifferent(sceneUrlState, currentParams) {\n for (let key in sceneUrlState) {\n if (!isUrlValueEqual(currentParams.getAll(key), sceneUrlState[key])) {\n return true;\n }\n }\n return false;\n}\nfunction useUrlSyncManager(options, locationService) {\n return useMemo(\n () => new UrlSyncManager(\n {\n updateUrlOnInit: options.updateUrlOnInit,\n createBrowserHistorySteps: options.createBrowserHistorySteps\n },\n locationService\n ),\n [options.updateUrlOnInit, options.createBrowserHistorySteps, locationService]\n );\n}\n\nexport { NewSceneObjectAddedEvent, UrlSyncManager, useUrlSyncManager };\n//# sourceMappingURL=UrlSyncManager.js.map\n","import { css } from '@emotion/css';\nimport { useStyles2 } from '@grafana/ui';\nimport React from 'react';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { setWindowGrafanaSceneContext } from '../utils/compatibility/setWindowGrafanaSceneContext.js';\n\nclass EmbeddedScene extends SceneObjectBase {\n constructor(state) {\n super(state);\n this.addActivationHandler(() => {\n const unsetGlobalScene = setWindowGrafanaSceneContext(this);\n return () => {\n unsetGlobalScene();\n };\n });\n }\n}\nEmbeddedScene.Component = EmbeddedSceneRenderer;\nfunction EmbeddedSceneRenderer({ model }) {\n const { body, controls } = model.useState();\n const styles = useStyles2(getStyles);\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.container\n }, controls && /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.controls\n }, controls.map((control) => /* @__PURE__ */ React.createElement(control.Component, {\n key: control.state.key,\n model: control\n }))), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.body\n }, /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n })));\n}\nconst getStyles = (theme) => {\n return {\n container: css({\n flexGrow: 1,\n display: \"flex\",\n gap: theme.spacing(2),\n minHeight: \"100%\",\n flexDirection: \"column\"\n }),\n body: css({\n flexGrow: 1,\n display: \"flex\",\n gap: theme.spacing(1)\n }),\n controls: css({\n display: \"flex\",\n gap: theme.spacing(2),\n alignItems: \"flex-end\",\n flexWrap: \"wrap\"\n })\n };\n};\n\nexport { EmbeddedScene };\n//# sourceMappingURL=EmbeddedScene.js.map\n","import { writeSceneLog } from '../writeSceneLog.js';\n\nfunction setWindowGrafanaSceneContext(activeScene) {\n const prevScene = window.__grafanaSceneContext;\n writeSceneLog(\"setWindowGrafanaScene\", \"set window.__grafanaSceneContext\", activeScene);\n window.__grafanaSceneContext = activeScene;\n return () => {\n if (window.__grafanaSceneContext === activeScene) {\n writeSceneLog(\"setWindowGrafanaScene\", \"restore window.__grafanaSceneContext\", prevScene);\n window.__grafanaSceneContext = prevScene;\n }\n };\n}\n\nexport { setWindowGrafanaSceneContext };\n//# sourceMappingURL=setWindowGrafanaSceneContext.js.map\n","import React, { useEffect } from 'react';\nimport { Menu } from '@grafana/ui';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { selectors } from '@grafana/e2e-selectors';\n\nclass VizPanelMenu extends SceneObjectBase {\n addItem(item) {\n this.setState({\n items: this.state.items ? [...this.state.items, item] : [item]\n });\n }\n setItems(items) {\n this.setState({\n items\n });\n }\n}\nVizPanelMenu.Component = VizPanelMenuRenderer;\nfunction VizPanelMenuRenderer({ model }) {\n const { items = [] } = model.useState();\n const ref = React.useRef(null);\n useEffect(() => {\n if (ref.current) {\n ref.current.focus();\n }\n }, []);\n const renderItems = (items2) => {\n return items2.map((item) => {\n switch (item.type) {\n case \"divider\":\n return /* @__PURE__ */ React.createElement(Menu.Divider, {\n key: item.text\n });\n case \"group\":\n return /* @__PURE__ */ React.createElement(Menu.Group, {\n key: item.text,\n label: item.text\n }, item.subMenu ? renderItems(item.subMenu) : void 0);\n default:\n return /* @__PURE__ */ React.createElement(Menu.Item, {\n key: item.text,\n label: item.text,\n icon: item.iconClassName,\n childItems: item.subMenu ? renderItems(item.subMenu) : void 0,\n url: item.href,\n onClick: item.onClick,\n shortcut: item.shortcut,\n testId: selectors.components.Panels.Panel.menuItems(item.text)\n });\n }\n });\n };\n return /* @__PURE__ */ React.createElement(Menu, {\n ref\n }, renderItems(items));\n}\n\nexport { VizPanelMenu };\n//# sourceMappingURL=VizPanelMenu.js.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","import React from 'react';\nimport { SceneObjectBase } from '../../../core/SceneObjectBase.js';\nimport { SceneGridLayout } from './SceneGridLayout.js';\nimport { SceneGridRow } from './SceneGridRow.js';\n\nclass SceneGridItem extends SceneObjectBase {\n}\nSceneGridItem.Component = SceneGridItemRenderer;\nfunction SceneGridItemRenderer({ model }) {\n const { body } = model.useState();\n const parent = model.parent;\n if (parent && !isSceneGridLayout(parent) && !isSceneGridRow(parent)) {\n throw new Error(\"SceneGridItem must be a child of SceneGridLayout or SceneGridRow\");\n }\n if (!body) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n });\n}\nfunction isSceneGridRow(child) {\n return child instanceof SceneGridRow;\n}\nfunction isSceneGridLayout(child) {\n return child instanceof SceneGridLayout;\n}\n\nexport { SceneGridItem, isSceneGridRow };\n//# sourceMappingURL=SceneGridItem.js.map\n","import React from 'react';\nimport { LinkButton } from '@grafana/ui';\nimport { useAsync } from 'react-use';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { sceneGraph } from '../../core/sceneGraph/index.js';\nimport { getExploreURL } from '../../utils/explore.js';\nimport { useReturnToPrevious } from '@grafana/runtime';\n\nclass VizPanelExploreButton extends SceneObjectBase {\n constructor(options = {}) {\n super({ options });\n }\n}\nVizPanelExploreButton.Component = VizPanelExploreButtonComponent;\nfunction VizPanelExploreButtonComponent({ model }) {\n const { options } = model.useState();\n const { data } = sceneGraph.getData(model).useState();\n const { from, to } = sceneGraph.getTimeRange(model).useState();\n const { value: exploreLink } = useAsync(\n async () => data ? getExploreURL(data, model, { from, to }, options.transform) : \"\",\n [data, model, from, to]\n );\n const returnToPrevious = useReturnToPrevious();\n if (exploreLink) {\n return /* @__PURE__ */ React.createElement(LinkButton, {\n key: \"explore\",\n icon: \"compass\",\n size: \"sm\",\n variant: \"secondary\",\n href: exploreLink,\n onClick: () => {\n var _a;\n if (options.returnToPrevious) {\n returnToPrevious(options.returnToPrevious.title, options.returnToPrevious.href);\n }\n (_a = options.onClick) == null ? void 0 : _a.call(options);\n }\n }, \"Explore\");\n }\n return null;\n}\n\nexport { VizPanelExploreButton };\n//# sourceMappingURL=VizPanelExploreButton.js.map\n","import { useEffect } from 'react';\nimport useAsyncFn from './useAsyncFn';\nexport default function useAsync(fn, deps) {\n if (deps === void 0) { deps = []; }\n var _a = useAsyncFn(fn, deps, {\n loading: true,\n }), state = _a[0], callback = _a[1];\n useEffect(function () {\n callback();\n }, [callback]);\n return state;\n}\n","import { __assign } from \"tslib\";\nimport { useCallback, useRef, useState } from 'react';\nimport useMountedState from './useMountedState';\nexport default function useAsyncFn(fn, deps, initialState) {\n if (deps === void 0) { deps = []; }\n if (initialState === void 0) { initialState = { loading: false }; }\n var lastCallId = useRef(0);\n var isMounted = useMountedState();\n var _a = useState(initialState), state = _a[0], set = _a[1];\n var callback = useCallback(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var callId = ++lastCallId.current;\n if (!state.loading) {\n set(function (prevState) { return (__assign(__assign({}, prevState), { loading: true })); });\n }\n return fn.apply(void 0, args).then(function (value) {\n isMounted() && callId === lastCallId.current && set({ value: value, loading: false });\n return value;\n }, function (error) {\n isMounted() && callId === lastCallId.current && set({ error: error, loading: false });\n return error;\n });\n }, deps);\n return [state, callback];\n}\n","import { useCallback, useEffect, useRef } from 'react';\nexport default function useMountedState() {\n var mountedRef = useRef(false);\n var get = useCallback(function () { return mountedRef.current; }, []);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n return get;\n}\n","import { wrapInSafeSerializableSceneObject } from './wrapInSafeSerializableSceneObject.js';\nimport { getDataSourceSrv } from '@grafana/runtime';\n\nasync function getExploreURL(data, model, timeRange, transform) {\n var _a, _b, _c, _d;\n const targets = (_a = data.request) == null ? void 0 : _a.targets;\n if (!targets) {\n return \"\";\n }\n const { from, to } = timeRange;\n const filters = (_b = data.request) == null ? void 0 : _b.filters;\n const scopedVars = {\n __sceneObject: wrapInSafeSerializableSceneObject(model)\n };\n const interpolatedQueries = (await Promise.allSettled(\n targets.map(async (q) => {\n var _a2;\n const queryDs = await getDataSourceSrv().get(q.datasource);\n return ((_a2 = queryDs.interpolateVariablesInQueries) == null ? void 0 : _a2.call(queryDs, [q], scopedVars != null ? scopedVars : {}, filters)[0]) || q;\n })\n )).filter((promise) => promise.status === \"fulfilled\").map((q) => q.value).map((q) => {\n var _a2;\n return (_a2 = transform == null ? void 0 : transform(q)) != null ? _a2 : q;\n });\n const queries = interpolatedQueries != null ? interpolatedQueries : [];\n const datasource = (_d = (_c = queries.find((query) => {\n var _a2;\n return !!((_a2 = query.datasource) == null ? void 0 : _a2.uid);\n })) == null ? void 0 : _c.datasource) == null ? void 0 : _d.uid;\n if ((queries == null ? void 0 : queries.length) && datasource && from && to) {\n const left = encodeURIComponent(\n JSON.stringify({\n datasource,\n queries,\n range: {\n from,\n to\n }\n })\n );\n return `/explore?left=${left}`;\n }\n return \"\";\n}\n\nexport { getExploreURL };\n//# sourceMappingURL=explore.js.map\n","import React, { useState, useRef, useImperativeHandle } from 'react';\nimport { useEffectOnce } from 'react-use';\nimport { uniqueId } from 'lodash';\nimport { css } from '@emotion/css';\nimport { useStyles2 } from '@grafana/ui';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction useUniqueId() {\n var _a;\n const idRefLazy = useRef(void 0);\n (_a = idRefLazy.current) != null ? _a : idRefLazy.current = uniqueId();\n return idRefLazy.current;\n}\nconst LazyLoader = React.forwardRef(\n (_a, ref) => {\n var _b = _a, { children, onLoad, onChange, className } = _b, rest = __objRest(_b, [\"children\", \"onLoad\", \"onChange\", \"className\"]);\n const id = useUniqueId();\n const { hideEmpty } = useStyles2(getStyles);\n const [loaded, setLoaded] = useState(false);\n const [isInView, setIsInView] = useState(false);\n const innerRef = useRef(null);\n useImperativeHandle(ref, () => innerRef.current);\n useEffectOnce(() => {\n LazyLoader.addCallback(id, (entry) => {\n if (!loaded && entry.isIntersecting) {\n setLoaded(true);\n onLoad == null ? void 0 : onLoad();\n }\n setIsInView(entry.isIntersecting);\n onChange == null ? void 0 : onChange(entry.isIntersecting);\n });\n const wrapperEl = innerRef.current;\n if (wrapperEl) {\n LazyLoader.observer.observe(wrapperEl);\n }\n return () => {\n wrapperEl && LazyLoader.observer.unobserve(wrapperEl);\n delete LazyLoader.callbacks[id];\n if (Object.keys(LazyLoader.callbacks).length === 0) {\n LazyLoader.observer.disconnect();\n }\n };\n });\n return /* @__PURE__ */ React.createElement(\"div\", __spreadValues({\n id,\n ref: innerRef,\n className: `${hideEmpty} ${className}`\n }, rest), !loaded && \"\\xA0\", loaded && (typeof children === \"function\" ? children({ isInView }) : children));\n }\n);\nfunction getStyles() {\n return {\n hideEmpty: css({\n \"&:empty\": {\n display: \"none\"\n }\n })\n };\n}\nLazyLoader.displayName = \"LazyLoader\";\nLazyLoader.callbacks = {};\nLazyLoader.addCallback = (id, c) => LazyLoader.callbacks[id] = c;\nLazyLoader.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (typeof LazyLoader.callbacks[entry.target.id] === \"function\") {\n LazyLoader.callbacks[entry.target.id](entry);\n }\n }\n },\n { rootMargin: \"100px\" }\n);\n\nexport { LazyLoader, useUniqueId };\n//# sourceMappingURL=LazyLoader.js.map\n","import { useEffect } from 'react';\nvar useEffectOnce = function (effect) {\n useEffect(effect, []);\n};\nexport default useEffectOnce;\n","import React, { useRef, useEffect } from 'react';\nimport ReactGridLayout from 'react-grid-layout';\nimport { GRID_CELL_VMARGIN, GRID_COLUMN_COUNT, GRID_CELL_HEIGHT } from './constants.js';\nimport { LazyLoader } from '../LazyLoader.js';\nimport { useStyles2 } from '@grafana/ui';\nimport { cx, css } from '@emotion/css';\nimport { useMeasure } from 'react-use';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nvar __objRest = (source, exclude) => {\n var target = {};\n for (var prop in source)\n if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)\n target[prop] = source[prop];\n if (source != null && __getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(source)) {\n if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))\n target[prop] = source[prop];\n }\n return target;\n};\nfunction SceneGridLayoutRenderer({ model }) {\n const { children, isLazy, isDraggable, isResizable } = model.useState();\n const [outerDivRef, { width, height }] = useMeasure();\n const ref = useRef(null);\n useEffect(() => {\n updateAnimationClass(ref, !!isDraggable);\n }, [isDraggable]);\n validateChildrenSize(children);\n const renderGrid = (width2, height2) => {\n if (!width2 || !height2) {\n return null;\n }\n const layout = model.buildGridLayout(width2, height2);\n return /* @__PURE__ */ React.createElement(\"div\", {\n ref,\n style: { width: `${width2}px`, height: \"100%\" },\n className: \"react-grid-layout\"\n }, /* @__PURE__ */ React.createElement(ReactGridLayout, {\n width: width2,\n isDraggable: isDraggable && width2 > 768,\n isResizable: isResizable != null ? isResizable : false,\n containerPadding: [0, 0],\n useCSSTransforms: true,\n margin: [GRID_CELL_VMARGIN, GRID_CELL_VMARGIN],\n cols: GRID_COLUMN_COUNT,\n rowHeight: GRID_CELL_HEIGHT,\n draggableHandle: `.grid-drag-handle-${model.state.key}`,\n draggableCancel: \".grid-drag-cancel\",\n layout,\n onDragStart: model.onDragStart,\n onDragStop: model.onDragStop,\n onResizeStop: model.onResizeStop,\n onLayoutChange: model.onLayoutChange,\n isBounded: false,\n resizeHandle: /* @__PURE__ */ React.createElement(ResizeHandle, null)\n }, layout.map((gridItem, index) => /* @__PURE__ */ React.createElement(GridItemWrapper, {\n key: gridItem.i,\n grid: model,\n layoutItem: gridItem,\n index,\n isLazy,\n totalCount: layout.length\n }))));\n };\n return /* @__PURE__ */ React.createElement(\"div\", {\n ref: outerDivRef,\n style: { flex: \"1 1 auto\", position: \"relative\", zIndex: 1, width: \"100%\" }\n }, renderGrid(width, height));\n}\nconst GridItemWrapper = React.forwardRef((props, ref) => {\n var _b;\n const _a = props, { grid, layoutItem, index, totalCount, isLazy, style, onLoad, onChange, children } = _a, divProps = __objRest(_a, [\"grid\", \"layoutItem\", \"index\", \"totalCount\", \"isLazy\", \"style\", \"onLoad\", \"onChange\", \"children\"]);\n const sceneChild = grid.getSceneLayoutChild(layoutItem.i);\n const className = (_b = sceneChild.getClassName) == null ? void 0 : _b.call(sceneChild);\n const innerContent = /* @__PURE__ */ React.createElement(sceneChild.Component, {\n model: sceneChild,\n key: sceneChild.state.key\n });\n if (isLazy) {\n return /* @__PURE__ */ React.createElement(LazyLoader, __spreadProps(__spreadValues({}, divProps), {\n key: sceneChild.state.key,\n \"data-griditem-key\": sceneChild.state.key,\n className: cx(className, props.className),\n style,\n ref\n }), innerContent, children);\n }\n return /* @__PURE__ */ React.createElement(\"div\", __spreadProps(__spreadValues({}, divProps), {\n ref,\n key: sceneChild.state.key,\n \"data-griditem-key\": sceneChild.state.key,\n className: cx(className, props.className),\n style\n }), innerContent, children);\n});\nGridItemWrapper.displayName = \"GridItemWrapper\";\nfunction validateChildrenSize(children) {\n if (children.some(\n (c) => c.state.height === void 0 || c.state.width === void 0 || c.state.x === void 0 || c.state.y === void 0\n )) {\n throw new Error(\"All children must have a size specified\");\n }\n}\nfunction updateAnimationClass(ref, isDraggable, retry) {\n if (ref.current) {\n if (isDraggable) {\n ref.current.classList.add(\"react-grid-layout--enable-move-animations\");\n } else {\n ref.current.classList.remove(\"react-grid-layout--enable-move-animations\");\n }\n } else if (!retry) {\n setTimeout(() => updateAnimationClass(ref, isDraggable, true), 50);\n }\n}\nconst ResizeHandle = React.forwardRef((_a, ref) => {\n var _b = _a, divProps = __objRest(_b, [\"handleAxis\"]);\n const customCssClass = useStyles2(getResizeHandleStyles);\n return /* @__PURE__ */ React.createElement(\"div\", __spreadProps(__spreadValues({\n ref\n }, divProps), {\n className: `${customCssClass} scene-resize-handle`\n }), /* @__PURE__ */ React.createElement(\"svg\", {\n width: \"16px\",\n height: \"16px\",\n viewBox: \"0 0 24 24\",\n fill: \"none\",\n xmlns: \"http://www.w3.org/2000/svg\"\n }, /* @__PURE__ */ React.createElement(\"path\", {\n d: \"M21 15L15 21M21 8L8 21\",\n stroke: \"currentColor\",\n strokeWidth: \"2\",\n strokeLinecap: \"round\",\n strokeLinejoin: \"round\"\n })));\n});\nResizeHandle.displayName = \"ResizeHandle\";\nfunction getResizeHandleStyles(theme) {\n return css({\n position: \"absolute\",\n bottom: 0,\n right: 0,\n zIndex: 999,\n padding: theme.spacing(1.5, 0, 0, 1.5),\n color: theme.colors.border.strong,\n cursor: \"se-resize\",\n \"&:hover\": {\n color: theme.colors.text.link\n },\n svg: {\n display: \"block\"\n },\n \".react-resizable-hide &\": {\n display: \"none\"\n }\n });\n}\n\nexport { SceneGridLayoutRenderer };\n//# sourceMappingURL=SceneGridLayoutRenderer.js.map\n","import { GRID_CELL_HEIGHT, GRID_CELL_VMARGIN } from './constants.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nfunction fitPanelsInHeight(cells, height) {\n const visibleHeight = height - GRID_CELL_VMARGIN * 4;\n const currentGridHeight = Math.max(...cells.map((cell) => cell.h + cell.y));\n const visibleGridHeight = Math.floor(visibleHeight / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN));\n const scaleFactor = currentGridHeight / visibleGridHeight;\n return cells.map((cell) => {\n return __spreadProps(__spreadValues({}, cell), {\n y: Math.round(cell.y / scaleFactor) || 0,\n h: Math.round(cell.h / scaleFactor) || 1\n });\n });\n}\n\nexport { fitPanelsInHeight };\n//# sourceMappingURL=utils.js.map\n","import { SceneObjectBase } from '../../../core/SceneObjectBase.js';\nimport { DEFAULT_PANEL_SPAN } from './constants.js';\nimport { isSceneGridRow } from './SceneGridItem.js';\nimport { SceneGridLayoutRenderer } from './SceneGridLayoutRenderer.js';\nimport { SceneGridRow } from './SceneGridRow.js';\nimport { fitPanelsInHeight } from './utils.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst _SceneGridLayout = class extends SceneObjectBase {\n constructor(state) {\n super(__spreadProps(__spreadValues({}, state), {\n children: sortChildrenByPosition(state.children)\n }));\n this._skipOnLayoutChange = false;\n this._oldLayout = [];\n this._loadOldLayout = false;\n this.onLayoutChange = (layout) => {\n if (this._skipOnLayoutChange) {\n this._skipOnLayoutChange = false;\n return;\n }\n if (this._loadOldLayout) {\n layout = [...this._oldLayout];\n this._loadOldLayout = false;\n }\n for (const item of layout) {\n const child = this.getSceneLayoutChild(item.i);\n const nextSize = {\n x: item.x,\n y: item.y,\n width: item.w,\n height: item.h\n };\n if (!isItemSizeEqual(child.state, nextSize)) {\n child.setState(__spreadValues({}, nextSize));\n }\n }\n this.setState({ children: sortChildrenByPosition(this.state.children) });\n };\n this.onResizeStop = (_, o, n) => {\n const child = this.getSceneLayoutChild(n.i);\n child.setState({\n width: n.w,\n height: n.h\n });\n };\n this.onDragStart = (gridLayout) => {\n this._oldLayout = [...gridLayout];\n };\n this.onDragStop = (gridLayout, o, updatedItem) => {\n const sceneChild = this.getSceneLayoutChild(updatedItem.i);\n gridLayout = sortGridLayout(gridLayout);\n for (let i = 0; i < gridLayout.length; i++) {\n const gridItem = gridLayout[i];\n const child = this.getSceneLayoutChild(gridItem.i);\n const childSize = child.state;\n if ((childSize == null ? void 0 : childSize.x) !== gridItem.x || (childSize == null ? void 0 : childSize.y) !== gridItem.y) {\n child.setState({\n x: gridItem.x,\n y: gridItem.y\n });\n }\n }\n const indexOfUpdatedItem = gridLayout.findIndex((item) => item.i === updatedItem.i);\n let newParent = this.findGridItemSceneParent(gridLayout, indexOfUpdatedItem - 1);\n let newChildren = this.state.children;\n if (sceneChild instanceof SceneGridRow && newParent instanceof SceneGridRow) {\n if (!this.isRowDropValid(gridLayout, updatedItem, indexOfUpdatedItem)) {\n this._loadOldLayout = true;\n }\n newParent = this;\n }\n if (newParent !== sceneChild.parent) {\n newChildren = this.moveChildTo(sceneChild, newParent);\n }\n this.setState({ children: sortChildrenByPosition(newChildren) });\n this._skipOnLayoutChange = true;\n };\n }\n isDraggable() {\n var _a;\n return (_a = this.state.isDraggable) != null ? _a : false;\n }\n getDragClass() {\n return `grid-drag-handle-${this.state.key}`;\n }\n getDragClassCancel() {\n return `grid-drag-cancel`;\n }\n toggleRow(row) {\n var _a, _b;\n const isCollapsed = row.state.isCollapsed;\n if (!isCollapsed) {\n row.setState({ isCollapsed: true });\n this.setState({});\n return;\n }\n const rowChildren = row.state.children;\n if (rowChildren.length === 0) {\n row.setState({ isCollapsed: false });\n this.setState({});\n return;\n }\n const rowY = row.state.y;\n const firstPanelYPos = (_a = rowChildren[0].state.y) != null ? _a : rowY;\n const yDiff = firstPanelYPos - (rowY + 1);\n let yMax = rowY;\n for (const panel of rowChildren) {\n const newSize = __spreadValues({}, panel.state);\n newSize.y = (_b = newSize.y) != null ? _b : rowY;\n newSize.y -= yDiff;\n if (newSize.y !== panel.state.y) {\n panel.setState(newSize);\n }\n yMax = Math.max(yMax, Number(newSize.y) + Number(newSize.height));\n }\n const pushDownAmount = yMax - rowY - 1;\n for (const child of this.state.children) {\n if (child.state.y > rowY) {\n this.pushChildDown(child, pushDownAmount);\n }\n if (isSceneGridRow(child) && child !== row) {\n for (const rowChild of child.state.children) {\n if (rowChild.state.y > rowY) {\n this.pushChildDown(rowChild, pushDownAmount);\n }\n }\n }\n }\n row.setState({ isCollapsed: false });\n this.setState({});\n }\n ignoreLayoutChange(shouldIgnore) {\n this._skipOnLayoutChange = shouldIgnore;\n }\n getSceneLayoutChild(key) {\n for (const child of this.state.children) {\n if (child.state.key === key) {\n return child;\n }\n if (child instanceof SceneGridRow) {\n for (const rowChild of child.state.children) {\n if (rowChild.state.key === key) {\n return rowChild;\n }\n }\n }\n }\n throw new Error(\"Scene layout child not found for GridItem\");\n }\n pushChildDown(child, amount) {\n child.setState({\n y: child.state.y + amount\n });\n }\n findGridItemSceneParent(layout, startAt) {\n for (let i = startAt; i >= 0; i--) {\n const gridItem = layout[i];\n const sceneChild = this.getSceneLayoutChild(gridItem.i);\n if (sceneChild instanceof SceneGridRow) {\n if (sceneChild.state.isCollapsed) {\n return this;\n }\n return sceneChild;\n }\n }\n return this;\n }\n isRowDropValid(gridLayout, updatedItem, indexOfUpdatedItem) {\n if (gridLayout[gridLayout.length - 1].i === updatedItem.i) {\n return true;\n }\n const nextSceneChild = this.getSceneLayoutChild(gridLayout[indexOfUpdatedItem + 1].i);\n if (nextSceneChild instanceof SceneGridRow) {\n return true;\n } else if (nextSceneChild.parent instanceof _SceneGridLayout) {\n return true;\n }\n return false;\n }\n moveChildTo(child, target) {\n const currentParent = child.parent;\n let rootChildren = this.state.children;\n const newChild = child.clone({ key: child.state.key });\n if (currentParent instanceof SceneGridRow) {\n const newRow = currentParent.clone();\n newRow.setState({\n children: newRow.state.children.filter((c) => c.state.key !== child.state.key)\n });\n rootChildren = rootChildren.map((c) => c === currentParent ? newRow : c);\n if (target instanceof SceneGridRow) {\n const targetRow = target.clone();\n targetRow.setState({ children: [...targetRow.state.children, newChild] });\n rootChildren = rootChildren.map((c) => c === target ? targetRow : c);\n } else {\n rootChildren = [...rootChildren, newChild];\n }\n } else {\n if (!(target instanceof _SceneGridLayout)) {\n rootChildren = rootChildren.filter((c) => c.state.key !== child.state.key);\n const targetRow = target.clone();\n targetRow.setState({ children: [...targetRow.state.children, newChild] });\n rootChildren = rootChildren.map((c) => c === target ? targetRow : c);\n }\n }\n return rootChildren;\n }\n toGridCell(child) {\n var _a, _b;\n const size = child.state;\n let x = (_a = size.x) != null ? _a : 0;\n let y = (_b = size.y) != null ? _b : 0;\n const w = Number.isInteger(Number(size.width)) ? Number(size.width) : DEFAULT_PANEL_SPAN;\n const h = Number.isInteger(Number(size.height)) ? Number(size.height) : DEFAULT_PANEL_SPAN;\n let isDraggable = child.state.isDraggable;\n let isResizable = child.state.isResizable;\n if (child instanceof SceneGridRow) {\n isDraggable = child.state.isCollapsed ? true : false;\n isResizable = false;\n }\n return { i: child.state.key, x, y, h, w, isResizable, isDraggable };\n }\n buildGridLayout(width, height) {\n let cells = [];\n for (const child of this.state.children) {\n cells.push(this.toGridCell(child));\n if (child instanceof SceneGridRow && !child.state.isCollapsed) {\n for (const rowChild of child.state.children) {\n cells.push(this.toGridCell(rowChild));\n }\n }\n }\n cells = sortGridLayout(cells);\n if (this.state.UNSAFE_fitPanels) {\n cells = fitPanelsInHeight(cells, height);\n }\n if (width < 768) {\n this._skipOnLayoutChange = true;\n return cells.map((cell) => __spreadProps(__spreadValues({}, cell), { w: 24 }));\n }\n this._skipOnLayoutChange = false;\n return cells;\n }\n};\nlet SceneGridLayout = _SceneGridLayout;\nSceneGridLayout.Component = SceneGridLayoutRenderer;\nfunction isItemSizeEqual(a, b) {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\nfunction sortChildrenByPosition(children) {\n children.forEach((child) => {\n if (child instanceof SceneGridRow) {\n child.setState({ children: sortChildrenByPosition(child.state.children) });\n }\n });\n return [...children].sort((a, b) => {\n return a.state.y - b.state.y || a.state.x - b.state.x;\n });\n}\nfunction sortGridLayout(layout) {\n return [...layout].sort((a, b) => a.y - b.y || a.x - b.x);\n}\n\nexport { SceneGridLayout };\n//# sourceMappingURL=SceneGridLayout.js.map\n","const DEFAULT_PANEL_SPAN = 4;\nconst GRID_CELL_HEIGHT = 30;\nconst GRID_CELL_VMARGIN = 8;\nconst GRID_COLUMN_COUNT = 24;\n\nexport { DEFAULT_PANEL_SPAN, GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, GRID_COLUMN_COUNT };\n//# sourceMappingURL=constants.js.map\n","import { cx, css } from '@emotion/css';\nimport React from 'react';\nimport { useStyles2, Icon } from '@grafana/ui';\nimport { SceneObjectBase } from '../../../core/SceneObjectBase.js';\nimport { SceneGridLayout } from './SceneGridLayout.js';\nimport { GRID_COLUMN_COUNT } from './constants.js';\nimport { sceneGraph } from '../../../core/sceneGraph/index.js';\nimport { selectors } from '@grafana/e2e-selectors';\nimport { VariableDependencyConfig } from '../../../variables/VariableDependencyConfig.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass SceneGridRow extends SceneObjectBase {\n constructor(state) {\n super(__spreadProps(__spreadValues({\n children: state.children || [],\n isCollapsible: state.isCollapsible || true,\n title: state.title || \"\"\n }, state), {\n x: 0,\n height: 1,\n width: GRID_COLUMN_COUNT\n }));\n this._variableDependency = new VariableDependencyConfig(this, {\n statePaths: [\"title\"],\n handleTimeMacros: true\n });\n this.onCollapseToggle = () => {\n if (!this.state.isCollapsible) {\n return;\n }\n this.getGridLayout().toggleRow(this);\n };\n }\n getGridLayout() {\n const layout = this.parent;\n if (!layout || !(layout instanceof SceneGridLayout)) {\n throw new Error(\"SceneGridRow must be a child of SceneGridLayout\");\n }\n return layout;\n }\n getUrlState() {\n return { rowc: this.state.isCollapsed ? \"1\" : \"0\" };\n }\n updateFromUrl(values) {\n if (values.rowc == null) {\n return;\n }\n if (values.rowc !== this.getUrlState().rowc) {\n this.onCollapseToggle();\n }\n }\n}\nSceneGridRow.Component = SceneGridRowRenderer;\nfunction SceneGridRowRenderer({ model }) {\n const styles = useStyles2(getSceneGridRowStyles);\n const { isCollapsible, isCollapsed, title, actions, children } = model.useState();\n const layout = model.getGridLayout();\n const layoutDragClass = layout.getDragClass();\n const isDraggable = layout.isDraggable();\n const count = children ? children.length : 0;\n const panels = count === 1 ? \"panel\" : \"panels\";\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.row, isCollapsed && styles.rowCollapsed)\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.rowTitleAndActionsGroup\n }, /* @__PURE__ */ React.createElement(\"button\", {\n onClick: model.onCollapseToggle,\n className: styles.rowTitleButton,\n \"aria-label\": isCollapsed ? \"Expand row\" : \"Collapse row\",\n \"data-testid\": selectors.components.DashboardRow.title(sceneGraph.interpolate(model, title, void 0, \"text\"))\n }, isCollapsible && /* @__PURE__ */ React.createElement(Icon, {\n name: isCollapsed ? \"angle-right\" : \"angle-down\"\n }), /* @__PURE__ */ React.createElement(\"span\", {\n className: styles.rowTitle,\n role: \"heading\"\n }, sceneGraph.interpolate(model, title, void 0, \"text\"))), /* @__PURE__ */ React.createElement(\"span\", {\n className: cx(styles.panelCount, isCollapsed && styles.panelCountCollapsed)\n }, \"(\", count, \" \", panels, \")\"), actions && /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.rowActions\n }, /* @__PURE__ */ React.createElement(actions.Component, {\n model: actions\n }))), isDraggable && isCollapsed && /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.dragHandle, layoutDragClass)\n }, /* @__PURE__ */ React.createElement(Icon, {\n name: \"draggabledots\"\n })));\n}\nconst getSceneGridRowStyles = (theme) => {\n return {\n row: css({\n width: \"100%\",\n height: \"30px\",\n display: \"flex\",\n justifyContent: \"space-between\",\n gap: theme.spacing(1)\n }),\n rowTitleButton: css({\n display: \"flex\",\n alignItems: \"center\",\n cursor: \"pointer\",\n background: \"transparent\",\n border: \"none\",\n minWidth: 0,\n gap: theme.spacing(1)\n }),\n rowCollapsed: css({\n borderBottom: `1px solid ${theme.colors.border.weak}`\n }),\n rowTitle: css({\n fontSize: theme.typography.h5.fontSize,\n fontWeight: theme.typography.fontWeightMedium,\n whiteSpace: \"nowrap\",\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n maxWidth: \"100%\",\n flexGrow: 1,\n minWidth: 0\n }),\n collapsedInfo: css({\n fontSize: theme.typography.bodySmall.fontSize,\n color: theme.colors.text.secondary,\n display: \"flex\",\n alignItems: \"center\",\n flexGrow: 1\n }),\n rowTitleAndActionsGroup: css({\n display: \"flex\",\n minWidth: 0,\n \"&:hover, &:focus-within\": {\n \"& > div\": {\n opacity: 1\n }\n }\n }),\n rowActions: css({\n display: \"flex\",\n whiteSpace: \"nowrap\",\n opacity: 0,\n transition: \"200ms opacity ease-in 200ms\",\n \"&:hover, &:focus-within\": {\n opacity: 1\n }\n }),\n dragHandle: css({\n display: \"flex\",\n padding: theme.spacing(0, 1),\n alignItems: \"center\",\n justifyContent: \"flex-end\",\n cursor: \"move\",\n color: theme.colors.text.secondary,\n \"&:hover\": {\n color: theme.colors.text.primary\n }\n }),\n panelCount: css({\n whiteSpace: \"nowrap\",\n paddingLeft: theme.spacing(2),\n color: theme.colors.text.secondary,\n fontStyle: \"italic\",\n fontSize: theme.typography.size.sm,\n fontWeight: \"normal\",\n display: \"none\",\n lineHeight: \"30px\"\n }),\n panelCountCollapsed: css({\n display: \"inline-block\"\n })\n };\n};\n\nexport { SceneGridRow, SceneGridRowRenderer, getSceneGridRowStyles };\n//# sourceMappingURL=SceneGridRow.js.map\n","import { cx, css } from '@emotion/css';\nimport React from 'react';\nimport { useStyles2, ToolbarButton, Icon } from '@grafana/ui';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { getSceneGridRowStyles } from './layout/grid/SceneGridRow.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\n\nclass NestedScene extends SceneObjectBase {\n constructor() {\n super(...arguments);\n this.onToggle = () => {\n this.setState({\n isCollapsed: !this.state.isCollapsed\n });\n };\n this.onRemove = () => {\n const parent = this.parent;\n if (isSceneLayoutItem(parent)) {\n parent.setState({\n body: void 0\n });\n }\n };\n }\n}\nNestedScene.Component = NestedSceneRenderer;\nfunction NestedSceneRenderer({ model }) {\n const { title, isCollapsed, canCollapse, canRemove, body, controls } = model.useState();\n const gridRow = useStyles2(getSceneGridRowStyles);\n const styles = useStyles2(getStyles);\n const toolbarControls = (controls != null ? controls : []).map((action) => /* @__PURE__ */ React.createElement(action.Component, {\n key: action.state.key,\n model: action\n }));\n if (canRemove) {\n toolbarControls.push(\n /* @__PURE__ */ React.createElement(ToolbarButton, {\n icon: \"times\",\n variant: \"default\",\n onClick: model.onRemove,\n key: \"remove-button\",\n \"aria-label\": \"Remove scene\"\n })\n );\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.wrapper\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.row, isCollapsed && styles.rowCollapsed)\n }, /* @__PURE__ */ React.createElement(\"button\", {\n onClick: model.onToggle,\n className: gridRow.rowTitleButton,\n \"aria-label\": isCollapsed ? \"Expand scene\" : \"Collapse scene\"\n }, canCollapse && /* @__PURE__ */ React.createElement(Icon, {\n name: isCollapsed ? \"angle-right\" : \"angle-down\"\n }), /* @__PURE__ */ React.createElement(\"span\", {\n className: gridRow.rowTitle,\n role: \"heading\"\n }, sceneGraph.interpolate(model, title, void 0, \"text\"))), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.actions\n }, toolbarControls)), !isCollapsed && /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n }));\n}\nconst getStyles = (theme) => ({\n wrapper: css({\n display: \"flex\",\n flexDirection: \"column\",\n flexGrow: 1,\n gap: theme.spacing(1)\n }),\n row: css({\n width: \"100%\",\n display: \"flex\",\n justifyContent: \"space-between\",\n gap: theme.spacing(1)\n }),\n rowCollapsed: css({\n borderBottom: `1px solid ${theme.colors.border.weak}`,\n paddingBottom: theme.spacing(1)\n }),\n actions: css({\n display: \"flex\",\n alignItems: \"center\",\n gap: theme.spacing(1),\n justifyContent: \"flex-end\",\n flexGrow: 1\n })\n});\nfunction isSceneLayoutItem(x) {\n return \"body\" in x.state;\n}\n\nexport { NestedScene, NestedSceneRenderer };\n//# sourceMappingURL=NestedScene.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig.js';\nimport { useTheme2 } from '@grafana/ui';\nimport { css } from '@emotion/css';\n\nclass SceneCanvasText extends SceneObjectBase {\n constructor() {\n super(...arguments);\n this._variableDependency = new VariableDependencyConfig(this, { statePaths: [\"text\"] });\n }\n}\nSceneCanvasText.Component = ({ model }) => {\n const { text, fontSize = 20, align = \"left\", key, spacing } = model.useState();\n const theme = useTheme2();\n const style = css({\n fontSize,\n display: \"flex\",\n flexGrow: 1,\n alignItems: \"center\",\n padding: spacing ? theme.spacing(spacing, 0) : void 0,\n justifyContent: align\n });\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: style,\n \"data-testid\": key\n }, sceneGraph.interpolate(model, text));\n};\n\nexport { SceneCanvasText };\n//# sourceMappingURL=SceneCanvasText.js.map\n","import React from 'react';\nimport { ToolbarButton, Input } from '@grafana/ui';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { ControlsLabel } from '../utils/ControlsLabel.js';\n\nclass SceneToolbarButton extends SceneObjectBase {\n}\nSceneToolbarButton.Component = ({ model }) => {\n const state = model.useState();\n return /* @__PURE__ */ React.createElement(ToolbarButton, {\n onClick: state.onClick,\n icon: state.icon\n });\n};\nclass SceneToolbarInput extends SceneObjectBase {\n}\nSceneToolbarInput.Component = ({ model }) => {\n const state = model.useState();\n return /* @__PURE__ */ React.createElement(\"div\", {\n style: { display: \"flex\" }\n }, state.label && /* @__PURE__ */ React.createElement(ControlsLabel, {\n label: state.label\n }), /* @__PURE__ */ React.createElement(Input, {\n defaultValue: state.value,\n width: 8,\n onBlur: (evt) => {\n model.state.onChange(parseInt(evt.currentTarget.value, 10));\n }\n }));\n};\n\nexport { SceneToolbarButton, SceneToolbarInput };\n//# sourceMappingURL=SceneToolbarButton.js.map\n","import React from 'react';\nimport { useLocalStorage } from 'react-use';\nimport { uniqBy } from 'lodash';\nimport { toUtc, rangeUtil, isDateTime } from '@grafana/data';\nimport { TimeRangePicker } from '@grafana/ui';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\n\nclass SceneTimePicker extends SceneObjectBase {\n constructor() {\n super(...arguments);\n this.onZoom = () => {\n const timeRange = sceneGraph.getTimeRange(this);\n const zoomedTimeRange = getZoomedTimeRange(timeRange.state.value, 2);\n timeRange.onTimeRangeChange(zoomedTimeRange);\n };\n this.onChangeFiscalYearStartMonth = (month) => {\n const timeRange = sceneGraph.getTimeRange(this);\n timeRange.setState({ fiscalYearStartMonth: month });\n };\n this.toAbsolute = () => {\n const timeRange = sceneGraph.getTimeRange(this);\n const timeRangeVal = timeRange.state.value;\n const from = toUtc(timeRangeVal.from);\n const to = toUtc(timeRangeVal.to);\n timeRange.onTimeRangeChange({ from, to, raw: { from, to } });\n };\n this.onMoveBackward = () => {\n const timeRange = sceneGraph.getTimeRange(this);\n const {\n state: { value: range }\n } = timeRange;\n timeRange.onTimeRangeChange(getShiftedTimeRange(TimeRangeDirection.Backward, range, Date.now()));\n };\n this.onMoveForward = () => {\n const timeRange = sceneGraph.getTimeRange(this);\n const {\n state: { value: range }\n } = timeRange;\n timeRange.onTimeRangeChange(getShiftedTimeRange(TimeRangeDirection.Forward, range, Date.now()));\n };\n }\n}\nSceneTimePicker.Component = SceneTimePickerRenderer;\nfunction SceneTimePickerRenderer({ model }) {\n const { hidePicker, isOnCanvas } = model.useState();\n const timeRange = sceneGraph.getTimeRange(model);\n const timeZone = timeRange.getTimeZone();\n const timeRangeState = timeRange.useState();\n const [timeRangeHistory, setTimeRangeHistory] = useLocalStorage(HISTORY_LOCAL_STORAGE_KEY, [], {\n raw: false,\n serializer: serializeHistory,\n deserializer: deserializeHistory\n });\n if (hidePicker) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(TimeRangePicker, {\n isOnCanvas: isOnCanvas != null ? isOnCanvas : true,\n value: timeRangeState.value,\n onChange: (range) => {\n if (isAbsolute(range)) {\n setTimeRangeHistory([range, ...timeRangeHistory != null ? timeRangeHistory : []]);\n }\n timeRange.onTimeRangeChange(range);\n },\n timeZone,\n fiscalYearStartMonth: timeRangeState.fiscalYearStartMonth,\n onMoveBackward: model.onMoveBackward,\n onMoveForward: model.onMoveForward,\n onZoom: model.onZoom,\n onChangeTimeZone: timeRange.onTimeZoneChange,\n onChangeFiscalYearStartMonth: model.onChangeFiscalYearStartMonth,\n weekStart: timeRangeState.weekStart,\n history: timeRangeHistory\n });\n}\nfunction getZoomedTimeRange(timeRange, factor) {\n const timespan = timeRange.to.valueOf() - timeRange.from.valueOf();\n const center = timeRange.to.valueOf() - timespan / 2;\n const newTimespan = timespan === 0 ? 3e4 : timespan * factor;\n const to = center + newTimespan / 2;\n const from = center - newTimespan / 2;\n return { from: toUtc(from), to: toUtc(to), raw: { from: toUtc(from), to: toUtc(to) } };\n}\nvar TimeRangeDirection = /* @__PURE__ */ ((TimeRangeDirection2) => {\n TimeRangeDirection2[TimeRangeDirection2[\"Backward\"] = 0] = \"Backward\";\n TimeRangeDirection2[TimeRangeDirection2[\"Forward\"] = 1] = \"Forward\";\n return TimeRangeDirection2;\n})(TimeRangeDirection || {});\nfunction getShiftedTimeRange(dir, timeRange, upperLimit) {\n const oldTo = timeRange.to.valueOf();\n const oldFrom = timeRange.from.valueOf();\n const halfSpan = (oldTo - oldFrom) / 2;\n let fromRaw;\n let toRaw;\n if (dir === 0 /* Backward */) {\n fromRaw = oldFrom - halfSpan;\n toRaw = oldTo - halfSpan;\n } else {\n fromRaw = oldFrom + halfSpan;\n toRaw = oldTo + halfSpan;\n if (toRaw > upperLimit && oldTo < upperLimit) {\n toRaw = upperLimit;\n fromRaw = oldFrom;\n }\n }\n const from = toUtc(fromRaw);\n const to = toUtc(toRaw);\n return {\n from,\n to,\n raw: { from, to }\n };\n}\nconst HISTORY_LOCAL_STORAGE_KEY = \"grafana.dashboard.timepicker.history\";\nfunction deserializeHistory(value) {\n const values = JSON.parse(value);\n return values.map((item) => rangeUtil.convertRawToRange(item, \"utc\", void 0, \"YYYY-MM-DD HH:mm:ss\"));\n}\nfunction serializeHistory(values) {\n return JSON.stringify(\n limit(\n values.map((v) => ({\n from: typeof v.raw.from === \"string\" ? v.raw.from : v.raw.from.toISOString(),\n to: typeof v.raw.to === \"string\" ? v.raw.to : v.raw.to.toISOString()\n }))\n )\n );\n}\nfunction limit(value) {\n return uniqBy(value, (v) => v.from + v.to).slice(0, 4);\n}\nfunction isAbsolute(value) {\n return isDateTime(value.raw.from) || isDateTime(value.raw.to);\n}\n\nexport { SceneTimePicker, TimeRangeDirection, getShiftedTimeRange, getZoomedTimeRange };\n//# sourceMappingURL=SceneTimePicker.js.map\n","import { useCallback, useState, useRef, useLayoutEffect } from 'react';\nimport { isBrowser, noop } from './misc/util';\nvar useLocalStorage = function (key, initialValue, options) {\n if (!isBrowser) {\n return [initialValue, noop, noop];\n }\n if (!key) {\n throw new Error('useLocalStorage key may not be falsy');\n }\n var deserializer = options\n ? options.raw\n ? function (value) { return value; }\n : options.deserializer\n : JSON.parse;\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var initializer = useRef(function (key) {\n try {\n var serializer = options ? (options.raw ? String : options.serializer) : JSON.stringify;\n var localStorageValue = localStorage.getItem(key);\n if (localStorageValue !== null) {\n return deserializer(localStorageValue);\n }\n else {\n initialValue && localStorage.setItem(key, serializer(initialValue));\n return initialValue;\n }\n }\n catch (_a) {\n // If user is in private mode or has storage restriction\n // localStorage can throw. JSON.parse and JSON.stringify\n // can throw, too.\n return initialValue;\n }\n });\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var _a = useState(function () { return initializer.current(key); }), state = _a[0], setState = _a[1];\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useLayoutEffect(function () { return setState(initializer.current(key)); }, [key]);\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var set = useCallback(function (valOrFunc) {\n try {\n var newState = typeof valOrFunc === 'function' ? valOrFunc(state) : valOrFunc;\n if (typeof newState === 'undefined')\n return;\n var value = void 0;\n if (options)\n if (options.raw)\n if (typeof newState === 'string')\n value = newState;\n else\n value = JSON.stringify(newState);\n else if (options.serializer)\n value = options.serializer(newState);\n else\n value = JSON.stringify(newState);\n else\n value = JSON.stringify(newState);\n localStorage.setItem(key, value);\n setState(deserializer(value));\n }\n catch (_a) {\n // If user is in private mode or has storage restriction\n // localStorage can throw. Also JSON.stringify can throw.\n }\n }, [key, setState]);\n // eslint-disable-next-line react-hooks/rules-of-hooks\n var remove = useCallback(function () {\n try {\n localStorage.removeItem(key);\n setState(undefined);\n }\n catch (_a) {\n // If user is in private mode or has storage restriction\n // localStorage can throw.\n }\n }, [key, setState]);\n return [state, set, remove];\n};\nexport default useLocalStorage;\n","import React from 'react';\nimport { rangeUtil } from '@grafana/data';\nimport { config } from '@grafana/runtime';\nimport { RefreshPicker } from '@grafana/ui';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { SceneObjectUrlSyncConfig } from '../services/SceneObjectUrlSyncConfig.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst DEFAULT_INTERVALS = [\"5s\", \"10s\", \"30s\", \"1m\", \"5m\", \"15m\", \"30m\", \"1h\", \"2h\", \"1d\"];\nclass SceneRefreshPicker extends SceneObjectBase {\n constructor(state) {\n var _a, _b, _c;\n const filterDissalowedIntervals = (i) => {\n var _a2;\n const minInterval = (_a2 = state.minRefreshInterval) != null ? _a2 : config.minRefreshInterval;\n try {\n return minInterval ? rangeUtil.intervalToMs(i) >= rangeUtil.intervalToMs(minInterval) : true;\n } catch (e) {\n return false;\n }\n };\n super(__spreadProps(__spreadValues({\n refresh: \"\"\n }, state), {\n autoValue: void 0,\n autoEnabled: (_a = state.autoEnabled) != null ? _a : true,\n autoMinInterval: (_b = state.autoMinInterval) != null ? _b : config.minRefreshInterval,\n intervals: ((_c = state.intervals) != null ? _c : DEFAULT_INTERVALS).filter(filterDissalowedIntervals)\n }));\n this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: [\"refresh\"] });\n this._autoRefreshBlocked = false;\n this.onRefresh = () => {\n const queryController = sceneGraph.getQueryController(this);\n queryController == null ? void 0 : queryController.startProfile(this);\n if (queryController == null ? void 0 : queryController.state.isRunning) {\n queryController.cancelAll();\n return;\n }\n const timeRange = sceneGraph.getTimeRange(this);\n if (this._intervalTimer) {\n clearInterval(this._intervalTimer);\n }\n timeRange.onRefresh();\n this.setupIntervalTimer();\n };\n this.onIntervalChanged = (interval) => {\n this.setState({ refresh: interval });\n this.setupIntervalTimer();\n };\n this.setupAutoTimeRangeListener = () => {\n return sceneGraph.getTimeRange(this).subscribeToState((newState, prevState) => {\n if (newState.from !== prevState.from || newState.to !== prevState.to) {\n this.setupIntervalTimer();\n }\n });\n };\n this.calculateAutoRefreshInterval = () => {\n var _a;\n const timeRange = sceneGraph.getTimeRange(this);\n const resolution = (_a = window == null ? void 0 : window.innerWidth) != null ? _a : 2e3;\n return rangeUtil.calculateInterval(timeRange.state.value, resolution, this.state.autoMinInterval);\n };\n this.setupIntervalTimer = () => {\n var _a;\n const timeRange = sceneGraph.getTimeRange(this);\n const { refresh, intervals } = this.state;\n if (this._intervalTimer || refresh === \"\") {\n clearInterval(this._intervalTimer);\n }\n if (refresh === \"\") {\n return;\n }\n if (refresh !== RefreshPicker.autoOption.value && intervals && !intervals.includes(refresh)) {\n return;\n }\n let intervalMs;\n (_a = this._autoTimeRangeListener) == null ? void 0 : _a.unsubscribe();\n if (refresh === RefreshPicker.autoOption.value) {\n const autoRefreshInterval = this.calculateAutoRefreshInterval();\n intervalMs = autoRefreshInterval.intervalMs;\n this._autoTimeRangeListener = this.setupAutoTimeRangeListener();\n if (autoRefreshInterval.interval !== this.state.autoValue) {\n this.setState({ autoValue: autoRefreshInterval.interval });\n }\n } else {\n intervalMs = rangeUtil.intervalToMs(refresh);\n }\n this._intervalTimer = setInterval(() => {\n if (this.isTabVisible()) {\n const queryController = sceneGraph.getQueryController(this);\n queryController == null ? void 0 : queryController.startProfile(this);\n timeRange.onRefresh();\n } else {\n this._autoRefreshBlocked = true;\n }\n }, intervalMs);\n };\n this.addActivationHandler(() => {\n this.setupIntervalTimer();\n const onVisibilityChange = () => {\n if (this._autoRefreshBlocked && document.visibilityState === \"visible\") {\n this._autoRefreshBlocked = false;\n this.onRefresh();\n }\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => {\n var _a2;\n if (this._intervalTimer) {\n clearInterval(this._intervalTimer);\n }\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n (_a2 = this._autoTimeRangeListener) == null ? void 0 : _a2.unsubscribe();\n };\n });\n }\n getUrlState() {\n let refresh = this.state.refresh;\n if (typeof refresh !== \"string\" || refresh.length === 0) {\n refresh = void 0;\n }\n return { refresh };\n }\n updateFromUrl(values) {\n const { intervals } = this.state;\n let refresh = values.refresh;\n if (typeof refresh === \"string\" && isIntervalString(refresh)) {\n if (intervals == null ? void 0 : intervals.includes(refresh)) {\n this.setState({ refresh });\n } else {\n this.setState({\n refresh: intervals ? intervals[0] : void 0\n });\n }\n }\n }\n isTabVisible() {\n return document.visibilityState === void 0 || document.visibilityState === \"visible\";\n }\n}\nSceneRefreshPicker.Component = SceneRefreshPickerRenderer;\nfunction SceneRefreshPickerRenderer({ model }) {\n var _a;\n const { refresh, intervals, autoEnabled, autoValue, isOnCanvas, primary, withText } = model.useState();\n const isRunning = useQueryControllerState(model);\n let text = refresh === ((_a = RefreshPicker.autoOption) == null ? void 0 : _a.value) ? autoValue : withText ? \"Refresh\" : void 0;\n let tooltip;\n let width;\n if (isRunning) {\n tooltip = \"Cancel all queries\";\n if (withText) {\n text = \"Cancel\";\n }\n }\n if (withText) {\n width = \"96px\";\n }\n return /* @__PURE__ */ React.createElement(RefreshPicker, {\n showAutoInterval: autoEnabled,\n value: refresh,\n intervals,\n tooltip,\n width,\n text,\n onRefresh: () => {\n model.onRefresh();\n },\n primary,\n onIntervalChanged: model.onIntervalChanged,\n isLoading: isRunning,\n isOnCanvas: isOnCanvas != null ? isOnCanvas : true\n });\n}\nfunction useQueryControllerState(model) {\n const queryController = sceneGraph.getQueryController(model);\n if (!queryController) {\n return false;\n }\n return queryController.useState().isRunning;\n}\nfunction isIntervalString(str) {\n try {\n const res = rangeUtil.describeInterval(str);\n return res.count > 0;\n } catch (e) {\n return false;\n }\n}\n\nexport { DEFAULT_INTERVALS, SceneRefreshPicker, SceneRefreshPickerRenderer };\n//# sourceMappingURL=SceneRefreshPicker.js.map\n","const getCompareSeriesRefId = (refId) => `${refId}-compare`;\n\nexport { getCompareSeriesRefId };\n//# sourceMappingURL=getCompareSeriesRefId.js.map\n","import { rangeUtil, dateTime, FieldType } from '@grafana/data';\nimport { config } from '@grafana/runtime';\nimport { useStyles2, ButtonGroup, ToolbarButton, Checkbox, ButtonSelect } from '@grafana/ui';\nimport React from 'react';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { SceneObjectUrlSyncConfig } from '../services/SceneObjectUrlSyncConfig.js';\nimport { getCompareSeriesRefId } from '../utils/getCompareSeriesRefId.js';\nimport { parseUrlParam } from '../utils/parseUrlParam.js';\nimport { css } from '@emotion/css';\nimport { of } from 'rxjs';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nconst PREVIOUS_PERIOD_VALUE = \"__previousPeriod\";\nconst NO_PERIOD_VALUE = \"__noPeriod\";\nconst PREVIOUS_PERIOD_COMPARE_OPTION = {\n label: \"Previous period\",\n value: PREVIOUS_PERIOD_VALUE\n};\nconst NO_COMPARE_OPTION = {\n label: \"No comparison\",\n value: NO_PERIOD_VALUE\n};\nconst DEFAULT_COMPARE_OPTIONS = [\n { label: \"Day before\", value: \"24h\" },\n { label: \"Week before\", value: \"1w\" },\n { label: \"Month before\", value: \"1M\" }\n];\nclass SceneTimeRangeCompare extends SceneObjectBase {\n constructor(state) {\n super(__spreadValues({ compareOptions: DEFAULT_COMPARE_OPTIONS }, state));\n this._urlSync = new SceneObjectUrlSyncConfig(this, { keys: [\"compareWith\"] });\n this._onActivate = () => {\n const sceneTimeRange = sceneGraph.getTimeRange(this);\n this.setState({ compareOptions: this.getCompareOptions(sceneTimeRange.state.value) });\n this._subs.add(\n sceneTimeRange.subscribeToState((timeRange) => {\n const compareOptions = this.getCompareOptions(timeRange.value);\n const stateUpdate = { compareOptions };\n if (Boolean(this.state.compareWith) && !compareOptions.find(({ value }) => value === this.state.compareWith)) {\n stateUpdate.compareWith = PREVIOUS_PERIOD_VALUE;\n }\n this.setState(stateUpdate);\n })\n );\n };\n this.getCompareOptions = (timeRange) => {\n const diffDays = Math.ceil(timeRange.to.diff(timeRange.from));\n const matchIndex = DEFAULT_COMPARE_OPTIONS.findIndex(({ value }) => {\n const intervalInMs = rangeUtil.intervalToMs(value);\n return intervalInMs >= diffDays;\n });\n return [\n NO_COMPARE_OPTION,\n PREVIOUS_PERIOD_COMPARE_OPTION,\n ...DEFAULT_COMPARE_OPTIONS.slice(matchIndex).map(({ label, value }) => ({ label, value }))\n ];\n };\n this.onCompareWithChanged = (compareWith) => {\n if (compareWith === NO_PERIOD_VALUE) {\n this.onClearCompare();\n } else {\n this.setState({ compareWith });\n }\n };\n this.onClearCompare = () => {\n this.setState({ compareWith: void 0 });\n };\n this.addActivationHandler(this._onActivate);\n }\n getExtraQueries(request) {\n const extraQueries = [];\n const compareRange = this.getCompareTimeRange(request.range);\n if (!compareRange) {\n return extraQueries;\n }\n const targets = request.targets.filter((query) => query.timeRangeCompare !== false);\n if (targets.length) {\n extraQueries.push({\n req: __spreadProps(__spreadValues({}, request), {\n targets,\n range: compareRange\n }),\n processor: timeShiftAlignmentProcessor\n });\n }\n return extraQueries;\n }\n shouldRerun(prev, next, queries) {\n return prev.compareWith !== next.compareWith && queries.find((query) => query.timeRangeCompare !== false) !== void 0;\n }\n getCompareTimeRange(timeRange) {\n let compareFrom;\n let compareTo;\n if (this.state.compareWith) {\n if (this.state.compareWith === PREVIOUS_PERIOD_VALUE) {\n const diffMs = timeRange.to.diff(timeRange.from);\n compareFrom = dateTime(timeRange.from).subtract(diffMs);\n compareTo = dateTime(timeRange.to).subtract(diffMs);\n } else {\n compareFrom = dateTime(timeRange.from).subtract(rangeUtil.intervalToMs(this.state.compareWith));\n compareTo = dateTime(timeRange.to).subtract(rangeUtil.intervalToMs(this.state.compareWith));\n }\n return {\n from: compareFrom,\n to: compareTo,\n raw: {\n from: compareFrom,\n to: compareTo\n }\n };\n }\n return void 0;\n }\n getUrlState() {\n return {\n compareWith: this.state.compareWith\n };\n }\n updateFromUrl(values) {\n if (!values.compareWith) {\n return;\n }\n const compareWith = parseUrlParam(values.compareWith);\n if (compareWith) {\n const compareOptions = this.getCompareOptions(sceneGraph.getTimeRange(this).state.value);\n if (compareOptions.find(({ value }) => value === compareWith)) {\n this.setState({\n compareWith\n });\n } else {\n this.setState({\n compareWith: \"__previousPeriod\"\n });\n }\n }\n }\n}\nSceneTimeRangeCompare.Component = SceneTimeRangeCompareRenderer;\nconst timeShiftAlignmentProcessor = (primary, secondary) => {\n const diff = secondary.timeRange.from.diff(primary.timeRange.from);\n secondary.series.forEach((series) => {\n series.refId = getCompareSeriesRefId(series.refId || \"\");\n series.meta = __spreadProps(__spreadValues({}, series.meta), {\n timeCompare: {\n diffMs: diff,\n isTimeShiftQuery: true\n }\n });\n series.fields.forEach((field) => {\n if (field.type === FieldType.time) {\n field.values = field.values.map((v) => {\n return diff < 0 ? v - diff : v + diff;\n });\n }\n field.config = __spreadProps(__spreadValues({}, field.config), {\n color: {\n mode: \"fixed\",\n fixedColor: config.theme.palette.gray60\n }\n });\n return field;\n });\n });\n return of(secondary);\n};\nfunction SceneTimeRangeCompareRenderer({ model }) {\n var _a;\n const styles = useStyles2(getStyles);\n const { compareWith, compareOptions } = model.useState();\n const [previousCompare, setPreviousCompare] = React.useState(compareWith);\n const previousValue = (_a = compareOptions.find(({ value: value2 }) => value2 === previousCompare)) != null ? _a : PREVIOUS_PERIOD_COMPARE_OPTION;\n const value = compareOptions.find(({ value: value2 }) => value2 === compareWith);\n const enabled = Boolean(value);\n const onClick = () => {\n if (enabled) {\n setPreviousCompare(compareWith);\n model.onClearCompare();\n } else if (!enabled) {\n model.onCompareWithChanged(previousValue.value);\n }\n };\n return /* @__PURE__ */ React.createElement(ButtonGroup, null, /* @__PURE__ */ React.createElement(ToolbarButton, {\n variant: \"canvas\",\n tooltip: \"Enable time frame comparison\",\n onClick: (e) => {\n e.stopPropagation();\n e.preventDefault();\n onClick();\n }\n }, /* @__PURE__ */ React.createElement(Checkbox, {\n label: \" \",\n value: enabled,\n onClick\n }), \"Comparison\"), enabled ? /* @__PURE__ */ React.createElement(ButtonSelect, {\n variant: \"canvas\",\n value,\n options: compareOptions,\n onChange: (v) => {\n model.onCompareWithChanged(v.value);\n }\n }) : /* @__PURE__ */ React.createElement(ToolbarButton, {\n className: styles.previewButton,\n disabled: true,\n variant: \"canvas\",\n isOpen: false\n }, previousValue.label));\n}\nfunction getStyles(theme) {\n return {\n previewButton: css({\n \"&:disabled\": {\n border: `1px solid ${theme.colors.secondary.border}`,\n color: theme.colors.text.disabled,\n opacity: 1\n }\n })\n };\n}\n\nexport { DEFAULT_COMPARE_OPTIONS, NO_COMPARE_OPTION, PREVIOUS_PERIOD_COMPARE_OPTION, SceneTimeRangeCompare };\n//# sourceMappingURL=SceneTimeRangeCompare.js.map\n","import React from 'react';\nimport { LoadingState } from '@grafana/data';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\n\nclass SceneByFrameRepeater extends SceneObjectBase {\n constructor(state) {\n super(state);\n this.addActivationHandler(() => {\n const dataProvider = sceneGraph.getData(this);\n this._subs.add(\n dataProvider.subscribeToState((data) => {\n var _a;\n if (((_a = data.data) == null ? void 0 : _a.state) === LoadingState.Done) {\n this.performRepeat(data.data);\n }\n })\n );\n if (dataProvider.state.data) {\n this.performRepeat(dataProvider.state.data);\n }\n });\n }\n performRepeat(data) {\n const newChildren = [];\n for (let seriesIndex = 0; seriesIndex < data.series.length; seriesIndex++) {\n const layoutChild = this.state.getLayoutChild(data, data.series[seriesIndex], seriesIndex);\n newChildren.push(layoutChild);\n }\n this.state.body.setState({ children: newChildren });\n }\n}\nSceneByFrameRepeater.Component = ({ model }) => {\n const { body } = model.useState();\n return /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n });\n};\n\nexport { SceneByFrameRepeater };\n//# sourceMappingURL=SceneByFrameRepeater.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\nimport { sceneGraph } from '../core/sceneGraph/index.js';\nimport { VariableDependencyConfig } from '../variables/VariableDependencyConfig.js';\nimport { MultiValueVariable } from '../variables/variants/MultiValueVariable.js';\n\nclass SceneByVariableRepeater extends SceneObjectBase {\n constructor(state) {\n super(state);\n this._variableDependency = new VariableDependencyConfig(\n this,\n {\n variableNames: [this.state.variableName],\n onVariableUpdateCompleted: () => this.performRepeat()\n }\n );\n this.addActivationHandler(() => this.performRepeat());\n }\n performRepeat() {\n if (this._variableDependency.hasDependencyInLoadingState()) {\n return;\n }\n const variable = sceneGraph.lookupVariable(this.state.variableName, this);\n if (!(variable instanceof MultiValueVariable)) {\n console.error(\"SceneByVariableRepeater: variable is not a MultiValueVariable\");\n return;\n }\n const values = getMultiVariableValues(variable);\n const newChildren = [];\n for (const option of values) {\n const layoutChild = this.state.getLayoutChild(option);\n newChildren.push(layoutChild);\n }\n this.state.body.setState({ children: newChildren });\n }\n}\nSceneByVariableRepeater.Component = ({ model }) => {\n const { body } = model.useState();\n return /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n });\n};\nfunction getMultiVariableValues(variable) {\n const { value, text, options } = variable.state;\n if (variable.hasAllValue()) {\n return options;\n }\n if (Array.isArray(value) && Array.isArray(text)) {\n return value.map((v, i) => ({ value: v, label: text[i] }));\n }\n return [{ value, label: text }];\n}\n\nexport { SceneByVariableRepeater, getMultiVariableValues };\n//# sourceMappingURL=SceneByVariableRepeater.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\n\nclass SceneControlsSpacer extends SceneObjectBase {\n constructor() {\n super({});\n this._renderBeforeActivation = true;\n }\n}\nSceneControlsSpacer.Component = (_props) => {\n return /* @__PURE__ */ React.createElement(\"div\", {\n style: { flexGrow: 1 }\n });\n};\n\nexport { SceneControlsSpacer };\n//# sourceMappingURL=SceneControlsSpacer.js.map\n","import { css } from '@emotion/css';\nimport { config } from '@grafana/runtime';\nimport React, { useMemo } from 'react';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\n\nclass SceneFlexLayout extends SceneObjectBase {\n toggleDirection() {\n this.setState({\n direction: this.state.direction === \"row\" ? \"column\" : \"row\"\n });\n }\n isDraggable() {\n return false;\n }\n}\nSceneFlexLayout.Component = SceneFlexLayoutRenderer;\nfunction SceneFlexLayoutRenderer({ model, parentState }) {\n const { children, isHidden } = model.useState();\n const style = useLayoutStyle(model.state, parentState);\n if (isHidden) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: style\n }, children.map((item) => {\n const Component = item.Component;\n return /* @__PURE__ */ React.createElement(Component, {\n key: item.state.key,\n model: item,\n parentState: model.state\n });\n }));\n}\nclass SceneFlexItem extends SceneObjectBase {\n}\nSceneFlexItem.Component = SceneFlexItemRenderer;\nfunction SceneFlexItemRenderer({ model, parentState }) {\n if (!parentState) {\n throw new Error(\"SceneFlexItem must be a child of SceneFlexLayout\");\n }\n const { body, isHidden } = model.useState();\n const style = useLayoutItemStyle(model.state, parentState);\n if (!body || isHidden) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: style\n }, /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n }));\n}\nfunction applyItemStyles(style, state, parentState) {\n var _a, _b, _c;\n const parentDirection = (_a = parentState.direction) != null ? _a : \"row\";\n const { xSizing = \"fill\", ySizing = \"fill\" } = state;\n style.display = \"flex\";\n style.position = \"relative\";\n style.flexDirection = parentDirection;\n if (parentDirection === \"column\") {\n if (state.height) {\n style.height = state.height;\n } else {\n style.flexGrow = ySizing === \"fill\" ? 1 : 0;\n }\n if (state.width) {\n style.width = state.width;\n } else {\n style.alignSelf = xSizing === \"fill\" ? \"stretch\" : \"flex-start\";\n }\n } else {\n if (state.height) {\n style.height = state.height;\n } else {\n style.alignSelf = ySizing === \"fill\" ? \"stretch\" : \"flex-start\";\n }\n if (state.width) {\n style.width = state.width;\n } else {\n style.flexGrow = xSizing === \"fill\" ? 1 : 0;\n }\n }\n style.minWidth = state.minWidth;\n style.maxWidth = state.maxWidth;\n style.maxHeight = state.maxHeight;\n style.minHeight = (_b = state.minHeight) != null ? _b : parentState.minHeight;\n style.height = (_c = state.height) != null ? _c : parentState.height;\n return style;\n}\nfunction useLayoutItemStyle(state, parentState) {\n return useMemo(() => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n const theme = config.theme2;\n const style = applyItemStyles({}, state, parentState);\n style[theme.breakpoints.down(\"md\")] = {\n maxWidth: (_b = (_a = state.md) == null ? void 0 : _a.maxWidth) != null ? _b : \"unset\",\n maxHeight: (_d = (_c = state.md) == null ? void 0 : _c.maxHeight) != null ? _d : \"unset\",\n height: (_g = (_e = state.md) == null ? void 0 : _e.height) != null ? _g : (_f = parentState.md) == null ? void 0 : _f.height,\n width: (_j = (_h = state.md) == null ? void 0 : _h.width) != null ? _j : (_i = parentState.md) == null ? void 0 : _i.width\n };\n return css(style);\n }, [state, parentState]);\n}\nfunction useLayoutStyle(state, parentState) {\n return useMemo(() => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n const { direction = \"row\", wrap } = state;\n const theme = config.theme2;\n const style = {};\n if (parentState) {\n applyItemStyles(style, state, parentState);\n } else {\n style.display = \"flex\";\n style.flexGrow = 1;\n style.minWidth = state.minWidth;\n style.minHeight = state.minHeight;\n }\n style.flexDirection = direction;\n style.gap = \"8px\";\n style.flexWrap = wrap || \"nowrap\";\n style.alignContent = \"baseline\";\n style.minWidth = style.minWidth || 0;\n style.minHeight = style.minHeight || 0;\n style[theme.breakpoints.down(\"md\")] = {\n flexDirection: (_b = (_a = state.md) == null ? void 0 : _a.direction) != null ? _b : \"column\",\n maxWidth: (_d = (_c = state.md) == null ? void 0 : _c.maxWidth) != null ? _d : \"unset\",\n maxHeight: (_f = (_e = state.md) == null ? void 0 : _e.maxHeight) != null ? _f : \"unset\",\n height: (_h = (_g = state.md) == null ? void 0 : _g.height) != null ? _h : \"unset\",\n width: (_j = (_i = state.md) == null ? void 0 : _i.width) != null ? _j : \"unset\"\n };\n return css(style);\n }, [parentState, state]);\n}\n\nexport { SceneFlexItem, SceneFlexLayout };\n//# sourceMappingURL=SceneFlexLayout.js.map\n","import { css } from '@emotion/css';\nimport React, { useMemo } from 'react';\nimport { SceneObjectBase } from '../../../core/SceneObjectBase.js';\nimport { config } from '@grafana/runtime';\nimport { LazyLoader } from '../LazyLoader.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass SceneCSSGridLayout extends SceneObjectBase {\n constructor(state) {\n var _a, _b;\n super(__spreadValues({\n rowGap: 1,\n columnGap: 1,\n templateColumns: \"repeat(auto-fit, minmax(400px, 1fr))\",\n autoRows: (_a = state.autoRows) != null ? _a : `320px`,\n children: (_b = state.children) != null ? _b : []\n }, state));\n }\n isDraggable() {\n return false;\n }\n}\nSceneCSSGridLayout.Component = SceneCSSGridLayoutRenderer;\nfunction SceneCSSGridLayoutRenderer({ model }) {\n const { children, isHidden, isLazy } = model.useState();\n const style = useLayoutStyle(model.state);\n if (isHidden) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: style\n }, children.map((item) => {\n const Component = item.Component;\n if (isLazy) {\n return /* @__PURE__ */ React.createElement(LazyLoader, {\n key: item.state.key,\n className: style\n }, /* @__PURE__ */ React.createElement(Component, {\n key: item.state.key,\n model: item,\n parentState: model.state\n }));\n }\n return /* @__PURE__ */ React.createElement(Component, {\n key: item.state.key,\n model: item,\n parentState: model.state\n });\n }));\n}\nclass SceneCSSGridItem extends SceneObjectBase {\n}\nSceneCSSGridItem.Component = SceneCSSGridItemRenderer;\nfunction SceneCSSGridItemRenderer({ model, parentState }) {\n if (!parentState) {\n throw new Error(\"SceneCSSGridItem must be a child of SceneCSSGridLayout\");\n }\n const { body, isHidden } = model.useState();\n const style = useItemStyle(model.state);\n if (!body || isHidden) {\n return null;\n }\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: style\n }, /* @__PURE__ */ React.createElement(body.Component, {\n model: body\n }));\n}\nfunction useLayoutStyle(state) {\n return useMemo(() => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;\n const style = {};\n const theme = config.theme2;\n style.display = \"grid\";\n style.gridTemplateColumns = state.templateColumns;\n style.gridTemplateRows = state.templateRows || \"unset\";\n style.gridAutoRows = state.autoRows || \"unset\";\n style.rowGap = theme.spacing((_a = state.rowGap) != null ? _a : 1);\n style.columnGap = theme.spacing((_b = state.columnGap) != null ? _b : 1);\n style.justifyItems = state.justifyItems || \"unset\";\n style.alignItems = state.alignItems || \"unset\";\n style.justifyContent = state.justifyContent || \"unset\";\n style.flexGrow = 1;\n if (state.md) {\n style[theme.breakpoints.down(\"md\")] = {\n gridTemplateRows: (_c = state.md) == null ? void 0 : _c.templateRows,\n gridTemplateColumns: (_d = state.md) == null ? void 0 : _d.templateColumns,\n rowGap: state.md.rowGap ? theme.spacing((_f = (_e = state.md) == null ? void 0 : _e.rowGap) != null ? _f : 1) : void 0,\n columnGap: state.md.columnGap ? theme.spacing((_h = (_g = state.md) == null ? void 0 : _g.rowGap) != null ? _h : 1) : void 0,\n justifyItems: (_i = state.md) == null ? void 0 : _i.justifyItems,\n alignItems: (_j = state.md) == null ? void 0 : _j.alignItems,\n justifyContent: (_k = state.md) == null ? void 0 : _k.justifyContent\n };\n }\n return css(style);\n }, [state]);\n}\nfunction useItemStyle(state) {\n return useMemo(() => {\n const style = {};\n style.gridColumn = state.gridColumn || \"unset\";\n style.gridRow = state.gridRow || \"unset\";\n style.position = \"relative\";\n return css(style);\n }, [state]);\n}\n\nexport { SceneCSSGridItem, SceneCSSGridLayout };\n//# sourceMappingURL=SceneCSSGridLayout.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2 } from '@grafana/ui';\nimport { clamp, throttle } from 'lodash';\nimport React, { useRef, useCallback, useLayoutEffect } from 'react';\nimport { useUniqueId } from '../LazyLoader.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nconst PIXELS_PER_MS = 0.3;\nconst VERTICAL_KEYS = /* @__PURE__ */ new Set([\"ArrowUp\", \"ArrowDown\"]);\nconst HORIZONTAL_KEYS = /* @__PURE__ */ new Set([\"ArrowLeft\", \"ArrowRight\"]);\nconst propsForDirection = {\n row: {\n dim: \"width\",\n axis: \"clientX\",\n min: \"minWidth\",\n max: \"maxWidth\"\n },\n column: {\n dim: \"height\",\n axis: \"clientY\",\n min: \"minHeight\",\n max: \"maxHeight\"\n }\n};\nfunction Splitter({\n direction = \"row\",\n handleSize = 32,\n initialSize = \"auto\",\n primaryPaneStyles,\n secondaryPaneStyles,\n onDragFinished,\n children\n}) {\n const kids = React.Children.toArray(children);\n const splitterRef = useRef(null);\n const firstPaneRef = useRef(null);\n const secondPaneRef = useRef(null);\n const containerRef = useRef(null);\n const containerSize = useRef(null);\n const primarySizeRef = useRef(\"1fr\");\n const firstPaneMeasurements = useRef(void 0);\n const savedPos = useRef(void 0);\n const measurementProp = propsForDirection[direction].dim;\n const clientAxis = propsForDirection[direction].axis;\n const minDimProp = propsForDirection[direction].min;\n const maxDimProp = propsForDirection[direction].max;\n useResizeObserver(\n containerRef.current,\n (entries) => {\n for (const entry of entries) {\n if (!entry.target.isSameNode(containerRef.current)) {\n return;\n }\n const curSize = firstPaneRef.current.getBoundingClientRect()[measurementProp];\n const newDims = measureElement(firstPaneRef.current);\n splitterRef.current.ariaValueNow = `${clamp(\n (curSize - newDims[minDimProp]) / (newDims[maxDimProp] - newDims[minDimProp]) * 100,\n 0,\n 100\n )}`;\n }\n },\n 500,\n [maxDimProp, minDimProp, direction, measurementProp]\n );\n const dragStart = useRef(null);\n const onPointerDown = useCallback(\n (e) => {\n primarySizeRef.current = firstPaneRef.current.getBoundingClientRect()[measurementProp];\n containerSize.current = containerRef.current.getBoundingClientRect()[measurementProp];\n dragStart.current = e[clientAxis];\n splitterRef.current.setPointerCapture(e.pointerId);\n firstPaneMeasurements.current = measureElement(firstPaneRef.current);\n savedPos.current = void 0;\n },\n [measurementProp, clientAxis]\n );\n const onPointerMove = useCallback(\n (e) => {\n if (dragStart.current !== null && primarySizeRef.current !== \"1fr\") {\n const diff = e[clientAxis] - dragStart.current;\n const dims = firstPaneMeasurements.current;\n const newSize = clamp(primarySizeRef.current + diff, dims[minDimProp], dims[maxDimProp]);\n const newFlex = newSize / (containerSize.current - handleSize);\n firstPaneRef.current.style.flexGrow = `${newFlex}`;\n secondPaneRef.current.style.flexGrow = `${1 - newFlex}`;\n const ariaValueNow = clamp(\n (newSize - dims[minDimProp]) / (dims[maxDimProp] - dims[minDimProp]) * 100,\n 0,\n 100\n );\n splitterRef.current.ariaValueNow = `${ariaValueNow}`;\n }\n },\n [handleSize, clientAxis, minDimProp, maxDimProp]\n );\n const onPointerUp = useCallback(\n (e) => {\n e.preventDefault();\n e.stopPropagation();\n splitterRef.current.releasePointerCapture(e.pointerId);\n dragStart.current = null;\n onDragFinished == null ? void 0 : onDragFinished(parseFloat(firstPaneRef.current.style.flexGrow));\n },\n [onDragFinished]\n );\n const pressedKeys = useRef(/* @__PURE__ */ new Set());\n const keysLastHandledAt = useRef(null);\n const handlePressedKeys = useCallback(\n (time) => {\n var _a;\n const nothingPressed = pressedKeys.current.size === 0;\n if (nothingPressed) {\n keysLastHandledAt.current = null;\n return;\n } else if (primarySizeRef.current === \"1fr\") {\n return;\n }\n const dt = time - ((_a = keysLastHandledAt.current) != null ? _a : time);\n const dx = dt * PIXELS_PER_MS;\n let sizeChange = 0;\n if (direction === \"row\") {\n if (pressedKeys.current.has(\"ArrowLeft\")) {\n sizeChange -= dx;\n }\n if (pressedKeys.current.has(\"ArrowRight\")) {\n sizeChange += dx;\n }\n } else {\n if (pressedKeys.current.has(\"ArrowUp\")) {\n sizeChange -= dx;\n }\n if (pressedKeys.current.has(\"ArrowDown\")) {\n sizeChange += dx;\n }\n }\n const firstPaneDims = firstPaneMeasurements.current;\n const curSize = firstPaneRef.current.getBoundingClientRect()[measurementProp];\n const newSize = clamp(curSize + sizeChange, firstPaneDims[minDimProp], firstPaneDims[maxDimProp]);\n const newFlex = newSize / (containerSize.current - handleSize);\n firstPaneRef.current.style.flexGrow = `${newFlex}`;\n secondPaneRef.current.style.flexGrow = `${1 - newFlex}`;\n const ariaValueNow = (newSize - firstPaneDims[minDimProp]) / (firstPaneDims[maxDimProp] - firstPaneDims[minDimProp]) * 100;\n splitterRef.current.ariaValueNow = `${clamp(ariaValueNow, 0, 100)}`;\n keysLastHandledAt.current = time;\n window.requestAnimationFrame(handlePressedKeys);\n },\n [direction, handleSize, minDimProp, maxDimProp, measurementProp]\n );\n const onKeyDown = useCallback(\n (e) => {\n if (e.key === \"Enter\") {\n if (savedPos.current === void 0) {\n savedPos.current = firstPaneRef.current.style.flexGrow;\n firstPaneRef.current.style.flexGrow = \"0\";\n secondPaneRef.current.style.flexGrow = \"1\";\n } else {\n firstPaneRef.current.style.flexGrow = savedPos.current;\n secondPaneRef.current.style.flexGrow = `${1 - parseFloat(savedPos.current)}`;\n savedPos.current = void 0;\n }\n return;\n } else if (e.key === \"Home\") {\n firstPaneMeasurements.current = measureElement(firstPaneRef.current);\n containerSize.current = containerRef.current.getBoundingClientRect()[measurementProp];\n const newFlex = firstPaneMeasurements.current[minDimProp] / (containerSize.current - handleSize);\n firstPaneRef.current.style.flexGrow = `${newFlex}`;\n secondPaneRef.current.style.flexGrow = `${1 - newFlex}`;\n splitterRef.current.ariaValueNow = \"0\";\n return;\n } else if (e.key === \"End\") {\n firstPaneMeasurements.current = measureElement(firstPaneRef.current);\n containerSize.current = containerRef.current.getBoundingClientRect()[measurementProp];\n const newFlex = firstPaneMeasurements.current[maxDimProp] / (containerSize.current - handleSize);\n firstPaneRef.current.style.flexGrow = `${newFlex}`;\n secondPaneRef.current.style.flexGrow = `${1 - newFlex}`;\n splitterRef.current.ariaValueNow = \"100\";\n return;\n }\n if (!(direction === \"column\" && VERTICAL_KEYS.has(e.key) || direction === \"row\" && HORIZONTAL_KEYS.has(e.key)) || pressedKeys.current.has(e.key)) {\n return;\n }\n savedPos.current = void 0;\n e.preventDefault();\n e.stopPropagation();\n primarySizeRef.current = firstPaneRef.current.getBoundingClientRect()[measurementProp];\n containerSize.current = containerRef.current.getBoundingClientRect()[measurementProp];\n firstPaneMeasurements.current = measureElement(firstPaneRef.current);\n const newKey = !pressedKeys.current.has(e.key);\n if (newKey) {\n const initiateAnimationLoop = pressedKeys.current.size === 0;\n pressedKeys.current.add(e.key);\n if (initiateAnimationLoop) {\n window.requestAnimationFrame(handlePressedKeys);\n }\n }\n },\n [direction, handlePressedKeys, handleSize, maxDimProp, measurementProp, minDimProp]\n );\n const onKeyUp = useCallback(\n (e) => {\n if (direction === \"row\" && !HORIZONTAL_KEYS.has(e.key) || direction === \"column\" && !VERTICAL_KEYS.has(e.key)) {\n return;\n }\n pressedKeys.current.delete(e.key);\n onDragFinished == null ? void 0 : onDragFinished(parseFloat(firstPaneRef.current.style.flexGrow));\n },\n [direction, onDragFinished]\n );\n const onDoubleClick = useCallback(() => {\n firstPaneRef.current.style.flexGrow = \"0.5\";\n secondPaneRef.current.style.flexGrow = \"0.5\";\n const dim = measureElement(firstPaneRef.current);\n firstPaneMeasurements.current = dim;\n primarySizeRef.current = firstPaneRef.current.getBoundingClientRect()[measurementProp];\n splitterRef.current.ariaValueNow = `${(primarySizeRef.current - dim[minDimProp]) / (dim[maxDimProp] - dim[minDimProp]) * 100}`;\n }, [maxDimProp, measurementProp, minDimProp]);\n const onBlur = useCallback(() => {\n if (pressedKeys.current.size > 0) {\n pressedKeys.current.clear();\n dragStart.current = null;\n onDragFinished == null ? void 0 : onDragFinished(parseFloat(firstPaneRef.current.style.flexGrow));\n }\n }, [onDragFinished]);\n const styles = useStyles2(getStyles);\n const id = useUniqueId();\n const secondAvailable = kids.length === 2;\n const visibilitySecond = secondAvailable ? \"visible\" : \"hidden\";\n return /* @__PURE__ */ React.createElement(\"div\", {\n ref: containerRef,\n className: styles.container,\n style: {\n flexDirection: direction\n }\n }, /* @__PURE__ */ React.createElement(\"div\", {\n ref: firstPaneRef,\n className: styles.panel,\n style: __spreadValues({\n flexGrow: initialSize === \"auto\" ? 0.5 : clamp(initialSize, 0, 1),\n [minDimProp]: \"min-content\"\n }, primaryPaneStyles),\n id: `start-panel-${id}`\n }, kids[0]), kids[1] && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(\"div\", {\n ref: splitterRef,\n style: { [measurementProp]: `${handleSize}px` },\n className: cx(styles.handle, { [styles.handleHorizontal]: direction === \"column\" }),\n onPointerUp,\n onPointerDown,\n onPointerMove,\n onKeyDown,\n onKeyUp,\n onDoubleClick,\n onBlur,\n role: \"separator\",\n \"aria-valuemin\": 0,\n \"aria-valuemax\": 100,\n \"aria-valuenow\": 50,\n \"aria-controls\": `start-panel-${id}`,\n \"aria-label\": \"Pane resize widget\",\n tabIndex: 0\n }), /* @__PURE__ */ React.createElement(\"div\", {\n ref: secondPaneRef,\n className: styles.panel,\n style: __spreadValues({\n flexGrow: initialSize === \"auto\" ? 0.5 : clamp(1 - initialSize, 0, 1),\n [minDimProp]: \"min-content\",\n visibility: `${visibilitySecond}`\n }, secondaryPaneStyles),\n id: `end-panel-${id}`\n }, kids[1])));\n}\nfunction getStyles(theme) {\n return {\n handle: css({\n cursor: \"col-resize\",\n position: \"relative\",\n flexShrink: 0,\n userSelect: \"none\",\n \"&::before\": {\n content: '\"\"',\n position: \"absolute\",\n backgroundColor: theme.colors.primary.main,\n left: \"50%\",\n transform: \"translate(-50%)\",\n top: 0,\n height: \"100%\",\n width: \"1px\",\n opacity: 0,\n transition: \"opacity ease-in-out 0.2s\"\n },\n \"&::after\": {\n content: '\"\"',\n width: \"4px\",\n borderRadius: \"4px\",\n backgroundColor: theme.colors.border.weak,\n transition: \"background-color ease-in-out 0.2s\",\n height: \"50%\",\n top: \"calc(50% - (50%) / 2)\",\n transform: \"translateX(-50%)\",\n position: \"absolute\",\n left: \"50%\"\n },\n \"&:hover, &:focus-visible\": {\n outline: \"none\",\n \"&::before\": {\n opacity: 1\n },\n \"&::after\": {\n backgroundColor: theme.colors.primary.main\n }\n }\n }),\n handleHorizontal: css({\n cursor: \"row-resize\",\n \"&::before\": {\n left: \"inherit\",\n transform: \"translateY(-50%)\",\n top: \"50%\",\n height: \"1px\",\n width: \"100%\"\n },\n \"&::after\": {\n width: \"50%\",\n height: \"4px\",\n top: \"50%\",\n transform: \"translateY(-50%)\",\n left: \"calc(50% - (50%) / 2)\"\n }\n }),\n container: css({\n display: \"flex\",\n width: \"100%\",\n flexGrow: 1,\n overflow: \"hidden\"\n }),\n panel: css({ display: \"flex\", position: \"relative\", flexBasis: 0 })\n };\n}\nfunction measureElement(ref) {\n if (ref === null) {\n return void 0;\n }\n const savedBodyOverflow = document.body.style.overflow;\n const savedWidth = ref.style.width;\n const savedHeight = ref.style.height;\n const savedFlex = ref.style.flexGrow;\n document.body.style.overflow = \"hidden\";\n ref.style.flexGrow = \"0\";\n const { width: minWidth, height: minHeight } = ref.getBoundingClientRect();\n ref.style.flexGrow = \"100\";\n const { width: maxWidth, height: maxHeight } = ref.getBoundingClientRect();\n document.body.style.overflow = savedBodyOverflow;\n ref.style.width = savedWidth;\n ref.style.height = savedHeight;\n ref.style.flexGrow = savedFlex;\n return { minWidth, maxWidth, minHeight, maxHeight };\n}\nfunction useResizeObserver(target, cb, throttleWait = 0, deps) {\n const throttledCallback = throttle(cb, throttleWait);\n useLayoutEffect(() => {\n if (!target) {\n return;\n }\n const resizeObserver = new ResizeObserver(throttledCallback);\n resizeObserver.observe(target, { box: \"device-pixel-content-box\" });\n return () => resizeObserver.disconnect();\n }, deps);\n}\n\nexport { Splitter };\n//# sourceMappingURL=Splitter.js.map\n","import { SceneObjectBase } from '../../../core/SceneObjectBase.js';\nimport { SplitLayoutRenderer } from './SplitLayoutRenderer.js';\n\nclass SplitLayout extends SceneObjectBase {\n toggleDirection() {\n this.setState({\n direction: this.state.direction === \"row\" ? \"column\" : \"row\"\n });\n }\n isDraggable() {\n return false;\n }\n}\nSplitLayout.Component = SplitLayoutRenderer;\n\nexport { SplitLayout };\n//# sourceMappingURL=SplitLayout.js.map\n","import React from 'react';\nimport { Splitter } from './Splitter.js';\n\nfunction SplitLayoutRenderer({ model }) {\n const { primary, secondary, direction, isHidden, initialSize, primaryPaneStyles, secondaryPaneStyles } = model.useState();\n if (isHidden) {\n return null;\n }\n const Prim = primary.Component;\n const Sec = secondary == null ? void 0 : secondary.Component;\n let startSize = secondary ? initialSize : 1;\n return /* @__PURE__ */ React.createElement(Splitter, {\n direction,\n initialSize: startSize != null ? startSize : 0.5,\n primaryPaneStyles,\n secondaryPaneStyles\n }, /* @__PURE__ */ React.createElement(Prim, {\n key: primary.state.key,\n model: primary,\n parentState: model.state\n }), Sec && secondary && /* @__PURE__ */ React.createElement(Sec, {\n key: secondary.state.key,\n model: secondary,\n parentState: model.state\n }));\n}\n\nexport { SplitLayoutRenderer };\n//# sourceMappingURL=SplitLayoutRenderer.js.map\n","import React, { createContext } from 'react';\nimport { Switch, Route } from 'react-router-dom';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { renderSceneComponentWithRouteProps } from './utils.js';\n\nclass SceneApp extends SceneObjectBase {\n enrichDataRequest() {\n return {\n app: this.state.name || \"app\"\n };\n }\n}\nSceneApp.Component = ({ model }) => {\n const { pages } = model.useState();\n return /* @__PURE__ */ React.createElement(SceneAppContext.Provider, {\n value: model\n }, /* @__PURE__ */ React.createElement(Switch, null, pages.map((page) => /* @__PURE__ */ React.createElement(Route, {\n key: page.state.url,\n exact: false,\n path: page.state.url,\n render: (props) => renderSceneComponentWithRouteProps(page, props)\n }))));\n};\nconst SceneAppContext = createContext(null);\nconst sceneAppCache = /* @__PURE__ */ new Map();\nfunction useSceneApp(factory) {\n const cachedApp = sceneAppCache.get(factory);\n if (cachedApp) {\n return cachedApp;\n }\n const newApp = factory();\n sceneAppCache.set(factory, newApp);\n return newApp;\n}\n\nexport { SceneApp, SceneAppContext, useSceneApp };\n//# sourceMappingURL=SceneApp.js.map\n","import React from 'react';\nimport { SceneObjectBase } from '../core/SceneObjectBase.js';\n\nvar __defProp = Object.defineProperty;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nclass SceneReactObject extends SceneObjectBase {\n}\nSceneReactObject.Component = ({ model }) => {\n const { component: Component, props, reactNode } = model.useState();\n if (Component) {\n return /* @__PURE__ */ React.createElement(Component, __spreadValues({}, props));\n }\n if (reactNode) {\n return reactNode;\n }\n return null;\n};\n\nexport { SceneReactObject };\n//# sourceMappingURL=SceneReactObject.js.map\n","import { css } from '@emotion/css';\nimport { useStyles2, JSONFormatter, Input } from '@grafana/ui';\nimport { isPlainObject, isArray } from 'lodash';\nimport React from 'react';\nimport { isSceneObject } from '../../core/types.js';\n\nfunction DebugDetails({ node }) {\n const state = node.useState();\n const styles = useStyles2(getStyles);\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.container\n }, Object.keys(state).map((key) => /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.row,\n key\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.keyName\n }, key), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.value\n }, renderValue(key, state[key], node)))));\n}\nfunction renderValue(key, value, node) {\n if (value === null) {\n return \"null\";\n }\n switch (typeof value) {\n case \"number\":\n return /* @__PURE__ */ React.createElement(Input, {\n type: \"number\",\n defaultValue: value,\n onBlur: (evt) => node.setState({ [key]: evt.currentTarget.valueAsNumber })\n });\n case \"string\":\n return /* @__PURE__ */ React.createElement(Input, {\n type: \"text\",\n defaultValue: value,\n onBlur: (evt) => node.setState({ [key]: evt.currentTarget.value })\n });\n case \"object\":\n if (isSceneObject(value)) {\n return value.constructor.name;\n }\n if (isPlainObject(value) || isArray(value)) {\n return /* @__PURE__ */ React.createElement(JSONFormatter, {\n json: value,\n open: 0\n });\n }\n return String(value);\n default:\n return typeof value;\n }\n}\nfunction getStyles(theme) {\n return {\n container: css({\n flexGrow: 1,\n display: \"flex\",\n gap: theme.spacing(0.5),\n flexDirection: \"column\"\n }),\n row: css({\n display: \"flex\",\n gap: theme.spacing(2)\n }),\n keyName: css({\n display: \"flex\",\n flexGrow: \"0\",\n width: 120,\n alignItems: \"center\",\n height: theme.spacing(theme.components.height.md)\n }),\n value: css({\n flexGrow: 1,\n minHeight: theme.spacing(theme.components.height.md),\n display: \"flex\",\n alignItems: \"center\"\n })\n };\n}\n\nexport { DebugDetails };\n//# sourceMappingURL=DebugDetails.js.map\n","import { cx, css } from '@emotion/css';\nimport { useStyles2 } from '@grafana/ui';\nimport React from 'react';\n\nfunction DebugTreeNode({ node, selectedObject, onSelect }) {\n const styles = useStyles2(getStyles);\n const children = [];\n const isSelected = node === selectedObject;\n node.forEachChild((child) => {\n children.push(\n /* @__PURE__ */ React.createElement(DebugTreeNode, {\n node: child,\n key: child.state.key,\n selectedObject,\n onSelect\n })\n );\n });\n return /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.container\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: cx(styles.name, isSelected && styles.selected),\n onClick: () => onSelect(node)\n }, node.constructor.name), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.children\n }, children));\n}\nfunction getStyles(theme) {\n return {\n container: css({\n flexGrow: 1,\n display: \"flex\",\n gap: theme.spacing(0.5),\n flexDirection: \"column\"\n }),\n name: css({\n flexGrow: 1,\n display: \"flex\",\n gap: theme.spacing(1),\n fontSize: theme.typography.bodySmall.fontSize,\n cursor: \"pointer\",\n padding: theme.spacing(0, 1),\n borderRadius: theme.shape.borderRadius(2),\n position: \"relative\",\n \"&:hover\": {\n background: theme.colors.background.secondary\n }\n }),\n selected: css({\n \"&::before\": {\n display: \"block\",\n content: \"' '\",\n position: \"absolute\",\n left: 0,\n width: 4,\n bottom: 2,\n top: 2,\n borderRadius: theme.shape.radius.default,\n backgroundImage: theme.colors.gradients.brandVertical\n }\n }),\n children: css({\n flexGrow: 1,\n display: \"flex\",\n flexDirection: \"column\",\n paddingLeft: theme.spacing(1)\n })\n };\n}\n\nexport { DebugTreeNode };\n//# sourceMappingURL=DebugTreeNode.js.map\n","import { css } from '@emotion/css';\nimport { useStyles2, ToolbarButton, Drawer, CustomScrollbar } from '@grafana/ui';\nimport React, { useState } from 'react';\nimport { DebugDetails } from './DebugDetails.js';\nimport { DebugTreeNode } from './DebugTreeNode.js';\n\nfunction SceneDebugger({ scene }) {\n const styles = useStyles2(getStyles);\n const [isOpen, setIsOpen] = useState(false);\n const [selectedObject, setSelectedObject] = useState();\n return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ToolbarButton, {\n variant: \"canvas\",\n icon: \"bug\",\n onClick: () => setIsOpen(true)\n }), isOpen && /* @__PURE__ */ React.createElement(Drawer, {\n title: \"Scene debugger\",\n onClose: () => setIsOpen(false),\n size: \"lg\"\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.panes\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.pane1\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.paneHeading\n }, \"Scene graph\"), /* @__PURE__ */ React.createElement(CustomScrollbar, {\n autoHeightMin: \"100%\"\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.treeWrapper\n }, /* @__PURE__ */ React.createElement(DebugTreeNode, {\n node: scene,\n selectedObject,\n onSelect: setSelectedObject\n })))), /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.pane2\n }, /* @__PURE__ */ React.createElement(\"div\", {\n className: styles.paneHeading\n }, \"Object details\"), selectedObject && /* @__PURE__ */ React.createElement(DebugDetails, {\n node: selectedObject\n })))));\n}\nfunction getStyles(theme) {\n return {\n panes: css({\n flexGrow: 1,\n display: \"flex\",\n height: \"100%\",\n flexDirection: \"row\",\n marginTop: theme.spacing(-2)\n }),\n pane1: css({\n flexGrow: 0,\n display: \"flex\",\n height: \"100%\",\n flexDirection: \"column\",\n borderRight: `1px solid ${theme.colors.border.weak}`\n }),\n pane2: css({\n flexGrow: 1,\n display: \"flex\",\n minHeight: \"100%\",\n flexDirection: \"column\",\n paddingLeft: theme.spacing(2)\n }),\n treeWrapper: css({\n paddingRight: theme.spacing(2),\n height: \"100%\",\n marginLeft: theme.spacing(-1)\n }),\n paneHeading: css({\n padding: theme.spacing(1, 0),\n fontWeight: theme.typography.fontWeightMedium\n })\n };\n}\n\nexport { SceneDebugger };\n//# sourceMappingURL=SceneDebugger.js.map\n","import { PluginPage } from '@grafana/runtime';\nimport React, { useContext, useLayoutEffect, useEffect } from 'react';\nimport { SceneDebugger } from '../SceneDebugger/SceneDebugger.js';\nimport { SceneAppPage } from './SceneAppPage.js';\nimport { useAppQueryParams, getUrlWithAppState, renderSceneComponentWithRouteProps } from './utils.js';\nimport { useUrlSync } from '../../services/useUrlSync.js';\nimport { SceneAppContext } from './SceneApp.js';\nimport { useLocationServiceSafe } from '../../utils/utils.js';\n\nfunction SceneAppPageView({ page, routeProps }) {\n const containerPage = getParentPageIfTab(page);\n const containerState = containerPage.useState();\n const params = useAppQueryParams();\n const scene = page.getScene(routeProps.match);\n const appContext = useContext(SceneAppContext);\n const isInitialized = containerState.initializedScene === scene;\n const { layout } = page.state;\n const locationService = useLocationServiceSafe();\n useLayoutEffect(() => {\n if (!isInitialized) {\n containerPage.initializeScene(scene);\n }\n }, [scene, containerPage, isInitialized]);\n useEffect(() => {\n return () => containerPage.setState({ initializedScene: void 0 });\n }, [containerPage]);\n const urlSyncInitialized = useUrlSync(containerPage, appContext == null ? void 0 : appContext.state.urlSyncOptions);\n if (!isInitialized && !urlSyncInitialized) {\n return null;\n }\n const pageNav = {\n text: containerState.title,\n img: containerState.titleImg,\n icon: containerState.titleIcon,\n url: getUrlWithAppState(containerState.url, locationService.getSearchObject(), containerState.preserveUrlKeys),\n hideFromBreadcrumbs: containerState.hideFromBreadcrumbs,\n parentItem: getParentBreadcrumbs(\n containerState.getParentPage ? containerState.getParentPage() : containerPage.parent,\n params,\n locationService.getSearchObject()\n )\n };\n if (containerState.tabs) {\n pageNav.children = containerState.tabs.map((tab) => {\n return {\n text: tab.state.title,\n icon: tab.state.titleIcon,\n tabSuffix: tab.state.tabSuffix,\n active: page === tab,\n url: getUrlWithAppState(tab.state.url, locationService.getSearchObject(), tab.state.preserveUrlKeys),\n parentItem: pageNav\n };\n });\n }\n let pageActions = [];\n if (containerState.controls) {\n pageActions = containerState.controls.map((control) => /* @__PURE__ */ React.createElement(control.Component, {\n model: control,\n key: control.state.key\n }));\n }\n if (params[\"scene-debugger\"]) {\n pageActions.push(/* @__PURE__ */ React.createElement(SceneDebugger, {\n scene: containerPage,\n key: \"scene-debugger\"\n }));\n }\n return /* @__PURE__ */ React.createElement(PluginPage, {\n layout,\n pageNav,\n actions: pageActions,\n renderTitle: containerState.renderTitle,\n subTitle: containerState.subTitle\n }, /* @__PURE__ */ React.createElement(scene.Component, {\n model: scene\n }));\n}\nfunction getParentPageIfTab(page) {\n if (page.parent instanceof SceneAppPage) {\n return page.parent;\n }\n return page;\n}\nfunction getParentBreadcrumbs(parent, params, searchObject) {\n if (parent instanceof SceneAppPage) {\n return {\n text: parent.state.title,\n url: getUrlWithAppState(parent.state.url, searchObject, parent.state.preserveUrlKeys),\n hideFromBreadcrumbs: parent.state.hideFromBreadcrumbs,\n parentItem: getParentBreadcrumbs(\n parent.state.getParentPage ? parent.state.getParentPage() : parent.parent,\n params,\n searchObject\n )\n };\n }\n return void 0;\n}\nfunction SceneAppDrilldownViewRender({ drilldown, parent, routeProps }) {\n return renderSceneComponentWithRouteProps(parent.getDrilldownPage(drilldown, routeProps.match), routeProps);\n}\n\nexport { SceneAppDrilldownViewRender, SceneAppPageView };\n//# sourceMappingURL=SceneAppPageView.js.map\n","import { useState, useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\nimport { writeSceneLog } from '../utils/writeSceneLog.js';\nimport { useUrlSyncManager } from './UrlSyncManager.js';\nimport { useLocationServiceSafe } from '../utils/utils.js';\n\nfunction useUrlSync(sceneRoot, options = {}) {\n const location = useLocation();\n const locationService = useLocationServiceSafe();\n const [isInitialized, setIsInitialized] = useState(false);\n const urlSyncManager = useUrlSyncManager(options, locationService);\n useEffect(() => {\n urlSyncManager.initSync(sceneRoot);\n setIsInitialized(true);\n return () => urlSyncManager.cleanUp(sceneRoot);\n }, [sceneRoot, urlSyncManager]);\n useEffect(() => {\n const latestLocation = locationService.getLocation();\n const locationToHandle = latestLocation !== location ? latestLocation : location;\n if (latestLocation !== location) {\n writeSceneLog(\"useUrlSync\", \"latestLocation different from location\");\n }\n urlSyncManager.handleNewLocation(locationToHandle);\n }, [sceneRoot, urlSyncManager, location, locationService]);\n return isInitialized;\n}\n\nexport { useUrlSync };\n//# sourceMappingURL=useUrlSync.js.map\n","import React from 'react';\nimport { Route, Switch } from 'react-router-dom';\nimport { SceneObjectBase } from '../../core/SceneObjectBase.js';\nimport { isDataRequestEnricher } from '../../core/types.js';\nimport { EmbeddedScene } from '../EmbeddedScene.js';\nimport { SceneFlexLayout, SceneFlexItem } from '../layout/SceneFlexLayout.js';\nimport { SceneReactObject } from '../SceneReactObject.js';\nimport { SceneAppDrilldownViewRender, SceneAppPageView } from './SceneAppPageView.js';\nimport { renderSceneComponentWithRouteProps } from './utils.js';\n\nclass SceneAppPage extends SceneObjectBase {\n constructor(state) {\n super(state);\n this._sceneCache = /* @__PURE__ */ new Map();\n this._drilldownCache = /* @__PURE__ */ new Map();\n }\n initializeScene(scene) {\n this.setState({ initializedScene: scene });\n }\n getScene(routeMatch) {\n let scene = this._sceneCache.get(routeMatch.url);\n if (scene) {\n return scene;\n }\n if (!this.state.getScene) {\n throw new Error(\"Missing getScene on SceneAppPage \" + this.state.title);\n }\n scene = this.state.getScene(routeMatch);\n this._sceneCache.set(routeMatch.url, scene);\n return scene;\n }\n getDrilldownPage(drilldown, routeMatch) {\n let page = this._drilldownCache.get(routeMatch.url);\n if (page) {\n return page;\n }\n page = drilldown.getPage(routeMatch, this);\n this._drilldownCache.set(routeMatch.url, page);\n return page;\n }\n enrichDataRequest(source) {\n if (this.state.getParentPage) {\n return this.state.getParentPage().enrichDataRequest(source);\n }\n if (!this.parent) {\n return null;\n }\n const root = this.getRoot();\n if (isDataRequestEnricher(root)) {\n return root.enrichDataRequest(source);\n }\n return null;\n }\n}\nSceneAppPage.Component = SceneAppPageRenderer;\nfunction SceneAppPageRenderer({ model, routeProps }) {\n var _a, _b;\n const { tabs, drilldowns } = model.useState();\n const routes = [];\n if (tabs && tabs.length > 0) {\n for (let tabIndex = 0; tabIndex < tabs.length; tabIndex++) {\n const tab = tabs[tabIndex];\n if (tabIndex === 0) {\n routes.push(\n /* @__PURE__ */ React.createElement(Route, {\n exact: true,\n key: model.state.url,\n path: (_a = model.state.routePath) != null ? _a : model.state.url,\n render: (props) => renderSceneComponentWithRouteProps(tab, props)\n })\n );\n }\n routes.push(\n /* @__PURE__ */ React.createElement(Route, {\n exact: true,\n key: tab.state.url,\n path: (_b = tab.state.routePath) != null ? _b : tab.state.url,\n render: (props) => renderSceneComponentWithRouteProps(tab, props)\n })\n );\n if (tab.state.drilldowns) {\n for (const drilldown of tab.state.drilldowns) {\n routes.push(\n /* @__PURE__ */ React.createElement(Route, {\n exact: false,\n key: drilldown.routePath,\n path: drilldown.routePath,\n render: (props) => /* @__PURE__ */ React.createElement(SceneAppDrilldownViewRender, {\n drilldown,\n parent: tab,\n routeProps: props\n })\n })\n );\n }\n }\n }\n }\n if (drilldowns) {\n for (const drilldown of drilldowns) {\n routes.push(\n /* @__PURE__ */ React.createElement(Route, {\n key: drilldown.routePath,\n exact: false,\n path: drilldown.routePath,\n render: (props) => /* @__PURE__ */ React.createElement(SceneAppDrilldownViewRender, {\n drilldown,\n parent: model,\n routeProps: props\n })\n })\n );\n }\n }\n if (!tabs && isCurrentPageRouteMatch(model, routeProps.match)) {\n return /* @__PURE__ */ React.createElement(SceneAppPageView, {\n page: model,\n routeProps\n });\n }\n routes.push(getFallbackRoute(model, routeProps));\n return /* @__PURE__ */ React.createElement(Switch, null, routes);\n}\nfunction getFallbackRoute(page, routeProps) {\n return /* @__PURE__ */ React.createElement(Route, {\n key: \"fallback route\",\n render: (props) => {\n var _a, _b, _c;\n const fallbackPage = (_c = (_b = (_a = page.state).getFallbackPage) == null ? void 0 : _b.call(_a)) != null ? _c : getDefaultFallbackPage();\n return /* @__PURE__ */ React.createElement(SceneAppPageView, {\n page: fallbackPage,\n routeProps\n });\n }\n });\n}\nfunction isCurrentPageRouteMatch(page, match) {\n if (!match.isExact) {\n return false;\n }\n if (match.url === page.state.url) {\n return true;\n }\n if (page.parent instanceof SceneAppPage && page.parent.state.tabs[0] === page && page.parent.state.url === match.url) {\n return true;\n }\n return false;\n}\nfunction getDefaultFallbackPage() {\n return new SceneAppPage({\n url: \"\",\n title: \"Not found\",\n subTitle: \"The url did not match any page\",\n getScene: () => {\n return new EmbeddedScene({\n body: new SceneFlexLayout({\n direction: \"column\",\n children: [\n new SceneFlexItem({\n body: new SceneReactObject({\n component: () => {\n return /* @__PURE__ */ React.createElement(\"div\", {\n \"data-testid\": \"default-fallback-content\"\n }, \"If you found your way here using a link then there might be a bug in this application.\");\n }\n })\n })\n ]\n })\n });\n }\n });\n}\n\nexport { SceneAppPage };\n//# sourceMappingURL=SceneAppPage.js.map\n","var VisibilityMode = /* @__PURE__ */ ((VisibilityMode2) => {\n VisibilityMode2[\"Always\"] = \"always\";\n VisibilityMode2[\"Auto\"] = \"auto\";\n VisibilityMode2[\"Never\"] = \"never\";\n return VisibilityMode2;\n})(VisibilityMode || {});\nvar GraphGradientMode = /* @__PURE__ */ ((GraphGradientMode2) => {\n GraphGradientMode2[\"Hue\"] = \"hue\";\n GraphGradientMode2[\"None\"] = \"none\";\n GraphGradientMode2[\"Opacity\"] = \"opacity\";\n GraphGradientMode2[\"Scheme\"] = \"scheme\";\n return GraphGradientMode2;\n})(GraphGradientMode || {});\nvar StackingMode = /* @__PURE__ */ ((StackingMode2) => {\n StackingMode2[\"None\"] = \"none\";\n StackingMode2[\"Normal\"] = \"normal\";\n StackingMode2[\"Percent\"] = \"percent\";\n return StackingMode2;\n})(StackingMode || {});\nvar VizOrientation = /* @__PURE__ */ ((VizOrientation2) => {\n VizOrientation2[\"Auto\"] = \"auto\";\n VizOrientation2[\"Horizontal\"] = \"horizontal\";\n VizOrientation2[\"Vertical\"] = \"vertical\";\n return VizOrientation2;\n})(VizOrientation || {});\nvar BigValueColorMode = /* @__PURE__ */ ((BigValueColorMode2) => {\n BigValueColorMode2[\"Background\"] = \"background\";\n BigValueColorMode2[\"BackgroundSolid\"] = \"background_solid\";\n BigValueColorMode2[\"None\"] = \"none\";\n BigValueColorMode2[\"Value\"] = \"value\";\n return BigValueColorMode2;\n})(BigValueColorMode || {});\nvar BigValueGraphMode = /* @__PURE__ */ ((BigValueGraphMode2) => {\n BigValueGraphMode2[\"Area\"] = \"area\";\n BigValueGraphMode2[\"Line\"] = \"line\";\n BigValueGraphMode2[\"None\"] = \"none\";\n return BigValueGraphMode2;\n})(BigValueGraphMode || {});\nvar BigValueJustifyMode = /* @__PURE__ */ ((BigValueJustifyMode2) => {\n BigValueJustifyMode2[\"Auto\"] = \"auto\";\n BigValueJustifyMode2[\"Center\"] = \"center\";\n return BigValueJustifyMode2;\n})(BigValueJustifyMode || {});\nvar BigValueTextMode = /* @__PURE__ */ ((BigValueTextMode2) => {\n BigValueTextMode2[\"Auto\"] = \"auto\";\n BigValueTextMode2[\"Name\"] = \"name\";\n BigValueTextMode2[\"None\"] = \"none\";\n BigValueTextMode2[\"Value\"] = \"value\";\n BigValueTextMode2[\"ValueAndName\"] = \"value_and_name\";\n return BigValueTextMode2;\n})(BigValueTextMode || {});\nvar PercentChangeColorMode = /* @__PURE__ */ ((PercentChangeColorMode2) => {\n PercentChangeColorMode2[\"Inverted\"] = \"inverted\";\n PercentChangeColorMode2[\"SameAsValue\"] = \"same_as_value\";\n PercentChangeColorMode2[\"Standard\"] = \"standard\";\n return PercentChangeColorMode2;\n})(PercentChangeColorMode || {});\nvar TooltipDisplayMode = /* @__PURE__ */ ((TooltipDisplayMode2) => {\n TooltipDisplayMode2[\"Multi\"] = \"multi\";\n TooltipDisplayMode2[\"None\"] = \"none\";\n TooltipDisplayMode2[\"Single\"] = \"single\";\n return TooltipDisplayMode2;\n})(TooltipDisplayMode || {});\nvar BarGaugeDisplayMode = /* @__PURE__ */ ((BarGaugeDisplayMode2) => {\n BarGaugeDisplayMode2[\"Basic\"] = \"basic\";\n BarGaugeDisplayMode2[\"Gradient\"] = \"gradient\";\n BarGaugeDisplayMode2[\"Lcd\"] = \"lcd\";\n return BarGaugeDisplayMode2;\n})(BarGaugeDisplayMode || {});\nvar BarGaugeValueMode = /* @__PURE__ */ ((BarGaugeValueMode2) => {\n BarGaugeValueMode2[\"Color\"] = \"color\";\n BarGaugeValueMode2[\"Hidden\"] = \"hidden\";\n BarGaugeValueMode2[\"Text\"] = \"text\";\n return BarGaugeValueMode2;\n})(BarGaugeValueMode || {});\nvar BarGaugeNamePlacement = /* @__PURE__ */ ((BarGaugeNamePlacement2) => {\n BarGaugeNamePlacement2[\"Auto\"] = \"auto\";\n BarGaugeNamePlacement2[\"Hidden\"] = \"hidden\";\n BarGaugeNamePlacement2[\"Left\"] = \"left\";\n BarGaugeNamePlacement2[\"Top\"] = \"top\";\n return BarGaugeNamePlacement2;\n})(BarGaugeNamePlacement || {});\nvar BarGaugeSizing = /* @__PURE__ */ ((BarGaugeSizing2) => {\n BarGaugeSizing2[\"Auto\"] = \"auto\";\n BarGaugeSizing2[\"Manual\"] = \"manual\";\n return BarGaugeSizing2;\n})(BarGaugeSizing || {});\nvar TableCellHeight = /* @__PURE__ */ ((TableCellHeight2) => {\n TableCellHeight2[\"Auto\"] = \"auto\";\n TableCellHeight2[\"Lg\"] = \"lg\";\n TableCellHeight2[\"Md\"] = \"md\";\n TableCellHeight2[\"Sm\"] = \"sm\";\n return TableCellHeight2;\n})(TableCellHeight || {});\n\nexport { BigValueColorMode as B, GraphGradientMode as G, PercentChangeColorMode as P, StackingMode as S, TableCellHeight as T, VisibilityMode as V, BigValueGraphMode as a, BigValueJustifyMode as b, BigValueTextMode as c, TooltipDisplayMode as d, BarGaugeSizing as e, BarGaugeDisplayMode as f, BarGaugeNamePlacement as g, BarGaugeValueMode as h, VizOrientation as i };\n","import { i as VizOrientation, V as VisibilityMode, S as StackingMode, G as GraphGradientMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n barRadius: 0,\n barWidth: 0.97,\n fullHighlight: false,\n groupWidth: 0.7,\n orientation: VizOrientation.Auto,\n showValue: VisibilityMode.Auto,\n stacking: StackingMode.None,\n xTickLabelRotation: 0,\n xTickLabelSpacing: 0\n};\nconst defaultFieldConfig = {\n fillOpacity: 80,\n gradientMode: GraphGradientMode.None,\n lineWidth: 1\n};\n\nexport { defaultFieldConfig, defaultOptions, pluginVersion };\n","import { f as BarGaugeDisplayMode, g as BarGaugeNamePlacement, e as BarGaugeSizing, h as BarGaugeValueMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n displayMode: BarGaugeDisplayMode.Gradient,\n maxVizHeight: 300,\n minVizHeight: 16,\n minVizWidth: 8,\n namePlacement: BarGaugeNamePlacement.Auto,\n showUnfilled: true,\n sizing: BarGaugeSizing.Auto,\n valueMode: BarGaugeValueMode.Color\n};\n\nexport { defaultOptions, pluginVersion };\n","const pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n selectedSeries: 0\n};\n\nexport { defaultOptions, pluginVersion };\n","import { e as BarGaugeSizing } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n minVizHeight: 75,\n minVizWidth: 75,\n showThresholdLabels: false,\n showThresholdMarkers: true,\n sizing: BarGaugeSizing.Auto\n};\n\nexport { defaultOptions, pluginVersion };\n","const pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n layers: []\n};\nconst defaultMapViewConfig = {\n allLayers: true,\n id: \"zero\",\n lat: 0,\n lon: 0,\n zoom: 1\n};\nvar TooltipMode = /* @__PURE__ */ ((TooltipMode2) => {\n TooltipMode2[\"Details\"] = \"details\";\n TooltipMode2[\"None\"] = \"none\";\n return TooltipMode2;\n})(TooltipMode || {});\nvar MapCenterID = /* @__PURE__ */ ((MapCenterID2) => {\n MapCenterID2[\"Coords\"] = \"coords\";\n MapCenterID2[\"Fit\"] = \"fit\";\n MapCenterID2[\"Zero\"] = \"zero\";\n return MapCenterID2;\n})(MapCenterID || {});\n\nexport { MapCenterID, TooltipMode, defaultMapViewConfig, defaultOptions, pluginVersion };\n","import { V as VisibilityMode, d as TooltipDisplayMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nvar HeatmapColorMode = /* @__PURE__ */ ((HeatmapColorMode2) => {\n HeatmapColorMode2[\"Opacity\"] = \"opacity\";\n HeatmapColorMode2[\"Scheme\"] = \"scheme\";\n return HeatmapColorMode2;\n})(HeatmapColorMode || {});\nvar HeatmapColorScale = /* @__PURE__ */ ((HeatmapColorScale2) => {\n HeatmapColorScale2[\"Exponential\"] = \"exponential\";\n HeatmapColorScale2[\"Linear\"] = \"linear\";\n return HeatmapColorScale2;\n})(HeatmapColorScale || {});\nvar HeatmapSelectionMode = /* @__PURE__ */ ((HeatmapSelectionMode2) => {\n HeatmapSelectionMode2[\"X\"] = \"x\";\n HeatmapSelectionMode2[\"Xy\"] = \"xy\";\n HeatmapSelectionMode2[\"Y\"] = \"y\";\n return HeatmapSelectionMode2;\n})(HeatmapSelectionMode || {});\nconst defaultOptions = {\n calculate: false,\n cellGap: 1,\n cellValues: {},\n color: {\n /**\n * mode: HeatmapColorMode // TODO: fix after remove when https://github.com/grafana/cuetsy/issues/74 is fixed\n */\n scheme: \"Oranges\",\n fill: \"dark-orange\",\n /**\n * scale: HeatmapColorScale // TODO: fix after remove when https://github.com/grafana/cuetsy/issues/74 is fixed\n */\n reverse: false,\n exponent: 0.5,\n steps: 64\n },\n exemplars: {\n color: \"rgba(255,0,255,0.7)\"\n },\n filterValues: {\n le: 1e-9\n },\n legend: {\n show: true\n },\n selectionMode: \"x\" /* X */,\n showValue: VisibilityMode.Auto,\n tooltip: {\n mode: TooltipDisplayMode.Single,\n yHistogram: false,\n showColorScale: false\n }\n};\n\nexport { HeatmapColorMode, HeatmapColorScale, HeatmapSelectionMode, defaultOptions, pluginVersion };\n","import { G as GraphGradientMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n bucketCount: 30,\n bucketOffset: 0\n};\nconst defaultFieldConfig = {\n fillOpacity: 80,\n gradientMode: GraphGradientMode.None,\n lineWidth: 1\n};\n\nexport { defaultFieldConfig, defaultOptions, pluginVersion };\n","const pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n showImage: true\n};\n\nexport { defaultOptions, pluginVersion };\n","const pluginVersion = \"11.3.1\";\nvar PieChartType = /* @__PURE__ */ ((PieChartType2) => {\n PieChartType2[\"Donut\"] = \"donut\";\n PieChartType2[\"Pie\"] = \"pie\";\n return PieChartType2;\n})(PieChartType || {});\nvar PieChartLabels = /* @__PURE__ */ ((PieChartLabels2) => {\n PieChartLabels2[\"Name\"] = \"name\";\n PieChartLabels2[\"Percent\"] = \"percent\";\n PieChartLabels2[\"Value\"] = \"value\";\n return PieChartLabels2;\n})(PieChartLabels || {});\nvar PieChartLegendValues = /* @__PURE__ */ ((PieChartLegendValues2) => {\n PieChartLegendValues2[\"Percent\"] = \"percent\";\n PieChartLegendValues2[\"Value\"] = \"value\";\n return PieChartLegendValues2;\n})(PieChartLegendValues || {});\nconst defaultPieChartLegendOptions = {\n values: []\n};\nconst defaultOptions = {\n displayLabels: []\n};\n\nexport { PieChartLabels, PieChartLegendValues, PieChartType, defaultOptions, defaultPieChartLegendOptions, pluginVersion };\n","import { B as BigValueColorMode, a as BigValueGraphMode, b as BigValueJustifyMode, P as PercentChangeColorMode, c as BigValueTextMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n colorMode: BigValueColorMode.Value,\n graphMode: BigValueGraphMode.Area,\n justifyMode: BigValueJustifyMode.Auto,\n percentChangeColorMode: PercentChangeColorMode.Standard,\n showPercentChange: false,\n textMode: BigValueTextMode.Auto,\n wideLayout: true\n};\n\nexport { defaultOptions, pluginVersion };\n","import { V as VisibilityMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n alignValue: \"left\",\n mergeValues: true,\n perPage: 20,\n rowHeight: 0.9,\n showValue: VisibilityMode.Auto\n};\nconst defaultFieldConfig = {\n fillOpacity: 70,\n lineWidth: 0\n};\n\nexport { defaultFieldConfig, defaultOptions, pluginVersion };\n","import { V as VisibilityMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n colWidth: 0.9,\n rowHeight: 0.9,\n showValue: VisibilityMode.Auto\n};\nconst defaultFieldConfig = {\n fillOpacity: 70,\n lineWidth: 1\n};\n\nexport { defaultFieldConfig, defaultOptions, pluginVersion };\n","import { T as TableCellHeight } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nconst defaultOptions = {\n cellHeight: TableCellHeight.Sm,\n footer: {\n /**\n * Controls whether the footer should be shown\n */\n show: false,\n /**\n * Controls whether the footer should show the total number of rows on Count calculation\n */\n countRows: false,\n /**\n * Represents the selected calculations\n */\n reducer: []\n },\n frameIndex: 0,\n showHeader: true,\n showTypeIcons: false,\n sortBy: []\n};\n\nexport { defaultOptions, pluginVersion };\n","const pluginVersion = \"11.3.1\";\nvar TextMode = /* @__PURE__ */ ((TextMode2) => {\n TextMode2[\"Code\"] = \"code\";\n TextMode2[\"HTML\"] = \"html\";\n TextMode2[\"Markdown\"] = \"markdown\";\n return TextMode2;\n})(TextMode || {});\nvar CodeLanguage = /* @__PURE__ */ ((CodeLanguage2) => {\n CodeLanguage2[\"Go\"] = \"go\";\n CodeLanguage2[\"Html\"] = \"html\";\n CodeLanguage2[\"Json\"] = \"json\";\n CodeLanguage2[\"Markdown\"] = \"markdown\";\n CodeLanguage2[\"Plaintext\"] = \"plaintext\";\n CodeLanguage2[\"Sql\"] = \"sql\";\n CodeLanguage2[\"Typescript\"] = \"typescript\";\n CodeLanguage2[\"Xml\"] = \"xml\";\n CodeLanguage2[\"Yaml\"] = \"yaml\";\n return CodeLanguage2;\n})(CodeLanguage || {});\nconst defaultCodeLanguage = \"plaintext\" /* Plaintext */;\nconst defaultCodeOptions = {\n language: \"plaintext\" /* Plaintext */,\n showLineNumbers: false,\n showMiniMap: false\n};\nconst defaultOptions = {\n content: `# Title\n\nFor markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)`,\n mode: \"markdown\" /* Markdown */\n};\n\nexport { CodeLanguage, TextMode, defaultCodeLanguage, defaultCodeOptions, defaultOptions, pluginVersion };\n","import { V as VisibilityMode } from '../../../../../common.gen-CZ1M9G8L.js';\n\nconst pluginVersion = \"11.3.1\";\nvar SeriesMapping = /* @__PURE__ */ ((SeriesMapping2) => {\n SeriesMapping2[\"Auto\"] = \"auto\";\n SeriesMapping2[\"Manual\"] = \"manual\";\n return SeriesMapping2;\n})(SeriesMapping || {});\nvar ScatterShow = /* @__PURE__ */ ((ScatterShow2) => {\n ScatterShow2[\"Lines\"] = \"lines\";\n ScatterShow2[\"Points\"] = \"points\";\n ScatterShow2[\"PointsAndLines\"] = \"points+lines\";\n return ScatterShow2;\n})(ScatterShow || {});\nconst defaultXYDimensionConfig = {\n exclude: []\n};\nconst defaultFieldConfig = {\n label: VisibilityMode.Auto,\n show: \"points\" /* Points */\n};\nconst defaultOptions = {\n series: []\n};\n\nexport { ScatterShow, SeriesMapping, defaultFieldConfig, defaultOptions, defaultXYDimensionConfig, pluginVersion };\n","class StandardFieldConfigOverridesBuilder {\n constructor() {\n this._overrides = [];\n }\n overrideColor(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"color\", value });\n return this;\n }\n overrideDecimals(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"decimals\", value });\n return this;\n }\n overrideDisplayName(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"displayName\", value });\n return this;\n }\n overrideFilterable(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"filterable\", value });\n return this;\n }\n overrideLinks(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"links\", value });\n return this;\n }\n overrideMappings(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"mappings\", value });\n return this;\n }\n overrideMax(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"max\", value });\n return this;\n }\n overrideMin(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"min\", value });\n return this;\n }\n overrideNoValue(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"noValue\", value });\n return this;\n }\n overrideThresholds(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"thresholds\", value });\n return this;\n }\n overrideUnit(value) {\n this._overrides[this._overrides.length - 1].properties.push({ id: \"unit\", value });\n return this;\n }\n}\n\nexport { StandardFieldConfigOverridesBuilder };\n//# sourceMappingURL=StandardFieldConfigBuilders.js.map\n","import { FieldMatcherID } from '@grafana/data';\nimport { getCompareSeriesRefId } from '../../utils/getCompareSeriesRefId.js';\nimport { StandardFieldConfigOverridesBuilder } from './StandardFieldConfigBuilders.js';\n\nclass FieldConfigOverridesBuilder extends StandardFieldConfigOverridesBuilder {\n match(matcher) {\n this._overrides.push({ matcher, properties: [] });\n return this;\n }\n matchFieldsWithName(name) {\n this._overrides.push({\n matcher: {\n id: FieldMatcherID.byName,\n options: name\n },\n properties: []\n });\n return this;\n }\n matchFieldsWithNameByRegex(regex) {\n this._overrides.push({\n matcher: {\n id: FieldMatcherID.byRegexp,\n options: regex\n },\n properties: []\n });\n return this;\n }\n matchFieldsByType(fieldType) {\n this._overrides.push({\n matcher: {\n id: FieldMatcherID.byType,\n options: fieldType\n },\n properties: []\n });\n return this;\n }\n matchFieldsByQuery(refId) {\n this._overrides.push({\n matcher: {\n id: FieldMatcherID.byFrameRefID,\n options: refId\n },\n properties: []\n });\n return this;\n }\n matchFieldsByValue(options) {\n this._overrides.push({\n matcher: {\n id: FieldMatcherID.byValue,\n options\n },\n properties: []\n });\n return this;\n }\n matchComparisonQuery(refId) {\n return this.matchFieldsByQuery(getCompareSeriesRefId(refId));\n }\n overrideCustomFieldConfig(id, value) {\n const _id = `custom.${String(id)}`;\n const last = this._overrides[this._overrides.length - 1];\n last.properties.push({ id: _id, value });\n return this;\n }\n build() {\n return this._overrides;\n }\n}\n\nexport { FieldConfigOverridesBuilder };\n//# sourceMappingURL=FieldConfigOverridesBuilder.js.map\n","import { cloneDeep, merge } from 'lodash';\nimport { FieldConfigOverridesBuilder } from './FieldConfigOverridesBuilder.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass FieldConfigBuilder {\n constructor(defaultFieldConfig) {\n this.defaultFieldConfig = defaultFieldConfig;\n this._fieldConfig = {\n defaults: {},\n overrides: []\n };\n this._overridesBuilder = new FieldConfigOverridesBuilder();\n this.setDefaults();\n }\n setDefaults() {\n const fieldConfig = {\n defaults: {\n custom: this.defaultFieldConfig ? cloneDeep(this.defaultFieldConfig()) : {}\n },\n overrides: []\n };\n this._fieldConfig = fieldConfig;\n }\n setColor(color) {\n return this.setFieldConfigDefaults(\"color\", color);\n }\n setDecimals(decimals) {\n return this.setFieldConfigDefaults(\"decimals\", decimals);\n }\n setDisplayName(displayName) {\n return this.setFieldConfigDefaults(\"displayName\", displayName);\n }\n setFilterable(filterable) {\n return this.setFieldConfigDefaults(\"filterable\", filterable);\n }\n setLinks(links) {\n return this.setFieldConfigDefaults(\"links\", links);\n }\n setMappings(mappings) {\n return this.setFieldConfigDefaults(\"mappings\", mappings);\n }\n setMax(max) {\n return this.setFieldConfigDefaults(\"max\", max);\n }\n setMin(min) {\n return this.setFieldConfigDefaults(\"min\", min);\n }\n setNoValue(noValue) {\n return this.setFieldConfigDefaults(\"noValue\", noValue);\n }\n setThresholds(thresholds) {\n return this.setFieldConfigDefaults(\"thresholds\", thresholds);\n }\n setUnit(unit) {\n return this.setFieldConfigDefaults(\"unit\", unit);\n }\n setCustomFieldConfig(id, value) {\n this._fieldConfig.defaults = __spreadProps(__spreadValues({}, this._fieldConfig.defaults), {\n custom: merge(this._fieldConfig.defaults.custom, { [id]: value })\n });\n return this;\n }\n setOverrides(builder) {\n builder(this._overridesBuilder);\n return this;\n }\n setFieldConfigDefaults(key, value) {\n this._fieldConfig.defaults = __spreadProps(__spreadValues({}, this._fieldConfig.defaults), {\n [key]: value\n });\n return this;\n }\n build() {\n return {\n defaults: this._fieldConfig.defaults,\n overrides: this._overridesBuilder.build()\n };\n }\n}\n\nexport { FieldConfigBuilder };\n//# sourceMappingURL=FieldConfigBuilder.js.map\n","import { cloneDeep, merge } from 'lodash';\n\nclass PanelOptionsBuilder {\n constructor(defaultOptions) {\n this.defaultOptions = defaultOptions;\n this._options = {};\n this.setDefaults();\n }\n setDefaults() {\n this._options = this.defaultOptions ? cloneDeep(this.defaultOptions()) : {};\n }\n setOption(id, value) {\n this._options = merge(this._options, { [id]: value });\n return this;\n }\n build() {\n return this._options;\n }\n}\n\nexport { PanelOptionsBuilder };\n//# sourceMappingURL=PanelOptionsBuilder.js.map\n","import { VizPanel } from '../../components/VizPanel/VizPanel.js';\nimport { FieldConfigBuilder } from './FieldConfigBuilder.js';\nimport { PanelOptionsBuilder } from './PanelOptionsBuilder.js';\n\nvar __defProp = Object.defineProperty;\nvar __defProps = Object.defineProperties;\nvar __getOwnPropDescs = Object.getOwnPropertyDescriptors;\nvar __getOwnPropSymbols = Object.getOwnPropertySymbols;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __propIsEnum = Object.prototype.propertyIsEnumerable;\nvar __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;\nvar __spreadValues = (a, b) => {\n for (var prop in b || (b = {}))\n if (__hasOwnProp.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n if (__getOwnPropSymbols)\n for (var prop of __getOwnPropSymbols(b)) {\n if (__propIsEnum.call(b, prop))\n __defNormalProp(a, prop, b[prop]);\n }\n return a;\n};\nvar __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));\nclass VizPanelBuilder {\n constructor(pluginId, pluginVersion, defaultOptions, defaultFieldConfig) {\n this._state = {};\n this._state.title = \"\";\n this._state.description = \"\";\n this._state.displayMode = \"default\";\n this._state.hoverHeader = false;\n this._state.pluginId = pluginId;\n this._state.pluginVersion = pluginVersion;\n this._fieldConfigBuilder = new FieldConfigBuilder(defaultFieldConfig);\n this._panelOptionsBuilder = new PanelOptionsBuilder(defaultOptions);\n }\n setTitle(title) {\n this._state.title = title;\n return this;\n }\n setDescription(description) {\n this._state.description = description;\n return this;\n }\n setDisplayMode(displayMode) {\n this._state.displayMode = displayMode;\n return this;\n }\n setHoverHeader(hoverHeader) {\n this._state.hoverHeader = hoverHeader;\n return this;\n }\n setShowMenuAlways(showMenuAlways) {\n this._state.showMenuAlways = showMenuAlways;\n return this;\n }\n setMenu(menu) {\n this._state.menu = menu;\n return this;\n }\n setHeaderActions(headerActions) {\n this._state.headerActions = headerActions;\n return this;\n }\n setCollapsible(collapsible) {\n this._state.collapsible = collapsible;\n return this;\n }\n setCollapsed(collapsed) {\n this._state.collapsed = collapsed;\n return this;\n }\n setColor(color) {\n this._fieldConfigBuilder.setColor(color);\n return this;\n }\n setDecimals(decimals) {\n this._fieldConfigBuilder.setDecimals(decimals);\n return this;\n }\n setDisplayName(displayName) {\n this._fieldConfigBuilder.setDisplayName(displayName);\n return this;\n }\n setFilterable(filterable) {\n this._fieldConfigBuilder.setFilterable(filterable);\n return this;\n }\n setLinks(links) {\n this._fieldConfigBuilder.setLinks(links);\n return this;\n }\n setMappings(mappings) {\n this._fieldConfigBuilder.setMappings(mappings);\n return this;\n }\n setMax(max) {\n this._fieldConfigBuilder.setMax(max);\n return this;\n }\n setMin(min) {\n this._fieldConfigBuilder.setMin(min);\n return this;\n }\n setNoValue(noValue) {\n this._fieldConfigBuilder.setNoValue(noValue);\n return this;\n }\n setThresholds(thresholds) {\n this._fieldConfigBuilder.setThresholds(thresholds);\n return this;\n }\n setUnit(unit) {\n this._fieldConfigBuilder.setUnit(unit);\n return this;\n }\n setCustomFieldConfig(id, value) {\n this._fieldConfigBuilder.setCustomFieldConfig(id, value);\n return this;\n }\n setOverrides(builder) {\n this._fieldConfigBuilder.setOverrides(builder);\n return this;\n }\n setOption(id, value) {\n this._panelOptionsBuilder.setOption(id, value);\n return this;\n }\n setData(data) {\n this._state.$data = data;\n return this;\n }\n setTimeRange(timeRange) {\n this._state.$timeRange = timeRange;\n return this;\n }\n setVariables(variables) {\n this._state.$variables = variables;\n return this;\n }\n setBehaviors(behaviors) {\n this._state.$behaviors = behaviors;\n return this;\n }\n setSeriesLimit(seriesLimit) {\n this._state.seriesLimit = seriesLimit;\n return this;\n }\n applyMixin(mixin) {\n mixin(this);\n return this;\n }\n build() {\n const panel = new VizPanel(__spreadProps(__spreadValues({}, this._state), {\n options: this._panelOptionsBuilder.build(),\n fieldConfig: this._fieldConfigBuilder.build()\n }));\n return panel;\n }\n}\n\nexport { VizPanelBuilder };\n//# sourceMappingURL=VizPanelBuilder.js.map\n","import { defaultOptions, defaultFieldConfig } from '@grafana/schema/dist/esm/raw/composable/barchart/panelcfg/x/BarChartPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$1 } from '@grafana/schema/dist/esm/raw/composable/bargauge/panelcfg/x/BarGaugePanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$2 } from '@grafana/schema/dist/esm/raw/composable/datagrid/panelcfg/x/DatagridPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$3 } from '@grafana/schema/dist/esm/raw/composable/gauge/panelcfg/x/GaugePanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$4 } from '@grafana/schema/dist/esm/raw/composable/geomap/panelcfg/x/GeomapPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$5 } from '@grafana/schema/dist/esm/raw/composable/heatmap/panelcfg/x/HeatmapPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$6, defaultFieldConfig as defaultFieldConfig$1 } from '@grafana/schema/dist/esm/raw/composable/histogram/panelcfg/x/HistogramPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$7 } from '@grafana/schema/dist/esm/raw/composable/news/panelcfg/x/NewsPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$8 } from '@grafana/schema/dist/esm/raw/composable/piechart/panelcfg/x/PieChartPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$9 } from '@grafana/schema/dist/esm/raw/composable/stat/panelcfg/x/StatPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$a, defaultFieldConfig as defaultFieldConfig$2 } from '@grafana/schema/dist/esm/raw/composable/statetimeline/panelcfg/x/StateTimelinePanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$b, defaultFieldConfig as defaultFieldConfig$3 } from '@grafana/schema/dist/esm/raw/composable/statushistory/panelcfg/x/StatusHistoryPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$c } from '@grafana/schema/dist/esm/raw/composable/table/panelcfg/x/TablePanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$d } from '@grafana/schema/dist/esm/raw/composable/text/panelcfg/x/TextPanelCfg_types.gen';\nimport { defaultOptions as defaultOptions$e, defaultFieldConfig as defaultFieldConfig$4 } from '@grafana/schema/dist/esm/raw/composable/xychart/panelcfg/x/XYChartPanelCfg_types.gen';\nimport { VizPanelBuilder } from './VizPanelBuilder.js';\nimport 'lodash';\nimport '@grafana/data';\n\nconst PanelBuilders = {\n barchart() {\n return new VizPanelBuilder(\n \"barchart\",\n \"10.0.0\",\n () => defaultOptions,\n () => defaultFieldConfig\n );\n },\n bargauge() {\n return new VizPanelBuilder(\"bargauge\", \"10.0.0\", () => defaultOptions$1);\n },\n datagrid() {\n return new VizPanelBuilder(\"datagrid\", \"10.0.0\", () => defaultOptions$2);\n },\n flamegraph() {\n return new VizPanelBuilder(\"flamegraph\", \"10.0.0\");\n },\n gauge() {\n return new VizPanelBuilder(\"gauge\", \"10.0.0\", () => defaultOptions$3);\n },\n geomap() {\n return new VizPanelBuilder(\"geomap\", \"10.0.0\", () => defaultOptions$4);\n },\n heatmap() {\n return new VizPanelBuilder(\"heatmap\", \"10.0.0\", () => defaultOptions$5);\n },\n histogram() {\n return new VizPanelBuilder(\n \"histogram\",\n \"10.0.0\",\n () => defaultOptions$6,\n () => defaultFieldConfig$1\n );\n },\n logs() {\n return new VizPanelBuilder(\"logs\", \"10.0.0\");\n },\n news() {\n return new VizPanelBuilder(\"news\", \"10.0.0\", () => defaultOptions$7);\n },\n nodegraph() {\n return new VizPanelBuilder(\"nodeGraph\", \"10.0.0\");\n },\n piechart() {\n return new VizPanelBuilder(\n \"piechart\",\n \"10.0.0\",\n () => defaultOptions$8\n );\n },\n stat() {\n return new VizPanelBuilder(\"stat\", \"10.0.0\", () => defaultOptions$9);\n },\n statetimeline() {\n return new VizPanelBuilder(\n \"state-timeline\",\n \"10.0.0\",\n () => defaultOptions$a,\n () => defaultFieldConfig$2\n );\n },\n statushistory() {\n return new VizPanelBuilder(\n \"status-history\",\n \"10.0.0\",\n () => defaultOptions$b,\n () => defaultFieldConfig$3\n );\n },\n table() {\n return new VizPanelBuilder(\"table\", \"10.0.0\", () => defaultOptions$c);\n },\n text() {\n return new VizPanelBuilder(\"text\", \"10.0.0\", () => defaultOptions$d);\n },\n timeseries() {\n return new VizPanelBuilder(\"timeseries\", \"10.0.0\");\n },\n trend() {\n return new VizPanelBuilder(\"trend\", \"10.0.0\");\n },\n traces() {\n return new VizPanelBuilder(\"traces\", \"10.0.0\");\n },\n xychart() {\n return new VizPanelBuilder(\n \"xychart\",\n \"10.0.0\",\n () => defaultOptions$e,\n () => defaultFieldConfig$4\n );\n }\n};\n\nexport { PanelBuilders };\n//# sourceMappingURL=index.js.map\n","import { defaultFieldConfig } from '@grafana/schema/dist/esm/raw/composable/barchart/panelcfg/x/BarChartPanelCfg_types.gen';\nimport { defaultFieldConfig as defaultFieldConfig$1 } from '@grafana/schema/dist/esm/raw/composable/histogram/panelcfg/x/HistogramPanelCfg_types.gen';\nimport { defaultFieldConfig as defaultFieldConfig$2 } from '@grafana/schema/dist/esm/raw/composable/statetimeline/panelcfg/x/StateTimelinePanelCfg_types.gen';\nimport { defaultFieldConfig as defaultFieldConfig$3 } from '@grafana/schema/dist/esm/raw/composable/statushistory/panelcfg/x/StatusHistoryPanelCfg_types.gen';\nimport { defaultFieldConfig as defaultFieldConfig$4 } from '@grafana/schema/dist/esm/raw/composable/xychart/panelcfg/x/XYChartPanelCfg_types.gen';\nimport { FieldConfigBuilder } from './FieldConfigBuilder.js';\n\nconst FieldConfigBuilders = {\n barchart() {\n return new FieldConfigBuilder(() => defaultFieldConfig);\n },\n bargauge() {\n return new FieldConfigBuilder();\n },\n datagrid() {\n return new FieldConfigBuilder();\n },\n flamegraph() {\n return new FieldConfigBuilder();\n },\n gauge() {\n return new FieldConfigBuilder();\n },\n geomap() {\n return new FieldConfigBuilder();\n },\n heatmap() {\n return new FieldConfigBuilder();\n },\n histogram() {\n return new FieldConfigBuilder(() => defaultFieldConfig$1);\n },\n logs() {\n return new FieldConfigBuilder();\n },\n news() {\n return new FieldConfigBuilder();\n },\n nodegraph() {\n return new FieldConfigBuilder();\n },\n piechart() {\n return new FieldConfigBuilder();\n },\n stat() {\n return new FieldConfigBuilder();\n },\n statetimeline() {\n return new FieldConfigBuilder(() => defaultFieldConfig$2);\n },\n statushistory() {\n return new FieldConfigBuilder(() => defaultFieldConfig$3);\n },\n table() {\n return new FieldConfigBuilder();\n },\n text() {\n return new FieldConfigBuilder();\n },\n timeseries() {\n return new FieldConfigBuilder();\n },\n trend() {\n return new FieldConfigBuilder();\n },\n traces() {\n return new FieldConfigBuilder();\n },\n xychart() {\n return new FieldConfigBuilder(() => defaultFieldConfig$4);\n }\n};\n\nexport { FieldConfigBuilders };\n//# sourceMappingURL=FieldConfigBuilders.js.map\n","import { getUrlWithAppState } from './components/SceneApp/utils.js';\nimport { registerRuntimePanelPlugin } from './components/VizPanel/registerRuntimePanelPlugin.js';\nimport { cloneSceneObjectState } from './core/sceneGraph/utils.js';\nimport { registerRuntimeDataSource } from './querying/RuntimeDataSource.js';\nexport { RuntimeDataSource, registerRuntimeDataSource } from './querying/RuntimeDataSource.js';\nimport { syncStateFromSearchParams, getUrlState } from './services/utils.js';\nimport { registerVariableMacro } from './variables/macros/index.js';\nimport { renderPrometheusLabelFilters, escapeLabelValueInRegexSelector, escapeLabelValueInExactSelector, escapeURLDelimiters } from './variables/utils.js';\nimport { isAdHocVariable, isConstantVariable, isCustomVariable, isDataSourceVariable, isIntervalVariable, isQueryVariable, isTextBoxVariable, isGroupByVariable } from './variables/variants/guards.js';\nexport { isDataLayer, isDataRequestEnricher, isFiltersRequestEnricher, isSceneObject } from './core/types.js';\nexport { SceneObjectStateChangedEvent, UserActionEvent } from './core/events.js';\nexport { sceneGraph } from './core/sceneGraph/index.js';\nimport * as index from './behaviors/index.js';\nexport { index as behaviors };\nimport * as index$1 from './querying/layers/index.js';\nexport { index$1 as dataLayers };\nexport { SceneObjectBase, useSceneObjectState } from './core/SceneObjectBase.js';\nexport { SceneDataNode } from './core/SceneDataNode.js';\nexport { SceneTimeRange } from './core/SceneTimeRange.js';\nexport { SceneTimeZoneOverride } from './core/SceneTimeZoneOverride.js';\nexport { SceneQueryRunner } from './querying/SceneQueryRunner.js';\nexport { DataProviderProxy } from './querying/DataProviderProxy.js';\nexport { SceneDataLayerSet, SceneDataLayerSetBase } from './querying/SceneDataLayerSet.js';\nexport { SceneDataLayerBase } from './querying/layers/SceneDataLayerBase.js';\nexport { SceneDataLayerControls } from './querying/layers/SceneDataLayerControls.js';\nexport { SceneDataTransformer } from './querying/SceneDataTransformer.js';\nexport { registerQueryWithController } from './querying/registerQueryWithController.js';\nexport { SceneVariableValueChangedEvent, isCustomVariableValue } from './variables/types.js';\nexport { VariableDependencyConfig } from './variables/VariableDependencyConfig.js';\nexport { formatRegistry } from './variables/interpolation/formatRegistry.js';\nexport { VariableValueSelectWrapper, VariableValueSelectors } from './variables/components/VariableValueSelectors.js';\nexport { VariableValueControl } from './variables/components/VariableValueControl.js';\nexport { SceneVariableSet } from './variables/sets/SceneVariableSet.js';\nexport { ConstantVariable } from './variables/variants/ConstantVariable.js';\nexport { CustomVariable } from './variables/variants/CustomVariable.js';\nexport { DataSourceVariable } from './variables/variants/DataSourceVariable.js';\nexport { QueryVariable } from './variables/variants/query/QueryVariable.js';\nexport { TestVariable } from './variables/variants/TestVariable.js';\nexport { TextBoxVariable } from './variables/variants/TextBoxVariable.js';\nexport { MultiValueVariable } from './variables/variants/MultiValueVariable.js';\nexport { LocalValueVariable } from './variables/variants/LocalValueVariable.js';\nexport { IntervalVariable } from './variables/variants/IntervalVariable.js';\nexport { AdHocFiltersVariable } from './variables/adhoc/AdHocFiltersVariable.js';\nexport { GroupByVariable } from './variables/groupby/GroupByVariable.js';\nexport { NewSceneObjectAddedEvent, UrlSyncManager } from './services/UrlSyncManager.js';\nexport { useUrlSync } from './services/useUrlSync.js';\nexport { UrlSyncContextProvider } from './services/UrlSyncContextProvider.js';\nexport { SceneObjectUrlSyncConfig } from './services/SceneObjectUrlSyncConfig.js';\nexport { EmbeddedScene } from './components/EmbeddedScene.js';\nexport { VizPanel } from './components/VizPanel/VizPanel.js';\nexport { VizPanelMenu } from './components/VizPanel/VizPanelMenu.js';\nexport { VizPanelExploreButton } from './components/VizPanel/VizPanelExploreButton.js';\nexport { NestedScene } from './components/NestedScene.js';\nexport { SceneCanvasText } from './components/SceneCanvasText.js';\nexport { SceneToolbarButton, SceneToolbarInput } from './components/SceneToolbarButton.js';\nexport { SceneTimePicker } from './components/SceneTimePicker.js';\nexport { SceneRefreshPicker } from './components/SceneRefreshPicker.js';\nexport { SceneTimeRangeTransformerBase } from './core/SceneTimeRangeTransformerBase.js';\nexport { SceneTimeRangeCompare } from './components/SceneTimeRangeCompare.js';\nexport { SceneByFrameRepeater } from './components/SceneByFrameRepeater.js';\nexport { SceneByVariableRepeater } from './components/SceneByVariableRepeater.js';\nexport { SceneControlsSpacer } from './components/SceneControlsSpacer.js';\nexport { SceneFlexItem, SceneFlexLayout } from './components/layout/SceneFlexLayout.js';\nexport { SceneCSSGridItem, SceneCSSGridLayout } from './components/layout/CSSGrid/SceneCSSGridLayout.js';\nexport { SceneGridLayout } from './components/layout/grid/SceneGridLayout.js';\nexport { SceneGridItem } from './components/layout/grid/SceneGridItem.js';\nexport { SceneGridRow } from './components/layout/grid/SceneGridRow.js';\nexport { SplitLayout } from './components/layout/split/SplitLayout.js';\nexport { SceneApp, useSceneApp } from './components/SceneApp/SceneApp.js';\nexport { SceneAppPage } from './components/SceneApp/SceneAppPage.js';\nexport { SceneReactObject } from './components/SceneReactObject.js';\nexport { SceneObjectRef } from './core/SceneObjectRef.js';\nexport { PanelBuilders } from './core/PanelBuilders/index.js';\nexport { FieldConfigBuilder } from './core/PanelBuilders/FieldConfigBuilder.js';\nexport { VizPanelBuilder } from './core/PanelBuilders/VizPanelBuilder.js';\nexport { SceneDebugger } from './components/SceneDebugger/SceneDebugger.js';\nexport { ControlsLabel } from './utils/ControlsLabel.js';\nexport { renderSelectForVariable } from './variables/components/VariableValueSelect.js';\nexport { VizConfigBuilder } from './core/PanelBuilders/VizConfigBuilder.js';\nexport { VizConfigBuilders } from './core/PanelBuilders/VizConfigBuilders.js';\nexport { SafeSerializableSceneObject } from './utils/SafeSerializableSceneObject.js';\nexport { getExploreURL } from './utils/explore.js';\nexport { PanelOptionsBuilders } from './core/PanelBuilders/PanelOptionsBuilders.js';\nexport { FieldConfigBuilders } from './core/PanelBuilders/FieldConfigBuilders.js';\nexport { FieldConfigOverridesBuilder } from './core/PanelBuilders/FieldConfigOverridesBuilder.js';\n\nconst sceneUtils = {\n getUrlWithAppState,\n registerRuntimePanelPlugin,\n registerRuntimeDataSource,\n registerVariableMacro,\n cloneSceneObjectState,\n syncStateFromSearchParams,\n getUrlState,\n renderPrometheusLabelFilters,\n escapeLabelValueInRegexSelector,\n escapeLabelValueInExactSelector,\n escapeURLDelimiters,\n isAdHocVariable,\n isConstantVariable,\n isCustomVariable,\n isDataSourceVariable,\n isIntervalVariable,\n isQueryVariable,\n isTextBoxVariable,\n isGroupByVariable\n};\n\nexport { sceneUtils };\n//# sourceMappingURL=index.js.map\n","function isAdHocVariable(variable) {\n return variable.state.type === \"adhoc\";\n}\nfunction isConstantVariable(variable) {\n return variable.state.type === \"constant\";\n}\nfunction isCustomVariable(variable) {\n return variable.state.type === \"custom\";\n}\nfunction isDataSourceVariable(variable) {\n return variable.state.type === \"datasource\";\n}\nfunction isIntervalVariable(variable) {\n return variable.state.type === \"interval\";\n}\nfunction isQueryVariable(variable) {\n return variable.state.type === \"query\";\n}\nfunction isTextBoxVariable(variable) {\n return variable.state.type === \"textbox\";\n}\nfunction isGroupByVariable(variable) {\n return variable.state.type === \"groupby\";\n}\n\nexport { isAdHocVariable, isConstantVariable, isCustomVariable, isDataSourceVariable, isGroupByVariable, isIntervalVariable, isQueryVariable, isTextBoxVariable };\n//# sourceMappingURL=guards.js.map\n","var DataTopic = /* @__PURE__ */ ((DataTopic2) => {\n DataTopic2[\"AlertStates\"] = \"alertStates\";\n DataTopic2[\"Annotations\"] = \"annotations\";\n DataTopic2[\"Series\"] = \"series\";\n return DataTopic2;\n})(DataTopic || {});\nvar ScaleDimensionMode = /* @__PURE__ */ ((ScaleDimensionMode2) => {\n ScaleDimensionMode2[\"Linear\"] = \"linear\";\n ScaleDimensionMode2[\"Quad\"] = \"quad\";\n return ScaleDimensionMode2;\n})(ScaleDimensionMode || {});\nvar ScalarDimensionMode = /* @__PURE__ */ ((ScalarDimensionMode2) => {\n ScalarDimensionMode2[\"Clamped\"] = \"clamped\";\n ScalarDimensionMode2[\"Mod\"] = \"mod\";\n return ScalarDimensionMode2;\n})(ScalarDimensionMode || {});\nvar TextDimensionMode = /* @__PURE__ */ ((TextDimensionMode2) => {\n TextDimensionMode2[\"Field\"] = \"field\";\n TextDimensionMode2[\"Fixed\"] = \"fixed\";\n TextDimensionMode2[\"Template\"] = \"template\";\n return TextDimensionMode2;\n})(TextDimensionMode || {});\nvar ResourceDimensionMode = /* @__PURE__ */ ((ResourceDimensionMode2) => {\n ResourceDimensionMode2[\"Field\"] = \"field\";\n ResourceDimensionMode2[\"Fixed\"] = \"fixed\";\n ResourceDimensionMode2[\"Mapping\"] = \"mapping\";\n return ResourceDimensionMode2;\n})(ResourceDimensionMode || {});\nvar FrameGeometrySourceMode = /* @__PURE__ */ ((FrameGeometrySourceMode2) => {\n FrameGeometrySourceMode2[\"Auto\"] = \"auto\";\n FrameGeometrySourceMode2[\"Coords\"] = \"coords\";\n FrameGeometrySourceMode2[\"Geohash\"] = \"geohash\";\n FrameGeometrySourceMode2[\"Lookup\"] = \"lookup\";\n return FrameGeometrySourceMode2;\n})(FrameGeometrySourceMode || {});\nvar HeatmapCalculationMode = /* @__PURE__ */ ((HeatmapCalculationMode2) => {\n HeatmapCalculationMode2[\"Count\"] = \"count\";\n HeatmapCalculationMode2[\"Size\"] = \"size\";\n return HeatmapCalculationMode2;\n})(HeatmapCalculationMode || {});\nvar HeatmapCellLayout = /* @__PURE__ */ ((HeatmapCellLayout2) => {\n HeatmapCellLayout2[\"auto\"] = \"auto\";\n HeatmapCellLayout2[\"ge\"] = \"ge\";\n HeatmapCellLayout2[\"le\"] = \"le\";\n HeatmapCellLayout2[\"unknown\"] = \"unknown\";\n return HeatmapCellLayout2;\n})(HeatmapCellLayout || {});\nvar LogsSortOrder = /* @__PURE__ */ ((LogsSortOrder2) => {\n LogsSortOrder2[\"Ascending\"] = \"Ascending\";\n LogsSortOrder2[\"Descending\"] = \"Descending\";\n return LogsSortOrder2;\n})(LogsSortOrder || {});\nvar AxisPlacement = /* @__PURE__ */ ((AxisPlacement2) => {\n AxisPlacement2[\"Auto\"] = \"auto\";\n AxisPlacement2[\"Bottom\"] = \"bottom\";\n AxisPlacement2[\"Hidden\"] = \"hidden\";\n AxisPlacement2[\"Left\"] = \"left\";\n AxisPlacement2[\"Right\"] = \"right\";\n AxisPlacement2[\"Top\"] = \"top\";\n return AxisPlacement2;\n})(AxisPlacement || {});\nvar AxisColorMode = /* @__PURE__ */ ((AxisColorMode2) => {\n AxisColorMode2[\"Series\"] = \"series\";\n AxisColorMode2[\"Text\"] = \"text\";\n return AxisColorMode2;\n})(AxisColorMode || {});\nvar VisibilityMode = /* @__PURE__ */ ((VisibilityMode2) => {\n VisibilityMode2[\"Always\"] = \"always\";\n VisibilityMode2[\"Auto\"] = \"auto\";\n VisibilityMode2[\"Never\"] = \"never\";\n return VisibilityMode2;\n})(VisibilityMode || {});\nvar GraphDrawStyle = /* @__PURE__ */ ((GraphDrawStyle2) => {\n GraphDrawStyle2[\"Bars\"] = \"bars\";\n GraphDrawStyle2[\"Line\"] = \"line\";\n GraphDrawStyle2[\"Points\"] = \"points\";\n return GraphDrawStyle2;\n})(GraphDrawStyle || {});\nvar GraphTransform = /* @__PURE__ */ ((GraphTransform2) => {\n GraphTransform2[\"Constant\"] = \"constant\";\n GraphTransform2[\"NegativeY\"] = \"negative-Y\";\n return GraphTransform2;\n})(GraphTransform || {});\nvar LineInterpolation = /* @__PURE__ */ ((LineInterpolation2) => {\n LineInterpolation2[\"Linear\"] = \"linear\";\n LineInterpolation2[\"Smooth\"] = \"smooth\";\n LineInterpolation2[\"StepAfter\"] = \"stepAfter\";\n LineInterpolation2[\"StepBefore\"] = \"stepBefore\";\n return LineInterpolation2;\n})(LineInterpolation || {});\nvar ScaleDistribution = /* @__PURE__ */ ((ScaleDistribution2) => {\n ScaleDistribution2[\"Linear\"] = \"linear\";\n ScaleDistribution2[\"Log\"] = \"log\";\n ScaleDistribution2[\"Ordinal\"] = \"ordinal\";\n ScaleDistribution2[\"Symlog\"] = \"symlog\";\n return ScaleDistribution2;\n})(ScaleDistribution || {});\nvar GraphGradientMode = /* @__PURE__ */ ((GraphGradientMode2) => {\n GraphGradientMode2[\"Hue\"] = \"hue\";\n GraphGradientMode2[\"None\"] = \"none\";\n GraphGradientMode2[\"Opacity\"] = \"opacity\";\n GraphGradientMode2[\"Scheme\"] = \"scheme\";\n return GraphGradientMode2;\n})(GraphGradientMode || {});\nvar StackingMode = /* @__PURE__ */ ((StackingMode2) => {\n StackingMode2[\"None\"] = \"none\";\n StackingMode2[\"Normal\"] = \"normal\";\n StackingMode2[\"Percent\"] = \"percent\";\n return StackingMode2;\n})(StackingMode || {});\nvar BarAlignment = /* @__PURE__ */ ((BarAlignment2) => {\n BarAlignment2[BarAlignment2[\"After\"] = 1] = \"After\";\n BarAlignment2[BarAlignment2[\"Before\"] = -1] = \"Before\";\n BarAlignment2[BarAlignment2[\"Center\"] = 0] = \"Center\";\n return BarAlignment2;\n})(BarAlignment || {});\nvar ScaleOrientation = /* @__PURE__ */ ((ScaleOrientation2) => {\n ScaleOrientation2[ScaleOrientation2[\"Horizontal\"] = 0] = \"Horizontal\";\n ScaleOrientation2[ScaleOrientation2[\"Vertical\"] = 1] = \"Vertical\";\n return ScaleOrientation2;\n})(ScaleOrientation || {});\nvar ScaleDirection = /* @__PURE__ */ ((ScaleDirection2) => {\n ScaleDirection2[ScaleDirection2[\"Down\"] = -1] = \"Down\";\n ScaleDirection2[ScaleDirection2[\"Left\"] = -1] = \"Left\";\n ScaleDirection2[ScaleDirection2[\"Right\"] = 1] = \"Right\";\n ScaleDirection2[ScaleDirection2[\"Up\"] = 1] = \"Up\";\n return ScaleDirection2;\n})(ScaleDirection || {});\nconst defaultLineStyle = {\n dash: []\n};\nvar GraphThresholdsStyleMode = /* @__PURE__ */ ((GraphThresholdsStyleMode2) => {\n GraphThresholdsStyleMode2[\"Area\"] = \"area\";\n GraphThresholdsStyleMode2[\"Dashed\"] = \"dashed\";\n GraphThresholdsStyleMode2[\"DashedAndArea\"] = \"dashed+area\";\n GraphThresholdsStyleMode2[\"Line\"] = \"line\";\n GraphThresholdsStyleMode2[\"LineAndArea\"] = \"line+area\";\n GraphThresholdsStyleMode2[\"Off\"] = \"off\";\n GraphThresholdsStyleMode2[\"Series\"] = \"series\";\n return GraphThresholdsStyleMode2;\n})(GraphThresholdsStyleMode || {});\nvar LegendDisplayMode = /* @__PURE__ */ ((LegendDisplayMode2) => {\n LegendDisplayMode2[\"Hidden\"] = \"hidden\";\n LegendDisplayMode2[\"List\"] = \"list\";\n LegendDisplayMode2[\"Table\"] = \"table\";\n return LegendDisplayMode2;\n})(LegendDisplayMode || {});\nconst defaultReduceDataOptions = {\n calcs: []\n};\nvar VizOrientation = /* @__PURE__ */ ((VizOrientation2) => {\n VizOrientation2[\"Auto\"] = \"auto\";\n VizOrientation2[\"Horizontal\"] = \"horizontal\";\n VizOrientation2[\"Vertical\"] = \"vertical\";\n return VizOrientation2;\n})(VizOrientation || {});\nconst defaultOptionsWithTimezones = {\n timezone: []\n};\nvar BigValueColorMode = /* @__PURE__ */ ((BigValueColorMode2) => {\n BigValueColorMode2[\"Background\"] = \"background\";\n BigValueColorMode2[\"BackgroundSolid\"] = \"background_solid\";\n BigValueColorMode2[\"None\"] = \"none\";\n BigValueColorMode2[\"Value\"] = \"value\";\n return BigValueColorMode2;\n})(BigValueColorMode || {});\nvar BigValueGraphMode = /* @__PURE__ */ ((BigValueGraphMode2) => {\n BigValueGraphMode2[\"Area\"] = \"area\";\n BigValueGraphMode2[\"Line\"] = \"line\";\n BigValueGraphMode2[\"None\"] = \"none\";\n return BigValueGraphMode2;\n})(BigValueGraphMode || {});\nvar BigValueJustifyMode = /* @__PURE__ */ ((BigValueJustifyMode2) => {\n BigValueJustifyMode2[\"Auto\"] = \"auto\";\n BigValueJustifyMode2[\"Center\"] = \"center\";\n return BigValueJustifyMode2;\n})(BigValueJustifyMode || {});\nvar BigValueTextMode = /* @__PURE__ */ ((BigValueTextMode2) => {\n BigValueTextMode2[\"Auto\"] = \"auto\";\n BigValueTextMode2[\"Name\"] = \"name\";\n BigValueTextMode2[\"None\"] = \"none\";\n BigValueTextMode2[\"Value\"] = \"value\";\n BigValueTextMode2[\"ValueAndName\"] = \"value_and_name\";\n return BigValueTextMode2;\n})(BigValueTextMode || {});\nvar PercentChangeColorMode = /* @__PURE__ */ ((PercentChangeColorMode2) => {\n PercentChangeColorMode2[\"Inverted\"] = \"inverted\";\n PercentChangeColorMode2[\"SameAsValue\"] = \"same_as_value\";\n PercentChangeColorMode2[\"Standard\"] = \"standard\";\n return PercentChangeColorMode2;\n})(PercentChangeColorMode || {});\nvar TooltipDisplayMode = /* @__PURE__ */ ((TooltipDisplayMode2) => {\n TooltipDisplayMode2[\"Multi\"] = \"multi\";\n TooltipDisplayMode2[\"None\"] = \"none\";\n TooltipDisplayMode2[\"Single\"] = \"single\";\n return TooltipDisplayMode2;\n})(TooltipDisplayMode || {});\nvar SortOrder = /* @__PURE__ */ ((SortOrder2) => {\n SortOrder2[\"Ascending\"] = \"asc\";\n SortOrder2[\"Descending\"] = \"desc\";\n SortOrder2[\"None\"] = \"none\";\n return SortOrder2;\n})(SortOrder || {});\nconst defaultVizLegendOptions = {\n calcs: []\n};\nvar BarGaugeDisplayMode = /* @__PURE__ */ ((BarGaugeDisplayMode2) => {\n BarGaugeDisplayMode2[\"Basic\"] = \"basic\";\n BarGaugeDisplayMode2[\"Gradient\"] = \"gradient\";\n BarGaugeDisplayMode2[\"Lcd\"] = \"lcd\";\n return BarGaugeDisplayMode2;\n})(BarGaugeDisplayMode || {});\nvar BarGaugeValueMode = /* @__PURE__ */ ((BarGaugeValueMode2) => {\n BarGaugeValueMode2[\"Color\"] = \"color\";\n BarGaugeValueMode2[\"Hidden\"] = \"hidden\";\n BarGaugeValueMode2[\"Text\"] = \"text\";\n return BarGaugeValueMode2;\n})(BarGaugeValueMode || {});\nvar BarGaugeNamePlacement = /* @__PURE__ */ ((BarGaugeNamePlacement2) => {\n BarGaugeNamePlacement2[\"Auto\"] = \"auto\";\n BarGaugeNamePlacement2[\"Hidden\"] = \"hidden\";\n BarGaugeNamePlacement2[\"Left\"] = \"left\";\n BarGaugeNamePlacement2[\"Top\"] = \"top\";\n return BarGaugeNamePlacement2;\n})(BarGaugeNamePlacement || {});\nvar BarGaugeSizing = /* @__PURE__ */ ((BarGaugeSizing2) => {\n BarGaugeSizing2[\"Auto\"] = \"auto\";\n BarGaugeSizing2[\"Manual\"] = \"manual\";\n return BarGaugeSizing2;\n})(BarGaugeSizing || {});\nvar TableCellDisplayMode = /* @__PURE__ */ ((TableCellDisplayMode2) => {\n TableCellDisplayMode2[\"Auto\"] = \"auto\";\n TableCellDisplayMode2[\"BasicGauge\"] = \"basic\";\n TableCellDisplayMode2[\"ColorBackground\"] = \"color-background\";\n TableCellDisplayMode2[\"ColorBackgroundSolid\"] = \"color-background-solid\";\n TableCellDisplayMode2[\"ColorText\"] = \"color-text\";\n TableCellDisplayMode2[\"Custom\"] = \"custom\";\n TableCellDisplayMode2[\"DataLinks\"] = \"data-links\";\n TableCellDisplayMode2[\"Gauge\"] = \"gauge\";\n TableCellDisplayMode2[\"GradientGauge\"] = \"gradient-gauge\";\n TableCellDisplayMode2[\"Image\"] = \"image\";\n TableCellDisplayMode2[\"JSONView\"] = \"json-view\";\n TableCellDisplayMode2[\"LcdGauge\"] = \"lcd-gauge\";\n TableCellDisplayMode2[\"Sparkline\"] = \"sparkline\";\n return TableCellDisplayMode2;\n})(TableCellDisplayMode || {});\nvar TableCellBackgroundDisplayMode = /* @__PURE__ */ ((TableCellBackgroundDisplayMode2) => {\n TableCellBackgroundDisplayMode2[\"Basic\"] = \"basic\";\n TableCellBackgroundDisplayMode2[\"Gradient\"] = \"gradient\";\n return TableCellBackgroundDisplayMode2;\n})(TableCellBackgroundDisplayMode || {});\nconst defaultTableFooterOptions = {\n fields: [],\n reducer: []\n};\nvar TableCellHeight = /* @__PURE__ */ ((TableCellHeight2) => {\n TableCellHeight2[\"Auto\"] = \"auto\";\n TableCellHeight2[\"Lg\"] = \"lg\";\n TableCellHeight2[\"Md\"] = \"md\";\n TableCellHeight2[\"Sm\"] = \"sm\";\n return TableCellHeight2;\n})(TableCellHeight || {});\nvar VariableFormatID = /* @__PURE__ */ ((VariableFormatID2) => {\n VariableFormatID2[\"CSV\"] = \"csv\";\n VariableFormatID2[\"Date\"] = \"date\";\n VariableFormatID2[\"Distributed\"] = \"distributed\";\n VariableFormatID2[\"DoubleQuote\"] = \"doublequote\";\n VariableFormatID2[\"Glob\"] = \"glob\";\n VariableFormatID2[\"HTML\"] = \"html\";\n VariableFormatID2[\"JSON\"] = \"json\";\n VariableFormatID2[\"Lucene\"] = \"lucene\";\n VariableFormatID2[\"PercentEncode\"] = \"percentencode\";\n VariableFormatID2[\"Pipe\"] = \"pipe\";\n VariableFormatID2[\"QueryParam\"] = \"queryparam\";\n VariableFormatID2[\"Raw\"] = \"raw\";\n VariableFormatID2[\"Regex\"] = \"regex\";\n VariableFormatID2[\"SQLString\"] = \"sqlstring\";\n VariableFormatID2[\"SingleQuote\"] = \"singlequote\";\n VariableFormatID2[\"Text\"] = \"text\";\n VariableFormatID2[\"UriEncode\"] = \"uriencode\";\n return VariableFormatID2;\n})(VariableFormatID || {});\nvar LogsDedupStrategy = /* @__PURE__ */ ((LogsDedupStrategy2) => {\n LogsDedupStrategy2[\"exact\"] = \"exact\";\n LogsDedupStrategy2[\"none\"] = \"none\";\n LogsDedupStrategy2[\"numbers\"] = \"numbers\";\n LogsDedupStrategy2[\"signature\"] = \"signature\";\n return LogsDedupStrategy2;\n})(LogsDedupStrategy || {});\nvar ComparisonOperation = /* @__PURE__ */ ((ComparisonOperation2) => {\n ComparisonOperation2[\"EQ\"] = \"eq\";\n ComparisonOperation2[\"GT\"] = \"gt\";\n ComparisonOperation2[\"GTE\"] = \"gte\";\n ComparisonOperation2[\"LT\"] = \"lt\";\n ComparisonOperation2[\"LTE\"] = \"lte\";\n ComparisonOperation2[\"NEQ\"] = \"neq\";\n return ComparisonOperation2;\n})(ComparisonOperation || {});\nconst defaultTimeZone = \"browser\";\n\nexport { AxisColorMode, AxisPlacement, BarAlignment, BarGaugeDisplayMode, BarGaugeNamePlacement, BarGaugeSizing, BarGaugeValueMode, BigValueColorMode, BigValueGraphMode, BigValueJustifyMode, BigValueTextMode, ComparisonOperation, DataTopic, FrameGeometrySourceMode, GraphDrawStyle, GraphGradientMode, GraphThresholdsStyleMode, GraphTransform, HeatmapCalculationMode, HeatmapCellLayout, LegendDisplayMode, LineInterpolation, LogsDedupStrategy, LogsSortOrder, PercentChangeColorMode, ResourceDimensionMode, ScalarDimensionMode, ScaleDimensionMode, ScaleDirection, ScaleDistribution, ScaleOrientation, SortOrder, StackingMode, TableCellBackgroundDisplayMode, TableCellDisplayMode, TableCellHeight, TextDimensionMode, TooltipDisplayMode, VariableFormatID, VisibilityMode, VizOrientation, defaultLineStyle, defaultOptionsWithTimezones, defaultReduceDataOptions, defaultTableFooterOptions, defaultTimeZone, defaultVizLegendOptions };\n//# sourceMappingURL=common.gen.js.map\n","const defaultAnnotationTarget = {\n tags: []\n};\nconst defaultAnnotationPanelFilter = {\n exclude: false,\n ids: []\n};\nconst defaultAnnotationContainer = {\n list: []\n};\nconst defaultAnnotationQuery = {\n builtIn: 0,\n enable: true,\n hide: false\n};\nconst defaultVariableModel = {\n includeAll: false,\n multi: false,\n options: [],\n skipUrlSync: false\n};\nvar VariableRefresh = /* @__PURE__ */ ((VariableRefresh2) => {\n VariableRefresh2[VariableRefresh2[\"never\"] = 0] = \"never\";\n VariableRefresh2[VariableRefresh2[\"onDashboardLoad\"] = 1] = \"onDashboardLoad\";\n VariableRefresh2[VariableRefresh2[\"onTimeRangeChanged\"] = 2] = \"onTimeRangeChanged\";\n return VariableRefresh2;\n})(VariableRefresh || {});\nvar VariableSort = /* @__PURE__ */ ((VariableSort2) => {\n VariableSort2[VariableSort2[\"alphabeticalAsc\"] = 1] = \"alphabeticalAsc\";\n VariableSort2[VariableSort2[\"alphabeticalCaseInsensitiveAsc\"] = 5] = \"alphabeticalCaseInsensitiveAsc\";\n VariableSort2[VariableSort2[\"alphabeticalCaseInsensitiveDesc\"] = 6] = \"alphabeticalCaseInsensitiveDesc\";\n VariableSort2[VariableSort2[\"alphabeticalDesc\"] = 2] = \"alphabeticalDesc\";\n VariableSort2[VariableSort2[\"disabled\"] = 0] = \"disabled\";\n VariableSort2[VariableSort2[\"naturalAsc\"] = 7] = \"naturalAsc\";\n VariableSort2[VariableSort2[\"naturalDesc\"] = 8] = \"naturalDesc\";\n VariableSort2[VariableSort2[\"numericalAsc\"] = 3] = \"numericalAsc\";\n VariableSort2[VariableSort2[\"numericalDesc\"] = 4] = \"numericalDesc\";\n return VariableSort2;\n})(VariableSort || {});\nconst defaultDashboardLink = {\n asDropdown: false,\n includeVars: false,\n keepTime: false,\n tags: [],\n targetBlank: false\n};\nvar FieldColorModeId = /* @__PURE__ */ ((FieldColorModeId2) => {\n FieldColorModeId2[\"ContinuousBlPu\"] = \"continuous-BlPu\";\n FieldColorModeId2[\"ContinuousBlYlRd\"] = \"continuous-BlYlRd\";\n FieldColorModeId2[\"ContinuousBlues\"] = \"continuous-blues\";\n FieldColorModeId2[\"ContinuousGrYlRd\"] = \"continuous-GrYlRd\";\n FieldColorModeId2[\"ContinuousGreens\"] = \"continuous-greens\";\n FieldColorModeId2[\"ContinuousPurples\"] = \"continuous-purples\";\n FieldColorModeId2[\"ContinuousRdYlGr\"] = \"continuous-RdYlGr\";\n FieldColorModeId2[\"ContinuousReds\"] = \"continuous-reds\";\n FieldColorModeId2[\"ContinuousYlBl\"] = \"continuous-YlBl\";\n FieldColorModeId2[\"ContinuousYlRd\"] = \"continuous-YlRd\";\n FieldColorModeId2[\"Fixed\"] = \"fixed\";\n FieldColorModeId2[\"PaletteClassic\"] = \"palette-classic\";\n FieldColorModeId2[\"PaletteClassicByName\"] = \"palette-classic-by-name\";\n FieldColorModeId2[\"Shades\"] = \"shades\";\n FieldColorModeId2[\"Thresholds\"] = \"thresholds\";\n return FieldColorModeId2;\n})(FieldColorModeId || {});\nconst defaultGridPos = {\n h: 9,\n w: 12,\n x: 0,\n y: 0\n};\nvar ThresholdsMode = /* @__PURE__ */ ((ThresholdsMode2) => {\n ThresholdsMode2[\"Absolute\"] = \"absolute\";\n ThresholdsMode2[\"Percentage\"] = \"percentage\";\n return ThresholdsMode2;\n})(ThresholdsMode || {});\nconst defaultThresholdsConfig = {\n steps: []\n};\nvar MappingType = /* @__PURE__ */ ((MappingType2) => {\n MappingType2[\"RangeToText\"] = \"range\";\n MappingType2[\"RegexToText\"] = \"regex\";\n MappingType2[\"SpecialValue\"] = \"special\";\n MappingType2[\"ValueToText\"] = \"value\";\n return MappingType2;\n})(MappingType || {});\nvar SpecialValueMatch = /* @__PURE__ */ ((SpecialValueMatch2) => {\n SpecialValueMatch2[\"Empty\"] = \"empty\";\n SpecialValueMatch2[\"False\"] = \"false\";\n SpecialValueMatch2[\"NaN\"] = \"nan\";\n SpecialValueMatch2[\"Null\"] = \"null\";\n SpecialValueMatch2[\"NullAndNan\"] = \"null+nan\";\n SpecialValueMatch2[\"True\"] = \"true\";\n return SpecialValueMatch2;\n})(SpecialValueMatch || {});\nconst defaultTimePickerConfig = {\n hidden: false,\n refresh_intervals: [\"5s\", \"10s\", \"30s\", \"1m\", \"5m\", \"15m\", \"30m\", \"1h\", \"2h\", \"1d\"],\n time_options: [\"5m\", \"15m\", \"1h\", \"6h\", \"12h\", \"24h\", \"2d\", \"7d\", \"30d\"]\n};\nvar DashboardCursorSync = /* @__PURE__ */ ((DashboardCursorSync2) => {\n DashboardCursorSync2[DashboardCursorSync2[\"Crosshair\"] = 1] = \"Crosshair\";\n DashboardCursorSync2[DashboardCursorSync2[\"Off\"] = 0] = \"Off\";\n DashboardCursorSync2[DashboardCursorSync2[\"Tooltip\"] = 2] = \"Tooltip\";\n return DashboardCursorSync2;\n})(DashboardCursorSync || {});\nconst defaultDashboardCursorSync = 0 /* Off */;\nconst defaultPanel = {\n links: [],\n repeatDirection: \"h\",\n targets: [],\n transformations: [],\n transparent: false\n};\nconst defaultFieldConfigSource = {\n overrides: []\n};\nconst defaultMatcherConfig = {\n id: \"\"\n};\nconst defaultFieldConfig = {\n links: [],\n mappings: []\n};\nconst defaultRowPanel = {\n collapsed: false,\n panels: []\n};\nconst defaultDashboard = {\n editable: true,\n fiscalYearStartMonth: 0,\n graphTooltip: 0 /* Off */,\n links: [],\n panels: [],\n schemaVersion: 39,\n tags: [],\n timezone: \"browser\"\n};\n\nexport { DashboardCursorSync, FieldColorModeId, MappingType, SpecialValueMatch, ThresholdsMode, VariableRefresh, VariableSort, defaultAnnotationContainer, defaultAnnotationPanelFilter, defaultAnnotationQuery, defaultAnnotationTarget, defaultDashboard, defaultDashboardCursorSync, defaultDashboardLink, defaultFieldConfig, defaultFieldConfigSource, defaultGridPos, defaultMatcherConfig, defaultPanel, defaultRowPanel, defaultThresholdsConfig, defaultTimePickerConfig, defaultVariableModel };\n//# sourceMappingURL=dashboard_types.gen.js.map\n","import { defaultDashboard as defaultDashboard$1, defaultVariableModel as defaultVariableModel$1, defaultTimePickerConfig as defaultTimePickerConfig$1, defaultPanel as defaultPanel$1, defaultRowPanel as defaultRowPanel$1, defaultFieldConfig as defaultFieldConfig$1, defaultFieldConfigSource as defaultFieldConfigSource$1, defaultMatcherConfig as defaultMatcherConfig$1, defaultAnnotationQuery as defaultAnnotationQuery$1, defaultAnnotationContainer as defaultAnnotationContainer$1 } from '../raw/dashboard/x/dashboard_types.gen.js';\n\nvar VariableHide = /* @__PURE__ */ ((VariableHide2) => {\n VariableHide2[VariableHide2[\"dontHide\"] = 0] = \"dontHide\";\n VariableHide2[VariableHide2[\"hideLabel\"] = 1] = \"hideLabel\";\n VariableHide2[VariableHide2[\"hideVariable\"] = 2] = \"hideVariable\";\n return VariableHide2;\n})(VariableHide || {});\nconst defaultDashboard = defaultDashboard$1;\nconst defaultVariableModel = {\n ...defaultVariableModel$1\n};\nconst defaultTimePickerConfig = defaultTimePickerConfig$1;\nconst defaultPanel = defaultPanel$1;\nconst defaultRowPanel = defaultRowPanel$1;\nconst defaultFieldConfig = defaultFieldConfig$1;\nconst defaultFieldConfigSource = defaultFieldConfigSource$1;\nconst defaultMatcherConfig = defaultMatcherConfig$1;\nconst defaultAnnotationQuery = defaultAnnotationQuery$1;\nconst defaultAnnotationContainer = defaultAnnotationContainer$1;\n\nexport { VariableHide, defaultAnnotationContainer, defaultAnnotationQuery, defaultDashboard, defaultFieldConfig, defaultFieldConfigSource, defaultMatcherConfig, defaultPanel, defaultRowPanel, defaultTimePickerConfig, defaultVariableModel };\n//# sourceMappingURL=dashboard.types.js.map\n","import { jsx } from 'react/jsx-runtime';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport memoize from 'micro-memoize';\nimport * as React from 'react';\nimport { useContext } from 'react';\nimport { ThemeContext } from '@grafana/data';\nimport { stylesFactory } from './stylesFactory.js';\n\nlet ThemeContextMock = null;\nconst memoizedStyleCreators = /* @__PURE__ */ new WeakMap();\nconst withTheme = (Component) => {\n const WithTheme = (props) => {\n const ContextComponent = ThemeContextMock || ThemeContext;\n return (\n // @ts-ignore\n /* @__PURE__ */ jsx(ContextComponent.Consumer, { children: (theme) => /* @__PURE__ */ jsx(Component, { ...props, theme: theme.v1 }) })\n );\n };\n WithTheme.displayName = `WithTheme(${Component.displayName})`;\n hoistNonReactStatics(WithTheme, Component);\n return WithTheme;\n};\nconst withTheme2 = (Component) => {\n const WithTheme = (props) => {\n const ContextComponent = ThemeContextMock || ThemeContext;\n return (\n // @ts-ignore\n /* @__PURE__ */ jsx(ContextComponent.Consumer, { children: (theme) => /* @__PURE__ */ jsx(Component, { ...props, theme }) })\n );\n };\n WithTheme.displayName = `WithTheme(${Component.displayName})`;\n hoistNonReactStatics(WithTheme, Component);\n return WithTheme;\n};\nfunction useTheme() {\n return useContext(ThemeContextMock || ThemeContext).v1;\n}\nfunction useTheme2() {\n return useContext(ThemeContextMock || ThemeContext);\n}\nfunction useStyles(getStyles) {\n const theme = useTheme();\n let memoizedStyleCreator = memoizedStyleCreators.get(getStyles);\n if (!memoizedStyleCreator) {\n memoizedStyleCreator = stylesFactory(getStyles);\n memoizedStyleCreators.set(getStyles, memoizedStyleCreator);\n }\n return memoizedStyleCreator(theme);\n}\nfunction useStyles2(getStyles, ...additionalArguments) {\n const theme = useTheme2();\n let memoizedStyleCreator = memoizedStyleCreators.get(getStyles);\n if (!memoizedStyleCreator) {\n memoizedStyleCreator = memoize(getStyles, { maxSize: 10 });\n memoizedStyleCreators.set(getStyles, memoizedStyleCreator);\n }\n return memoizedStyleCreator(theme, ...additionalArguments);\n}\nconst mockThemeContext = (theme) => {\n ThemeContextMock = React.createContext(theme);\n return () => {\n ThemeContextMock = null;\n };\n};\n\nexport { memoizedStyleCreators, mockThemeContext, useStyles, useStyles2, useTheme, useTheme2, withTheme, withTheme2 };\n//# sourceMappingURL=ThemeContext.js.map\n","import { useState, useRef, useEffect } from 'react';\n\nfunction areInputsEqual(newInputs, lastInputs) {\n if (newInputs.length !== lastInputs.length) {\n return false;\n }\n\n for (var i = 0; i < newInputs.length; i++) {\n if (newInputs[i] !== lastInputs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction useMemoOne(getResult, inputs) {\n var initial = useState(function () {\n return {\n inputs: inputs,\n result: getResult()\n };\n })[0];\n var isFirstRun = useRef(true);\n var committed = useRef(initial);\n var useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs));\n var cache = useCache ? committed.current : {\n inputs: inputs,\n result: getResult()\n };\n useEffect(function () {\n isFirstRun.current = false;\n committed.current = cache;\n }, [cache]);\n return cache.result;\n}\nfunction useCallbackOne(callback, inputs) {\n return useMemoOne(function () {\n return callback;\n }, inputs);\n}\nvar useMemo = useMemoOne;\nvar useCallback = useCallbackOne;\n\nexport { useCallback, useCallbackOne, useMemo, useMemoOne };\n","import invariant from 'tiny-invariant';\n\nvar getRect = function getRect(_ref) {\n var top = _ref.top,\n right = _ref.right,\n bottom = _ref.bottom,\n left = _ref.left;\n var width = right - left;\n var height = bottom - top;\n var rect = {\n top: top,\n right: right,\n bottom: bottom,\n left: left,\n width: width,\n height: height,\n x: left,\n y: top,\n center: {\n x: (right + left) / 2,\n y: (bottom + top) / 2\n }\n };\n return rect;\n};\nvar expand = function expand(target, expandBy) {\n return {\n top: target.top - expandBy.top,\n left: target.left - expandBy.left,\n bottom: target.bottom + expandBy.bottom,\n right: target.right + expandBy.right\n };\n};\nvar shrink = function shrink(target, shrinkBy) {\n return {\n top: target.top + shrinkBy.top,\n left: target.left + shrinkBy.left,\n bottom: target.bottom - shrinkBy.bottom,\n right: target.right - shrinkBy.right\n };\n};\n\nvar shift = function shift(target, shiftBy) {\n return {\n top: target.top + shiftBy.y,\n left: target.left + shiftBy.x,\n bottom: target.bottom + shiftBy.y,\n right: target.right + shiftBy.x\n };\n};\n\nvar noSpacing = {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n};\nvar createBox = function createBox(_ref2) {\n var borderBox = _ref2.borderBox,\n _ref2$margin = _ref2.margin,\n margin = _ref2$margin === void 0 ? noSpacing : _ref2$margin,\n _ref2$border = _ref2.border,\n border = _ref2$border === void 0 ? noSpacing : _ref2$border,\n _ref2$padding = _ref2.padding,\n padding = _ref2$padding === void 0 ? noSpacing : _ref2$padding;\n var marginBox = getRect(expand(borderBox, margin));\n var paddingBox = getRect(shrink(borderBox, border));\n var contentBox = getRect(shrink(paddingBox, padding));\n return {\n marginBox: marginBox,\n borderBox: getRect(borderBox),\n paddingBox: paddingBox,\n contentBox: contentBox,\n margin: margin,\n border: border,\n padding: padding\n };\n};\n\nvar parse = function parse(raw) {\n var value = raw.slice(0, -2);\n var suffix = raw.slice(-2);\n\n if (suffix !== 'px') {\n return 0;\n }\n\n var result = Number(value);\n !!isNaN(result) ? process.env.NODE_ENV !== \"production\" ? invariant(false, \"Could not parse value [raw: \" + raw + \", without suffix: \" + value + \"]\") : invariant(false) : void 0;\n return result;\n};\n\nvar getWindowScroll = function getWindowScroll() {\n return {\n x: window.pageXOffset,\n y: window.pageYOffset\n };\n};\n\nvar offset = function offset(original, change) {\n var borderBox = original.borderBox,\n border = original.border,\n margin = original.margin,\n padding = original.padding;\n var shifted = shift(borderBox, change);\n return createBox({\n borderBox: shifted,\n border: border,\n margin: margin,\n padding: padding\n });\n};\nvar withScroll = function withScroll(original, scroll) {\n if (scroll === void 0) {\n scroll = getWindowScroll();\n }\n\n return offset(original, scroll);\n};\nvar calculateBox = function calculateBox(borderBox, styles) {\n var margin = {\n top: parse(styles.marginTop),\n right: parse(styles.marginRight),\n bottom: parse(styles.marginBottom),\n left: parse(styles.marginLeft)\n };\n var padding = {\n top: parse(styles.paddingTop),\n right: parse(styles.paddingRight),\n bottom: parse(styles.paddingBottom),\n left: parse(styles.paddingLeft)\n };\n var border = {\n top: parse(styles.borderTopWidth),\n right: parse(styles.borderRightWidth),\n bottom: parse(styles.borderBottomWidth),\n left: parse(styles.borderLeftWidth)\n };\n return createBox({\n borderBox: borderBox,\n margin: margin,\n padding: padding,\n border: border\n });\n};\nvar getBox = function getBox(el) {\n var borderBox = el.getBoundingClientRect();\n var styles = window.getComputedStyle(el);\n return calculateBox(borderBox, styles);\n};\n\nexport { calculateBox, createBox, expand, getBox, getRect, offset, shrink, withScroll };\n","var isProduction = process.env.NODE_ENV === 'production';\nvar prefix = 'Invariant failed';\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new Error(prefix);\n }\n var provided = typeof message === 'function' ? message() : message;\n var value = provided ? \"\".concat(prefix, \": \").concat(provided) : prefix;\n throw new Error(value);\n}\n\nexport { invariant as default };\n","var safeIsNaN = Number.isNaN ||\n function ponyfill(value) {\n return typeof value === 'number' && value !== value;\n };\nfunction isEqual(first, second) {\n if (first === second) {\n return true;\n }\n if (safeIsNaN(first) && safeIsNaN(second)) {\n return true;\n }\n return false;\n}\nfunction areInputsEqual(newInputs, lastInputs) {\n if (newInputs.length !== lastInputs.length) {\n return false;\n }\n for (var i = 0; i < newInputs.length; i++) {\n if (!isEqual(newInputs[i], lastInputs[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction memoizeOne(resultFn, isEqual) {\n if (isEqual === void 0) { isEqual = areInputsEqual; }\n var cache = null;\n function memoized() {\n var newArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n newArgs[_i] = arguments[_i];\n }\n if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) {\n return cache.lastResult;\n }\n var lastResult = resultFn.apply(this, newArgs);\n cache = {\n lastResult: lastResult,\n lastArgs: newArgs,\n lastThis: this,\n };\n return lastResult;\n }\n memoized.clear = function clear() {\n cache = null;\n };\n return memoized;\n}\n\nexport { memoizeOne as default };\n","var rafSchd = function rafSchd(fn) {\n var lastArgs = [];\n var frameId = null;\n\n var wrapperFn = function wrapperFn() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n lastArgs = args;\n\n if (frameId) {\n return;\n }\n\n frameId = requestAnimationFrame(function () {\n frameId = null;\n fn.apply(void 0, lastArgs);\n });\n };\n\n wrapperFn.cancel = function () {\n if (!frameId) {\n return;\n }\n\n cancelAnimationFrame(frameId);\n frameId = null;\n };\n\n return wrapperFn;\n};\n\nexport default rafSchd;\n","function _extends() {\n return _extends = Object.assign ? Object.assign.bind() : function (n) {\n for (var e = 1; e < arguments.length; e++) {\n var t = arguments[e];\n for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);\n }\n return n;\n }, _extends.apply(null, arguments);\n}\nexport { _extends as default };","import React, { useLayoutEffect as useLayoutEffect$1, useEffect, useRef, useState, useContext } from 'react';\nimport ReactDOM, { flushSync } from 'react-dom';\nimport { createStore as createStore$1, applyMiddleware, compose, bindActionCreators } from 'redux';\nimport { Provider, connect } from 'react-redux';\nimport { useMemo, useCallback } from 'use-memo-one';\nimport { getRect, expand, offset, withScroll, calculateBox, getBox, createBox } from 'css-box-model';\nimport memoizeOne from 'memoize-one';\nimport rafSchd from 'raf-schd';\nimport _extends from '@babel/runtime/helpers/esm/extends';\n\nconst isProduction$1 = process.env.NODE_ENV === 'production';\nconst spacesAndTabs = /[ \\t]{2,}/g;\nconst lineStartWithSpaces = /^[ \\t]*/gm;\nconst clean$2 = value => value.replace(spacesAndTabs, ' ').replace(lineStartWithSpaces, '').trim();\nconst getDevMessage = message => clean$2(`\n %c@hello-pangea/dnd\n\n %c${clean$2(message)}\n\n %c👷 This is a development only message. It will be removed in production builds.\n`);\nconst getFormattedMessage = message => [getDevMessage(message), 'color: #00C584; font-size: 1.2em; font-weight: bold;', 'line-height: 1.5', 'color: #723874;'];\nconst isDisabledFlag = '__@hello-pangea/dnd-disable-dev-warnings';\nfunction log(type, message) {\n if (isProduction$1) {\n return;\n }\n if (typeof window !== 'undefined' && window[isDisabledFlag]) {\n return;\n }\n console[type](...getFormattedMessage(message));\n}\nconst warning = log.bind(null, 'warn');\nconst error = log.bind(null, 'error');\n\nfunction noop$2() {}\n\nfunction getOptions(shared, fromBinding) {\n return {\n ...shared,\n ...fromBinding\n };\n}\nfunction bindEvents(el, bindings, sharedOptions) {\n const unbindings = bindings.map(binding => {\n const options = getOptions(sharedOptions, binding.options);\n el.addEventListener(binding.eventName, binding.fn, options);\n return function unbind() {\n el.removeEventListener(binding.eventName, binding.fn, options);\n };\n });\n return function unbindAll() {\n unbindings.forEach(unbind => {\n unbind();\n });\n };\n}\n\nconst isProduction = process.env.NODE_ENV === 'production';\nconst prefix$1 = 'Invariant failed';\nclass RbdInvariant extends Error {}\nRbdInvariant.prototype.toString = function toString() {\n return this.message;\n};\nfunction invariant(condition, message) {\n if (condition) {\n return;\n }\n if (isProduction) {\n throw new RbdInvariant(prefix$1);\n } else {\n throw new RbdInvariant(`${prefix$1}: ${message || ''}`);\n }\n}\n\nclass ErrorBoundary extends React.Component {\n constructor(...args) {\n super(...args);\n this.callbacks = null;\n this.unbind = noop$2;\n this.onWindowError = event => {\n const callbacks = this.getCallbacks();\n if (callbacks.isDragging()) {\n callbacks.tryAbort();\n process.env.NODE_ENV !== \"production\" ? warning(`\n An error was caught by our window 'error' event listener while a drag was occurring.\n The active drag has been aborted.\n `) : void 0;\n }\n const err = event.error;\n if (err instanceof RbdInvariant) {\n event.preventDefault();\n if (process.env.NODE_ENV !== 'production') {\n error(err.message);\n }\n }\n };\n this.getCallbacks = () => {\n if (!this.callbacks) {\n throw new Error('Unable to find AppCallbacks in
');\n }\n return this.callbacks;\n };\n this.setCallbacks = callbacks => {\n this.callbacks = callbacks;\n };\n }\n componentDidMount() {\n this.unbind = bindEvents(window, [{\n eventName: 'error',\n fn: this.onWindowError\n }]);\n }\n componentDidCatch(err) {\n if (err instanceof RbdInvariant) {\n if (process.env.NODE_ENV !== 'production') {\n error(err.message);\n }\n this.setState({});\n return;\n }\n throw err;\n }\n componentWillUnmount() {\n this.unbind();\n }\n render() {\n return this.props.children(this.setCallbacks);\n }\n}\n\nconst dragHandleUsageInstructions = `\n Press space bar to start a drag.\n When dragging you can use the arrow keys to move the item around and escape to cancel.\n Some screen readers may require you to be in focus mode or to use your pass through key\n`;\nconst position = index => index + 1;\nconst onDragStart = start => `\n You have lifted an item in position ${position(start.source.index)}\n`;\nconst withLocation = (source, destination) => {\n const isInHomeList = source.droppableId === destination.droppableId;\n const startPosition = position(source.index);\n const endPosition = position(destination.index);\n if (isInHomeList) {\n return `\n You have moved the item from position ${startPosition}\n to position ${endPosition}\n `;\n }\n return `\n You have moved the item from position ${startPosition}\n in list ${source.droppableId}\n to list ${destination.droppableId}\n in position ${endPosition}\n `;\n};\nconst withCombine = (id, source, combine) => {\n const inHomeList = source.droppableId === combine.droppableId;\n if (inHomeList) {\n return `\n The item ${id}\n has been combined with ${combine.draggableId}`;\n }\n return `\n The item ${id}\n in list ${source.droppableId}\n has been combined with ${combine.draggableId}\n in list ${combine.droppableId}\n `;\n};\nconst onDragUpdate = update => {\n const location = update.destination;\n if (location) {\n return withLocation(update.source, location);\n }\n const combine = update.combine;\n if (combine) {\n return withCombine(update.draggableId, update.source, combine);\n }\n return 'You are over an area that cannot be dropped on';\n};\nconst returnedToStart = source => `\n The item has returned to its starting position\n of ${position(source.index)}\n`;\nconst onDragEnd = result => {\n if (result.reason === 'CANCEL') {\n return `\n Movement cancelled.\n ${returnedToStart(result.source)}\n `;\n }\n const location = result.destination;\n const combine = result.combine;\n if (location) {\n return `\n You have dropped the item.\n ${withLocation(result.source, location)}\n `;\n }\n if (combine) {\n return `\n You have dropped the item.\n ${withCombine(result.draggableId, result.source, combine)}\n `;\n }\n return `\n The item has been dropped while not over a drop area.\n ${returnedToStart(result.source)}\n `;\n};\nconst preset = {\n dragHandleUsageInstructions,\n onDragStart,\n onDragUpdate,\n onDragEnd\n};\nvar preset$1 = preset;\n\nconst origin = {\n x: 0,\n y: 0\n};\nconst add = (point1, point2) => ({\n x: point1.x + point2.x,\n y: point1.y + point2.y\n});\nconst subtract = (point1, point2) => ({\n x: point1.x - point2.x,\n y: point1.y - point2.y\n});\nconst isEqual$1 = (point1, point2) => point1.x === point2.x && point1.y === point2.y;\nconst negate = point => ({\n x: point.x !== 0 ? -point.x : 0,\n y: point.y !== 0 ? -point.y : 0\n});\nconst patch = (line, value, otherValue = 0) => {\n if (line === 'x') {\n return {\n x: value,\n y: otherValue\n };\n }\n return {\n x: otherValue,\n y: value\n };\n};\nconst distance = (point1, point2) => Math.sqrt((point2.x - point1.x) ** 2 + (point2.y - point1.y) ** 2);\nconst closest$1 = (target, points) => Math.min(...points.map(point => distance(target, point)));\nconst apply = fn => point => ({\n x: fn(point.x),\n y: fn(point.y)\n});\n\nvar executeClip = ((frame, subject) => {\n const result = getRect({\n top: Math.max(subject.top, frame.top),\n right: Math.min(subject.right, frame.right),\n bottom: Math.min(subject.bottom, frame.bottom),\n left: Math.max(subject.left, frame.left)\n });\n if (result.width <= 0 || result.height <= 0) {\n return null;\n }\n return result;\n});\n\nconst offsetByPosition = (spacing, point) => ({\n top: spacing.top + point.y,\n left: spacing.left + point.x,\n bottom: spacing.bottom + point.y,\n right: spacing.right + point.x\n});\nconst getCorners = spacing => [{\n x: spacing.left,\n y: spacing.top\n}, {\n x: spacing.right,\n y: spacing.top\n}, {\n x: spacing.left,\n y: spacing.bottom\n}, {\n x: spacing.right,\n y: spacing.bottom\n}];\nconst noSpacing = {\n top: 0,\n right: 0,\n bottom: 0,\n left: 0\n};\n\nconst scroll$1 = (target, frame) => {\n if (!frame) {\n return target;\n }\n return offsetByPosition(target, frame.scroll.diff.displacement);\n};\nconst increase = (target, axis, withPlaceholder) => {\n if (withPlaceholder && withPlaceholder.increasedBy) {\n return {\n ...target,\n [axis.end]: target[axis.end] + withPlaceholder.increasedBy[axis.line]\n };\n }\n return target;\n};\nconst clip = (target, frame) => {\n if (frame && frame.shouldClipSubject) {\n return executeClip(frame.pageMarginBox, target);\n }\n return getRect(target);\n};\nvar getSubject = (({\n page,\n withPlaceholder,\n axis,\n frame\n}) => {\n const scrolled = scroll$1(page.marginBox, frame);\n const increased = increase(scrolled, axis, withPlaceholder);\n const clipped = clip(increased, frame);\n return {\n page,\n withPlaceholder,\n active: clipped\n };\n});\n\nvar scrollDroppable = ((droppable, newScroll) => {\n !droppable.frame ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n const scrollable = droppable.frame;\n const scrollDiff = subtract(newScroll, scrollable.scroll.initial);\n const scrollDisplacement = negate(scrollDiff);\n const frame = {\n ...scrollable,\n scroll: {\n initial: scrollable.scroll.initial,\n current: newScroll,\n diff: {\n value: scrollDiff,\n displacement: scrollDisplacement\n },\n max: scrollable.scroll.max\n }\n };\n const subject = getSubject({\n page: droppable.subject.page,\n withPlaceholder: droppable.subject.withPlaceholder,\n axis: droppable.axis,\n frame\n });\n const result = {\n ...droppable,\n frame,\n subject\n };\n return result;\n});\n\nconst toDroppableMap = memoizeOne(droppables => droppables.reduce((previous, current) => {\n previous[current.descriptor.id] = current;\n return previous;\n}, {}));\nconst toDraggableMap = memoizeOne(draggables => draggables.reduce((previous, current) => {\n previous[current.descriptor.id] = current;\n return previous;\n}, {}));\nconst toDroppableList = memoizeOne(droppables => Object.values(droppables));\nconst toDraggableList = memoizeOne(draggables => Object.values(draggables));\n\nvar getDraggablesInsideDroppable = memoizeOne((droppableId, draggables) => {\n const result = toDraggableList(draggables).filter(draggable => droppableId === draggable.descriptor.droppableId).sort((a, b) => a.descriptor.index - b.descriptor.index);\n return result;\n});\n\nfunction tryGetDestination(impact) {\n if (impact.at && impact.at.type === 'REORDER') {\n return impact.at.destination;\n }\n return null;\n}\nfunction tryGetCombine(impact) {\n if (impact.at && impact.at.type === 'COMBINE') {\n return impact.at.combine;\n }\n return null;\n}\n\nvar removeDraggableFromList = memoizeOne((remove, list) => list.filter(item => item.descriptor.id !== remove.descriptor.id));\n\nvar moveToNextCombine = (({\n isMovingForward,\n draggable,\n destination,\n insideDestination,\n previousImpact\n}) => {\n if (!destination.isCombineEnabled) {\n return null;\n }\n const location = tryGetDestination(previousImpact);\n if (!location) {\n return null;\n }\n function getImpact(target) {\n const at = {\n type: 'COMBINE',\n combine: {\n draggableId: target,\n droppableId: destination.descriptor.id\n }\n };\n return {\n ...previousImpact,\n at\n };\n }\n const all = previousImpact.displaced.all;\n const closestId = all.length ? all[0] : null;\n if (isMovingForward) {\n return closestId ? getImpact(closestId) : null;\n }\n const withoutDraggable = removeDraggableFromList(draggable, insideDestination);\n if (!closestId) {\n if (!withoutDraggable.length) {\n return null;\n }\n const last = withoutDraggable[withoutDraggable.length - 1];\n return getImpact(last.descriptor.id);\n }\n const indexOfClosest = withoutDraggable.findIndex(d => d.descriptor.id === closestId);\n !(indexOfClosest !== -1) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find displaced item in set') : invariant(false) : void 0;\n const proposedIndex = indexOfClosest - 1;\n if (proposedIndex < 0) {\n return null;\n }\n const before = withoutDraggable[proposedIndex];\n return getImpact(before.descriptor.id);\n});\n\nvar isHomeOf = ((draggable, destination) => draggable.descriptor.droppableId === destination.descriptor.id);\n\nconst noDisplacedBy = {\n point: origin,\n value: 0\n};\nconst emptyGroups = {\n invisible: {},\n visible: {},\n all: []\n};\nconst noImpact = {\n displaced: emptyGroups,\n displacedBy: noDisplacedBy,\n at: null\n};\nvar noImpact$1 = noImpact;\n\nvar isWithin = ((lowerBound, upperBound) => value => lowerBound <= value && value <= upperBound);\n\nvar isPartiallyVisibleThroughFrame = (frame => {\n const isWithinVertical = isWithin(frame.top, frame.bottom);\n const isWithinHorizontal = isWithin(frame.left, frame.right);\n return subject => {\n const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);\n if (isContained) {\n return true;\n }\n const isPartiallyVisibleVertically = isWithinVertical(subject.top) || isWithinVertical(subject.bottom);\n const isPartiallyVisibleHorizontally = isWithinHorizontal(subject.left) || isWithinHorizontal(subject.right);\n const isPartiallyContained = isPartiallyVisibleVertically && isPartiallyVisibleHorizontally;\n if (isPartiallyContained) {\n return true;\n }\n const isBiggerVertically = subject.top < frame.top && subject.bottom > frame.bottom;\n const isBiggerHorizontally = subject.left < frame.left && subject.right > frame.right;\n const isTargetBiggerThanFrame = isBiggerVertically && isBiggerHorizontally;\n if (isTargetBiggerThanFrame) {\n return true;\n }\n const isTargetBiggerOnOneAxis = isBiggerVertically && isPartiallyVisibleHorizontally || isBiggerHorizontally && isPartiallyVisibleVertically;\n return isTargetBiggerOnOneAxis;\n };\n});\n\nvar isTotallyVisibleThroughFrame = (frame => {\n const isWithinVertical = isWithin(frame.top, frame.bottom);\n const isWithinHorizontal = isWithin(frame.left, frame.right);\n return subject => {\n const isContained = isWithinVertical(subject.top) && isWithinVertical(subject.bottom) && isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);\n return isContained;\n };\n});\n\nconst vertical = {\n direction: 'vertical',\n line: 'y',\n crossAxisLine: 'x',\n start: 'top',\n end: 'bottom',\n size: 'height',\n crossAxisStart: 'left',\n crossAxisEnd: 'right',\n crossAxisSize: 'width'\n};\nconst horizontal = {\n direction: 'horizontal',\n line: 'x',\n crossAxisLine: 'y',\n start: 'left',\n end: 'right',\n size: 'width',\n crossAxisStart: 'top',\n crossAxisEnd: 'bottom',\n crossAxisSize: 'height'\n};\n\nvar isTotallyVisibleThroughFrameOnAxis = (axis => frame => {\n const isWithinVertical = isWithin(frame.top, frame.bottom);\n const isWithinHorizontal = isWithin(frame.left, frame.right);\n return subject => {\n if (axis === vertical) {\n return isWithinVertical(subject.top) && isWithinVertical(subject.bottom);\n }\n return isWithinHorizontal(subject.left) && isWithinHorizontal(subject.right);\n };\n});\n\nconst getDroppableDisplaced = (target, destination) => {\n const displacement = destination.frame ? destination.frame.scroll.diff.displacement : origin;\n return offsetByPosition(target, displacement);\n};\nconst isVisibleInDroppable = (target, destination, isVisibleThroughFrameFn) => {\n if (!destination.subject.active) {\n return false;\n }\n return isVisibleThroughFrameFn(destination.subject.active)(target);\n};\nconst isVisibleInViewport = (target, viewport, isVisibleThroughFrameFn) => isVisibleThroughFrameFn(viewport)(target);\nconst isVisible$1 = ({\n target: toBeDisplaced,\n destination,\n viewport,\n withDroppableDisplacement,\n isVisibleThroughFrameFn\n}) => {\n const displacedTarget = withDroppableDisplacement ? getDroppableDisplaced(toBeDisplaced, destination) : toBeDisplaced;\n return isVisibleInDroppable(displacedTarget, destination, isVisibleThroughFrameFn) && isVisibleInViewport(displacedTarget, viewport, isVisibleThroughFrameFn);\n};\nconst isPartiallyVisible = args => isVisible$1({\n ...args,\n isVisibleThroughFrameFn: isPartiallyVisibleThroughFrame\n});\nconst isTotallyVisible = args => isVisible$1({\n ...args,\n isVisibleThroughFrameFn: isTotallyVisibleThroughFrame\n});\nconst isTotallyVisibleOnAxis = args => isVisible$1({\n ...args,\n isVisibleThroughFrameFn: isTotallyVisibleThroughFrameOnAxis(args.destination.axis)\n});\n\nconst getShouldAnimate = (id, last, forceShouldAnimate) => {\n if (typeof forceShouldAnimate === 'boolean') {\n return forceShouldAnimate;\n }\n if (!last) {\n return true;\n }\n const {\n invisible,\n visible\n } = last;\n if (invisible[id]) {\n return false;\n }\n const previous = visible[id];\n return previous ? previous.shouldAnimate : true;\n};\nfunction getTarget(draggable, displacedBy) {\n const marginBox = draggable.page.marginBox;\n const expandBy = {\n top: displacedBy.point.y,\n right: 0,\n bottom: 0,\n left: displacedBy.point.x\n };\n return getRect(expand(marginBox, expandBy));\n}\nfunction getDisplacementGroups({\n afterDragging,\n destination,\n displacedBy,\n viewport,\n forceShouldAnimate,\n last\n}) {\n return afterDragging.reduce(function process(groups, draggable) {\n const target = getTarget(draggable, displacedBy);\n const id = draggable.descriptor.id;\n groups.all.push(id);\n const isVisible = isPartiallyVisible({\n target,\n destination,\n viewport,\n withDroppableDisplacement: true\n });\n if (!isVisible) {\n groups.invisible[draggable.descriptor.id] = true;\n return groups;\n }\n const shouldAnimate = getShouldAnimate(id, last, forceShouldAnimate);\n const displacement = {\n draggableId: id,\n shouldAnimate\n };\n groups.visible[id] = displacement;\n return groups;\n }, {\n all: [],\n visible: {},\n invisible: {}\n });\n}\n\nfunction getIndexOfLastItem(draggables, options) {\n if (!draggables.length) {\n return 0;\n }\n const indexOfLastItem = draggables[draggables.length - 1].descriptor.index;\n return options.inHomeList ? indexOfLastItem : indexOfLastItem + 1;\n}\nfunction goAtEnd({\n insideDestination,\n inHomeList,\n displacedBy,\n destination\n}) {\n const newIndex = getIndexOfLastItem(insideDestination, {\n inHomeList\n });\n return {\n displaced: emptyGroups,\n displacedBy,\n at: {\n type: 'REORDER',\n destination: {\n droppableId: destination.descriptor.id,\n index: newIndex\n }\n }\n };\n}\nfunction calculateReorderImpact({\n draggable,\n insideDestination,\n destination,\n viewport,\n displacedBy,\n last,\n index,\n forceShouldAnimate\n}) {\n const inHomeList = isHomeOf(draggable, destination);\n if (index == null) {\n return goAtEnd({\n insideDestination,\n inHomeList,\n displacedBy,\n destination\n });\n }\n const match = insideDestination.find(item => item.descriptor.index === index);\n if (!match) {\n return goAtEnd({\n insideDestination,\n inHomeList,\n displacedBy,\n destination\n });\n }\n const withoutDragging = removeDraggableFromList(draggable, insideDestination);\n const sliceFrom = insideDestination.indexOf(match);\n const impacted = withoutDragging.slice(sliceFrom);\n const displaced = getDisplacementGroups({\n afterDragging: impacted,\n destination,\n displacedBy,\n last,\n viewport: viewport.frame,\n forceShouldAnimate\n });\n return {\n displaced,\n displacedBy,\n at: {\n type: 'REORDER',\n destination: {\n droppableId: destination.descriptor.id,\n index\n }\n }\n };\n}\n\nfunction didStartAfterCritical(draggableId, afterCritical) {\n return Boolean(afterCritical.effected[draggableId]);\n}\n\nvar fromCombine = (({\n isMovingForward,\n destination,\n draggables,\n combine,\n afterCritical\n}) => {\n if (!destination.isCombineEnabled) {\n return null;\n }\n const combineId = combine.draggableId;\n const combineWith = draggables[combineId];\n const combineWithIndex = combineWith.descriptor.index;\n const didCombineWithStartAfterCritical = didStartAfterCritical(combineId, afterCritical);\n if (didCombineWithStartAfterCritical) {\n if (isMovingForward) {\n return combineWithIndex;\n }\n return combineWithIndex - 1;\n }\n if (isMovingForward) {\n return combineWithIndex + 1;\n }\n return combineWithIndex;\n});\n\nvar fromReorder = (({\n isMovingForward,\n isInHomeList,\n insideDestination,\n location\n}) => {\n if (!insideDestination.length) {\n return null;\n }\n const currentIndex = location.index;\n const proposedIndex = isMovingForward ? currentIndex + 1 : currentIndex - 1;\n const firstIndex = insideDestination[0].descriptor.index;\n const lastIndex = insideDestination[insideDestination.length - 1].descriptor.index;\n const upperBound = isInHomeList ? lastIndex : lastIndex + 1;\n if (proposedIndex < firstIndex) {\n return null;\n }\n if (proposedIndex > upperBound) {\n return null;\n }\n return proposedIndex;\n});\n\nvar moveToNextIndex = (({\n isMovingForward,\n isInHomeList,\n draggable,\n draggables,\n destination,\n insideDestination,\n previousImpact,\n viewport,\n afterCritical\n}) => {\n const wasAt = previousImpact.at;\n !wasAt ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot move in direction without previous impact location') : invariant(false) : void 0;\n if (wasAt.type === 'REORDER') {\n const newIndex = fromReorder({\n isMovingForward,\n isInHomeList,\n location: wasAt.destination,\n insideDestination\n });\n if (newIndex == null) {\n return null;\n }\n return calculateReorderImpact({\n draggable,\n insideDestination,\n destination,\n viewport,\n last: previousImpact.displaced,\n displacedBy: previousImpact.displacedBy,\n index: newIndex\n });\n }\n const newIndex = fromCombine({\n isMovingForward,\n destination,\n displaced: previousImpact.displaced,\n draggables,\n combine: wasAt.combine,\n afterCritical\n });\n if (newIndex == null) {\n return null;\n }\n return calculateReorderImpact({\n draggable,\n insideDestination,\n destination,\n viewport,\n last: previousImpact.displaced,\n displacedBy: previousImpact.displacedBy,\n index: newIndex\n });\n});\n\nvar getCombinedItemDisplacement = (({\n displaced,\n afterCritical,\n combineWith,\n displacedBy\n}) => {\n const isDisplaced = Boolean(displaced.visible[combineWith] || displaced.invisible[combineWith]);\n if (didStartAfterCritical(combineWith, afterCritical)) {\n return isDisplaced ? origin : negate(displacedBy.point);\n }\n return isDisplaced ? displacedBy.point : origin;\n});\n\nvar whenCombining = (({\n afterCritical,\n impact,\n draggables\n}) => {\n const combine = tryGetCombine(impact);\n !combine ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n const combineWith = combine.draggableId;\n const center = draggables[combineWith].page.borderBox.center;\n const displaceBy = getCombinedItemDisplacement({\n displaced: impact.displaced,\n afterCritical,\n combineWith,\n displacedBy: impact.displacedBy\n });\n return add(center, displaceBy);\n});\n\nconst distanceFromStartToBorderBoxCenter = (axis, box) => box.margin[axis.start] + box.borderBox[axis.size] / 2;\nconst distanceFromEndToBorderBoxCenter = (axis, box) => box.margin[axis.end] + box.borderBox[axis.size] / 2;\nconst getCrossAxisBorderBoxCenter = (axis, target, isMoving) => target[axis.crossAxisStart] + isMoving.margin[axis.crossAxisStart] + isMoving.borderBox[axis.crossAxisSize] / 2;\nconst goAfter = ({\n axis,\n moveRelativeTo,\n isMoving\n}) => patch(axis.line, moveRelativeTo.marginBox[axis.end] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));\nconst goBefore = ({\n axis,\n moveRelativeTo,\n isMoving\n}) => patch(axis.line, moveRelativeTo.marginBox[axis.start] - distanceFromEndToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveRelativeTo.marginBox, isMoving));\nconst goIntoStart = ({\n axis,\n moveInto,\n isMoving\n}) => patch(axis.line, moveInto.contentBox[axis.start] + distanceFromStartToBorderBoxCenter(axis, isMoving), getCrossAxisBorderBoxCenter(axis, moveInto.contentBox, isMoving));\n\nvar whenReordering = (({\n impact,\n draggable,\n draggables,\n droppable,\n afterCritical\n}) => {\n const insideDestination = getDraggablesInsideDroppable(droppable.descriptor.id, draggables);\n const draggablePage = draggable.page;\n const axis = droppable.axis;\n if (!insideDestination.length) {\n return goIntoStart({\n axis,\n moveInto: droppable.page,\n isMoving: draggablePage\n });\n }\n const {\n displaced,\n displacedBy\n } = impact;\n const closestAfter = displaced.all[0];\n if (closestAfter) {\n const closest = draggables[closestAfter];\n if (didStartAfterCritical(closestAfter, afterCritical)) {\n return goBefore({\n axis,\n moveRelativeTo: closest.page,\n isMoving: draggablePage\n });\n }\n const withDisplacement = offset(closest.page, displacedBy.point);\n return goBefore({\n axis,\n moveRelativeTo: withDisplacement,\n isMoving: draggablePage\n });\n }\n const last = insideDestination[insideDestination.length - 1];\n if (last.descriptor.id === draggable.descriptor.id) {\n return draggablePage.borderBox.center;\n }\n if (didStartAfterCritical(last.descriptor.id, afterCritical)) {\n const page = offset(last.page, negate(afterCritical.displacedBy.point));\n return goAfter({\n axis,\n moveRelativeTo: page,\n isMoving: draggablePage\n });\n }\n return goAfter({\n axis,\n moveRelativeTo: last.page,\n isMoving: draggablePage\n });\n});\n\nvar withDroppableDisplacement = ((droppable, point) => {\n const frame = droppable.frame;\n if (!frame) {\n return point;\n }\n return add(point, frame.scroll.diff.displacement);\n});\n\nconst getResultWithoutDroppableDisplacement = ({\n impact,\n draggable,\n droppable,\n draggables,\n afterCritical\n}) => {\n const original = draggable.page.borderBox.center;\n const at = impact.at;\n if (!droppable) {\n return original;\n }\n if (!at) {\n return original;\n }\n if (at.type === 'REORDER') {\n return whenReordering({\n impact,\n draggable,\n draggables,\n droppable,\n afterCritical\n });\n }\n return whenCombining({\n impact,\n draggables,\n afterCritical\n });\n};\nvar getPageBorderBoxCenterFromImpact = (args => {\n const withoutDisplacement = getResultWithoutDroppableDisplacement(args);\n const droppable = args.droppable;\n const withDisplacement = droppable ? withDroppableDisplacement(droppable, withoutDisplacement) : withoutDisplacement;\n return withDisplacement;\n});\n\nvar scrollViewport = ((viewport, newScroll) => {\n const diff = subtract(newScroll, viewport.scroll.initial);\n const displacement = negate(diff);\n const frame = getRect({\n top: newScroll.y,\n bottom: newScroll.y + viewport.frame.height,\n left: newScroll.x,\n right: newScroll.x + viewport.frame.width\n });\n const updated = {\n frame,\n scroll: {\n initial: viewport.scroll.initial,\n max: viewport.scroll.max,\n current: newScroll,\n diff: {\n value: diff,\n displacement\n }\n }\n };\n return updated;\n});\n\nfunction getDraggables$1(ids, draggables) {\n return ids.map(id => draggables[id]);\n}\nfunction tryGetVisible(id, groups) {\n for (let i = 0; i < groups.length; i++) {\n const displacement = groups[i].visible[id];\n if (displacement) {\n return displacement;\n }\n }\n return null;\n}\nvar speculativelyIncrease = (({\n impact,\n viewport,\n destination,\n draggables,\n maxScrollChange\n}) => {\n const scrolledViewport = scrollViewport(viewport, add(viewport.scroll.current, maxScrollChange));\n const scrolledDroppable = destination.frame ? scrollDroppable(destination, add(destination.frame.scroll.current, maxScrollChange)) : destination;\n const last = impact.displaced;\n const withViewportScroll = getDisplacementGroups({\n afterDragging: getDraggables$1(last.all, draggables),\n destination,\n displacedBy: impact.displacedBy,\n viewport: scrolledViewport.frame,\n last,\n forceShouldAnimate: false\n });\n const withDroppableScroll = getDisplacementGroups({\n afterDragging: getDraggables$1(last.all, draggables),\n destination: scrolledDroppable,\n displacedBy: impact.displacedBy,\n viewport: viewport.frame,\n last,\n forceShouldAnimate: false\n });\n const invisible = {};\n const visible = {};\n const groups = [last, withViewportScroll, withDroppableScroll];\n last.all.forEach(id => {\n const displacement = tryGetVisible(id, groups);\n if (displacement) {\n visible[id] = displacement;\n return;\n }\n invisible[id] = true;\n });\n const newImpact = {\n ...impact,\n displaced: {\n all: last.all,\n invisible,\n visible\n }\n };\n return newImpact;\n});\n\nvar withViewportDisplacement = ((viewport, point) => add(viewport.scroll.diff.displacement, point));\n\nvar getClientFromPageBorderBoxCenter = (({\n pageBorderBoxCenter,\n draggable,\n viewport\n}) => {\n const withoutPageScrollChange = withViewportDisplacement(viewport, pageBorderBoxCenter);\n const offset = subtract(withoutPageScrollChange, draggable.page.borderBox.center);\n return add(draggable.client.borderBox.center, offset);\n});\n\nvar isTotallyVisibleInNewLocation = (({\n draggable,\n destination,\n newPageBorderBoxCenter,\n viewport,\n withDroppableDisplacement,\n onlyOnMainAxis = false\n}) => {\n const changeNeeded = subtract(newPageBorderBoxCenter, draggable.page.borderBox.center);\n const shifted = offsetByPosition(draggable.page.borderBox, changeNeeded);\n const args = {\n target: shifted,\n destination,\n withDroppableDisplacement,\n viewport\n };\n return onlyOnMainAxis ? isTotallyVisibleOnAxis(args) : isTotallyVisible(args);\n});\n\nvar moveToNextPlace = (({\n isMovingForward,\n draggable,\n destination,\n draggables,\n previousImpact,\n viewport,\n previousPageBorderBoxCenter,\n previousClientSelection,\n afterCritical\n}) => {\n if (!destination.isEnabled) {\n return null;\n }\n const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);\n const isInHomeList = isHomeOf(draggable, destination);\n const impact = moveToNextCombine({\n isMovingForward,\n draggable,\n destination,\n insideDestination,\n previousImpact\n }) || moveToNextIndex({\n isMovingForward,\n isInHomeList,\n draggable,\n draggables,\n destination,\n insideDestination,\n previousImpact,\n viewport,\n afterCritical\n });\n if (!impact) {\n return null;\n }\n const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({\n impact,\n draggable,\n droppable: destination,\n draggables,\n afterCritical\n });\n const isVisibleInNewLocation = isTotallyVisibleInNewLocation({\n draggable,\n destination,\n newPageBorderBoxCenter: pageBorderBoxCenter,\n viewport: viewport.frame,\n withDroppableDisplacement: false,\n onlyOnMainAxis: true\n });\n if (isVisibleInNewLocation) {\n const clientSelection = getClientFromPageBorderBoxCenter({\n pageBorderBoxCenter,\n draggable,\n viewport\n });\n return {\n clientSelection,\n impact,\n scrollJumpRequest: null\n };\n }\n const distance = subtract(pageBorderBoxCenter, previousPageBorderBoxCenter);\n const cautious = speculativelyIncrease({\n impact,\n viewport,\n destination,\n draggables,\n maxScrollChange: distance\n });\n return {\n clientSelection: previousClientSelection,\n impact: cautious,\n scrollJumpRequest: distance\n };\n});\n\nconst getKnownActive = droppable => {\n const rect = droppable.subject.active;\n !rect ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot get clipped area from droppable') : invariant(false) : void 0;\n return rect;\n};\nvar getBestCrossAxisDroppable = (({\n isMovingForward,\n pageBorderBoxCenter,\n source,\n droppables,\n viewport\n}) => {\n const active = source.subject.active;\n if (!active) {\n return null;\n }\n const axis = source.axis;\n const isBetweenSourceClipped = isWithin(active[axis.start], active[axis.end]);\n const candidates = toDroppableList(droppables).filter(droppable => droppable !== source).filter(droppable => droppable.isEnabled).filter(droppable => Boolean(droppable.subject.active)).filter(droppable => isPartiallyVisibleThroughFrame(viewport.frame)(getKnownActive(droppable))).filter(droppable => {\n const activeOfTarget = getKnownActive(droppable);\n if (isMovingForward) {\n return active[axis.crossAxisEnd] < activeOfTarget[axis.crossAxisEnd];\n }\n return activeOfTarget[axis.crossAxisStart] < active[axis.crossAxisStart];\n }).filter(droppable => {\n const activeOfTarget = getKnownActive(droppable);\n const isBetweenDestinationClipped = isWithin(activeOfTarget[axis.start], activeOfTarget[axis.end]);\n return isBetweenSourceClipped(activeOfTarget[axis.start]) || isBetweenSourceClipped(activeOfTarget[axis.end]) || isBetweenDestinationClipped(active[axis.start]) || isBetweenDestinationClipped(active[axis.end]);\n }).sort((a, b) => {\n const first = getKnownActive(a)[axis.crossAxisStart];\n const second = getKnownActive(b)[axis.crossAxisStart];\n if (isMovingForward) {\n return first - second;\n }\n return second - first;\n }).filter((droppable, index, array) => getKnownActive(droppable)[axis.crossAxisStart] === getKnownActive(array[0])[axis.crossAxisStart]);\n if (!candidates.length) {\n return null;\n }\n if (candidates.length === 1) {\n return candidates[0];\n }\n const contains = candidates.filter(droppable => {\n const isWithinDroppable = isWithin(getKnownActive(droppable)[axis.start], getKnownActive(droppable)[axis.end]);\n return isWithinDroppable(pageBorderBoxCenter[axis.line]);\n });\n if (contains.length === 1) {\n return contains[0];\n }\n if (contains.length > 1) {\n return contains.sort((a, b) => getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start])[0];\n }\n return candidates.sort((a, b) => {\n const first = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(a)));\n const second = closest$1(pageBorderBoxCenter, getCorners(getKnownActive(b)));\n if (first !== second) {\n return first - second;\n }\n return getKnownActive(a)[axis.start] - getKnownActive(b)[axis.start];\n })[0];\n});\n\nconst getCurrentPageBorderBoxCenter = (draggable, afterCritical) => {\n const original = draggable.page.borderBox.center;\n return didStartAfterCritical(draggable.descriptor.id, afterCritical) ? subtract(original, afterCritical.displacedBy.point) : original;\n};\nconst getCurrentPageBorderBox = (draggable, afterCritical) => {\n const original = draggable.page.borderBox;\n return didStartAfterCritical(draggable.descriptor.id, afterCritical) ? offsetByPosition(original, negate(afterCritical.displacedBy.point)) : original;\n};\n\nvar getClosestDraggable = (({\n pageBorderBoxCenter,\n viewport,\n destination,\n insideDestination,\n afterCritical\n}) => {\n const sorted = insideDestination.filter(draggable => isTotallyVisible({\n target: getCurrentPageBorderBox(draggable, afterCritical),\n destination,\n viewport: viewport.frame,\n withDroppableDisplacement: true\n })).sort((a, b) => {\n const distanceToA = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(a, afterCritical)));\n const distanceToB = distance(pageBorderBoxCenter, withDroppableDisplacement(destination, getCurrentPageBorderBoxCenter(b, afterCritical)));\n if (distanceToA < distanceToB) {\n return -1;\n }\n if (distanceToB < distanceToA) {\n return 1;\n }\n return a.descriptor.index - b.descriptor.index;\n });\n return sorted[0] || null;\n});\n\nvar getDisplacedBy = memoizeOne(function getDisplacedBy(axis, displaceBy) {\n const displacement = displaceBy[axis.line];\n return {\n value: displacement,\n point: patch(axis.line, displacement)\n };\n});\n\nconst getRequiredGrowthForPlaceholder = (droppable, placeholderSize, draggables) => {\n const axis = droppable.axis;\n if (droppable.descriptor.mode === 'virtual') {\n return patch(axis.line, placeholderSize[axis.line]);\n }\n const availableSpace = droppable.subject.page.contentBox[axis.size];\n const insideDroppable = getDraggablesInsideDroppable(droppable.descriptor.id, draggables);\n const spaceUsed = insideDroppable.reduce((sum, dimension) => sum + dimension.client.marginBox[axis.size], 0);\n const requiredSpace = spaceUsed + placeholderSize[axis.line];\n const needsToGrowBy = requiredSpace - availableSpace;\n if (needsToGrowBy <= 0) {\n return null;\n }\n return patch(axis.line, needsToGrowBy);\n};\nconst withMaxScroll = (frame, max) => ({\n ...frame,\n scroll: {\n ...frame.scroll,\n max\n }\n});\nconst addPlaceholder = (droppable, draggable, draggables) => {\n const frame = droppable.frame;\n !!isHomeOf(draggable, droppable) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Should not add placeholder space to home list') : invariant(false) : void 0;\n !!droppable.subject.withPlaceholder ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot add placeholder size to a subject when it already has one') : invariant(false) : void 0;\n const placeholderSize = getDisplacedBy(droppable.axis, draggable.displaceBy).point;\n const requiredGrowth = getRequiredGrowthForPlaceholder(droppable, placeholderSize, draggables);\n const added = {\n placeholderSize,\n increasedBy: requiredGrowth,\n oldFrameMaxScroll: droppable.frame ? droppable.frame.scroll.max : null\n };\n if (!frame) {\n const subject = getSubject({\n page: droppable.subject.page,\n withPlaceholder: added,\n axis: droppable.axis,\n frame: droppable.frame\n });\n return {\n ...droppable,\n subject\n };\n }\n const maxScroll = requiredGrowth ? add(frame.scroll.max, requiredGrowth) : frame.scroll.max;\n const newFrame = withMaxScroll(frame, maxScroll);\n const subject = getSubject({\n page: droppable.subject.page,\n withPlaceholder: added,\n axis: droppable.axis,\n frame: newFrame\n });\n return {\n ...droppable,\n subject,\n frame: newFrame\n };\n};\nconst removePlaceholder = droppable => {\n const added = droppable.subject.withPlaceholder;\n !added ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot remove placeholder form subject when there was none') : invariant(false) : void 0;\n const frame = droppable.frame;\n if (!frame) {\n const subject = getSubject({\n page: droppable.subject.page,\n axis: droppable.axis,\n frame: null,\n withPlaceholder: null\n });\n return {\n ...droppable,\n subject\n };\n }\n const oldMaxScroll = added.oldFrameMaxScroll;\n !oldMaxScroll ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected droppable with frame to have old max frame scroll when removing placeholder') : invariant(false) : void 0;\n const newFrame = withMaxScroll(frame, oldMaxScroll);\n const subject = getSubject({\n page: droppable.subject.page,\n axis: droppable.axis,\n frame: newFrame,\n withPlaceholder: null\n });\n return {\n ...droppable,\n subject,\n frame: newFrame\n };\n};\n\nvar moveToNewDroppable = (({\n previousPageBorderBoxCenter,\n moveRelativeTo,\n insideDestination,\n draggable,\n draggables,\n destination,\n viewport,\n afterCritical\n}) => {\n if (!moveRelativeTo) {\n if (insideDestination.length) {\n return null;\n }\n const proposed = {\n displaced: emptyGroups,\n displacedBy: noDisplacedBy,\n at: {\n type: 'REORDER',\n destination: {\n droppableId: destination.descriptor.id,\n index: 0\n }\n }\n };\n const proposedPageBorderBoxCenter = getPageBorderBoxCenterFromImpact({\n impact: proposed,\n draggable,\n droppable: destination,\n draggables,\n afterCritical\n });\n const withPlaceholder = isHomeOf(draggable, destination) ? destination : addPlaceholder(destination, draggable, draggables);\n const isVisibleInNewLocation = isTotallyVisibleInNewLocation({\n draggable,\n destination: withPlaceholder,\n newPageBorderBoxCenter: proposedPageBorderBoxCenter,\n viewport: viewport.frame,\n withDroppableDisplacement: false,\n onlyOnMainAxis: true\n });\n return isVisibleInNewLocation ? proposed : null;\n }\n const isGoingBeforeTarget = Boolean(previousPageBorderBoxCenter[destination.axis.line] <= moveRelativeTo.page.borderBox.center[destination.axis.line]);\n const proposedIndex = (() => {\n const relativeTo = moveRelativeTo.descriptor.index;\n if (moveRelativeTo.descriptor.id === draggable.descriptor.id) {\n return relativeTo;\n }\n if (isGoingBeforeTarget) {\n return relativeTo;\n }\n return relativeTo + 1;\n })();\n const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);\n return calculateReorderImpact({\n draggable,\n insideDestination,\n destination,\n viewport,\n displacedBy,\n last: emptyGroups,\n index: proposedIndex\n });\n});\n\nvar moveCrossAxis = (({\n isMovingForward,\n previousPageBorderBoxCenter,\n draggable,\n isOver,\n draggables,\n droppables,\n viewport,\n afterCritical\n}) => {\n const destination = getBestCrossAxisDroppable({\n isMovingForward,\n pageBorderBoxCenter: previousPageBorderBoxCenter,\n source: isOver,\n droppables,\n viewport\n });\n if (!destination) {\n return null;\n }\n const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);\n const moveRelativeTo = getClosestDraggable({\n pageBorderBoxCenter: previousPageBorderBoxCenter,\n viewport,\n destination,\n insideDestination,\n afterCritical\n });\n const impact = moveToNewDroppable({\n previousPageBorderBoxCenter,\n destination,\n draggable,\n draggables,\n moveRelativeTo,\n insideDestination,\n viewport,\n afterCritical\n });\n if (!impact) {\n return null;\n }\n const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({\n impact,\n draggable,\n droppable: destination,\n draggables,\n afterCritical\n });\n const clientSelection = getClientFromPageBorderBoxCenter({\n pageBorderBoxCenter,\n draggable,\n viewport\n });\n return {\n clientSelection,\n impact,\n scrollJumpRequest: null\n };\n});\n\nvar whatIsDraggedOver = (impact => {\n const at = impact.at;\n if (!at) {\n return null;\n }\n if (at.type === 'REORDER') {\n return at.destination.droppableId;\n }\n return at.combine.droppableId;\n});\n\nconst getDroppableOver$1 = (impact, droppables) => {\n const id = whatIsDraggedOver(impact);\n return id ? droppables[id] : null;\n};\nvar moveInDirection = (({\n state,\n type\n}) => {\n const isActuallyOver = getDroppableOver$1(state.impact, state.dimensions.droppables);\n const isMainAxisMovementAllowed = Boolean(isActuallyOver);\n const home = state.dimensions.droppables[state.critical.droppable.id];\n const isOver = isActuallyOver || home;\n const direction = isOver.axis.direction;\n const isMovingOnMainAxis = direction === 'vertical' && (type === 'MOVE_UP' || type === 'MOVE_DOWN') || direction === 'horizontal' && (type === 'MOVE_LEFT' || type === 'MOVE_RIGHT');\n if (isMovingOnMainAxis && !isMainAxisMovementAllowed) {\n return null;\n }\n const isMovingForward = type === 'MOVE_DOWN' || type === 'MOVE_RIGHT';\n const draggable = state.dimensions.draggables[state.critical.draggable.id];\n const previousPageBorderBoxCenter = state.current.page.borderBoxCenter;\n const {\n draggables,\n droppables\n } = state.dimensions;\n return isMovingOnMainAxis ? moveToNextPlace({\n isMovingForward,\n previousPageBorderBoxCenter,\n draggable,\n destination: isOver,\n draggables,\n viewport: state.viewport,\n previousClientSelection: state.current.client.selection,\n previousImpact: state.impact,\n afterCritical: state.afterCritical\n }) : moveCrossAxis({\n isMovingForward,\n previousPageBorderBoxCenter,\n draggable,\n isOver,\n draggables,\n droppables,\n viewport: state.viewport,\n afterCritical: state.afterCritical\n });\n});\n\nfunction isMovementAllowed(state) {\n return state.phase === 'DRAGGING' || state.phase === 'COLLECTING';\n}\n\nfunction isPositionInFrame(frame) {\n const isWithinVertical = isWithin(frame.top, frame.bottom);\n const isWithinHorizontal = isWithin(frame.left, frame.right);\n return function run(point) {\n return isWithinVertical(point.y) && isWithinHorizontal(point.x);\n };\n}\n\nfunction getHasOverlap(first, second) {\n return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;\n}\nfunction getFurthestAway({\n pageBorderBox,\n draggable,\n candidates\n}) {\n const startCenter = draggable.page.borderBox.center;\n const sorted = candidates.map(candidate => {\n const axis = candidate.axis;\n const target = patch(candidate.axis.line, pageBorderBox.center[axis.line], candidate.page.borderBox.center[axis.crossAxisLine]);\n return {\n id: candidate.descriptor.id,\n distance: distance(startCenter, target)\n };\n }).sort((a, b) => b.distance - a.distance);\n return sorted[0] ? sorted[0].id : null;\n}\nfunction getDroppableOver({\n pageBorderBox,\n draggable,\n droppables\n}) {\n const candidates = toDroppableList(droppables).filter(item => {\n if (!item.isEnabled) {\n return false;\n }\n const active = item.subject.active;\n if (!active) {\n return false;\n }\n if (!getHasOverlap(pageBorderBox, active)) {\n return false;\n }\n if (isPositionInFrame(active)(pageBorderBox.center)) {\n return true;\n }\n const axis = item.axis;\n const childCenter = active.center[axis.crossAxisLine];\n const crossAxisStart = pageBorderBox[axis.crossAxisStart];\n const crossAxisEnd = pageBorderBox[axis.crossAxisEnd];\n const isContained = isWithin(active[axis.crossAxisStart], active[axis.crossAxisEnd]);\n const isStartContained = isContained(crossAxisStart);\n const isEndContained = isContained(crossAxisEnd);\n if (!isStartContained && !isEndContained) {\n return true;\n }\n if (isStartContained) {\n return crossAxisStart < childCenter;\n }\n return crossAxisEnd > childCenter;\n });\n if (!candidates.length) {\n return null;\n }\n if (candidates.length === 1) {\n return candidates[0].descriptor.id;\n }\n return getFurthestAway({\n pageBorderBox,\n draggable,\n candidates\n });\n}\n\nconst offsetRectByPosition = (rect, point) => getRect(offsetByPosition(rect, point));\n\nvar withDroppableScroll = ((droppable, area) => {\n const frame = droppable.frame;\n if (!frame) {\n return area;\n }\n return offsetRectByPosition(area, frame.scroll.diff.value);\n});\n\nfunction getIsDisplaced({\n displaced,\n id\n}) {\n return Boolean(displaced.visible[id] || displaced.invisible[id]);\n}\n\nfunction atIndex({\n draggable,\n closest,\n inHomeList\n}) {\n if (!closest) {\n return null;\n }\n if (!inHomeList) {\n return closest.descriptor.index;\n }\n if (closest.descriptor.index > draggable.descriptor.index) {\n return closest.descriptor.index - 1;\n }\n return closest.descriptor.index;\n}\nvar getReorderImpact = (({\n pageBorderBoxWithDroppableScroll: targetRect,\n draggable,\n destination,\n insideDestination,\n last,\n viewport,\n afterCritical\n}) => {\n const axis = destination.axis;\n const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);\n const displacement = displacedBy.value;\n const targetStart = targetRect[axis.start];\n const targetEnd = targetRect[axis.end];\n const withoutDragging = removeDraggableFromList(draggable, insideDestination);\n const closest = withoutDragging.find(child => {\n const id = child.descriptor.id;\n const childCenter = child.page.borderBox.center[axis.line];\n const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);\n const isDisplaced = getIsDisplaced({\n displaced: last,\n id\n });\n if (didStartAfterCritical$1) {\n if (isDisplaced) {\n return targetEnd <= childCenter;\n }\n return targetStart < childCenter - displacement;\n }\n if (isDisplaced) {\n return targetEnd <= childCenter + displacement;\n }\n return targetStart < childCenter;\n }) || null;\n const newIndex = atIndex({\n draggable,\n closest,\n inHomeList: isHomeOf(draggable, destination)\n });\n return calculateReorderImpact({\n draggable,\n insideDestination,\n destination,\n viewport,\n last,\n displacedBy,\n index: newIndex\n });\n});\n\nconst combineThresholdDivisor = 4;\nvar getCombineImpact = (({\n draggable,\n pageBorderBoxWithDroppableScroll: targetRect,\n previousImpact,\n destination,\n insideDestination,\n afterCritical\n}) => {\n if (!destination.isCombineEnabled) {\n return null;\n }\n const axis = destination.axis;\n const displacedBy = getDisplacedBy(destination.axis, draggable.displaceBy);\n const displacement = displacedBy.value;\n const targetStart = targetRect[axis.start];\n const targetEnd = targetRect[axis.end];\n const withoutDragging = removeDraggableFromList(draggable, insideDestination);\n const combineWith = withoutDragging.find(child => {\n const id = child.descriptor.id;\n const childRect = child.page.borderBox;\n const childSize = childRect[axis.size];\n const threshold = childSize / combineThresholdDivisor;\n const didStartAfterCritical$1 = didStartAfterCritical(id, afterCritical);\n const isDisplaced = getIsDisplaced({\n displaced: previousImpact.displaced,\n id\n });\n if (didStartAfterCritical$1) {\n if (isDisplaced) {\n return targetEnd > childRect[axis.start] + threshold && targetEnd < childRect[axis.end] - threshold;\n }\n return targetStart > childRect[axis.start] - displacement + threshold && targetStart < childRect[axis.end] - displacement - threshold;\n }\n if (isDisplaced) {\n return targetEnd > childRect[axis.start] + displacement + threshold && targetEnd < childRect[axis.end] + displacement - threshold;\n }\n return targetStart > childRect[axis.start] + threshold && targetStart < childRect[axis.end] - threshold;\n });\n if (!combineWith) {\n return null;\n }\n const impact = {\n displacedBy,\n displaced: previousImpact.displaced,\n at: {\n type: 'COMBINE',\n combine: {\n draggableId: combineWith.descriptor.id,\n droppableId: destination.descriptor.id\n }\n }\n };\n return impact;\n});\n\nvar getDragImpact = (({\n pageOffset,\n draggable,\n draggables,\n droppables,\n previousImpact,\n viewport,\n afterCritical\n}) => {\n const pageBorderBox = offsetRectByPosition(draggable.page.borderBox, pageOffset);\n const destinationId = getDroppableOver({\n pageBorderBox,\n draggable,\n droppables\n });\n if (!destinationId) {\n return noImpact$1;\n }\n const destination = droppables[destinationId];\n const insideDestination = getDraggablesInsideDroppable(destination.descriptor.id, draggables);\n const pageBorderBoxWithDroppableScroll = withDroppableScroll(destination, pageBorderBox);\n return getCombineImpact({\n pageBorderBoxWithDroppableScroll,\n draggable,\n previousImpact,\n destination,\n insideDestination,\n afterCritical\n }) || getReorderImpact({\n pageBorderBoxWithDroppableScroll,\n draggable,\n destination,\n insideDestination,\n last: previousImpact.displaced,\n viewport,\n afterCritical\n });\n});\n\nvar patchDroppableMap = ((droppables, updated) => ({\n ...droppables,\n [updated.descriptor.id]: updated\n}));\n\nconst clearUnusedPlaceholder = ({\n previousImpact,\n impact,\n droppables\n}) => {\n const last = whatIsDraggedOver(previousImpact);\n const now = whatIsDraggedOver(impact);\n if (!last) {\n return droppables;\n }\n if (last === now) {\n return droppables;\n }\n const lastDroppable = droppables[last];\n if (!lastDroppable.subject.withPlaceholder) {\n return droppables;\n }\n const updated = removePlaceholder(lastDroppable);\n return patchDroppableMap(droppables, updated);\n};\nvar recomputePlaceholders = (({\n draggable,\n draggables,\n droppables,\n previousImpact,\n impact\n}) => {\n const cleaned = clearUnusedPlaceholder({\n previousImpact,\n impact,\n droppables\n });\n const isOver = whatIsDraggedOver(impact);\n if (!isOver) {\n return cleaned;\n }\n const droppable = droppables[isOver];\n if (isHomeOf(draggable, droppable)) {\n return cleaned;\n }\n if (droppable.subject.withPlaceholder) {\n return cleaned;\n }\n const patched = addPlaceholder(droppable, draggable, draggables);\n return patchDroppableMap(cleaned, patched);\n});\n\nvar update = (({\n state,\n clientSelection: forcedClientSelection,\n dimensions: forcedDimensions,\n viewport: forcedViewport,\n impact: forcedImpact,\n scrollJumpRequest\n}) => {\n const viewport = forcedViewport || state.viewport;\n const dimensions = forcedDimensions || state.dimensions;\n const clientSelection = forcedClientSelection || state.current.client.selection;\n const offset = subtract(clientSelection, state.initial.client.selection);\n const client = {\n offset,\n selection: clientSelection,\n borderBoxCenter: add(state.initial.client.borderBoxCenter, offset)\n };\n const page = {\n selection: add(client.selection, viewport.scroll.current),\n borderBoxCenter: add(client.borderBoxCenter, viewport.scroll.current),\n offset: add(client.offset, viewport.scroll.diff.value)\n };\n const current = {\n client,\n page\n };\n if (state.phase === 'COLLECTING') {\n return {\n ...state,\n dimensions,\n viewport,\n current\n };\n }\n const draggable = dimensions.draggables[state.critical.draggable.id];\n const newImpact = forcedImpact || getDragImpact({\n pageOffset: page.offset,\n draggable,\n draggables: dimensions.draggables,\n droppables: dimensions.droppables,\n previousImpact: state.impact,\n viewport,\n afterCritical: state.afterCritical\n });\n const withUpdatedPlaceholders = recomputePlaceholders({\n draggable,\n impact: newImpact,\n previousImpact: state.impact,\n draggables: dimensions.draggables,\n droppables: dimensions.droppables\n });\n const result = {\n ...state,\n current,\n dimensions: {\n draggables: dimensions.draggables,\n droppables: withUpdatedPlaceholders\n },\n impact: newImpact,\n viewport,\n scrollJumpRequest: scrollJumpRequest || null,\n forceShouldAnimate: scrollJumpRequest ? false : null\n };\n return result;\n});\n\nfunction getDraggables(ids, draggables) {\n return ids.map(id => draggables[id]);\n}\nvar recompute = (({\n impact,\n viewport,\n draggables,\n destination,\n forceShouldAnimate\n}) => {\n const last = impact.displaced;\n const afterDragging = getDraggables(last.all, draggables);\n const displaced = getDisplacementGroups({\n afterDragging,\n destination,\n displacedBy: impact.displacedBy,\n viewport: viewport.frame,\n forceShouldAnimate,\n last\n });\n return {\n ...impact,\n displaced\n };\n});\n\nvar getClientBorderBoxCenter = (({\n impact,\n draggable,\n droppable,\n draggables,\n viewport,\n afterCritical\n}) => {\n const pageBorderBoxCenter = getPageBorderBoxCenterFromImpact({\n impact,\n draggable,\n draggables,\n droppable,\n afterCritical\n });\n return getClientFromPageBorderBoxCenter({\n pageBorderBoxCenter,\n draggable,\n viewport\n });\n});\n\nvar refreshSnap = (({\n state,\n dimensions: forcedDimensions,\n viewport: forcedViewport\n}) => {\n !(state.movementMode === 'SNAP') ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n const needsVisibilityCheck = state.impact;\n const viewport = forcedViewport || state.viewport;\n const dimensions = forcedDimensions || state.dimensions;\n const {\n draggables,\n droppables\n } = dimensions;\n const draggable = draggables[state.critical.draggable.id];\n const isOver = whatIsDraggedOver(needsVisibilityCheck);\n !isOver ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Must be over a destination in SNAP movement mode') : invariant(false) : void 0;\n const destination = droppables[isOver];\n const impact = recompute({\n impact: needsVisibilityCheck,\n viewport,\n destination,\n draggables\n });\n const clientSelection = getClientBorderBoxCenter({\n impact,\n draggable,\n droppable: destination,\n draggables,\n viewport,\n afterCritical: state.afterCritical\n });\n return update({\n impact,\n clientSelection,\n state,\n dimensions,\n viewport\n });\n});\n\nvar getHomeLocation = (descriptor => ({\n index: descriptor.index,\n droppableId: descriptor.droppableId\n}));\n\nvar getLiftEffect = (({\n draggable,\n home,\n draggables,\n viewport\n}) => {\n const displacedBy = getDisplacedBy(home.axis, draggable.displaceBy);\n const insideHome = getDraggablesInsideDroppable(home.descriptor.id, draggables);\n const rawIndex = insideHome.indexOf(draggable);\n !(rawIndex !== -1) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected draggable to be inside home list') : invariant(false) : void 0;\n const afterDragging = insideHome.slice(rawIndex + 1);\n const effected = afterDragging.reduce((previous, item) => {\n previous[item.descriptor.id] = true;\n return previous;\n }, {});\n const afterCritical = {\n inVirtualList: home.descriptor.mode === 'virtual',\n displacedBy,\n effected\n };\n const displaced = getDisplacementGroups({\n afterDragging,\n destination: home,\n displacedBy,\n last: null,\n viewport: viewport.frame,\n forceShouldAnimate: false\n });\n const impact = {\n displaced,\n displacedBy,\n at: {\n type: 'REORDER',\n destination: getHomeLocation(draggable.descriptor)\n }\n };\n return {\n impact,\n afterCritical\n };\n});\n\nvar patchDimensionMap = ((dimensions, updated) => ({\n draggables: dimensions.draggables,\n droppables: patchDroppableMap(dimensions.droppables, updated)\n}));\n\nconst start = key => {\n if (process.env.NODE_ENV !== 'production') {\n {\n return;\n }\n }\n};\nconst finish = key => {\n if (process.env.NODE_ENV !== 'production') {\n {\n return;\n }\n }\n};\n\nvar offsetDraggable = (({\n draggable,\n offset: offset$1,\n initialWindowScroll\n}) => {\n const client = offset(draggable.client, offset$1);\n const page = withScroll(client, initialWindowScroll);\n const moved = {\n ...draggable,\n placeholder: {\n ...draggable.placeholder,\n client\n },\n client,\n page\n };\n return moved;\n});\n\nvar getFrame = (droppable => {\n const frame = droppable.frame;\n !frame ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected Droppable to have a frame') : invariant(false) : void 0;\n return frame;\n});\n\nvar adjustAdditionsForScrollChanges = (({\n additions,\n updatedDroppables,\n viewport\n}) => {\n const windowScrollChange = viewport.scroll.diff.value;\n return additions.map(draggable => {\n const droppableId = draggable.descriptor.droppableId;\n const modified = updatedDroppables[droppableId];\n const frame = getFrame(modified);\n const droppableScrollChange = frame.scroll.diff.value;\n const totalChange = add(windowScrollChange, droppableScrollChange);\n const moved = offsetDraggable({\n draggable,\n offset: totalChange,\n initialWindowScroll: viewport.scroll.initial\n });\n return moved;\n });\n});\n\nconst timingsKey = 'Processing dynamic changes';\nvar publishWhileDraggingInVirtual = (({\n state,\n published\n}) => {\n start();\n const withScrollChange = published.modified.map(update => {\n const existing = state.dimensions.droppables[update.droppableId];\n const scrolled = scrollDroppable(existing, update.scroll);\n return scrolled;\n });\n const droppables = {\n ...state.dimensions.droppables,\n ...toDroppableMap(withScrollChange)\n };\n const updatedAdditions = toDraggableMap(adjustAdditionsForScrollChanges({\n additions: published.additions,\n updatedDroppables: droppables,\n viewport: state.viewport\n }));\n const draggables = {\n ...state.dimensions.draggables,\n ...updatedAdditions\n };\n published.removals.forEach(id => {\n delete draggables[id];\n });\n const dimensions = {\n droppables,\n draggables\n };\n const wasOverId = whatIsDraggedOver(state.impact);\n const wasOver = wasOverId ? dimensions.droppables[wasOverId] : null;\n const draggable = dimensions.draggables[state.critical.draggable.id];\n const home = dimensions.droppables[state.critical.droppable.id];\n const {\n impact: onLiftImpact,\n afterCritical\n } = getLiftEffect({\n draggable,\n home,\n draggables,\n viewport: state.viewport\n });\n const previousImpact = wasOver && wasOver.isCombineEnabled ? state.impact : onLiftImpact;\n const impact = getDragImpact({\n pageOffset: state.current.page.offset,\n draggable: dimensions.draggables[state.critical.draggable.id],\n draggables: dimensions.draggables,\n droppables: dimensions.droppables,\n previousImpact,\n viewport: state.viewport,\n afterCritical\n });\n finish(timingsKey);\n const draggingState = {\n ...state,\n phase: 'DRAGGING',\n impact,\n onLiftImpact,\n dimensions,\n afterCritical,\n forceShouldAnimate: false\n };\n if (state.phase === 'COLLECTING') {\n return draggingState;\n }\n const dropPending = {\n ...draggingState,\n phase: 'DROP_PENDING',\n reason: state.reason,\n isWaiting: false\n };\n return dropPending;\n});\n\nconst isSnapping = state => state.movementMode === 'SNAP';\nconst postDroppableChange = (state, updated, isEnabledChanging) => {\n const dimensions = patchDimensionMap(state.dimensions, updated);\n if (!isSnapping(state) || isEnabledChanging) {\n return update({\n state,\n dimensions\n });\n }\n return refreshSnap({\n state,\n dimensions\n });\n};\nfunction removeScrollJumpRequest(state) {\n if (state.isDragging && state.movementMode === 'SNAP') {\n return {\n ...state,\n scrollJumpRequest: null\n };\n }\n return state;\n}\nconst idle$2 = {\n phase: 'IDLE',\n completed: null,\n shouldFlush: false\n};\nvar reducer = ((state = idle$2, action) => {\n if (action.type === 'FLUSH') {\n return {\n ...idle$2,\n shouldFlush: true\n };\n }\n if (action.type === 'INITIAL_PUBLISH') {\n !(state.phase === 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'INITIAL_PUBLISH must come after a IDLE phase') : invariant(false) : void 0;\n const {\n critical,\n clientSelection,\n viewport,\n dimensions,\n movementMode\n } = action.payload;\n const draggable = dimensions.draggables[critical.draggable.id];\n const home = dimensions.droppables[critical.droppable.id];\n const client = {\n selection: clientSelection,\n borderBoxCenter: draggable.client.borderBox.center,\n offset: origin\n };\n const initial = {\n client,\n page: {\n selection: add(client.selection, viewport.scroll.initial),\n borderBoxCenter: add(client.selection, viewport.scroll.initial),\n offset: add(client.selection, viewport.scroll.diff.value)\n }\n };\n const isWindowScrollAllowed = toDroppableList(dimensions.droppables).every(item => !item.isFixedOnPage);\n const {\n impact,\n afterCritical\n } = getLiftEffect({\n draggable,\n home,\n draggables: dimensions.draggables,\n viewport\n });\n const result = {\n phase: 'DRAGGING',\n isDragging: true,\n critical,\n movementMode,\n dimensions,\n initial,\n current: initial,\n isWindowScrollAllowed,\n impact,\n afterCritical,\n onLiftImpact: impact,\n viewport,\n scrollJumpRequest: null,\n forceShouldAnimate: null\n };\n return result;\n }\n if (action.type === 'COLLECTION_STARTING') {\n if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {\n return state;\n }\n !(state.phase === 'DRAGGING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Collection cannot start from phase ${state.phase}`) : invariant(false) : void 0;\n const result = {\n ...state,\n phase: 'COLLECTING'\n };\n return result;\n }\n if (action.type === 'PUBLISH_WHILE_DRAGGING') {\n !(state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Unexpected ${action.type} received in phase ${state.phase}`) : invariant(false) : void 0;\n return publishWhileDraggingInVirtual({\n state,\n published: action.payload\n });\n }\n if (action.type === 'MOVE') {\n if (state.phase === 'DROP_PENDING') {\n return state;\n }\n !isMovementAllowed(state) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : invariant(false) : void 0;\n const {\n client: clientSelection\n } = action.payload;\n if (isEqual$1(clientSelection, state.current.client.selection)) {\n return state;\n }\n return update({\n state,\n clientSelection,\n impact: isSnapping(state) ? state.impact : null\n });\n }\n if (action.type === 'UPDATE_DROPPABLE_SCROLL') {\n if (state.phase === 'DROP_PENDING') {\n return removeScrollJumpRequest(state);\n }\n if (state.phase === 'COLLECTING') {\n return removeScrollJumpRequest(state);\n }\n !isMovementAllowed(state) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `${action.type} not permitted in phase ${state.phase}`) : invariant(false) : void 0;\n const {\n id,\n newScroll\n } = action.payload;\n const target = state.dimensions.droppables[id];\n if (!target) {\n return state;\n }\n const scrolled = scrollDroppable(target, newScroll);\n return postDroppableChange(state, scrolled, false);\n }\n if (action.type === 'UPDATE_DROPPABLE_IS_ENABLED') {\n if (state.phase === 'DROP_PENDING') {\n return state;\n }\n !isMovementAllowed(state) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : invariant(false) : void 0;\n const {\n id,\n isEnabled\n } = action.payload;\n const target = state.dimensions.droppables[id];\n !target ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its enabled state`) : invariant(false) : void 0;\n !(target.isEnabled !== isEnabled) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Trying to set droppable isEnabled to ${String(isEnabled)}\n but it is already ${String(target.isEnabled)}`) : invariant(false) : void 0;\n const updated = {\n ...target,\n isEnabled\n };\n return postDroppableChange(state, updated, true);\n }\n if (action.type === 'UPDATE_DROPPABLE_IS_COMBINE_ENABLED') {\n if (state.phase === 'DROP_PENDING') {\n return state;\n }\n !isMovementAllowed(state) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Attempting to move in an unsupported phase ${state.phase}`) : invariant(false) : void 0;\n const {\n id,\n isCombineEnabled\n } = action.payload;\n const target = state.dimensions.droppables[id];\n !target ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot find Droppable[id: ${id}] to toggle its isCombineEnabled state`) : invariant(false) : void 0;\n !(target.isCombineEnabled !== isCombineEnabled) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Trying to set droppable isCombineEnabled to ${String(isCombineEnabled)}\n but it is already ${String(target.isCombineEnabled)}`) : invariant(false) : void 0;\n const updated = {\n ...target,\n isCombineEnabled\n };\n return postDroppableChange(state, updated, true);\n }\n if (action.type === 'MOVE_BY_WINDOW_SCROLL') {\n if (state.phase === 'DROP_PENDING' || state.phase === 'DROP_ANIMATING') {\n return state;\n }\n !isMovementAllowed(state) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot move by window in phase ${state.phase}`) : invariant(false) : void 0;\n !state.isWindowScrollAllowed ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Window scrolling is currently not supported for fixed lists') : invariant(false) : void 0;\n const newScroll = action.payload.newScroll;\n if (isEqual$1(state.viewport.scroll.current, newScroll)) {\n return removeScrollJumpRequest(state);\n }\n const viewport = scrollViewport(state.viewport, newScroll);\n if (isSnapping(state)) {\n return refreshSnap({\n state,\n viewport\n });\n }\n return update({\n state,\n viewport\n });\n }\n if (action.type === 'UPDATE_VIEWPORT_MAX_SCROLL') {\n if (!isMovementAllowed(state)) {\n return state;\n }\n const maxScroll = action.payload.maxScroll;\n if (isEqual$1(maxScroll, state.viewport.scroll.max)) {\n return state;\n }\n const withMaxScroll = {\n ...state.viewport,\n scroll: {\n ...state.viewport.scroll,\n max: maxScroll\n }\n };\n return {\n ...state,\n viewport: withMaxScroll\n };\n }\n if (action.type === 'MOVE_UP' || action.type === 'MOVE_DOWN' || action.type === 'MOVE_LEFT' || action.type === 'MOVE_RIGHT') {\n if (state.phase === 'COLLECTING' || state.phase === 'DROP_PENDING') {\n return state;\n }\n !(state.phase === 'DRAGGING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `${action.type} received while not in DRAGGING phase`) : invariant(false) : void 0;\n const result = moveInDirection({\n state,\n type: action.type\n });\n if (!result) {\n return state;\n }\n return update({\n state,\n impact: result.impact,\n clientSelection: result.clientSelection,\n scrollJumpRequest: result.scrollJumpRequest\n });\n }\n if (action.type === 'DROP_PENDING') {\n const reason = action.payload.reason;\n !(state.phase === 'COLLECTING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Can only move into the DROP_PENDING phase from the COLLECTING phase') : invariant(false) : void 0;\n const newState = {\n ...state,\n phase: 'DROP_PENDING',\n isWaiting: true,\n reason\n };\n return newState;\n }\n if (action.type === 'DROP_ANIMATE') {\n const {\n completed,\n dropDuration,\n newHomeClientOffset\n } = action.payload;\n !(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot animate drop from phase ${state.phase}`) : invariant(false) : void 0;\n const result = {\n phase: 'DROP_ANIMATING',\n completed,\n dropDuration,\n newHomeClientOffset,\n dimensions: state.dimensions\n };\n return result;\n }\n if (action.type === 'DROP_COMPLETE') {\n const {\n completed\n } = action.payload;\n return {\n phase: 'IDLE',\n completed,\n shouldFlush: false\n };\n }\n return state;\n});\n\nconst beforeInitialCapture = args => ({\n type: 'BEFORE_INITIAL_CAPTURE',\n payload: args\n});\nconst lift$1 = args => ({\n type: 'LIFT',\n payload: args\n});\nconst initialPublish = args => ({\n type: 'INITIAL_PUBLISH',\n payload: args\n});\nconst publishWhileDragging = args => ({\n type: 'PUBLISH_WHILE_DRAGGING',\n payload: args\n});\nconst collectionStarting = () => ({\n type: 'COLLECTION_STARTING',\n payload: null\n});\nconst updateDroppableScroll = args => ({\n type: 'UPDATE_DROPPABLE_SCROLL',\n payload: args\n});\nconst updateDroppableIsEnabled = args => ({\n type: 'UPDATE_DROPPABLE_IS_ENABLED',\n payload: args\n});\nconst updateDroppableIsCombineEnabled = args => ({\n type: 'UPDATE_DROPPABLE_IS_COMBINE_ENABLED',\n payload: args\n});\nconst move = args => ({\n type: 'MOVE',\n payload: args\n});\nconst moveByWindowScroll = args => ({\n type: 'MOVE_BY_WINDOW_SCROLL',\n payload: args\n});\nconst updateViewportMaxScroll = args => ({\n type: 'UPDATE_VIEWPORT_MAX_SCROLL',\n payload: args\n});\nconst moveUp = () => ({\n type: 'MOVE_UP',\n payload: null\n});\nconst moveDown = () => ({\n type: 'MOVE_DOWN',\n payload: null\n});\nconst moveRight = () => ({\n type: 'MOVE_RIGHT',\n payload: null\n});\nconst moveLeft = () => ({\n type: 'MOVE_LEFT',\n payload: null\n});\nconst flush = () => ({\n type: 'FLUSH',\n payload: null\n});\nconst animateDrop = args => ({\n type: 'DROP_ANIMATE',\n payload: args\n});\nconst completeDrop = args => ({\n type: 'DROP_COMPLETE',\n payload: args\n});\nconst drop$1 = args => ({\n type: 'DROP',\n payload: args\n});\nconst dropPending = args => ({\n type: 'DROP_PENDING',\n payload: args\n});\nconst dropAnimationFinished = () => ({\n type: 'DROP_ANIMATION_FINISHED',\n payload: null\n});\n\nfunction checkIndexes(insideDestination) {\n if (insideDestination.length <= 1) {\n return;\n }\n const indexes = insideDestination.map(d => d.descriptor.index);\n const errors = {};\n for (let i = 1; i < indexes.length; i++) {\n const current = indexes[i];\n const previous = indexes[i - 1];\n if (current !== previous + 1) {\n errors[current] = true;\n }\n }\n if (!Object.keys(errors).length) {\n return;\n }\n const formatted = indexes.map(index => {\n const hasError = Boolean(errors[index]);\n return hasError ? `[🔥${index}]` : `${index}`;\n }).join(', ');\n process.env.NODE_ENV !== \"production\" ? warning(`\n Detected non-consecutive
indexes.\n\n (This can cause unexpected bugs)\n\n ${formatted}\n `) : void 0;\n}\nfunction validateDimensions(critical, dimensions) {\n if (process.env.NODE_ENV !== 'production') {\n const insideDestination = getDraggablesInsideDroppable(critical.droppable.id, dimensions.draggables);\n checkIndexes(insideDestination);\n }\n}\n\nvar lift = (marshal => ({\n getState,\n dispatch\n}) => next => action => {\n if (action.type !== 'LIFT') {\n next(action);\n return;\n }\n const {\n id,\n clientSelection,\n movementMode\n } = action.payload;\n const initial = getState();\n if (initial.phase === 'DROP_ANIMATING') {\n dispatch(completeDrop({\n completed: initial.completed\n }));\n }\n !(getState().phase === 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Unexpected phase to start a drag') : invariant(false) : void 0;\n dispatch(flush());\n dispatch(beforeInitialCapture({\n draggableId: id,\n movementMode\n }));\n const scrollOptions = {\n shouldPublishImmediately: movementMode === 'SNAP'\n };\n const request = {\n draggableId: id,\n scrollOptions\n };\n const {\n critical,\n dimensions,\n viewport\n } = marshal.startPublishing(request);\n validateDimensions(critical, dimensions);\n dispatch(initialPublish({\n critical,\n dimensions,\n clientSelection,\n movementMode,\n viewport\n }));\n});\n\nvar style = (marshal => () => next => action => {\n if (action.type === 'INITIAL_PUBLISH') {\n marshal.dragging();\n }\n if (action.type === 'DROP_ANIMATE') {\n marshal.dropping(action.payload.completed.result.reason);\n }\n if (action.type === 'FLUSH' || action.type === 'DROP_COMPLETE') {\n marshal.resting();\n }\n next(action);\n});\n\nconst curves = {\n outOfTheWay: 'cubic-bezier(0.2, 0, 0, 1)',\n drop: 'cubic-bezier(.2,1,.1,1)'\n};\nconst combine = {\n opacity: {\n drop: 0,\n combining: 0.7\n },\n scale: {\n drop: 0.75\n }\n};\nconst timings = {\n outOfTheWay: 0.2,\n minDropTime: 0.33,\n maxDropTime: 0.55\n};\nconst outOfTheWayTiming = `${timings.outOfTheWay}s ${curves.outOfTheWay}`;\nconst transitions = {\n fluid: `opacity ${outOfTheWayTiming}`,\n snap: `transform ${outOfTheWayTiming}, opacity ${outOfTheWayTiming}`,\n drop: duration => {\n const timing = `${duration}s ${curves.drop}`;\n return `transform ${timing}, opacity ${timing}`;\n },\n outOfTheWay: `transform ${outOfTheWayTiming}`,\n placeholder: `height ${outOfTheWayTiming}, width ${outOfTheWayTiming}, margin ${outOfTheWayTiming}`\n};\nconst moveTo = offset => isEqual$1(offset, origin) ? undefined : `translate(${offset.x}px, ${offset.y}px)`;\nconst transforms = {\n moveTo,\n drop: (offset, isCombining) => {\n const translate = moveTo(offset);\n if (!translate) {\n return undefined;\n }\n if (!isCombining) {\n return translate;\n }\n return `${translate} scale(${combine.scale.drop})`;\n }\n};\n\nconst {\n minDropTime,\n maxDropTime\n} = timings;\nconst dropTimeRange = maxDropTime - minDropTime;\nconst maxDropTimeAtDistance = 1500;\nconst cancelDropModifier = 0.6;\nvar getDropDuration = (({\n current,\n destination,\n reason\n}) => {\n const distance$1 = distance(current, destination);\n if (distance$1 <= 0) {\n return minDropTime;\n }\n if (distance$1 >= maxDropTimeAtDistance) {\n return maxDropTime;\n }\n const percentage = distance$1 / maxDropTimeAtDistance;\n const duration = minDropTime + dropTimeRange * percentage;\n const withDuration = reason === 'CANCEL' ? duration * cancelDropModifier : duration;\n return Number(withDuration.toFixed(2));\n});\n\nvar getNewHomeClientOffset = (({\n impact,\n draggable,\n dimensions,\n viewport,\n afterCritical\n}) => {\n const {\n draggables,\n droppables\n } = dimensions;\n const droppableId = whatIsDraggedOver(impact);\n const destination = droppableId ? droppables[droppableId] : null;\n const home = droppables[draggable.descriptor.droppableId];\n const newClientCenter = getClientBorderBoxCenter({\n impact,\n draggable,\n draggables,\n afterCritical,\n droppable: destination || home,\n viewport\n });\n const offset = subtract(newClientCenter, draggable.client.borderBox.center);\n return offset;\n});\n\nvar getDropImpact = (({\n draggables,\n reason,\n lastImpact,\n home,\n viewport,\n onLiftImpact\n}) => {\n if (!lastImpact.at || reason !== 'DROP') {\n const recomputedHomeImpact = recompute({\n draggables,\n impact: onLiftImpact,\n destination: home,\n viewport,\n forceShouldAnimate: true\n });\n return {\n impact: recomputedHomeImpact,\n didDropInsideDroppable: false\n };\n }\n if (lastImpact.at.type === 'REORDER') {\n return {\n impact: lastImpact,\n didDropInsideDroppable: true\n };\n }\n const withoutMovement = {\n ...lastImpact,\n displaced: emptyGroups\n };\n return {\n impact: withoutMovement,\n didDropInsideDroppable: true\n };\n});\n\nconst dropMiddleware = ({\n getState,\n dispatch\n}) => next => action => {\n if (action.type !== 'DROP') {\n next(action);\n return;\n }\n const state = getState();\n const reason = action.payload.reason;\n if (state.phase === 'COLLECTING') {\n dispatch(dropPending({\n reason\n }));\n return;\n }\n if (state.phase === 'IDLE') {\n return;\n }\n const isWaitingForDrop = state.phase === 'DROP_PENDING' && state.isWaiting;\n !!isWaitingForDrop ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'A DROP action occurred while DROP_PENDING and still waiting') : invariant(false) : void 0;\n !(state.phase === 'DRAGGING' || state.phase === 'DROP_PENDING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot drop in phase: ${state.phase}`) : invariant(false) : void 0;\n const critical = state.critical;\n const dimensions = state.dimensions;\n const draggable = dimensions.draggables[state.critical.draggable.id];\n const {\n impact,\n didDropInsideDroppable\n } = getDropImpact({\n reason,\n lastImpact: state.impact,\n afterCritical: state.afterCritical,\n onLiftImpact: state.onLiftImpact,\n home: state.dimensions.droppables[state.critical.droppable.id],\n viewport: state.viewport,\n draggables: state.dimensions.draggables\n });\n const destination = didDropInsideDroppable ? tryGetDestination(impact) : null;\n const combine = didDropInsideDroppable ? tryGetCombine(impact) : null;\n const source = {\n index: critical.draggable.index,\n droppableId: critical.droppable.id\n };\n const result = {\n draggableId: draggable.descriptor.id,\n type: draggable.descriptor.type,\n source,\n reason,\n mode: state.movementMode,\n destination,\n combine\n };\n const newHomeClientOffset = getNewHomeClientOffset({\n impact,\n draggable,\n dimensions,\n viewport: state.viewport,\n afterCritical: state.afterCritical\n });\n const completed = {\n critical: state.critical,\n afterCritical: state.afterCritical,\n result,\n impact\n };\n const isAnimationRequired = !isEqual$1(state.current.client.offset, newHomeClientOffset) || Boolean(result.combine);\n if (!isAnimationRequired) {\n dispatch(completeDrop({\n completed\n }));\n return;\n }\n const dropDuration = getDropDuration({\n current: state.current.client.offset,\n destination: newHomeClientOffset,\n reason\n });\n const args = {\n newHomeClientOffset,\n dropDuration,\n completed\n };\n dispatch(animateDrop(args));\n};\nvar drop = dropMiddleware;\n\nvar getWindowScroll = (() => ({\n x: window.pageXOffset,\n y: window.pageYOffset\n}));\n\nfunction getWindowScrollBinding(update) {\n return {\n eventName: 'scroll',\n options: {\n passive: true,\n capture: false\n },\n fn: event => {\n if (event.target !== window && event.target !== window.document) {\n return;\n }\n update();\n }\n };\n}\nfunction getScrollListener({\n onWindowScroll\n}) {\n function updateScroll() {\n onWindowScroll(getWindowScroll());\n }\n const scheduled = rafSchd(updateScroll);\n const binding = getWindowScrollBinding(scheduled);\n let unbind = noop$2;\n function isActive() {\n return unbind !== noop$2;\n }\n function start() {\n !!isActive() ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot start scroll listener when already active') : invariant(false) : void 0;\n unbind = bindEvents(window, [binding]);\n }\n function stop() {\n !isActive() ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot stop scroll listener when not active') : invariant(false) : void 0;\n scheduled.cancel();\n unbind();\n unbind = noop$2;\n }\n return {\n start,\n stop,\n isActive\n };\n}\n\nconst shouldEnd = action => action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATE' || action.type === 'FLUSH';\nconst scrollListener = store => {\n const listener = getScrollListener({\n onWindowScroll: newScroll => {\n store.dispatch(moveByWindowScroll({\n newScroll\n }));\n }\n });\n return next => action => {\n if (!listener.isActive() && action.type === 'INITIAL_PUBLISH') {\n listener.start();\n }\n if (listener.isActive() && shouldEnd(action)) {\n listener.stop();\n }\n next(action);\n };\n};\nvar scrollListener$1 = scrollListener;\n\nvar getExpiringAnnounce = (announce => {\n let wasCalled = false;\n let isExpired = false;\n const timeoutId = setTimeout(() => {\n isExpired = true;\n });\n const result = message => {\n if (wasCalled) {\n process.env.NODE_ENV !== \"production\" ? warning('Announcement already made. Not making a second announcement') : void 0;\n return;\n }\n if (isExpired) {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Announcements cannot be made asynchronously.\n Default message has already been announced.\n `) : void 0;\n return;\n }\n wasCalled = true;\n announce(message);\n clearTimeout(timeoutId);\n };\n result.wasCalled = () => wasCalled;\n return result;\n});\n\nvar getAsyncMarshal = (() => {\n const entries = [];\n const execute = timerId => {\n const index = entries.findIndex(item => item.timerId === timerId);\n !(index !== -1) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find timer') : invariant(false) : void 0;\n const [entry] = entries.splice(index, 1);\n entry.callback();\n };\n const add = fn => {\n const timerId = setTimeout(() => execute(timerId));\n const entry = {\n timerId,\n callback: fn\n };\n entries.push(entry);\n };\n const flush = () => {\n if (!entries.length) {\n return;\n }\n const shallow = [...entries];\n entries.length = 0;\n shallow.forEach(entry => {\n clearTimeout(entry.timerId);\n entry.callback();\n });\n };\n return {\n add,\n flush\n };\n});\n\nconst areLocationsEqual = (first, second) => {\n if (first == null && second == null) {\n return true;\n }\n if (first == null || second == null) {\n return false;\n }\n return first.droppableId === second.droppableId && first.index === second.index;\n};\nconst isCombineEqual = (first, second) => {\n if (first == null && second == null) {\n return true;\n }\n if (first == null || second == null) {\n return false;\n }\n return first.draggableId === second.draggableId && first.droppableId === second.droppableId;\n};\nconst isCriticalEqual = (first, second) => {\n if (first === second) {\n return true;\n }\n const isDraggableEqual = first.draggable.id === second.draggable.id && first.draggable.droppableId === second.draggable.droppableId && first.draggable.type === second.draggable.type && first.draggable.index === second.draggable.index;\n const isDroppableEqual = first.droppable.id === second.droppable.id && first.droppable.type === second.droppable.type;\n return isDraggableEqual && isDroppableEqual;\n};\n\nconst withTimings = (key, fn) => {\n start();\n fn();\n finish();\n};\nconst getDragStart = (critical, mode) => ({\n draggableId: critical.draggable.id,\n type: critical.droppable.type,\n source: {\n droppableId: critical.droppable.id,\n index: critical.draggable.index\n },\n mode\n});\nfunction execute(responder, data, announce, getDefaultMessage) {\n if (!responder) {\n announce(getDefaultMessage(data));\n return;\n }\n const willExpire = getExpiringAnnounce(announce);\n const provided = {\n announce: willExpire\n };\n responder(data, provided);\n if (!willExpire.wasCalled()) {\n announce(getDefaultMessage(data));\n }\n}\nvar getPublisher = ((getResponders, announce) => {\n const asyncMarshal = getAsyncMarshal();\n let dragging = null;\n const beforeCapture = (draggableId, mode) => {\n !!dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fire onBeforeCapture as a drag start has already been published') : invariant(false) : void 0;\n withTimings('onBeforeCapture', () => {\n const fn = getResponders().onBeforeCapture;\n if (fn) {\n const before = {\n draggableId,\n mode\n };\n fn(before);\n }\n });\n };\n const beforeStart = (critical, mode) => {\n !!dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : invariant(false) : void 0;\n withTimings('onBeforeDragStart', () => {\n const fn = getResponders().onBeforeDragStart;\n if (fn) {\n fn(getDragStart(critical, mode));\n }\n });\n };\n const start = (critical, mode) => {\n !!dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fire onBeforeDragStart as a drag start has already been published') : invariant(false) : void 0;\n const data = getDragStart(critical, mode);\n dragging = {\n mode,\n lastCritical: critical,\n lastLocation: data.source,\n lastCombine: null\n };\n asyncMarshal.add(() => {\n withTimings('onDragStart', () => execute(getResponders().onDragStart, data, announce, preset$1.onDragStart));\n });\n };\n const update = (critical, impact) => {\n const location = tryGetDestination(impact);\n const combine = tryGetCombine(impact);\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fire onDragMove when onDragStart has not been called') : invariant(false) : void 0;\n const hasCriticalChanged = !isCriticalEqual(critical, dragging.lastCritical);\n if (hasCriticalChanged) {\n dragging.lastCritical = critical;\n }\n const hasLocationChanged = !areLocationsEqual(dragging.lastLocation, location);\n if (hasLocationChanged) {\n dragging.lastLocation = location;\n }\n const hasGroupingChanged = !isCombineEqual(dragging.lastCombine, combine);\n if (hasGroupingChanged) {\n dragging.lastCombine = combine;\n }\n if (!hasCriticalChanged && !hasLocationChanged && !hasGroupingChanged) {\n return;\n }\n const data = {\n ...getDragStart(critical, dragging.mode),\n combine,\n destination: location\n };\n asyncMarshal.add(() => {\n withTimings('onDragUpdate', () => execute(getResponders().onDragUpdate, data, announce, preset$1.onDragUpdate));\n });\n };\n const flush = () => {\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Can only flush responders while dragging') : invariant(false) : void 0;\n asyncMarshal.flush();\n };\n const drop = result => {\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fire onDragEnd when there is no matching onDragStart') : invariant(false) : void 0;\n dragging = null;\n withTimings('onDragEnd', () => execute(getResponders().onDragEnd, result, announce, preset$1.onDragEnd));\n };\n const abort = () => {\n if (!dragging) {\n return;\n }\n const result = {\n ...getDragStart(dragging.lastCritical, dragging.mode),\n combine: null,\n destination: null,\n reason: 'CANCEL'\n };\n drop(result);\n };\n return {\n beforeCapture,\n beforeStart,\n start,\n update,\n flush,\n drop,\n abort\n };\n});\n\nvar responders = ((getResponders, announce) => {\n const publisher = getPublisher(getResponders, announce);\n return store => next => action => {\n if (action.type === 'BEFORE_INITIAL_CAPTURE') {\n publisher.beforeCapture(action.payload.draggableId, action.payload.movementMode);\n return;\n }\n if (action.type === 'INITIAL_PUBLISH') {\n const critical = action.payload.critical;\n publisher.beforeStart(critical, action.payload.movementMode);\n next(action);\n publisher.start(critical, action.payload.movementMode);\n return;\n }\n if (action.type === 'DROP_COMPLETE') {\n const result = action.payload.completed.result;\n publisher.flush();\n next(action);\n publisher.drop(result);\n return;\n }\n next(action);\n if (action.type === 'FLUSH') {\n publisher.abort();\n return;\n }\n const state = store.getState();\n if (state.phase === 'DRAGGING') {\n publisher.update(state.critical, state.impact);\n }\n };\n});\n\nconst dropAnimationFinishMiddleware = store => next => action => {\n if (action.type !== 'DROP_ANIMATION_FINISHED') {\n next(action);\n return;\n }\n const state = store.getState();\n !(state.phase === 'DROP_ANIMATING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot finish a drop animating when no drop is occurring') : invariant(false) : void 0;\n store.dispatch(completeDrop({\n completed: state.completed\n }));\n};\nvar dropAnimationFinish = dropAnimationFinishMiddleware;\n\nconst dropAnimationFlushOnScrollMiddleware = store => {\n let unbind = null;\n let frameId = null;\n function clear() {\n if (frameId) {\n cancelAnimationFrame(frameId);\n frameId = null;\n }\n if (unbind) {\n unbind();\n unbind = null;\n }\n }\n return next => action => {\n if (action.type === 'FLUSH' || action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATION_FINISHED') {\n clear();\n }\n next(action);\n if (action.type !== 'DROP_ANIMATE') {\n return;\n }\n const binding = {\n eventName: 'scroll',\n options: {\n capture: true,\n passive: false,\n once: true\n },\n fn: function flushDropAnimation() {\n const state = store.getState();\n if (state.phase === 'DROP_ANIMATING') {\n store.dispatch(dropAnimationFinished());\n }\n }\n };\n frameId = requestAnimationFrame(() => {\n frameId = null;\n unbind = bindEvents(window, [binding]);\n });\n };\n};\nvar dropAnimationFlushOnScroll = dropAnimationFlushOnScrollMiddleware;\n\nvar dimensionMarshalStopper = (marshal => () => next => action => {\n if (action.type === 'DROP_COMPLETE' || action.type === 'FLUSH' || action.type === 'DROP_ANIMATE') {\n marshal.stopPublishing();\n }\n next(action);\n});\n\nvar focus = (marshal => {\n let isWatching = false;\n return () => next => action => {\n if (action.type === 'INITIAL_PUBLISH') {\n isWatching = true;\n marshal.tryRecordFocus(action.payload.critical.draggable.id);\n next(action);\n marshal.tryRestoreFocusRecorded();\n return;\n }\n next(action);\n if (!isWatching) {\n return;\n }\n if (action.type === 'FLUSH') {\n isWatching = false;\n marshal.tryRestoreFocusRecorded();\n return;\n }\n if (action.type === 'DROP_COMPLETE') {\n isWatching = false;\n const result = action.payload.completed.result;\n if (result.combine) {\n marshal.tryShiftRecord(result.draggableId, result.combine.draggableId);\n }\n marshal.tryRestoreFocusRecorded();\n }\n };\n});\n\nconst shouldStop = action => action.type === 'DROP_COMPLETE' || action.type === 'DROP_ANIMATE' || action.type === 'FLUSH';\nvar autoScroll = (autoScroller => store => next => action => {\n if (shouldStop(action)) {\n autoScroller.stop();\n next(action);\n return;\n }\n if (action.type === 'INITIAL_PUBLISH') {\n next(action);\n const state = store.getState();\n !(state.phase === 'DRAGGING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected phase to be DRAGGING after INITIAL_PUBLISH') : invariant(false) : void 0;\n autoScroller.start(state);\n return;\n }\n next(action);\n autoScroller.scroll(store.getState());\n});\n\nconst pendingDrop = store => next => action => {\n next(action);\n if (action.type !== 'PUBLISH_WHILE_DRAGGING') {\n return;\n }\n const postActionState = store.getState();\n if (postActionState.phase !== 'DROP_PENDING') {\n return;\n }\n if (postActionState.isWaiting) {\n return;\n }\n store.dispatch(drop$1({\n reason: postActionState.reason\n }));\n};\nvar pendingDrop$1 = pendingDrop;\n\nconst composeEnhancers = process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({\n name: '@hello-pangea/dnd'\n}) : compose;\nvar createStore = (({\n dimensionMarshal,\n focusMarshal,\n styleMarshal,\n getResponders,\n announce,\n autoScroller\n}) => createStore$1(reducer, composeEnhancers(applyMiddleware(style(styleMarshal), dimensionMarshalStopper(dimensionMarshal), lift(dimensionMarshal), drop, dropAnimationFinish, dropAnimationFlushOnScroll, pendingDrop$1, autoScroll(autoScroller), scrollListener$1, focus(focusMarshal), responders(getResponders, announce)))));\n\nconst clean$1 = () => ({\n additions: {},\n removals: {},\n modified: {}\n});\nfunction createPublisher({\n registry,\n callbacks\n}) {\n let staging = clean$1();\n let frameId = null;\n const collect = () => {\n if (frameId) {\n return;\n }\n callbacks.collectionStarting();\n frameId = requestAnimationFrame(() => {\n frameId = null;\n start();\n const {\n additions,\n removals,\n modified\n } = staging;\n const added = Object.keys(additions).map(id => registry.draggable.getById(id).getDimension(origin)).sort((a, b) => a.descriptor.index - b.descriptor.index);\n const updated = Object.keys(modified).map(id => {\n const entry = registry.droppable.getById(id);\n const scroll = entry.callbacks.getScrollWhileDragging();\n return {\n droppableId: id,\n scroll\n };\n });\n const result = {\n additions: added,\n removals: Object.keys(removals),\n modified: updated\n };\n staging = clean$1();\n finish();\n callbacks.publish(result);\n });\n };\n const add = entry => {\n const id = entry.descriptor.id;\n staging.additions[id] = entry;\n staging.modified[entry.descriptor.droppableId] = true;\n if (staging.removals[id]) {\n delete staging.removals[id];\n }\n collect();\n };\n const remove = entry => {\n const descriptor = entry.descriptor;\n staging.removals[descriptor.id] = true;\n staging.modified[descriptor.droppableId] = true;\n if (staging.additions[descriptor.id]) {\n delete staging.additions[descriptor.id];\n }\n collect();\n };\n const stop = () => {\n if (!frameId) {\n return;\n }\n cancelAnimationFrame(frameId);\n frameId = null;\n staging = clean$1();\n };\n return {\n add,\n remove,\n stop\n };\n}\n\nvar getMaxScroll = (({\n scrollHeight,\n scrollWidth,\n height,\n width\n}) => {\n const maxScroll = subtract({\n x: scrollWidth,\n y: scrollHeight\n }, {\n x: width,\n y: height\n });\n const adjustedMaxScroll = {\n x: Math.max(0, maxScroll.x),\n y: Math.max(0, maxScroll.y)\n };\n return adjustedMaxScroll;\n});\n\nvar getDocumentElement = (() => {\n const doc = document.documentElement;\n !doc ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot find document.documentElement') : invariant(false) : void 0;\n return doc;\n});\n\nvar getMaxWindowScroll = (() => {\n const doc = getDocumentElement();\n const maxScroll = getMaxScroll({\n scrollHeight: doc.scrollHeight,\n scrollWidth: doc.scrollWidth,\n width: doc.clientWidth,\n height: doc.clientHeight\n });\n return maxScroll;\n});\n\nvar getViewport = (() => {\n const scroll = getWindowScroll();\n const maxScroll = getMaxWindowScroll();\n const top = scroll.y;\n const left = scroll.x;\n const doc = getDocumentElement();\n const width = doc.clientWidth;\n const height = doc.clientHeight;\n const right = left + width;\n const bottom = top + height;\n const frame = getRect({\n top,\n left,\n right,\n bottom\n });\n const viewport = {\n frame,\n scroll: {\n initial: scroll,\n current: scroll,\n max: maxScroll,\n diff: {\n value: origin,\n displacement: origin\n }\n }\n };\n return viewport;\n});\n\nvar getInitialPublish = (({\n critical,\n scrollOptions,\n registry\n}) => {\n start();\n const viewport = getViewport();\n const windowScroll = viewport.scroll.current;\n const home = critical.droppable;\n const droppables = registry.droppable.getAllByType(home.type).map(entry => entry.callbacks.getDimensionAndWatchScroll(windowScroll, scrollOptions));\n const draggables = registry.draggable.getAllByType(critical.draggable.type).map(entry => entry.getDimension(windowScroll));\n const dimensions = {\n draggables: toDraggableMap(draggables),\n droppables: toDroppableMap(droppables)\n };\n finish();\n const result = {\n dimensions,\n critical,\n viewport\n };\n return result;\n});\n\nfunction shouldPublishUpdate(registry, dragging, entry) {\n if (entry.descriptor.id === dragging.id) {\n return false;\n }\n if (entry.descriptor.type !== dragging.type) {\n return false;\n }\n const home = registry.droppable.getById(entry.descriptor.droppableId);\n if (home.descriptor.mode !== 'virtual') {\n process.env.NODE_ENV !== \"production\" ? warning(`\n You are attempting to add or remove a Draggable [id: ${entry.descriptor.id}]\n while a drag is occurring. This is only supported for virtual lists.\n\n See https://github.com/hello-pangea/dnd/blob/main/docs/patterns/virtual-lists.md\n `) : void 0;\n return false;\n }\n return true;\n}\nvar createDimensionMarshal = ((registry, callbacks) => {\n let collection = null;\n const publisher = createPublisher({\n callbacks: {\n publish: callbacks.publishWhileDragging,\n collectionStarting: callbacks.collectionStarting\n },\n registry\n });\n const updateDroppableIsEnabled = (id, isEnabled) => {\n !registry.droppable.exists(id) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot update is enabled flag of Droppable ${id} as it is not registered`) : invariant(false) : void 0;\n if (!collection) {\n return;\n }\n callbacks.updateDroppableIsEnabled({\n id,\n isEnabled\n });\n };\n const updateDroppableIsCombineEnabled = (id, isCombineEnabled) => {\n if (!collection) {\n return;\n }\n !registry.droppable.exists(id) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot update isCombineEnabled flag of Droppable ${id} as it is not registered`) : invariant(false) : void 0;\n callbacks.updateDroppableIsCombineEnabled({\n id,\n isCombineEnabled\n });\n };\n const updateDroppableScroll = (id, newScroll) => {\n if (!collection) {\n return;\n }\n !registry.droppable.exists(id) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot update the scroll on Droppable ${id} as it is not registered`) : invariant(false) : void 0;\n callbacks.updateDroppableScroll({\n id,\n newScroll\n });\n };\n const scrollDroppable = (id, change) => {\n if (!collection) {\n return;\n }\n registry.droppable.getById(id).callbacks.scroll(change);\n };\n const stopPublishing = () => {\n if (!collection) {\n return;\n }\n publisher.stop();\n const home = collection.critical.droppable;\n registry.droppable.getAllByType(home.type).forEach(entry => entry.callbacks.dragStopped());\n collection.unsubscribe();\n collection = null;\n };\n const subscriber = event => {\n !collection ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Should only be subscribed when a collection is occurring') : invariant(false) : void 0;\n const dragging = collection.critical.draggable;\n if (event.type === 'ADDITION') {\n if (shouldPublishUpdate(registry, dragging, event.value)) {\n publisher.add(event.value);\n }\n }\n if (event.type === 'REMOVAL') {\n if (shouldPublishUpdate(registry, dragging, event.value)) {\n publisher.remove(event.value);\n }\n }\n };\n const startPublishing = request => {\n !!collection ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot start capturing critical dimensions as there is already a collection') : invariant(false) : void 0;\n const entry = registry.draggable.getById(request.draggableId);\n const home = registry.droppable.getById(entry.descriptor.droppableId);\n const critical = {\n draggable: entry.descriptor,\n droppable: home.descriptor\n };\n const unsubscribe = registry.subscribe(subscriber);\n collection = {\n critical,\n unsubscribe\n };\n return getInitialPublish({\n critical,\n registry,\n scrollOptions: request.scrollOptions\n });\n };\n const marshal = {\n updateDroppableIsEnabled,\n updateDroppableIsCombineEnabled,\n scrollDroppable,\n updateDroppableScroll,\n startPublishing,\n stopPublishing\n };\n return marshal;\n});\n\nvar canStartDrag = ((state, id) => {\n if (state.phase === 'IDLE') {\n return true;\n }\n if (state.phase !== 'DROP_ANIMATING') {\n return false;\n }\n if (state.completed.result.draggableId === id) {\n return false;\n }\n return state.completed.result.reason === 'DROP';\n});\n\nvar scrollWindow = (change => {\n window.scrollBy(change.x, change.y);\n});\n\nconst getScrollableDroppables = memoizeOne(droppables => toDroppableList(droppables).filter(droppable => {\n if (!droppable.isEnabled) {\n return false;\n }\n if (!droppable.frame) {\n return false;\n }\n return true;\n}));\nconst getScrollableDroppableOver = (target, droppables) => {\n const maybe = getScrollableDroppables(droppables).find(droppable => {\n !droppable.frame ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Invalid result') : invariant(false) : void 0;\n return isPositionInFrame(droppable.frame.pageMarginBox)(target);\n }) || null;\n return maybe;\n};\nvar getBestScrollableDroppable = (({\n center,\n destination,\n droppables\n}) => {\n if (destination) {\n const dimension = droppables[destination];\n if (!dimension.frame) {\n return null;\n }\n return dimension;\n }\n const dimension = getScrollableDroppableOver(center, droppables);\n return dimension;\n});\n\nconst defaultAutoScrollerOptions = {\n startFromPercentage: 0.25,\n maxScrollAtPercentage: 0.05,\n maxPixelScroll: 28,\n ease: percentage => percentage ** 2,\n durationDampening: {\n stopDampeningAt: 1200,\n accelerateAt: 360\n },\n disabled: false\n};\n\nvar getDistanceThresholds = ((container, axis, getAutoScrollerOptions = () => defaultAutoScrollerOptions) => {\n const autoScrollerOptions = getAutoScrollerOptions();\n const startScrollingFrom = container[axis.size] * autoScrollerOptions.startFromPercentage;\n const maxScrollValueAt = container[axis.size] * autoScrollerOptions.maxScrollAtPercentage;\n const thresholds = {\n startScrollingFrom,\n maxScrollValueAt\n };\n return thresholds;\n});\n\nvar getPercentage = (({\n startOfRange,\n endOfRange,\n current\n}) => {\n const range = endOfRange - startOfRange;\n if (range === 0) {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Detected distance range of 0 in the fluid auto scroller\n This is unexpected and would cause a divide by 0 issue.\n Not allowing an auto scroll\n `) : void 0;\n return 0;\n }\n const currentInRange = current - startOfRange;\n const percentage = currentInRange / range;\n return percentage;\n});\n\nvar minScroll = 1;\n\nvar getValueFromDistance = ((distanceToEdge, thresholds, getAutoScrollerOptions = () => defaultAutoScrollerOptions) => {\n const autoScrollerOptions = getAutoScrollerOptions();\n if (distanceToEdge > thresholds.startScrollingFrom) {\n return 0;\n }\n if (distanceToEdge <= thresholds.maxScrollValueAt) {\n return autoScrollerOptions.maxPixelScroll;\n }\n if (distanceToEdge === thresholds.startScrollingFrom) {\n return minScroll;\n }\n const percentageFromMaxScrollValueAt = getPercentage({\n startOfRange: thresholds.maxScrollValueAt,\n endOfRange: thresholds.startScrollingFrom,\n current: distanceToEdge\n });\n const percentageFromStartScrollingFrom = 1 - percentageFromMaxScrollValueAt;\n const scroll = autoScrollerOptions.maxPixelScroll * autoScrollerOptions.ease(percentageFromStartScrollingFrom);\n return Math.ceil(scroll);\n});\n\nvar dampenValueByTime = ((proposedScroll, dragStartTime, getAutoScrollerOptions) => {\n const autoScrollerOptions = getAutoScrollerOptions();\n const accelerateAt = autoScrollerOptions.durationDampening.accelerateAt;\n const stopAt = autoScrollerOptions.durationDampening.stopDampeningAt;\n const startOfRange = dragStartTime;\n const endOfRange = stopAt;\n const now = Date.now();\n const runTime = now - startOfRange;\n if (runTime >= stopAt) {\n return proposedScroll;\n }\n if (runTime < accelerateAt) {\n return minScroll;\n }\n const betweenAccelerateAtAndStopAtPercentage = getPercentage({\n startOfRange: accelerateAt,\n endOfRange,\n current: runTime\n });\n const scroll = proposedScroll * autoScrollerOptions.ease(betweenAccelerateAtAndStopAtPercentage);\n return Math.ceil(scroll);\n});\n\nvar getValue = (({\n distanceToEdge,\n thresholds,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n}) => {\n const scroll = getValueFromDistance(distanceToEdge, thresholds, getAutoScrollerOptions);\n if (scroll === 0) {\n return 0;\n }\n if (!shouldUseTimeDampening) {\n return scroll;\n }\n return Math.max(dampenValueByTime(scroll, dragStartTime, getAutoScrollerOptions), minScroll);\n});\n\nvar getScrollOnAxis = (({\n container,\n distanceToEdges,\n dragStartTime,\n axis,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n}) => {\n const thresholds = getDistanceThresholds(container, axis, getAutoScrollerOptions);\n const isCloserToEnd = distanceToEdges[axis.end] < distanceToEdges[axis.start];\n if (isCloserToEnd) {\n return getValue({\n distanceToEdge: distanceToEdges[axis.end],\n thresholds,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n }\n return -1 * getValue({\n distanceToEdge: distanceToEdges[axis.start],\n thresholds,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n});\n\nvar adjustForSizeLimits = (({\n container,\n subject,\n proposedScroll\n}) => {\n const isTooBigVertically = subject.height > container.height;\n const isTooBigHorizontally = subject.width > container.width;\n if (!isTooBigHorizontally && !isTooBigVertically) {\n return proposedScroll;\n }\n if (isTooBigHorizontally && isTooBigVertically) {\n return null;\n }\n return {\n x: isTooBigHorizontally ? 0 : proposedScroll.x,\n y: isTooBigVertically ? 0 : proposedScroll.y\n };\n});\n\nconst clean = apply(value => value === 0 ? 0 : value);\nvar getScroll$1 = (({\n dragStartTime,\n container,\n subject,\n center,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n}) => {\n const distanceToEdges = {\n top: center.y - container.top,\n right: container.right - center.x,\n bottom: container.bottom - center.y,\n left: center.x - container.left\n };\n const y = getScrollOnAxis({\n container,\n distanceToEdges,\n dragStartTime,\n axis: vertical,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n const x = getScrollOnAxis({\n container,\n distanceToEdges,\n dragStartTime,\n axis: horizontal,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n const required = clean({\n x,\n y\n });\n if (isEqual$1(required, origin)) {\n return null;\n }\n const limited = adjustForSizeLimits({\n container,\n subject,\n proposedScroll: required\n });\n if (!limited) {\n return null;\n }\n return isEqual$1(limited, origin) ? null : limited;\n});\n\nconst smallestSigned = apply(value => {\n if (value === 0) {\n return 0;\n }\n return value > 0 ? 1 : -1;\n});\nconst getOverlap = (() => {\n const getRemainder = (target, max) => {\n if (target < 0) {\n return target;\n }\n if (target > max) {\n return target - max;\n }\n return 0;\n };\n return ({\n current,\n max,\n change\n }) => {\n const targetScroll = add(current, change);\n const overlap = {\n x: getRemainder(targetScroll.x, max.x),\n y: getRemainder(targetScroll.y, max.y)\n };\n if (isEqual$1(overlap, origin)) {\n return null;\n }\n return overlap;\n };\n})();\nconst canPartiallyScroll = ({\n max: rawMax,\n current,\n change\n}) => {\n const max = {\n x: Math.max(current.x, rawMax.x),\n y: Math.max(current.y, rawMax.y)\n };\n const smallestChange = smallestSigned(change);\n const overlap = getOverlap({\n max,\n current,\n change: smallestChange\n });\n if (!overlap) {\n return true;\n }\n if (smallestChange.x !== 0 && overlap.x === 0) {\n return true;\n }\n if (smallestChange.y !== 0 && overlap.y === 0) {\n return true;\n }\n return false;\n};\nconst canScrollWindow = (viewport, change) => canPartiallyScroll({\n current: viewport.scroll.current,\n max: viewport.scroll.max,\n change\n});\nconst getWindowOverlap = (viewport, change) => {\n if (!canScrollWindow(viewport, change)) {\n return null;\n }\n const max = viewport.scroll.max;\n const current = viewport.scroll.current;\n return getOverlap({\n current,\n max,\n change\n });\n};\nconst canScrollDroppable = (droppable, change) => {\n const frame = droppable.frame;\n if (!frame) {\n return false;\n }\n return canPartiallyScroll({\n current: frame.scroll.current,\n max: frame.scroll.max,\n change\n });\n};\nconst getDroppableOverlap = (droppable, change) => {\n const frame = droppable.frame;\n if (!frame) {\n return null;\n }\n if (!canScrollDroppable(droppable, change)) {\n return null;\n }\n return getOverlap({\n current: frame.scroll.current,\n max: frame.scroll.max,\n change\n });\n};\n\nvar getWindowScrollChange = (({\n viewport,\n subject,\n center,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n}) => {\n const scroll = getScroll$1({\n dragStartTime,\n container: viewport.frame,\n subject,\n center,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n return scroll && canScrollWindow(viewport, scroll) ? scroll : null;\n});\n\nvar getDroppableScrollChange = (({\n droppable,\n subject,\n center,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n}) => {\n const frame = droppable.frame;\n if (!frame) {\n return null;\n }\n const scroll = getScroll$1({\n dragStartTime,\n container: frame.pageMarginBox,\n subject,\n center,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n return scroll && canScrollDroppable(droppable, scroll) ? scroll : null;\n});\n\nvar scroll = (({\n state,\n dragStartTime,\n shouldUseTimeDampening,\n scrollWindow,\n scrollDroppable,\n getAutoScrollerOptions\n}) => {\n const center = state.current.page.borderBoxCenter;\n const draggable = state.dimensions.draggables[state.critical.draggable.id];\n const subject = draggable.page.marginBox;\n if (state.isWindowScrollAllowed) {\n const viewport = state.viewport;\n const change = getWindowScrollChange({\n dragStartTime,\n viewport,\n subject,\n center,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n if (change) {\n scrollWindow(change);\n return;\n }\n }\n const droppable = getBestScrollableDroppable({\n center,\n destination: whatIsDraggedOver(state.impact),\n droppables: state.dimensions.droppables\n });\n if (!droppable) {\n return;\n }\n const change = getDroppableScrollChange({\n dragStartTime,\n droppable,\n subject,\n center,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n if (change) {\n scrollDroppable(droppable.descriptor.id, change);\n }\n});\n\nvar createFluidScroller = (({\n scrollWindow,\n scrollDroppable,\n getAutoScrollerOptions = () => defaultAutoScrollerOptions\n}) => {\n const scheduleWindowScroll = rafSchd(scrollWindow);\n const scheduleDroppableScroll = rafSchd(scrollDroppable);\n let dragging = null;\n const tryScroll = state => {\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot fluid scroll if not dragging') : invariant(false) : void 0;\n const {\n shouldUseTimeDampening,\n dragStartTime\n } = dragging;\n scroll({\n state,\n scrollWindow: scheduleWindowScroll,\n scrollDroppable: scheduleDroppableScroll,\n dragStartTime,\n shouldUseTimeDampening,\n getAutoScrollerOptions\n });\n };\n const start$1 = state => {\n start();\n !!dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot start auto scrolling when already started') : invariant(false) : void 0;\n const dragStartTime = Date.now();\n let wasScrollNeeded = false;\n const fakeScrollCallback = () => {\n wasScrollNeeded = true;\n };\n scroll({\n state,\n dragStartTime: 0,\n shouldUseTimeDampening: false,\n scrollWindow: fakeScrollCallback,\n scrollDroppable: fakeScrollCallback,\n getAutoScrollerOptions\n });\n dragging = {\n dragStartTime,\n shouldUseTimeDampening: wasScrollNeeded\n };\n finish();\n if (wasScrollNeeded) {\n tryScroll(state);\n }\n };\n const stop = () => {\n if (!dragging) {\n return;\n }\n scheduleWindowScroll.cancel();\n scheduleDroppableScroll.cancel();\n dragging = null;\n };\n return {\n start: start$1,\n stop,\n scroll: tryScroll\n };\n});\n\nvar createJumpScroller = (({\n move,\n scrollDroppable,\n scrollWindow\n}) => {\n const moveByOffset = (state, offset) => {\n const client = add(state.current.client.selection, offset);\n move({\n client\n });\n };\n const scrollDroppableAsMuchAsItCan = (droppable, change) => {\n if (!canScrollDroppable(droppable, change)) {\n return change;\n }\n const overlap = getDroppableOverlap(droppable, change);\n if (!overlap) {\n scrollDroppable(droppable.descriptor.id, change);\n return null;\n }\n const whatTheDroppableCanScroll = subtract(change, overlap);\n scrollDroppable(droppable.descriptor.id, whatTheDroppableCanScroll);\n const remainder = subtract(change, whatTheDroppableCanScroll);\n return remainder;\n };\n const scrollWindowAsMuchAsItCan = (isWindowScrollAllowed, viewport, change) => {\n if (!isWindowScrollAllowed) {\n return change;\n }\n if (!canScrollWindow(viewport, change)) {\n return change;\n }\n const overlap = getWindowOverlap(viewport, change);\n if (!overlap) {\n scrollWindow(change);\n return null;\n }\n const whatTheWindowCanScroll = subtract(change, overlap);\n scrollWindow(whatTheWindowCanScroll);\n const remainder = subtract(change, whatTheWindowCanScroll);\n return remainder;\n };\n const jumpScroller = state => {\n const request = state.scrollJumpRequest;\n if (!request) {\n return;\n }\n const destination = whatIsDraggedOver(state.impact);\n !destination ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot perform a jump scroll when there is no destination') : invariant(false) : void 0;\n const droppableRemainder = scrollDroppableAsMuchAsItCan(state.dimensions.droppables[destination], request);\n if (!droppableRemainder) {\n return;\n }\n const viewport = state.viewport;\n const windowRemainder = scrollWindowAsMuchAsItCan(state.isWindowScrollAllowed, viewport, droppableRemainder);\n if (!windowRemainder) {\n return;\n }\n moveByOffset(state, windowRemainder);\n };\n return jumpScroller;\n});\n\nvar createAutoScroller = (({\n scrollDroppable,\n scrollWindow,\n move,\n getAutoScrollerOptions\n}) => {\n const fluidScroller = createFluidScroller({\n scrollWindow,\n scrollDroppable,\n getAutoScrollerOptions\n });\n const jumpScroll = createJumpScroller({\n move,\n scrollWindow,\n scrollDroppable\n });\n const scroll = state => {\n const autoScrollerOptions = getAutoScrollerOptions();\n if (autoScrollerOptions.disabled || state.phase !== 'DRAGGING') {\n return;\n }\n if (state.movementMode === 'FLUID') {\n fluidScroller.scroll(state);\n return;\n }\n if (!state.scrollJumpRequest) {\n return;\n }\n jumpScroll(state);\n };\n const scroller = {\n scroll,\n start: fluidScroller.start,\n stop: fluidScroller.stop\n };\n return scroller;\n});\n\nconst prefix = 'data-rfd';\nconst dragHandle = (() => {\n const base = `${prefix}-drag-handle`;\n return {\n base,\n draggableId: `${base}-draggable-id`,\n contextId: `${base}-context-id`\n };\n})();\nconst draggable = (() => {\n const base = `${prefix}-draggable`;\n return {\n base,\n contextId: `${base}-context-id`,\n id: `${base}-id`\n };\n})();\nconst droppable = (() => {\n const base = `${prefix}-droppable`;\n return {\n base,\n contextId: `${base}-context-id`,\n id: `${base}-id`\n };\n})();\nconst scrollContainer = {\n contextId: `${prefix}-scroll-container-context-id`\n};\n\nconst makeGetSelector = context => attribute => `[${attribute}=\"${context}\"]`;\nconst getStyles = (rules, property) => rules.map(rule => {\n const value = rule.styles[property];\n if (!value) {\n return '';\n }\n return `${rule.selector} { ${value} }`;\n}).join(' ');\nconst noPointerEvents = 'pointer-events: none;';\nvar getStyles$1 = (contextId => {\n const getSelector = makeGetSelector(contextId);\n const dragHandle$1 = (() => {\n const grabCursor = `\n cursor: -webkit-grab;\n cursor: grab;\n `;\n return {\n selector: getSelector(dragHandle.contextId),\n styles: {\n always: `\n -webkit-touch-callout: none;\n -webkit-tap-highlight-color: rgba(0,0,0,0);\n touch-action: manipulation;\n `,\n resting: grabCursor,\n dragging: noPointerEvents,\n dropAnimating: grabCursor\n }\n };\n })();\n const draggable$1 = (() => {\n const transition = `\n transition: ${transitions.outOfTheWay};\n `;\n return {\n selector: getSelector(draggable.contextId),\n styles: {\n dragging: transition,\n dropAnimating: transition,\n userCancel: transition\n }\n };\n })();\n const droppable$1 = {\n selector: getSelector(droppable.contextId),\n styles: {\n always: `overflow-anchor: none;`\n }\n };\n const body = {\n selector: 'body',\n styles: {\n dragging: `\n cursor: grabbing;\n cursor: -webkit-grabbing;\n user-select: none;\n -webkit-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n overflow-anchor: none;\n `\n }\n };\n const rules = [draggable$1, dragHandle$1, droppable$1, body];\n return {\n always: getStyles(rules, 'always'),\n resting: getStyles(rules, 'resting'),\n dragging: getStyles(rules, 'dragging'),\n dropAnimating: getStyles(rules, 'dropAnimating'),\n userCancel: getStyles(rules, 'userCancel')\n };\n});\n\nconst useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? useLayoutEffect$1 : useEffect;\nvar useLayoutEffect = useIsomorphicLayoutEffect;\n\nconst getHead = () => {\n const head = document.querySelector('head');\n !head ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot find the head to append a style to') : invariant(false) : void 0;\n return head;\n};\nconst createStyleEl = nonce => {\n const el = document.createElement('style');\n if (nonce) {\n el.setAttribute('nonce', nonce);\n }\n el.type = 'text/css';\n return el;\n};\nfunction useStyleMarshal(contextId, nonce) {\n const styles = useMemo(() => getStyles$1(contextId), [contextId]);\n const alwaysRef = useRef(null);\n const dynamicRef = useRef(null);\n const setDynamicStyle = useCallback(memoizeOne(proposed => {\n const el = dynamicRef.current;\n !el ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot set dynamic style element if it is not set') : invariant(false) : void 0;\n el.textContent = proposed;\n }), []);\n const setAlwaysStyle = useCallback(proposed => {\n const el = alwaysRef.current;\n !el ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot set dynamic style element if it is not set') : invariant(false) : void 0;\n el.textContent = proposed;\n }, []);\n useLayoutEffect(() => {\n !(!alwaysRef.current && !dynamicRef.current) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'style elements already mounted') : invariant(false) : void 0;\n const always = createStyleEl(nonce);\n const dynamic = createStyleEl(nonce);\n alwaysRef.current = always;\n dynamicRef.current = dynamic;\n always.setAttribute(`${prefix}-always`, contextId);\n dynamic.setAttribute(`${prefix}-dynamic`, contextId);\n getHead().appendChild(always);\n getHead().appendChild(dynamic);\n setAlwaysStyle(styles.always);\n setDynamicStyle(styles.resting);\n return () => {\n const remove = ref => {\n const current = ref.current;\n !current ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot unmount ref as it is not set') : invariant(false) : void 0;\n getHead().removeChild(current);\n ref.current = null;\n };\n remove(alwaysRef);\n remove(dynamicRef);\n };\n }, [nonce, setAlwaysStyle, setDynamicStyle, styles.always, styles.resting, contextId]);\n const dragging = useCallback(() => setDynamicStyle(styles.dragging), [setDynamicStyle, styles.dragging]);\n const dropping = useCallback(reason => {\n if (reason === 'DROP') {\n setDynamicStyle(styles.dropAnimating);\n return;\n }\n setDynamicStyle(styles.userCancel);\n }, [setDynamicStyle, styles.dropAnimating, styles.userCancel]);\n const resting = useCallback(() => {\n if (!dynamicRef.current) {\n return;\n }\n setDynamicStyle(styles.resting);\n }, [setDynamicStyle, styles.resting]);\n const marshal = useMemo(() => ({\n dragging,\n dropping,\n resting\n }), [dragging, dropping, resting]);\n return marshal;\n}\n\nfunction querySelectorAll(parentNode, selector) {\n return Array.from(parentNode.querySelectorAll(selector));\n}\n\nvar getWindowFromEl = (el => {\n if (el && el.ownerDocument && el.ownerDocument.defaultView) {\n return el.ownerDocument.defaultView;\n }\n return window;\n});\n\nfunction isHtmlElement(el) {\n return el instanceof getWindowFromEl(el).HTMLElement;\n}\n\nfunction findDragHandle(contextId, draggableId) {\n const selector = `[${dragHandle.contextId}=\"${contextId}\"]`;\n const possible = querySelectorAll(document, selector);\n if (!possible.length) {\n process.env.NODE_ENV !== \"production\" ? warning(`Unable to find any drag handles in the context \"${contextId}\"`) : void 0;\n return null;\n }\n const handle = possible.find(el => {\n return el.getAttribute(dragHandle.draggableId) === draggableId;\n });\n if (!handle) {\n process.env.NODE_ENV !== \"production\" ? warning(`Unable to find drag handle with id \"${draggableId}\" as no handle with a matching id was found`) : void 0;\n return null;\n }\n if (!isHtmlElement(handle)) {\n process.env.NODE_ENV !== \"production\" ? warning('drag handle needs to be a HTMLElement') : void 0;\n return null;\n }\n return handle;\n}\n\nfunction useFocusMarshal(contextId) {\n const entriesRef = useRef({});\n const recordRef = useRef(null);\n const restoreFocusFrameRef = useRef(null);\n const isMountedRef = useRef(false);\n const register = useCallback(function register(id, focus) {\n const entry = {\n id,\n focus\n };\n entriesRef.current[id] = entry;\n return function unregister() {\n const entries = entriesRef.current;\n const current = entries[id];\n if (current !== entry) {\n delete entries[id];\n }\n };\n }, []);\n const tryGiveFocus = useCallback(function tryGiveFocus(tryGiveFocusTo) {\n const handle = findDragHandle(contextId, tryGiveFocusTo);\n if (handle && handle !== document.activeElement) {\n handle.focus();\n }\n }, [contextId]);\n const tryShiftRecord = useCallback(function tryShiftRecord(previous, redirectTo) {\n if (recordRef.current === previous) {\n recordRef.current = redirectTo;\n }\n }, []);\n const tryRestoreFocusRecorded = useCallback(function tryRestoreFocusRecorded() {\n if (restoreFocusFrameRef.current) {\n return;\n }\n if (!isMountedRef.current) {\n return;\n }\n restoreFocusFrameRef.current = requestAnimationFrame(() => {\n restoreFocusFrameRef.current = null;\n const record = recordRef.current;\n if (record) {\n tryGiveFocus(record);\n }\n });\n }, [tryGiveFocus]);\n const tryRecordFocus = useCallback(function tryRecordFocus(id) {\n recordRef.current = null;\n const focused = document.activeElement;\n if (!focused) {\n return;\n }\n if (focused.getAttribute(dragHandle.draggableId) !== id) {\n return;\n }\n recordRef.current = id;\n }, []);\n useLayoutEffect(() => {\n isMountedRef.current = true;\n return function clearFrameOnUnmount() {\n isMountedRef.current = false;\n const frameId = restoreFocusFrameRef.current;\n if (frameId) {\n cancelAnimationFrame(frameId);\n }\n };\n }, []);\n const marshal = useMemo(() => ({\n register,\n tryRecordFocus,\n tryRestoreFocusRecorded,\n tryShiftRecord\n }), [register, tryRecordFocus, tryRestoreFocusRecorded, tryShiftRecord]);\n return marshal;\n}\n\nfunction createRegistry() {\n const entries = {\n draggables: {},\n droppables: {}\n };\n const subscribers = [];\n function subscribe(cb) {\n subscribers.push(cb);\n return function unsubscribe() {\n const index = subscribers.indexOf(cb);\n if (index === -1) {\n return;\n }\n subscribers.splice(index, 1);\n };\n }\n function notify(event) {\n if (subscribers.length) {\n subscribers.forEach(cb => cb(event));\n }\n }\n function findDraggableById(id) {\n return entries.draggables[id] || null;\n }\n function getDraggableById(id) {\n const entry = findDraggableById(id);\n !entry ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot find draggable entry with id [${id}]`) : invariant(false) : void 0;\n return entry;\n }\n const draggableAPI = {\n register: entry => {\n entries.draggables[entry.descriptor.id] = entry;\n notify({\n type: 'ADDITION',\n value: entry\n });\n },\n update: (entry, last) => {\n const current = entries.draggables[last.descriptor.id];\n if (!current) {\n return;\n }\n if (current.uniqueId !== entry.uniqueId) {\n return;\n }\n delete entries.draggables[last.descriptor.id];\n entries.draggables[entry.descriptor.id] = entry;\n },\n unregister: entry => {\n const draggableId = entry.descriptor.id;\n const current = findDraggableById(draggableId);\n if (!current) {\n return;\n }\n if (entry.uniqueId !== current.uniqueId) {\n return;\n }\n delete entries.draggables[draggableId];\n if (entries.droppables[entry.descriptor.droppableId]) {\n notify({\n type: 'REMOVAL',\n value: entry\n });\n }\n },\n getById: getDraggableById,\n findById: findDraggableById,\n exists: id => Boolean(findDraggableById(id)),\n getAllByType: type => Object.values(entries.draggables).filter(entry => entry.descriptor.type === type)\n };\n function findDroppableById(id) {\n return entries.droppables[id] || null;\n }\n function getDroppableById(id) {\n const entry = findDroppableById(id);\n !entry ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot find droppable entry with id [${id}]`) : invariant(false) : void 0;\n return entry;\n }\n const droppableAPI = {\n register: entry => {\n entries.droppables[entry.descriptor.id] = entry;\n },\n unregister: entry => {\n const current = findDroppableById(entry.descriptor.id);\n if (!current) {\n return;\n }\n if (entry.uniqueId !== current.uniqueId) {\n return;\n }\n delete entries.droppables[entry.descriptor.id];\n },\n getById: getDroppableById,\n findById: findDroppableById,\n exists: id => Boolean(findDroppableById(id)),\n getAllByType: type => Object.values(entries.droppables).filter(entry => entry.descriptor.type === type)\n };\n function clean() {\n entries.draggables = {};\n entries.droppables = {};\n subscribers.length = 0;\n }\n return {\n draggable: draggableAPI,\n droppable: droppableAPI,\n subscribe,\n clean\n };\n}\n\nfunction useRegistry() {\n const registry = useMemo(createRegistry, []);\n useEffect(() => {\n return function unmount() {\n if (React.version.startsWith('16') || React.version.startsWith('17')) {\n requestAnimationFrame(registry.clean);\n } else {\n registry.clean();\n }\n };\n }, [registry]);\n return registry;\n}\n\nvar StoreContext = React.createContext(null);\n\nvar getBodyElement = (() => {\n const body = document.body;\n !body ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot find document.body') : invariant(false) : void 0;\n return body;\n});\n\nconst visuallyHidden = {\n position: 'absolute',\n width: '1px',\n height: '1px',\n margin: '-1px',\n border: '0',\n padding: '0',\n overflow: 'hidden',\n clip: 'rect(0 0 0 0)',\n 'clip-path': 'inset(100%)'\n};\nvar visuallyHidden$1 = visuallyHidden;\n\nconst getId = contextId => `rfd-announcement-${contextId}`;\nfunction useAnnouncer(contextId) {\n const id = useMemo(() => getId(contextId), [contextId]);\n const ref = useRef(null);\n useEffect(function setup() {\n const el = document.createElement('div');\n ref.current = el;\n el.id = id;\n el.setAttribute('aria-live', 'assertive');\n el.setAttribute('aria-atomic', 'true');\n _extends(el.style, visuallyHidden$1);\n getBodyElement().appendChild(el);\n return function cleanup() {\n setTimeout(function remove() {\n const body = getBodyElement();\n if (body.contains(el)) {\n body.removeChild(el);\n }\n if (el === ref.current) {\n ref.current = null;\n }\n });\n };\n }, [id]);\n const announce = useCallback(message => {\n const el = ref.current;\n if (el) {\n el.textContent = message;\n return;\n }\n process.env.NODE_ENV !== \"production\" ? warning(`\n A screen reader message was trying to be announced but it was unable to do so.\n This can occur if you unmount your
in your onDragEnd.\n Consider calling provided.announce() before the unmount so that the instruction will\n not be lost for users relying on a screen reader.\n\n Message not passed to screen reader:\n\n \"${message}\"\n `) : void 0;\n }, []);\n return announce;\n}\n\nlet count$1 = 0;\nconst defaults = {\n separator: '::'\n};\nfunction resetDeprecatedUniqueId() {\n count$1 = 0;\n}\nfunction useDeprecatedUniqueId(prefix, options = defaults) {\n return useMemo(() => `${prefix}${options.separator}${count$1++}`, [options.separator, prefix]);\n}\nfunction useUniqueId(prefix, options = defaults) {\n const id = React.useId();\n return useMemo(() => `${prefix}${options.separator}${id}`, [options.separator, prefix, id]);\n}\nvar useUniqueId$1 = 'useId' in React ? useUniqueId : useDeprecatedUniqueId;\n\nfunction getElementId({\n contextId,\n uniqueId\n}) {\n return `rfd-hidden-text-${contextId}-${uniqueId}`;\n}\nfunction useHiddenTextElement({\n contextId,\n text\n}) {\n const uniqueId = useUniqueId$1('hidden-text', {\n separator: '-'\n });\n const id = useMemo(() => getElementId({\n contextId,\n uniqueId\n }), [uniqueId, contextId]);\n useEffect(function mount() {\n const el = document.createElement('div');\n el.id = id;\n el.textContent = text;\n el.style.display = 'none';\n getBodyElement().appendChild(el);\n return function unmount() {\n const body = getBodyElement();\n if (body.contains(el)) {\n body.removeChild(el);\n }\n };\n }, [id, text]);\n return id;\n}\n\nvar AppContext = React.createContext(null);\n\nvar peerDependencies = {\n\treact: \"^16.8.5 || ^17.0.0 || ^18.0.0\",\n\t\"react-dom\": \"^16.8.5 || ^17.0.0 || ^18.0.0\"\n};\n\nconst semver = /(\\d+)\\.(\\d+)\\.(\\d+)/;\nconst getVersion = value => {\n const result = semver.exec(value);\n !(result != null) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Unable to parse React version ${value}`) : invariant(false) : void 0;\n const major = Number(result[1]);\n const minor = Number(result[2]);\n const patch = Number(result[3]);\n return {\n major,\n minor,\n patch,\n raw: value\n };\n};\nconst isSatisfied = (expected, actual) => {\n if (actual.major > expected.major) {\n return true;\n }\n if (actual.major < expected.major) {\n return false;\n }\n if (actual.minor > expected.minor) {\n return true;\n }\n if (actual.minor < expected.minor) {\n return false;\n }\n return actual.patch >= expected.patch;\n};\nvar checkReactVersion = ((peerDepValue, actualValue) => {\n const peerDep = getVersion(peerDepValue);\n const actual = getVersion(actualValue);\n if (isSatisfied(peerDep, actual)) {\n return;\n }\n process.env.NODE_ENV !== \"production\" ? warning(`\n React version: [${actual.raw}]\n does not satisfy expected peer dependency version: [${peerDep.raw}]\n\n This can result in run time bugs, and even fatal crashes\n `) : void 0;\n});\n\nconst suffix = `\n We expect a html5 doctype: \n This is to ensure consistent browser layout and measurement\n\n More information: https://github.com/hello-pangea/dnd/blob/main/docs/guides/doctype.md\n`;\nvar checkDoctype = (doc => {\n const doctype = doc.doctype;\n if (!doctype) {\n process.env.NODE_ENV !== \"production\" ? warning(`\n No found.\n\n ${suffix}\n `) : void 0;\n return;\n }\n if (doctype.name.toLowerCase() !== 'html') {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Unexpected found: (${doctype.name})\n\n ${suffix}\n `) : void 0;\n }\n if (doctype.publicId !== '') {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Unexpected publicId found: (${doctype.publicId})\n A html5 doctype does not have a publicId\n\n ${suffix}\n `) : void 0;\n }\n});\n\nfunction useDev(useHook) {\n if (process.env.NODE_ENV !== 'production') {\n useHook();\n }\n}\n\nfunction useDevSetupWarning(fn, inputs) {\n useDev(() => {\n useEffect(() => {\n try {\n fn();\n } catch (e) {\n error(`\n A setup problem was encountered.\n\n > ${e.message}\n `);\n }\n }, inputs);\n });\n}\n\nfunction useStartupValidation() {\n useDevSetupWarning(() => {\n checkReactVersion(peerDependencies.react, React.version);\n checkDoctype(document);\n }, []);\n}\n\nfunction usePrevious(current) {\n const ref = useRef(current);\n useEffect(() => {\n ref.current = current;\n });\n return ref;\n}\n\nfunction create() {\n let lock = null;\n function isClaimed() {\n return Boolean(lock);\n }\n function isActive(value) {\n return value === lock;\n }\n function claim(abandon) {\n !!lock ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot claim lock as it is already claimed') : invariant(false) : void 0;\n const newLock = {\n abandon\n };\n lock = newLock;\n return newLock;\n }\n function release() {\n !lock ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot release lock when there is no lock') : invariant(false) : void 0;\n lock = null;\n }\n function tryAbandon() {\n if (lock) {\n lock.abandon();\n release();\n }\n }\n return {\n isClaimed,\n isActive,\n claim,\n release,\n tryAbandon\n };\n}\n\nfunction isDragging(state) {\n if (state.phase === 'IDLE' || state.phase === 'DROP_ANIMATING') {\n return false;\n }\n return state.isDragging;\n}\n\nconst tab = 9;\nconst enter = 13;\nconst escape = 27;\nconst space = 32;\nconst pageUp = 33;\nconst pageDown = 34;\nconst end = 35;\nconst home = 36;\nconst arrowLeft = 37;\nconst arrowUp = 38;\nconst arrowRight = 39;\nconst arrowDown = 40;\n\nconst preventedKeys = {\n [enter]: true,\n [tab]: true\n};\nvar preventStandardKeyEvents = (event => {\n if (preventedKeys[event.keyCode]) {\n event.preventDefault();\n }\n});\n\nconst supportedEventName = (() => {\n const base = 'visibilitychange';\n if (typeof document === 'undefined') {\n return base;\n }\n const candidates = [base, `ms${base}`, `webkit${base}`, `moz${base}`, `o${base}`];\n const supported = candidates.find(eventName => `on${eventName}` in document);\n return supported || base;\n})();\nvar supportedPageVisibilityEventName = supportedEventName;\n\nconst primaryButton = 0;\nconst sloppyClickThreshold = 5;\nfunction isSloppyClickThresholdExceeded(original, current) {\n return Math.abs(current.x - original.x) >= sloppyClickThreshold || Math.abs(current.y - original.y) >= sloppyClickThreshold;\n}\nconst idle$1 = {\n type: 'IDLE'\n};\nfunction getCaptureBindings({\n cancel,\n completed,\n getPhase,\n setPhase\n}) {\n return [{\n eventName: 'mousemove',\n fn: event => {\n const {\n button,\n clientX,\n clientY\n } = event;\n if (button !== primaryButton) {\n return;\n }\n const point = {\n x: clientX,\n y: clientY\n };\n const phase = getPhase();\n if (phase.type === 'DRAGGING') {\n event.preventDefault();\n phase.actions.move(point);\n return;\n }\n !(phase.type === 'PENDING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot be IDLE') : invariant(false) : void 0;\n const pending = phase.point;\n if (!isSloppyClickThresholdExceeded(pending, point)) {\n return;\n }\n event.preventDefault();\n const actions = phase.actions.fluidLift(point);\n setPhase({\n type: 'DRAGGING',\n actions\n });\n }\n }, {\n eventName: 'mouseup',\n fn: event => {\n const phase = getPhase();\n if (phase.type !== 'DRAGGING') {\n cancel();\n return;\n }\n event.preventDefault();\n phase.actions.drop({\n shouldBlockNextClick: true\n });\n completed();\n }\n }, {\n eventName: 'mousedown',\n fn: event => {\n if (getPhase().type === 'DRAGGING') {\n event.preventDefault();\n }\n cancel();\n }\n }, {\n eventName: 'keydown',\n fn: event => {\n const phase = getPhase();\n if (phase.type === 'PENDING') {\n cancel();\n return;\n }\n if (event.keyCode === escape) {\n event.preventDefault();\n cancel();\n return;\n }\n preventStandardKeyEvents(event);\n }\n }, {\n eventName: 'resize',\n fn: cancel\n }, {\n eventName: 'scroll',\n options: {\n passive: true,\n capture: false\n },\n fn: () => {\n if (getPhase().type === 'PENDING') {\n cancel();\n }\n }\n }, {\n eventName: 'webkitmouseforcedown',\n fn: event => {\n const phase = getPhase();\n !(phase.type !== 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Unexpected phase') : invariant(false) : void 0;\n if (phase.actions.shouldRespectForcePress()) {\n cancel();\n return;\n }\n event.preventDefault();\n }\n }, {\n eventName: supportedPageVisibilityEventName,\n fn: cancel\n }];\n}\nfunction useMouseSensor(api) {\n const phaseRef = useRef(idle$1);\n const unbindEventsRef = useRef(noop$2);\n const startCaptureBinding = useMemo(() => ({\n eventName: 'mousedown',\n fn: function onMouseDown(event) {\n if (event.defaultPrevented) {\n return;\n }\n if (event.button !== primaryButton) {\n return;\n }\n if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) {\n return;\n }\n const draggableId = api.findClosestDraggableId(event);\n if (!draggableId) {\n return;\n }\n const actions = api.tryGetLock(draggableId, stop, {\n sourceEvent: event\n });\n if (!actions) {\n return;\n }\n event.preventDefault();\n const point = {\n x: event.clientX,\n y: event.clientY\n };\n unbindEventsRef.current();\n startPendingDrag(actions, point);\n }\n }), [api]);\n const preventForcePressBinding = useMemo(() => ({\n eventName: 'webkitmouseforcewillbegin',\n fn: event => {\n if (event.defaultPrevented) {\n return;\n }\n const id = api.findClosestDraggableId(event);\n if (!id) {\n return;\n }\n const options = api.findOptionsForDraggable(id);\n if (!options) {\n return;\n }\n if (options.shouldRespectForcePress) {\n return;\n }\n if (!api.canGetLock(id)) {\n return;\n }\n event.preventDefault();\n }\n }), [api]);\n const listenForCapture = useCallback(function listenForCapture() {\n const options = {\n passive: false,\n capture: true\n };\n unbindEventsRef.current = bindEvents(window, [preventForcePressBinding, startCaptureBinding], options);\n }, [preventForcePressBinding, startCaptureBinding]);\n const stop = useCallback(() => {\n const current = phaseRef.current;\n if (current.type === 'IDLE') {\n return;\n }\n phaseRef.current = idle$1;\n unbindEventsRef.current();\n listenForCapture();\n }, [listenForCapture]);\n const cancel = useCallback(() => {\n const phase = phaseRef.current;\n stop();\n if (phase.type === 'DRAGGING') {\n phase.actions.cancel({\n shouldBlockNextClick: true\n });\n }\n if (phase.type === 'PENDING') {\n phase.actions.abort();\n }\n }, [stop]);\n const bindCapturingEvents = useCallback(function bindCapturingEvents() {\n const options = {\n capture: true,\n passive: false\n };\n const bindings = getCaptureBindings({\n cancel,\n completed: stop,\n getPhase: () => phaseRef.current,\n setPhase: phase => {\n phaseRef.current = phase;\n }\n });\n unbindEventsRef.current = bindEvents(window, bindings, options);\n }, [cancel, stop]);\n const startPendingDrag = useCallback(function startPendingDrag(actions, point) {\n !(phaseRef.current.type === 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected to move from IDLE to PENDING drag') : invariant(false) : void 0;\n phaseRef.current = {\n type: 'PENDING',\n point,\n actions\n };\n bindCapturingEvents();\n }, [bindCapturingEvents]);\n useLayoutEffect(function mount() {\n listenForCapture();\n return function unmount() {\n unbindEventsRef.current();\n };\n }, [listenForCapture]);\n}\n\nfunction noop$1() {}\nconst scrollJumpKeys = {\n [pageDown]: true,\n [pageUp]: true,\n [home]: true,\n [end]: true\n};\nfunction getDraggingBindings(actions, stop) {\n function cancel() {\n stop();\n actions.cancel();\n }\n function drop() {\n stop();\n actions.drop();\n }\n return [{\n eventName: 'keydown',\n fn: event => {\n if (event.keyCode === escape) {\n event.preventDefault();\n cancel();\n return;\n }\n if (event.keyCode === space) {\n event.preventDefault();\n drop();\n return;\n }\n if (event.keyCode === arrowDown) {\n event.preventDefault();\n actions.moveDown();\n return;\n }\n if (event.keyCode === arrowUp) {\n event.preventDefault();\n actions.moveUp();\n return;\n }\n if (event.keyCode === arrowRight) {\n event.preventDefault();\n actions.moveRight();\n return;\n }\n if (event.keyCode === arrowLeft) {\n event.preventDefault();\n actions.moveLeft();\n return;\n }\n if (scrollJumpKeys[event.keyCode]) {\n event.preventDefault();\n return;\n }\n preventStandardKeyEvents(event);\n }\n }, {\n eventName: 'mousedown',\n fn: cancel\n }, {\n eventName: 'mouseup',\n fn: cancel\n }, {\n eventName: 'click',\n fn: cancel\n }, {\n eventName: 'touchstart',\n fn: cancel\n }, {\n eventName: 'resize',\n fn: cancel\n }, {\n eventName: 'wheel',\n fn: cancel,\n options: {\n passive: true\n }\n }, {\n eventName: supportedPageVisibilityEventName,\n fn: cancel\n }];\n}\nfunction useKeyboardSensor(api) {\n const unbindEventsRef = useRef(noop$1);\n const startCaptureBinding = useMemo(() => ({\n eventName: 'keydown',\n fn: function onKeyDown(event) {\n if (event.defaultPrevented) {\n return;\n }\n if (event.keyCode !== space) {\n return;\n }\n const draggableId = api.findClosestDraggableId(event);\n if (!draggableId) {\n return;\n }\n const preDrag = api.tryGetLock(draggableId, stop, {\n sourceEvent: event\n });\n if (!preDrag) {\n return;\n }\n event.preventDefault();\n let isCapturing = true;\n const actions = preDrag.snapLift();\n unbindEventsRef.current();\n function stop() {\n !isCapturing ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot stop capturing a keyboard drag when not capturing') : invariant(false) : void 0;\n isCapturing = false;\n unbindEventsRef.current();\n listenForCapture();\n }\n unbindEventsRef.current = bindEvents(window, getDraggingBindings(actions, stop), {\n capture: true,\n passive: false\n });\n }\n }), [api]);\n const listenForCapture = useCallback(function tryStartCapture() {\n const options = {\n passive: false,\n capture: true\n };\n unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);\n }, [startCaptureBinding]);\n useLayoutEffect(function mount() {\n listenForCapture();\n return function unmount() {\n unbindEventsRef.current();\n };\n }, [listenForCapture]);\n}\n\nconst idle = {\n type: 'IDLE'\n};\nconst timeForLongPress = 120;\nconst forcePressThreshold = 0.15;\nfunction getWindowBindings({\n cancel,\n getPhase\n}) {\n return [{\n eventName: 'orientationchange',\n fn: cancel\n }, {\n eventName: 'resize',\n fn: cancel\n }, {\n eventName: 'contextmenu',\n fn: event => {\n event.preventDefault();\n }\n }, {\n eventName: 'keydown',\n fn: event => {\n if (getPhase().type !== 'DRAGGING') {\n cancel();\n return;\n }\n if (event.keyCode === escape) {\n event.preventDefault();\n }\n cancel();\n }\n }, {\n eventName: supportedPageVisibilityEventName,\n fn: cancel\n }];\n}\nfunction getHandleBindings({\n cancel,\n completed,\n getPhase\n}) {\n return [{\n eventName: 'touchmove',\n options: {\n capture: false\n },\n fn: event => {\n const phase = getPhase();\n if (phase.type !== 'DRAGGING') {\n cancel();\n return;\n }\n phase.hasMoved = true;\n const {\n clientX,\n clientY\n } = event.touches[0];\n const point = {\n x: clientX,\n y: clientY\n };\n event.preventDefault();\n phase.actions.move(point);\n }\n }, {\n eventName: 'touchend',\n fn: event => {\n const phase = getPhase();\n if (phase.type !== 'DRAGGING') {\n cancel();\n return;\n }\n event.preventDefault();\n phase.actions.drop({\n shouldBlockNextClick: true\n });\n completed();\n }\n }, {\n eventName: 'touchcancel',\n fn: event => {\n if (getPhase().type !== 'DRAGGING') {\n cancel();\n return;\n }\n event.preventDefault();\n cancel();\n }\n }, {\n eventName: 'touchforcechange',\n fn: event => {\n const phase = getPhase();\n !(phase.type !== 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n const touch = event.touches[0];\n if (!touch) {\n return;\n }\n const isForcePress = touch.force >= forcePressThreshold;\n if (!isForcePress) {\n return;\n }\n const shouldRespect = phase.actions.shouldRespectForcePress();\n if (phase.type === 'PENDING') {\n if (shouldRespect) {\n cancel();\n }\n return;\n }\n if (shouldRespect) {\n if (phase.hasMoved) {\n event.preventDefault();\n return;\n }\n cancel();\n return;\n }\n event.preventDefault();\n }\n }, {\n eventName: supportedPageVisibilityEventName,\n fn: cancel\n }];\n}\nfunction useTouchSensor(api) {\n const phaseRef = useRef(idle);\n const unbindEventsRef = useRef(noop$2);\n const getPhase = useCallback(function getPhase() {\n return phaseRef.current;\n }, []);\n const setPhase = useCallback(function setPhase(phase) {\n phaseRef.current = phase;\n }, []);\n const startCaptureBinding = useMemo(() => ({\n eventName: 'touchstart',\n fn: function onTouchStart(event) {\n if (event.defaultPrevented) {\n return;\n }\n const draggableId = api.findClosestDraggableId(event);\n if (!draggableId) {\n return;\n }\n const actions = api.tryGetLock(draggableId, stop, {\n sourceEvent: event\n });\n if (!actions) {\n return;\n }\n const touch = event.touches[0];\n const {\n clientX,\n clientY\n } = touch;\n const point = {\n x: clientX,\n y: clientY\n };\n unbindEventsRef.current();\n startPendingDrag(actions, point);\n }\n }), [api]);\n const listenForCapture = useCallback(function listenForCapture() {\n const options = {\n capture: true,\n passive: false\n };\n unbindEventsRef.current = bindEvents(window, [startCaptureBinding], options);\n }, [startCaptureBinding]);\n const stop = useCallback(() => {\n const current = phaseRef.current;\n if (current.type === 'IDLE') {\n return;\n }\n if (current.type === 'PENDING') {\n clearTimeout(current.longPressTimerId);\n }\n setPhase(idle);\n unbindEventsRef.current();\n listenForCapture();\n }, [listenForCapture, setPhase]);\n const cancel = useCallback(() => {\n const phase = phaseRef.current;\n stop();\n if (phase.type === 'DRAGGING') {\n phase.actions.cancel({\n shouldBlockNextClick: true\n });\n }\n if (phase.type === 'PENDING') {\n phase.actions.abort();\n }\n }, [stop]);\n const bindCapturingEvents = useCallback(function bindCapturingEvents() {\n const options = {\n capture: true,\n passive: false\n };\n const args = {\n cancel,\n completed: stop,\n getPhase\n };\n const unbindTarget = bindEvents(window, getHandleBindings(args), options);\n const unbindWindow = bindEvents(window, getWindowBindings(args), options);\n unbindEventsRef.current = function unbindAll() {\n unbindTarget();\n unbindWindow();\n };\n }, [cancel, getPhase, stop]);\n const startDragging = useCallback(function startDragging() {\n const phase = getPhase();\n !(phase.type === 'PENDING') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot start dragging from phase ${phase.type}`) : invariant(false) : void 0;\n const actions = phase.actions.fluidLift(phase.point);\n setPhase({\n type: 'DRAGGING',\n actions,\n hasMoved: false\n });\n }, [getPhase, setPhase]);\n const startPendingDrag = useCallback(function startPendingDrag(actions, point) {\n !(getPhase().type === 'IDLE') ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected to move from IDLE to PENDING drag') : invariant(false) : void 0;\n const longPressTimerId = setTimeout(startDragging, timeForLongPress);\n setPhase({\n type: 'PENDING',\n point,\n actions,\n longPressTimerId\n });\n bindCapturingEvents();\n }, [bindCapturingEvents, getPhase, setPhase, startDragging]);\n useLayoutEffect(function mount() {\n listenForCapture();\n return function unmount() {\n unbindEventsRef.current();\n const phase = getPhase();\n if (phase.type === 'PENDING') {\n clearTimeout(phase.longPressTimerId);\n setPhase(idle);\n }\n };\n }, [getPhase, listenForCapture, setPhase]);\n useLayoutEffect(function webkitHack() {\n const unbind = bindEvents(window, [{\n eventName: 'touchmove',\n fn: () => {},\n options: {\n capture: false,\n passive: false\n }\n }]);\n return unbind;\n }, []);\n}\n\nfunction useValidateSensorHooks(sensorHooks) {\n useDev(() => {\n const previousRef = usePrevious(sensorHooks);\n useDevSetupWarning(() => {\n !(previousRef.current.length === sensorHooks.length) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot change the amount of sensor hooks after mounting') : invariant(false) : void 0;\n });\n });\n}\n\nconst interactiveTagNames = ['input', 'button', 'textarea', 'select', 'option', 'optgroup', 'video', 'audio'];\nfunction isAnInteractiveElement(parent, current) {\n if (current == null) {\n return false;\n }\n const hasAnInteractiveTag = interactiveTagNames.includes(current.tagName.toLowerCase());\n if (hasAnInteractiveTag) {\n return true;\n }\n const attribute = current.getAttribute('contenteditable');\n if (attribute === 'true' || attribute === '') {\n return true;\n }\n if (current === parent) {\n return false;\n }\n return isAnInteractiveElement(parent, current.parentElement);\n}\nfunction isEventInInteractiveElement(draggable, event) {\n const target = event.target;\n if (!isHtmlElement(target)) {\n return false;\n }\n return isAnInteractiveElement(draggable, target);\n}\n\nvar getBorderBoxCenterPosition = (el => getRect(el.getBoundingClientRect()).center);\n\nfunction isElement(el) {\n return el instanceof getWindowFromEl(el).Element;\n}\n\nconst supportedMatchesName = (() => {\n const base = 'matches';\n if (typeof document === 'undefined') {\n return base;\n }\n const candidates = [base, 'msMatchesSelector', 'webkitMatchesSelector'];\n const value = candidates.find(name => name in Element.prototype);\n return value || base;\n})();\nfunction closestPonyfill(el, selector) {\n if (el == null) {\n return null;\n }\n if (el[supportedMatchesName](selector)) {\n return el;\n }\n return closestPonyfill(el.parentElement, selector);\n}\nfunction closest(el, selector) {\n if (el.closest) {\n return el.closest(selector);\n }\n return closestPonyfill(el, selector);\n}\n\nfunction getSelector(contextId) {\n return `[${dragHandle.contextId}=\"${contextId}\"]`;\n}\nfunction findClosestDragHandleFromEvent(contextId, event) {\n const target = event.target;\n if (!isElement(target)) {\n process.env.NODE_ENV !== \"production\" ? warning('event.target must be a Element') : void 0;\n return null;\n }\n const selector = getSelector(contextId);\n const handle = closest(target, selector);\n if (!handle) {\n return null;\n }\n if (!isHtmlElement(handle)) {\n process.env.NODE_ENV !== \"production\" ? warning('drag handle must be a HTMLElement') : void 0;\n return null;\n }\n return handle;\n}\nfunction tryGetClosestDraggableIdFromEvent(contextId, event) {\n const handle = findClosestDragHandleFromEvent(contextId, event);\n if (!handle) {\n return null;\n }\n return handle.getAttribute(dragHandle.draggableId);\n}\n\nfunction findDraggable(contextId, draggableId) {\n const selector = `[${draggable.contextId}=\"${contextId}\"]`;\n const possible = querySelectorAll(document, selector);\n const draggable$1 = possible.find(el => {\n return el.getAttribute(draggable.id) === draggableId;\n });\n if (!draggable$1) {\n return null;\n }\n if (!isHtmlElement(draggable$1)) {\n process.env.NODE_ENV !== \"production\" ? warning('Draggable element is not a HTMLElement') : void 0;\n return null;\n }\n return draggable$1;\n}\n\nfunction preventDefault(event) {\n event.preventDefault();\n}\nfunction isActive({\n expected,\n phase,\n isLockActive,\n shouldWarn\n}) {\n if (!isLockActive()) {\n if (shouldWarn) {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Cannot perform action.\n The sensor no longer has an action lock.\n\n Tips:\n\n - Throw away your action handlers when forceStop() is called\n - Check actions.isActive() if you really need to\n `) : void 0;\n }\n return false;\n }\n if (expected !== phase) {\n if (shouldWarn) {\n process.env.NODE_ENV !== \"production\" ? warning(`\n Cannot perform action.\n The actions you used belong to an outdated phase\n\n Current phase: ${expected}\n You called an action from outdated phase: ${phase}\n\n Tips:\n\n - Do not use preDragActions actions after calling preDragActions.lift()\n `) : void 0;\n }\n return false;\n }\n return true;\n}\nfunction canStart({\n lockAPI,\n store,\n registry,\n draggableId\n}) {\n if (lockAPI.isClaimed()) {\n return false;\n }\n const entry = registry.draggable.findById(draggableId);\n if (!entry) {\n process.env.NODE_ENV !== \"production\" ? warning(`Unable to find draggable with id: ${draggableId}`) : void 0;\n return false;\n }\n if (!entry.options.isEnabled) {\n return false;\n }\n if (!canStartDrag(store.getState(), draggableId)) {\n return false;\n }\n return true;\n}\nfunction tryStart({\n lockAPI,\n contextId,\n store,\n registry,\n draggableId,\n forceSensorStop,\n sourceEvent\n}) {\n const shouldStart = canStart({\n lockAPI,\n store,\n registry,\n draggableId\n });\n if (!shouldStart) {\n return null;\n }\n const entry = registry.draggable.getById(draggableId);\n const el = findDraggable(contextId, entry.descriptor.id);\n if (!el) {\n process.env.NODE_ENV !== \"production\" ? warning(`Unable to find draggable element with id: ${draggableId}`) : void 0;\n return null;\n }\n if (sourceEvent && !entry.options.canDragInteractiveElements && isEventInInteractiveElement(el, sourceEvent)) {\n return null;\n }\n const lock = lockAPI.claim(forceSensorStop || noop$2);\n let phase = 'PRE_DRAG';\n function getShouldRespectForcePress() {\n return entry.options.shouldRespectForcePress;\n }\n function isLockActive() {\n return lockAPI.isActive(lock);\n }\n function tryDispatch(expected, getAction) {\n if (isActive({\n expected,\n phase,\n isLockActive,\n shouldWarn: true\n })) {\n store.dispatch(getAction());\n }\n }\n const tryDispatchWhenDragging = tryDispatch.bind(null, 'DRAGGING');\n function lift(args) {\n function completed() {\n lockAPI.release();\n phase = 'COMPLETED';\n }\n if (phase !== 'PRE_DRAG') {\n completed();\n process.env.NODE_ENV !== \"production\" ? invariant(false, `Cannot lift in phase ${phase}`) : invariant(false) ;\n }\n store.dispatch(lift$1(args.liftActionArgs));\n phase = 'DRAGGING';\n function finish(reason, options = {\n shouldBlockNextClick: false\n }) {\n args.cleanup();\n if (options.shouldBlockNextClick) {\n const unbind = bindEvents(window, [{\n eventName: 'click',\n fn: preventDefault,\n options: {\n once: true,\n passive: false,\n capture: true\n }\n }]);\n setTimeout(unbind);\n }\n completed();\n store.dispatch(drop$1({\n reason\n }));\n }\n return {\n isActive: () => isActive({\n expected: 'DRAGGING',\n phase,\n isLockActive,\n shouldWarn: false\n }),\n shouldRespectForcePress: getShouldRespectForcePress,\n drop: options => finish('DROP', options),\n cancel: options => finish('CANCEL', options),\n ...args.actions\n };\n }\n function fluidLift(clientSelection) {\n const move$1 = rafSchd(client => {\n tryDispatchWhenDragging(() => move({\n client\n }));\n });\n const api = lift({\n liftActionArgs: {\n id: draggableId,\n clientSelection,\n movementMode: 'FLUID'\n },\n cleanup: () => move$1.cancel(),\n actions: {\n move: move$1\n }\n });\n return {\n ...api,\n move: move$1\n };\n }\n function snapLift() {\n const actions = {\n moveUp: () => tryDispatchWhenDragging(moveUp),\n moveRight: () => tryDispatchWhenDragging(moveRight),\n moveDown: () => tryDispatchWhenDragging(moveDown),\n moveLeft: () => tryDispatchWhenDragging(moveLeft)\n };\n return lift({\n liftActionArgs: {\n id: draggableId,\n clientSelection: getBorderBoxCenterPosition(el),\n movementMode: 'SNAP'\n },\n cleanup: noop$2,\n actions\n });\n }\n function abortPreDrag() {\n const shouldRelease = isActive({\n expected: 'PRE_DRAG',\n phase,\n isLockActive,\n shouldWarn: true\n });\n if (shouldRelease) {\n lockAPI.release();\n }\n }\n const preDrag = {\n isActive: () => isActive({\n expected: 'PRE_DRAG',\n phase,\n isLockActive,\n shouldWarn: false\n }),\n shouldRespectForcePress: getShouldRespectForcePress,\n fluidLift,\n snapLift,\n abort: abortPreDrag\n };\n return preDrag;\n}\nconst defaultSensors = [useMouseSensor, useKeyboardSensor, useTouchSensor];\nfunction useSensorMarshal({\n contextId,\n store,\n registry,\n customSensors,\n enableDefaultSensors\n}) {\n const useSensors = [...(enableDefaultSensors ? defaultSensors : []), ...(customSensors || [])];\n const lockAPI = useState(() => create())[0];\n const tryAbandonLock = useCallback(function tryAbandonLock(previous, current) {\n if (isDragging(previous) && !isDragging(current)) {\n lockAPI.tryAbandon();\n }\n }, [lockAPI]);\n useLayoutEffect(function listenToStore() {\n let previous = store.getState();\n const unsubscribe = store.subscribe(() => {\n const current = store.getState();\n tryAbandonLock(previous, current);\n previous = current;\n });\n return unsubscribe;\n }, [lockAPI, store, tryAbandonLock]);\n useLayoutEffect(() => {\n return lockAPI.tryAbandon;\n }, [lockAPI.tryAbandon]);\n const canGetLock = useCallback(draggableId => {\n return canStart({\n lockAPI,\n registry,\n store,\n draggableId\n });\n }, [lockAPI, registry, store]);\n const tryGetLock = useCallback((draggableId, forceStop, options) => tryStart({\n lockAPI,\n registry,\n contextId,\n store,\n draggableId,\n forceSensorStop: forceStop || null,\n sourceEvent: options && options.sourceEvent ? options.sourceEvent : null\n }), [contextId, lockAPI, registry, store]);\n const findClosestDraggableId = useCallback(event => tryGetClosestDraggableIdFromEvent(contextId, event), [contextId]);\n const findOptionsForDraggable = useCallback(id => {\n const entry = registry.draggable.findById(id);\n return entry ? entry.options : null;\n }, [registry.draggable]);\n const tryReleaseLock = useCallback(function tryReleaseLock() {\n if (!lockAPI.isClaimed()) {\n return;\n }\n lockAPI.tryAbandon();\n if (store.getState().phase !== 'IDLE') {\n store.dispatch(flush());\n }\n }, [lockAPI, store]);\n const isLockClaimed = useCallback(() => lockAPI.isClaimed(), [lockAPI]);\n const api = useMemo(() => ({\n canGetLock,\n tryGetLock,\n findClosestDraggableId,\n findOptionsForDraggable,\n tryReleaseLock,\n isLockClaimed\n }), [canGetLock, tryGetLock, findClosestDraggableId, findOptionsForDraggable, tryReleaseLock, isLockClaimed]);\n useValidateSensorHooks(useSensors);\n for (let i = 0; i < useSensors.length; i++) {\n useSensors[i](api);\n }\n}\n\nconst createResponders = props => ({\n onBeforeCapture: t => {\n const onBeforeCapureCallback = () => {\n if (props.onBeforeCapture) {\n props.onBeforeCapture(t);\n }\n };\n if (React.version.startsWith('16') || React.version.startsWith('17')) {\n onBeforeCapureCallback();\n } else {\n flushSync(onBeforeCapureCallback);\n }\n },\n onBeforeDragStart: props.onBeforeDragStart,\n onDragStart: props.onDragStart,\n onDragEnd: props.onDragEnd,\n onDragUpdate: props.onDragUpdate\n});\nconst createAutoScrollerOptions = props => ({\n ...defaultAutoScrollerOptions,\n ...props.autoScrollerOptions,\n durationDampening: {\n ...defaultAutoScrollerOptions.durationDampening,\n ...props.autoScrollerOptions\n }\n});\nfunction getStore(lazyRef) {\n !lazyRef.current ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find store from lazy ref') : invariant(false) : void 0;\n return lazyRef.current;\n}\nfunction App(props) {\n const {\n contextId,\n setCallbacks,\n sensors,\n nonce,\n dragHandleUsageInstructions\n } = props;\n const lazyStoreRef = useRef(null);\n useStartupValidation();\n const lastPropsRef = usePrevious(props);\n const getResponders = useCallback(() => {\n return createResponders(lastPropsRef.current);\n }, [lastPropsRef]);\n const getAutoScrollerOptions = useCallback(() => {\n return createAutoScrollerOptions(lastPropsRef.current);\n }, [lastPropsRef]);\n const announce = useAnnouncer(contextId);\n const dragHandleUsageInstructionsId = useHiddenTextElement({\n contextId,\n text: dragHandleUsageInstructions\n });\n const styleMarshal = useStyleMarshal(contextId, nonce);\n const lazyDispatch = useCallback(action => {\n getStore(lazyStoreRef).dispatch(action);\n }, []);\n const marshalCallbacks = useMemo(() => bindActionCreators({\n publishWhileDragging,\n updateDroppableScroll,\n updateDroppableIsEnabled,\n updateDroppableIsCombineEnabled,\n collectionStarting\n }, lazyDispatch), [lazyDispatch]);\n const registry = useRegistry();\n const dimensionMarshal = useMemo(() => {\n return createDimensionMarshal(registry, marshalCallbacks);\n }, [registry, marshalCallbacks]);\n const autoScroller = useMemo(() => createAutoScroller({\n scrollWindow,\n scrollDroppable: dimensionMarshal.scrollDroppable,\n getAutoScrollerOptions,\n ...bindActionCreators({\n move\n }, lazyDispatch)\n }), [dimensionMarshal.scrollDroppable, lazyDispatch, getAutoScrollerOptions]);\n const focusMarshal = useFocusMarshal(contextId);\n const store = useMemo(() => createStore({\n announce,\n autoScroller,\n dimensionMarshal,\n focusMarshal,\n getResponders,\n styleMarshal\n }), [announce, autoScroller, dimensionMarshal, focusMarshal, getResponders, styleMarshal]);\n if (process.env.NODE_ENV !== 'production') {\n if (lazyStoreRef.current && lazyStoreRef.current !== store) {\n process.env.NODE_ENV !== \"production\" ? warning('unexpected store change') : void 0;\n }\n }\n lazyStoreRef.current = store;\n const tryResetStore = useCallback(() => {\n const current = getStore(lazyStoreRef);\n const state = current.getState();\n if (state.phase !== 'IDLE') {\n current.dispatch(flush());\n }\n }, []);\n const isDragging = useCallback(() => {\n const state = getStore(lazyStoreRef).getState();\n if (state.phase === 'DROP_ANIMATING') {\n return true;\n }\n if (state.phase === 'IDLE') {\n return false;\n }\n return state.isDragging;\n }, []);\n const appCallbacks = useMemo(() => ({\n isDragging,\n tryAbort: tryResetStore\n }), [isDragging, tryResetStore]);\n setCallbacks(appCallbacks);\n const getCanLift = useCallback(id => canStartDrag(getStore(lazyStoreRef).getState(), id), []);\n const getIsMovementAllowed = useCallback(() => isMovementAllowed(getStore(lazyStoreRef).getState()), []);\n const appContext = useMemo(() => ({\n marshal: dimensionMarshal,\n focus: focusMarshal,\n contextId,\n canLift: getCanLift,\n isMovementAllowed: getIsMovementAllowed,\n dragHandleUsageInstructionsId,\n registry\n }), [contextId, dimensionMarshal, dragHandleUsageInstructionsId, focusMarshal, getCanLift, getIsMovementAllowed, registry]);\n useSensorMarshal({\n contextId,\n store,\n registry,\n customSensors: sensors || null,\n enableDefaultSensors: props.enableDefaultSensors !== false\n });\n useEffect(() => {\n return tryResetStore;\n }, [tryResetStore]);\n return React.createElement(AppContext.Provider, {\n value: appContext\n }, React.createElement(Provider, {\n context: StoreContext,\n store: store\n }, props.children));\n}\n\nlet count = 0;\nfunction resetDeprecatedUniqueContextId() {\n count = 0;\n}\nfunction useDeprecatedUniqueContextId() {\n return useMemo(() => `${count++}`, []);\n}\nfunction useUniqueContextId() {\n return React.useId();\n}\nvar useUniqueContextId$1 = 'useId' in React ? useUniqueContextId : useDeprecatedUniqueContextId;\n\nfunction resetServerContext() {\n if ('useId' in React) {\n process.env.NODE_ENV !== \"production\" ? warning(`It is not necessary to call resetServerContext when using React 18+`) : void 0;\n return;\n }\n resetDeprecatedUniqueContextId();\n resetDeprecatedUniqueId();\n}\nfunction DragDropContext(props) {\n const contextId = useUniqueContextId$1();\n const dragHandleUsageInstructions = props.dragHandleUsageInstructions || preset$1.dragHandleUsageInstructions;\n return React.createElement(ErrorBoundary, null, setCallbacks => React.createElement(App, {\n nonce: props.nonce,\n contextId: contextId,\n setCallbacks: setCallbacks,\n dragHandleUsageInstructions: dragHandleUsageInstructions,\n enableDefaultSensors: props.enableDefaultSensors,\n sensors: props.sensors,\n onBeforeCapture: props.onBeforeCapture,\n onBeforeDragStart: props.onBeforeDragStart,\n onDragStart: props.onDragStart,\n onDragUpdate: props.onDragUpdate,\n onDragEnd: props.onDragEnd,\n autoScrollerOptions: props.autoScrollerOptions\n }, props.children));\n}\n\nconst zIndexOptions = {\n dragging: 5000,\n dropAnimating: 4500\n};\nconst getDraggingTransition = (shouldAnimateDragMovement, dropping) => {\n if (dropping) {\n return transitions.drop(dropping.duration);\n }\n if (shouldAnimateDragMovement) {\n return transitions.snap;\n }\n return transitions.fluid;\n};\nconst getDraggingOpacity = (isCombining, isDropAnimating) => {\n if (!isCombining) {\n return undefined;\n }\n return isDropAnimating ? combine.opacity.drop : combine.opacity.combining;\n};\nconst getShouldDraggingAnimate = dragging => {\n if (dragging.forceShouldAnimate != null) {\n return dragging.forceShouldAnimate;\n }\n return dragging.mode === 'SNAP';\n};\nfunction getDraggingStyle(dragging) {\n const dimension = dragging.dimension;\n const box = dimension.client;\n const {\n offset,\n combineWith,\n dropping\n } = dragging;\n const isCombining = Boolean(combineWith);\n const shouldAnimate = getShouldDraggingAnimate(dragging);\n const isDropAnimating = Boolean(dropping);\n const transform = isDropAnimating ? transforms.drop(offset, isCombining) : transforms.moveTo(offset);\n const style = {\n position: 'fixed',\n top: box.marginBox.top,\n left: box.marginBox.left,\n boxSizing: 'border-box',\n width: box.borderBox.width,\n height: box.borderBox.height,\n transition: getDraggingTransition(shouldAnimate, dropping),\n transform,\n opacity: getDraggingOpacity(isCombining, isDropAnimating),\n zIndex: isDropAnimating ? zIndexOptions.dropAnimating : zIndexOptions.dragging,\n pointerEvents: 'none'\n };\n return style;\n}\nfunction getSecondaryStyle(secondary) {\n return {\n transform: transforms.moveTo(secondary.offset),\n transition: secondary.shouldAnimateDisplacement ? undefined : 'none'\n };\n}\nfunction getStyle$1(mapped) {\n return mapped.type === 'DRAGGING' ? getDraggingStyle(mapped) : getSecondaryStyle(mapped);\n}\n\nfunction getDimension$1(descriptor, el, windowScroll = origin) {\n const computedStyles = window.getComputedStyle(el);\n const borderBox = el.getBoundingClientRect();\n const client = calculateBox(borderBox, computedStyles);\n const page = withScroll(client, windowScroll);\n const placeholder = {\n client,\n tagName: el.tagName.toLowerCase(),\n display: computedStyles.display\n };\n const displaceBy = {\n x: client.marginBox.width,\n y: client.marginBox.height\n };\n const dimension = {\n descriptor,\n placeholder,\n displaceBy,\n client,\n page\n };\n return dimension;\n}\n\nfunction useDraggablePublisher(args) {\n const uniqueId = useUniqueId$1('draggable');\n const {\n descriptor,\n registry,\n getDraggableRef,\n canDragInteractiveElements,\n shouldRespectForcePress,\n isEnabled\n } = args;\n const options = useMemo(() => ({\n canDragInteractiveElements,\n shouldRespectForcePress,\n isEnabled\n }), [canDragInteractiveElements, isEnabled, shouldRespectForcePress]);\n const getDimension = useCallback(windowScroll => {\n const el = getDraggableRef();\n !el ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot get dimension when no ref is set') : invariant(false) : void 0;\n return getDimension$1(descriptor, el, windowScroll);\n }, [descriptor, getDraggableRef]);\n const entry = useMemo(() => ({\n uniqueId,\n descriptor,\n options,\n getDimension\n }), [descriptor, getDimension, options, uniqueId]);\n const publishedRef = useRef(entry);\n const isFirstPublishRef = useRef(true);\n useLayoutEffect(() => {\n registry.draggable.register(publishedRef.current);\n return () => registry.draggable.unregister(publishedRef.current);\n }, [registry.draggable]);\n useLayoutEffect(() => {\n if (isFirstPublishRef.current) {\n isFirstPublishRef.current = false;\n return;\n }\n const last = publishedRef.current;\n publishedRef.current = entry;\n registry.draggable.update(entry, last);\n }, [entry, registry.draggable]);\n}\n\nvar DroppableContext = React.createContext(null);\n\nfunction checkIsValidInnerRef(el) {\n !(el && isHtmlElement(el)) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `\n provided.innerRef has not been provided with a HTMLElement.\n\n You can find a guide on using the innerRef callback functions at:\n https://github.com/hello-pangea/dnd/blob/main/docs/guides/using-inner-ref.md\n `) : invariant(false) : void 0;\n}\n\nfunction useValidation$1(props, contextId, getRef) {\n useDevSetupWarning(() => {\n function prefix(id) {\n return `Draggable[id: ${id}]: `;\n }\n const id = props.draggableId;\n !id ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Draggable requires a draggableId') : invariant(false) : void 0;\n !(typeof id === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `Draggable requires a [string] draggableId.\n Provided: [type: ${typeof id}] (value: ${id})`) : invariant(false) : void 0;\n !Number.isInteger(props.index) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `${prefix(id)} requires an integer index prop`) : invariant(false) : void 0;\n if (props.mapped.type === 'DRAGGING') {\n return;\n }\n checkIsValidInnerRef(getRef());\n if (props.isEnabled) {\n !findDragHandle(contextId, id) ? process.env.NODE_ENV !== \"production\" ? invariant(false, `${prefix(id)} Unable to find drag handle`) : invariant(false) : void 0;\n }\n });\n}\nfunction useClonePropValidation(isClone) {\n useDev(() => {\n const initialRef = useRef(isClone);\n useDevSetupWarning(() => {\n !(isClone === initialRef.current) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Draggable isClone prop value changed during component life') : invariant(false) : void 0;\n }, [isClone]);\n });\n}\n\nfunction useRequiredContext(Context) {\n const result = useContext(Context);\n !result ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find required context') : invariant(false) : void 0;\n return result;\n}\n\nfunction preventHtml5Dnd(event) {\n event.preventDefault();\n}\nconst Draggable = props => {\n const ref = useRef(null);\n const setRef = useCallback((el = null) => {\n ref.current = el;\n }, []);\n const getRef = useCallback(() => ref.current, []);\n const {\n contextId,\n dragHandleUsageInstructionsId,\n registry\n } = useRequiredContext(AppContext);\n const {\n type,\n droppableId\n } = useRequiredContext(DroppableContext);\n const descriptor = useMemo(() => ({\n id: props.draggableId,\n index: props.index,\n type,\n droppableId\n }), [props.draggableId, props.index, type, droppableId]);\n const {\n children,\n draggableId,\n isEnabled,\n shouldRespectForcePress,\n canDragInteractiveElements,\n isClone,\n mapped,\n dropAnimationFinished: dropAnimationFinishedAction\n } = props;\n useValidation$1(props, contextId, getRef);\n useClonePropValidation(isClone);\n if (!isClone) {\n const forPublisher = useMemo(() => ({\n descriptor,\n registry,\n getDraggableRef: getRef,\n canDragInteractiveElements,\n shouldRespectForcePress,\n isEnabled\n }), [descriptor, registry, getRef, canDragInteractiveElements, shouldRespectForcePress, isEnabled]);\n useDraggablePublisher(forPublisher);\n }\n const dragHandleProps = useMemo(() => isEnabled ? {\n tabIndex: 0,\n role: 'button',\n 'aria-describedby': dragHandleUsageInstructionsId,\n 'data-rfd-drag-handle-draggable-id': draggableId,\n 'data-rfd-drag-handle-context-id': contextId,\n draggable: false,\n onDragStart: preventHtml5Dnd\n } : null, [contextId, dragHandleUsageInstructionsId, draggableId, isEnabled]);\n const onMoveEnd = useCallback(event => {\n if (mapped.type !== 'DRAGGING') {\n return;\n }\n if (!mapped.dropping) {\n return;\n }\n if (event.propertyName !== 'transform') {\n return;\n }\n if (React.version.startsWith('16') || React.version.startsWith('17')) {\n dropAnimationFinishedAction();\n } else {\n flushSync(dropAnimationFinishedAction);\n }\n }, [dropAnimationFinishedAction, mapped]);\n const provided = useMemo(() => {\n const style = getStyle$1(mapped);\n const onTransitionEnd = mapped.type === 'DRAGGING' && mapped.dropping ? onMoveEnd : undefined;\n const result = {\n innerRef: setRef,\n draggableProps: {\n 'data-rfd-draggable-context-id': contextId,\n 'data-rfd-draggable-id': draggableId,\n style,\n onTransitionEnd\n },\n dragHandleProps\n };\n return result;\n }, [contextId, dragHandleProps, draggableId, mapped, onMoveEnd, setRef]);\n const rubric = useMemo(() => ({\n draggableId: descriptor.id,\n type: descriptor.type,\n source: {\n index: descriptor.index,\n droppableId: descriptor.droppableId\n }\n }), [descriptor.droppableId, descriptor.id, descriptor.index, descriptor.type]);\n return React.createElement(React.Fragment, null, children(provided, mapped.snapshot, rubric));\n};\nvar Draggable$1 = Draggable;\n\nvar isStrictEqual = ((a, b) => a === b);\n\nvar whatIsDraggedOverFromResult = (result => {\n const {\n combine,\n destination\n } = result;\n if (destination) {\n return destination.droppableId;\n }\n if (combine) {\n return combine.droppableId;\n }\n return null;\n});\n\nconst getCombineWithFromResult = result => {\n return result.combine ? result.combine.draggableId : null;\n};\nconst getCombineWithFromImpact = impact => {\n return impact.at && impact.at.type === 'COMBINE' ? impact.at.combine.draggableId : null;\n};\nfunction getDraggableSelector() {\n const memoizedOffset = memoizeOne((x, y) => ({\n x,\n y\n }));\n const getMemoizedSnapshot = memoizeOne((mode, isClone, draggingOver = null, combineWith = null, dropping = null) => ({\n isDragging: true,\n isClone,\n isDropAnimating: Boolean(dropping),\n dropAnimation: dropping,\n mode,\n draggingOver,\n combineWith,\n combineTargetFor: null\n }));\n const getMemoizedProps = memoizeOne((offset, mode, dimension, isClone, draggingOver = null, combineWith = null, forceShouldAnimate = null) => ({\n mapped: {\n type: 'DRAGGING',\n dropping: null,\n draggingOver,\n combineWith,\n mode,\n offset,\n dimension,\n forceShouldAnimate,\n snapshot: getMemoizedSnapshot(mode, isClone, draggingOver, combineWith, null)\n }\n }));\n const selector = (state, ownProps) => {\n if (isDragging(state)) {\n if (state.critical.draggable.id !== ownProps.draggableId) {\n return null;\n }\n const offset = state.current.client.offset;\n const dimension = state.dimensions.draggables[ownProps.draggableId];\n const draggingOver = whatIsDraggedOver(state.impact);\n const combineWith = getCombineWithFromImpact(state.impact);\n const forceShouldAnimate = state.forceShouldAnimate;\n return getMemoizedProps(memoizedOffset(offset.x, offset.y), state.movementMode, dimension, ownProps.isClone, draggingOver, combineWith, forceShouldAnimate);\n }\n if (state.phase === 'DROP_ANIMATING') {\n const completed = state.completed;\n if (completed.result.draggableId !== ownProps.draggableId) {\n return null;\n }\n const isClone = ownProps.isClone;\n const dimension = state.dimensions.draggables[ownProps.draggableId];\n const result = completed.result;\n const mode = result.mode;\n const draggingOver = whatIsDraggedOverFromResult(result);\n const combineWith = getCombineWithFromResult(result);\n const duration = state.dropDuration;\n const dropping = {\n duration,\n curve: curves.drop,\n moveTo: state.newHomeClientOffset,\n opacity: combineWith ? combine.opacity.drop : null,\n scale: combineWith ? combine.scale.drop : null\n };\n return {\n mapped: {\n type: 'DRAGGING',\n offset: state.newHomeClientOffset,\n dimension,\n dropping,\n draggingOver,\n combineWith,\n mode,\n forceShouldAnimate: null,\n snapshot: getMemoizedSnapshot(mode, isClone, draggingOver, combineWith, dropping)\n }\n };\n }\n return null;\n };\n return selector;\n}\nfunction getSecondarySnapshot(combineTargetFor = null) {\n return {\n isDragging: false,\n isDropAnimating: false,\n isClone: false,\n dropAnimation: null,\n mode: null,\n draggingOver: null,\n combineTargetFor,\n combineWith: null\n };\n}\nconst atRest = {\n mapped: {\n type: 'SECONDARY',\n offset: origin,\n combineTargetFor: null,\n shouldAnimateDisplacement: true,\n snapshot: getSecondarySnapshot(null)\n }\n};\nfunction getSecondarySelector() {\n const memoizedOffset = memoizeOne((x, y) => ({\n x,\n y\n }));\n const getMemoizedSnapshot = memoizeOne(getSecondarySnapshot);\n const getMemoizedProps = memoizeOne((offset, combineTargetFor = null, shouldAnimateDisplacement) => ({\n mapped: {\n type: 'SECONDARY',\n offset,\n combineTargetFor,\n shouldAnimateDisplacement,\n snapshot: getMemoizedSnapshot(combineTargetFor)\n }\n }));\n const getFallback = combineTargetFor => {\n return combineTargetFor ? getMemoizedProps(origin, combineTargetFor, true) : null;\n };\n const getProps = (ownId, draggingId, impact, afterCritical) => {\n const visualDisplacement = impact.displaced.visible[ownId];\n const isAfterCriticalInVirtualList = Boolean(afterCritical.inVirtualList && afterCritical.effected[ownId]);\n const combine = tryGetCombine(impact);\n const combineTargetFor = combine && combine.draggableId === ownId ? draggingId : null;\n if (!visualDisplacement) {\n if (!isAfterCriticalInVirtualList) {\n return getFallback(combineTargetFor);\n }\n if (impact.displaced.invisible[ownId]) {\n return null;\n }\n const change = negate(afterCritical.displacedBy.point);\n const offset = memoizedOffset(change.x, change.y);\n return getMemoizedProps(offset, combineTargetFor, true);\n }\n if (isAfterCriticalInVirtualList) {\n return getFallback(combineTargetFor);\n }\n const displaceBy = impact.displacedBy.point;\n const offset = memoizedOffset(displaceBy.x, displaceBy.y);\n return getMemoizedProps(offset, combineTargetFor, visualDisplacement.shouldAnimate);\n };\n const selector = (state, ownProps) => {\n if (isDragging(state)) {\n if (state.critical.draggable.id === ownProps.draggableId) {\n return null;\n }\n return getProps(ownProps.draggableId, state.critical.draggable.id, state.impact, state.afterCritical);\n }\n if (state.phase === 'DROP_ANIMATING') {\n const completed = state.completed;\n if (completed.result.draggableId === ownProps.draggableId) {\n return null;\n }\n return getProps(ownProps.draggableId, completed.result.draggableId, completed.impact, completed.afterCritical);\n }\n return null;\n };\n return selector;\n}\nconst makeMapStateToProps$1 = () => {\n const draggingSelector = getDraggableSelector();\n const secondarySelector = getSecondarySelector();\n const selector = (state, ownProps) => draggingSelector(state, ownProps) || secondarySelector(state, ownProps) || atRest;\n return selector;\n};\nconst mapDispatchToProps$1 = {\n dropAnimationFinished: dropAnimationFinished\n};\nconst ConnectedDraggable = connect(makeMapStateToProps$1, mapDispatchToProps$1, null, {\n context: StoreContext,\n areStatePropsEqual: isStrictEqual\n})(Draggable$1);\nvar ConnectedDraggable$1 = ConnectedDraggable;\n\nfunction PrivateDraggable(props) {\n const droppableContext = useRequiredContext(DroppableContext);\n const isUsingCloneFor = droppableContext.isUsingCloneFor;\n if (isUsingCloneFor === props.draggableId && !props.isClone) {\n return null;\n }\n return React.createElement(ConnectedDraggable$1, props);\n}\nfunction PublicDraggable(props) {\n const isEnabled = typeof props.isDragDisabled === 'boolean' ? !props.isDragDisabled : true;\n const canDragInteractiveElements = Boolean(props.disableInteractiveElementBlocking);\n const shouldRespectForcePress = Boolean(props.shouldRespectForcePress);\n return React.createElement(PrivateDraggable, _extends({}, props, {\n isClone: false,\n isEnabled: isEnabled,\n canDragInteractiveElements: canDragInteractiveElements,\n shouldRespectForcePress: shouldRespectForcePress\n }));\n}\n\nconst isEqual = base => value => base === value;\nconst isScroll = isEqual('scroll');\nconst isAuto = isEqual('auto');\nconst isVisible = isEqual('visible');\nconst isEither = (overflow, fn) => fn(overflow.overflowX) || fn(overflow.overflowY);\nconst isBoth = (overflow, fn) => fn(overflow.overflowX) && fn(overflow.overflowY);\nconst isElementScrollable = el => {\n const style = window.getComputedStyle(el);\n const overflow = {\n overflowX: style.overflowX,\n overflowY: style.overflowY\n };\n return isEither(overflow, isScroll) || isEither(overflow, isAuto);\n};\nconst isBodyScrollable = () => {\n if (process.env.NODE_ENV === 'production') {\n return false;\n }\n const body = getBodyElement();\n const html = document.documentElement;\n !html ? process.env.NODE_ENV !== \"production\" ? invariant(false) : invariant(false) : void 0;\n if (!isElementScrollable(body)) {\n return false;\n }\n const htmlStyle = window.getComputedStyle(html);\n const htmlOverflow = {\n overflowX: htmlStyle.overflowX,\n overflowY: htmlStyle.overflowY\n };\n if (isBoth(htmlOverflow, isVisible)) {\n return false;\n }\n process.env.NODE_ENV !== \"production\" ? warning(`\n We have detected that your element might be a scroll container.\n We have found no reliable way of detecting whether the element is a scroll container.\n Under most circumstances a scroll bar will be on the element (document.documentElement)\n\n Because we cannot determine if the is a scroll container, and generally it is not one,\n we will be treating the as *not* a scroll container\n\n More information: https://github.com/hello-pangea/dnd/blob/main/docs/guides/how-we-detect-scroll-containers.md\n `) : void 0;\n return false;\n};\nconst getClosestScrollable = el => {\n if (el == null) {\n return null;\n }\n if (el === document.body) {\n return isBodyScrollable() ? el : null;\n }\n if (el === document.documentElement) {\n return null;\n }\n if (!isElementScrollable(el)) {\n return getClosestScrollable(el.parentElement);\n }\n return el;\n};\n\nvar checkForNestedScrollContainers = (scrollable => {\n if (!scrollable) {\n return;\n }\n const anotherScrollParent = getClosestScrollable(scrollable.parentElement);\n if (!anotherScrollParent) {\n return;\n }\n process.env.NODE_ENV !== \"production\" ? warning(`\n Droppable: unsupported nested scroll container detected.\n A Droppable can only have one scroll parent (which can be itself)\n Nested scroll containers are currently not supported.\n\n We hope to support nested scroll containers soon: https://github.com/atlassian/react-beautiful-dnd/issues/131\n `) : void 0;\n});\n\nvar getScroll = (el => ({\n x: el.scrollLeft,\n y: el.scrollTop\n}));\n\nconst getIsFixed = el => {\n if (!el) {\n return false;\n }\n const style = window.getComputedStyle(el);\n if (style.position === 'fixed') {\n return true;\n }\n return getIsFixed(el.parentElement);\n};\nvar getEnv = (start => {\n const closestScrollable = getClosestScrollable(start);\n const isFixedOnPage = getIsFixed(start);\n return {\n closestScrollable,\n isFixedOnPage\n };\n});\n\nvar getDroppableDimension = (({\n descriptor,\n isEnabled,\n isCombineEnabled,\n isFixedOnPage,\n direction,\n client,\n page,\n closest\n}) => {\n const frame = (() => {\n if (!closest) {\n return null;\n }\n const {\n scrollSize,\n client: frameClient\n } = closest;\n const maxScroll = getMaxScroll({\n scrollHeight: scrollSize.scrollHeight,\n scrollWidth: scrollSize.scrollWidth,\n height: frameClient.paddingBox.height,\n width: frameClient.paddingBox.width\n });\n return {\n pageMarginBox: closest.page.marginBox,\n frameClient,\n scrollSize,\n shouldClipSubject: closest.shouldClipSubject,\n scroll: {\n initial: closest.scroll,\n current: closest.scroll,\n max: maxScroll,\n diff: {\n value: origin,\n displacement: origin\n }\n }\n };\n })();\n const axis = direction === 'vertical' ? vertical : horizontal;\n const subject = getSubject({\n page,\n withPlaceholder: null,\n axis,\n frame\n });\n const dimension = {\n descriptor,\n isCombineEnabled,\n isFixedOnPage,\n axis,\n isEnabled,\n client,\n page,\n frame,\n subject\n };\n return dimension;\n});\n\nconst getClient = (targetRef, closestScrollable) => {\n const base = getBox(targetRef);\n if (!closestScrollable) {\n return base;\n }\n if (targetRef !== closestScrollable) {\n return base;\n }\n const top = base.paddingBox.top - closestScrollable.scrollTop;\n const left = base.paddingBox.left - closestScrollable.scrollLeft;\n const bottom = top + closestScrollable.scrollHeight;\n const right = left + closestScrollable.scrollWidth;\n const paddingBox = {\n top,\n right,\n bottom,\n left\n };\n const borderBox = expand(paddingBox, base.border);\n const client = createBox({\n borderBox,\n margin: base.margin,\n border: base.border,\n padding: base.padding\n });\n return client;\n};\nvar getDimension = (({\n ref,\n descriptor,\n env,\n windowScroll,\n direction,\n isDropDisabled,\n isCombineEnabled,\n shouldClipSubject\n}) => {\n const closestScrollable = env.closestScrollable;\n const client = getClient(ref, closestScrollable);\n const page = withScroll(client, windowScroll);\n const closest = (() => {\n if (!closestScrollable) {\n return null;\n }\n const frameClient = getBox(closestScrollable);\n const scrollSize = {\n scrollHeight: closestScrollable.scrollHeight,\n scrollWidth: closestScrollable.scrollWidth\n };\n return {\n client: frameClient,\n page: withScroll(frameClient, windowScroll),\n scroll: getScroll(closestScrollable),\n scrollSize,\n shouldClipSubject\n };\n })();\n const dimension = getDroppableDimension({\n descriptor,\n isEnabled: !isDropDisabled,\n isCombineEnabled,\n isFixedOnPage: env.isFixedOnPage,\n direction,\n client,\n page,\n closest\n });\n return dimension;\n});\n\nconst immediate = {\n passive: false\n};\nconst delayed = {\n passive: true\n};\nvar getListenerOptions = (options => options.shouldPublishImmediately ? immediate : delayed);\n\nconst getClosestScrollableFromDrag = dragging => dragging && dragging.env.closestScrollable || null;\nfunction useDroppablePublisher(args) {\n const whileDraggingRef = useRef(null);\n const appContext = useRequiredContext(AppContext);\n const uniqueId = useUniqueId$1('droppable');\n const {\n registry,\n marshal\n } = appContext;\n const previousRef = usePrevious(args);\n const descriptor = useMemo(() => ({\n id: args.droppableId,\n type: args.type,\n mode: args.mode\n }), [args.droppableId, args.mode, args.type]);\n const publishedDescriptorRef = useRef(descriptor);\n const memoizedUpdateScroll = useMemo(() => memoizeOne((x, y) => {\n !whileDraggingRef.current ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Can only update scroll when dragging') : invariant(false) : void 0;\n const scroll = {\n x,\n y\n };\n marshal.updateDroppableScroll(descriptor.id, scroll);\n }), [descriptor.id, marshal]);\n const getClosestScroll = useCallback(() => {\n const dragging = whileDraggingRef.current;\n if (!dragging || !dragging.env.closestScrollable) {\n return origin;\n }\n return getScroll(dragging.env.closestScrollable);\n }, []);\n const updateScroll = useCallback(() => {\n const scroll = getClosestScroll();\n memoizedUpdateScroll(scroll.x, scroll.y);\n }, [getClosestScroll, memoizedUpdateScroll]);\n const scheduleScrollUpdate = useMemo(() => rafSchd(updateScroll), [updateScroll]);\n const onClosestScroll = useCallback(() => {\n const dragging = whileDraggingRef.current;\n const closest = getClosestScrollableFromDrag(dragging);\n !(dragging && closest) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find scroll options while scrolling') : invariant(false) : void 0;\n const options = dragging.scrollOptions;\n if (options.shouldPublishImmediately) {\n updateScroll();\n return;\n }\n scheduleScrollUpdate();\n }, [scheduleScrollUpdate, updateScroll]);\n const getDimensionAndWatchScroll = useCallback((windowScroll, options) => {\n !!whileDraggingRef.current ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot collect a droppable while a drag is occurring') : invariant(false) : void 0;\n const previous = previousRef.current;\n const ref = previous.getDroppableRef();\n !ref ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot collect without a droppable ref') : invariant(false) : void 0;\n const env = getEnv(ref);\n const dragging = {\n ref,\n descriptor,\n env,\n scrollOptions: options\n };\n whileDraggingRef.current = dragging;\n const dimension = getDimension({\n ref,\n descriptor,\n env,\n windowScroll,\n direction: previous.direction,\n isDropDisabled: previous.isDropDisabled,\n isCombineEnabled: previous.isCombineEnabled,\n shouldClipSubject: !previous.ignoreContainerClipping\n });\n const scrollable = env.closestScrollable;\n if (scrollable) {\n scrollable.setAttribute(scrollContainer.contextId, appContext.contextId);\n scrollable.addEventListener('scroll', onClosestScroll, getListenerOptions(dragging.scrollOptions));\n if (process.env.NODE_ENV !== 'production') {\n checkForNestedScrollContainers(scrollable);\n }\n }\n return dimension;\n }, [appContext.contextId, descriptor, onClosestScroll, previousRef]);\n const getScrollWhileDragging = useCallback(() => {\n const dragging = whileDraggingRef.current;\n const closest = getClosestScrollableFromDrag(dragging);\n !(dragging && closest) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Can only recollect Droppable client for Droppables that have a scroll container') : invariant(false) : void 0;\n return getScroll(closest);\n }, []);\n const dragStopped = useCallback(() => {\n const dragging = whileDraggingRef.current;\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot stop drag when no active drag') : invariant(false) : void 0;\n const closest = getClosestScrollableFromDrag(dragging);\n whileDraggingRef.current = null;\n if (!closest) {\n return;\n }\n scheduleScrollUpdate.cancel();\n closest.removeAttribute(scrollContainer.contextId);\n closest.removeEventListener('scroll', onClosestScroll, getListenerOptions(dragging.scrollOptions));\n }, [onClosestScroll, scheduleScrollUpdate]);\n const scroll = useCallback(change => {\n const dragging = whileDraggingRef.current;\n !dragging ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot scroll when there is no drag') : invariant(false) : void 0;\n const closest = getClosestScrollableFromDrag(dragging);\n !closest ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Cannot scroll a droppable with no closest scrollable') : invariant(false) : void 0;\n closest.scrollTop += change.y;\n closest.scrollLeft += change.x;\n }, []);\n const callbacks = useMemo(() => {\n return {\n getDimensionAndWatchScroll,\n getScrollWhileDragging,\n dragStopped,\n scroll\n };\n }, [dragStopped, getDimensionAndWatchScroll, getScrollWhileDragging, scroll]);\n const entry = useMemo(() => ({\n uniqueId,\n descriptor,\n callbacks\n }), [callbacks, descriptor, uniqueId]);\n useLayoutEffect(() => {\n publishedDescriptorRef.current = entry.descriptor;\n registry.droppable.register(entry);\n return () => {\n if (whileDraggingRef.current) {\n process.env.NODE_ENV !== \"production\" ? warning('Unsupported: changing the droppableId or type of a Droppable during a drag') : void 0;\n dragStopped();\n }\n registry.droppable.unregister(entry);\n };\n }, [callbacks, descriptor, dragStopped, entry, marshal, registry.droppable]);\n useLayoutEffect(() => {\n if (!whileDraggingRef.current) {\n return;\n }\n marshal.updateDroppableIsEnabled(publishedDescriptorRef.current.id, !args.isDropDisabled);\n }, [args.isDropDisabled, marshal]);\n useLayoutEffect(() => {\n if (!whileDraggingRef.current) {\n return;\n }\n marshal.updateDroppableIsCombineEnabled(publishedDescriptorRef.current.id, args.isCombineEnabled);\n }, [args.isCombineEnabled, marshal]);\n}\n\nfunction noop() {}\nconst empty = {\n width: 0,\n height: 0,\n margin: noSpacing\n};\nconst getSize = ({\n isAnimatingOpenOnMount,\n placeholder,\n animate\n}) => {\n if (isAnimatingOpenOnMount) {\n return empty;\n }\n if (animate === 'close') {\n return empty;\n }\n return {\n height: placeholder.client.borderBox.height,\n width: placeholder.client.borderBox.width,\n margin: placeholder.client.margin\n };\n};\nconst getStyle = ({\n isAnimatingOpenOnMount,\n placeholder,\n animate\n}) => {\n const size = getSize({\n isAnimatingOpenOnMount,\n placeholder,\n animate\n });\n return {\n display: placeholder.display,\n boxSizing: 'border-box',\n width: size.width,\n height: size.height,\n marginTop: size.margin.top,\n marginRight: size.margin.right,\n marginBottom: size.margin.bottom,\n marginLeft: size.margin.left,\n flexShrink: '0',\n flexGrow: '0',\n pointerEvents: 'none',\n transition: animate !== 'none' ? transitions.placeholder : null\n };\n};\nconst Placeholder = props => {\n const animateOpenTimerRef = useRef(null);\n const tryClearAnimateOpenTimer = useCallback(() => {\n if (!animateOpenTimerRef.current) {\n return;\n }\n clearTimeout(animateOpenTimerRef.current);\n animateOpenTimerRef.current = null;\n }, []);\n const {\n animate,\n onTransitionEnd,\n onClose,\n contextId\n } = props;\n const [isAnimatingOpenOnMount, setIsAnimatingOpenOnMount] = useState(props.animate === 'open');\n useEffect(() => {\n if (!isAnimatingOpenOnMount) {\n return noop;\n }\n if (animate !== 'open') {\n tryClearAnimateOpenTimer();\n setIsAnimatingOpenOnMount(false);\n return noop;\n }\n if (animateOpenTimerRef.current) {\n return noop;\n }\n animateOpenTimerRef.current = setTimeout(() => {\n animateOpenTimerRef.current = null;\n setIsAnimatingOpenOnMount(false);\n });\n return tryClearAnimateOpenTimer;\n }, [animate, isAnimatingOpenOnMount, tryClearAnimateOpenTimer]);\n const onSizeChangeEnd = useCallback(event => {\n if (event.propertyName !== 'height') {\n return;\n }\n onTransitionEnd();\n if (animate === 'close') {\n onClose();\n }\n }, [animate, onClose, onTransitionEnd]);\n const style = getStyle({\n isAnimatingOpenOnMount,\n animate: props.animate,\n placeholder: props.placeholder\n });\n return React.createElement(props.placeholder.tagName, {\n style,\n 'data-rfd-placeholder-context-id': contextId,\n onTransitionEnd: onSizeChangeEnd,\n ref: props.innerRef\n });\n};\nvar Placeholder$1 = React.memo(Placeholder);\n\nfunction isBoolean(value) {\n return typeof value === 'boolean';\n}\nfunction runChecks(args, checks) {\n checks.forEach(check => check(args));\n}\nconst shared = [function required({\n props\n}) {\n !props.droppableId ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'A Droppable requires a droppableId prop') : invariant(false) : void 0;\n !(typeof props.droppableId === 'string') ? process.env.NODE_ENV !== \"production\" ? invariant(false, `A Droppable requires a [string] droppableId. Provided: [${typeof props.droppableId}]`) : invariant(false) : void 0;\n}, function boolean({\n props\n}) {\n !isBoolean(props.isDropDisabled) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'isDropDisabled must be a boolean') : invariant(false) : void 0;\n !isBoolean(props.isCombineEnabled) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'isCombineEnabled must be a boolean') : invariant(false) : void 0;\n !isBoolean(props.ignoreContainerClipping) ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'ignoreContainerClipping must be a boolean') : invariant(false) : void 0;\n}, function ref({\n getDroppableRef\n}) {\n checkIsValidInnerRef(getDroppableRef());\n}];\nconst standard = [function placeholder({\n props,\n getPlaceholderRef\n}) {\n if (!props.placeholder) {\n return;\n }\n const ref = getPlaceholderRef();\n if (ref) {\n return;\n }\n process.env.NODE_ENV !== \"production\" ? warning(`\n Droppable setup issue [droppableId: \"${props.droppableId}\"]:\n DroppableProvided > placeholder could not be found.\n\n Please be sure to add the {provided.placeholder} React Node as a child of your Droppable.\n More information: https://github.com/hello-pangea/dnd/blob/main/docs/api/droppable.md\n `) : void 0;\n}];\nconst virtual = [function hasClone({\n props\n}) {\n !props.renderClone ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Must provide a clone render function (renderClone) for virtual lists') : invariant(false) : void 0;\n}, function hasNoPlaceholder({\n getPlaceholderRef\n}) {\n !!getPlaceholderRef() ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Expected virtual list to not have a placeholder') : invariant(false) : void 0;\n}];\nfunction useValidation(args) {\n useDevSetupWarning(() => {\n runChecks(args, shared);\n if (args.props.mode === 'standard') {\n runChecks(args, standard);\n }\n if (args.props.mode === 'virtual') {\n runChecks(args, virtual);\n }\n });\n}\n\nclass AnimateInOut extends React.PureComponent {\n constructor(...args) {\n super(...args);\n this.state = {\n isVisible: Boolean(this.props.on),\n data: this.props.on,\n animate: this.props.shouldAnimate && this.props.on ? 'open' : 'none'\n };\n this.onClose = () => {\n if (this.state.animate !== 'close') {\n return;\n }\n this.setState({\n isVisible: false\n });\n };\n }\n static getDerivedStateFromProps(props, state) {\n if (!props.shouldAnimate) {\n return {\n isVisible: Boolean(props.on),\n data: props.on,\n animate: 'none'\n };\n }\n if (props.on) {\n return {\n isVisible: true,\n data: props.on,\n animate: 'open'\n };\n }\n if (state.isVisible) {\n return {\n isVisible: true,\n data: state.data,\n animate: 'close'\n };\n }\n return {\n isVisible: false,\n animate: 'close',\n data: null\n };\n }\n render() {\n if (!this.state.isVisible) {\n return null;\n }\n const provided = {\n onClose: this.onClose,\n data: this.state.data,\n animate: this.state.animate\n };\n return this.props.children(provided);\n }\n}\n\nconst Droppable = props => {\n const appContext = useContext(AppContext);\n !appContext ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'Could not find app context') : invariant(false) : void 0;\n const {\n contextId,\n isMovementAllowed\n } = appContext;\n const droppableRef = useRef(null);\n const placeholderRef = useRef(null);\n const {\n children,\n droppableId,\n type,\n mode,\n direction,\n ignoreContainerClipping,\n isDropDisabled,\n isCombineEnabled,\n snapshot,\n useClone,\n updateViewportMaxScroll,\n getContainerForClone\n } = props;\n const getDroppableRef = useCallback(() => droppableRef.current, []);\n const setDroppableRef = useCallback((value = null) => {\n droppableRef.current = value;\n }, []);\n const getPlaceholderRef = useCallback(() => placeholderRef.current, []);\n const setPlaceholderRef = useCallback((value = null) => {\n placeholderRef.current = value;\n }, []);\n useValidation({\n props,\n getDroppableRef,\n getPlaceholderRef\n });\n const onPlaceholderTransitionEnd = useCallback(() => {\n if (isMovementAllowed()) {\n updateViewportMaxScroll({\n maxScroll: getMaxWindowScroll()\n });\n }\n }, [isMovementAllowed, updateViewportMaxScroll]);\n useDroppablePublisher({\n droppableId,\n type,\n mode,\n direction,\n isDropDisabled,\n isCombineEnabled,\n ignoreContainerClipping,\n getDroppableRef\n });\n const placeholder = useMemo(() => React.createElement(AnimateInOut, {\n on: props.placeholder,\n shouldAnimate: props.shouldAnimatePlaceholder\n }, ({\n onClose,\n data,\n animate\n }) => React.createElement(Placeholder$1, {\n placeholder: data,\n onClose: onClose,\n innerRef: setPlaceholderRef,\n animate: animate,\n contextId: contextId,\n onTransitionEnd: onPlaceholderTransitionEnd\n })), [contextId, onPlaceholderTransitionEnd, props.placeholder, props.shouldAnimatePlaceholder, setPlaceholderRef]);\n const provided = useMemo(() => ({\n innerRef: setDroppableRef,\n placeholder,\n droppableProps: {\n 'data-rfd-droppable-id': droppableId,\n 'data-rfd-droppable-context-id': contextId\n }\n }), [contextId, droppableId, placeholder, setDroppableRef]);\n const isUsingCloneFor = useClone ? useClone.dragging.draggableId : null;\n const droppableContext = useMemo(() => ({\n droppableId,\n type,\n isUsingCloneFor\n }), [droppableId, isUsingCloneFor, type]);\n function getClone() {\n if (!useClone) {\n return null;\n }\n const {\n dragging,\n render\n } = useClone;\n const node = React.createElement(PrivateDraggable, {\n draggableId: dragging.draggableId,\n index: dragging.source.index,\n isClone: true,\n isEnabled: true,\n shouldRespectForcePress: false,\n canDragInteractiveElements: true\n }, (draggableProvided, draggableSnapshot) => render(draggableProvided, draggableSnapshot, dragging));\n return ReactDOM.createPortal(node, getContainerForClone());\n }\n return React.createElement(DroppableContext.Provider, {\n value: droppableContext\n }, children(provided, snapshot), getClone());\n};\nvar Droppable$1 = Droppable;\n\nfunction getBody() {\n !document.body ? process.env.NODE_ENV !== \"production\" ? invariant(false, 'document.body is not ready') : invariant(false) : void 0;\n return document.body;\n}\nconst defaultProps = {\n mode: 'standard',\n type: 'DEFAULT',\n direction: 'vertical',\n isDropDisabled: false,\n isCombineEnabled: false,\n ignoreContainerClipping: false,\n renderClone: null,\n getContainerForClone: getBody\n};\nconst attachDefaultPropsToOwnProps = ownProps => {\n let mergedProps = {\n ...ownProps\n };\n let defaultPropKey;\n for (defaultPropKey in defaultProps) {\n if (ownProps[defaultPropKey] === undefined) {\n mergedProps = {\n ...mergedProps,\n [defaultPropKey]: defaultProps[defaultPropKey]\n };\n }\n }\n return mergedProps;\n};\nconst isMatchingType = (type, critical) => type === critical.droppable.type;\nconst getDraggable = (critical, dimensions) => dimensions.draggables[critical.draggable.id];\nconst makeMapStateToProps = () => {\n const idleWithAnimation = {\n placeholder: null,\n shouldAnimatePlaceholder: true,\n snapshot: {\n isDraggingOver: false,\n draggingOverWith: null,\n draggingFromThisWith: null,\n isUsingPlaceholder: false\n },\n useClone: null\n };\n const idleWithoutAnimation = {\n ...idleWithAnimation,\n shouldAnimatePlaceholder: false\n };\n const getDraggableRubric = memoizeOne(descriptor => ({\n draggableId: descriptor.id,\n type: descriptor.type,\n source: {\n index: descriptor.index,\n droppableId: descriptor.droppableId\n }\n }));\n const getMapProps = memoizeOne((id, isEnabled, isDraggingOverForConsumer, isDraggingOverForImpact, dragging, renderClone) => {\n const draggableId = dragging.descriptor.id;\n const isHome = dragging.descriptor.droppableId === id;\n if (isHome) {\n const useClone = renderClone ? {\n render: renderClone,\n dragging: getDraggableRubric(dragging.descriptor)\n } : null;\n const snapshot = {\n isDraggingOver: isDraggingOverForConsumer,\n draggingOverWith: isDraggingOverForConsumer ? draggableId : null,\n draggingFromThisWith: draggableId,\n isUsingPlaceholder: true\n };\n return {\n placeholder: dragging.placeholder,\n shouldAnimatePlaceholder: false,\n snapshot,\n useClone\n };\n }\n if (!isEnabled) {\n return idleWithoutAnimation;\n }\n if (!isDraggingOverForImpact) {\n return idleWithAnimation;\n }\n const snapshot = {\n isDraggingOver: isDraggingOverForConsumer,\n draggingOverWith: draggableId,\n draggingFromThisWith: null,\n isUsingPlaceholder: true\n };\n return {\n placeholder: dragging.placeholder,\n shouldAnimatePlaceholder: true,\n snapshot,\n useClone: null\n };\n });\n const selector = (state, ownProps) => {\n const ownPropsWithDefaultProps = attachDefaultPropsToOwnProps(ownProps);\n const id = ownPropsWithDefaultProps.droppableId;\n const type = ownPropsWithDefaultProps.type;\n const isEnabled = !ownPropsWithDefaultProps.isDropDisabled;\n const renderClone = ownPropsWithDefaultProps.renderClone;\n if (isDragging(state)) {\n const critical = state.critical;\n if (!isMatchingType(type, critical)) {\n return idleWithoutAnimation;\n }\n const dragging = getDraggable(critical, state.dimensions);\n const isDraggingOver = whatIsDraggedOver(state.impact) === id;\n return getMapProps(id, isEnabled, isDraggingOver, isDraggingOver, dragging, renderClone);\n }\n if (state.phase === 'DROP_ANIMATING') {\n const completed = state.completed;\n if (!isMatchingType(type, completed.critical)) {\n return idleWithoutAnimation;\n }\n const dragging = getDraggable(completed.critical, state.dimensions);\n return getMapProps(id, isEnabled, whatIsDraggedOverFromResult(completed.result) === id, whatIsDraggedOver(completed.impact) === id, dragging, renderClone);\n }\n if (state.phase === 'IDLE' && state.completed && !state.shouldFlush) {\n const completed = state.completed;\n if (!isMatchingType(type, completed.critical)) {\n return idleWithoutAnimation;\n }\n const wasOver = whatIsDraggedOver(completed.impact) === id;\n const wasCombining = Boolean(completed.impact.at && completed.impact.at.type === 'COMBINE');\n const isHome = completed.critical.droppable.id === id;\n if (wasOver) {\n return wasCombining ? idleWithAnimation : idleWithoutAnimation;\n }\n if (isHome) {\n return idleWithAnimation;\n }\n return idleWithoutAnimation;\n }\n return idleWithoutAnimation;\n };\n return selector;\n};\nconst mapDispatchToProps = {\n updateViewportMaxScroll: updateViewportMaxScroll\n};\nconst ConnectedDroppable = connect(makeMapStateToProps, mapDispatchToProps, (stateProps, dispatchProps, ownProps) => {\n return {\n ...attachDefaultPropsToOwnProps(ownProps),\n ...stateProps,\n ...dispatchProps\n };\n}, {\n context: StoreContext,\n areStatePropsEqual: isStrictEqual\n})(Droppable$1);\nvar ConnectedDroppable$1 = ConnectedDroppable;\n\nexport { DragDropContext, PublicDraggable as Draggable, ConnectedDroppable$1 as Droppable, resetServerContext, useKeyboardSensor, useMouseSensor, useTouchSensor };\n","/**\n* Copyright (c) 2023, Leon Sorokin\n* All rights reserved. (MIT Licensed)\n*\n* uFuzzy.js (μFuzzy)\n* A tiny, efficient fuzzy matcher that doesn't suck\n* https://github.com/leeoniya/uFuzzy (v1.0.14)\n*/\n\nconst cmp = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }).compare;\n\nconst inf = Infinity;\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#escaping\nconst escapeRegExp = str => str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n// meh, magic tmp placeholder, must be tolerant to toLocaleLowerCase(), interSplit, and intraSplit\nconst EXACT_HERE = 'eexxaacctt';\n\nconst LATIN_UPPER = 'A-Z';\nconst LATIN_LOWER = 'a-z';\n\nconst swapAlpha = (str, upper, lower) => str.replace(LATIN_UPPER, upper).replace(LATIN_LOWER, lower);\n\nconst OPTS = {\n\t// whether regexps use a /u unicode flag\n\tunicode: false,\n\n\talpha: null,\n\n\t// term segmentation & punct/whitespace merging\n\tinterSplit: \"[^A-Za-z\\\\d']+\",\n\tintraSplit: \"[a-z][A-Z]\",\n\n\t// intra bounds that will be used to increase lft1/rgt1 info counters\n\tintraBound: \"[A-Za-z]\\\\d|\\\\d[A-Za-z]|[a-z][A-Z]\",\n\n\t// inter-bounds mode\n\t// 2 = strict (will only match 'man' on whitepace and punct boundaries: Mega Man, Mega_Man, mega.man)\n\t// 1 = loose (plus allowance for alpha-num and case-change boundaries: MegaMan, 0007man)\n\t// 0 = any (will match 'man' as any substring: megamaniac)\n\tinterLft: 0,\n\tinterRgt: 0,\n\n\t// allowance between terms\n\tinterChars: '.',\n\tinterIns: inf,\n\n\t// allowance between chars in terms\n\tintraChars: \"[a-z\\\\d']\", // internally case-insensitive\n\tintraIns: null,\n\n\tintraContr: \"'[a-z]{1,2}\\\\b\",\n\n\t// multi-insert or single-error mode\n\tintraMode: 0,\n\n\t// single-error bounds for errors within terms, default requires exact first char\n\tintraSlice: [1, inf],\n\n\t// single-error tolerance toggles\n\tintraSub: null,\n\tintraTrn: null,\n\tintraDel: null,\n\n\t// can post-filter matches that are too far apart in distance or length\n\t// (since intraIns is between each char, it can accum to nonsense matches)\n\tintraFilt: (term, match, index) => true, // should this also accept WIP info?\n\n\t// final sorting fn\n\tsort: (info, haystack, needle) => {\n\t\tlet {\n\t\t\tidx,\n\t\t\tchars,\n\t\t\tterms,\n\t\t\tinterLft2,\n\t\t\tinterLft1,\n\t\t//\tinterRgt2,\n\t\t//\tinterRgt1,\n\t\t\tstart,\n\t\t\tintraIns,\n\t\t\tinterIns,\n\t\t} = info;\n\n\t\treturn idx.map((v, i) => i).sort((ia, ib) => (\n\t\t\t// most contig chars matched\n\t\t\tchars[ib] - chars[ia] ||\n\t\t\t// least char intra-fuzz (most contiguous)\n\t\t\tintraIns[ia] - intraIns[ib] ||\n\t\t\t// most prefix bounds, boosted by full term matches\n\t\t\t(\n\t\t\t\t(terms[ib] + interLft2[ib] + 0.5 * interLft1[ib]) -\n\t\t\t\t(terms[ia] + interLft2[ia] + 0.5 * interLft1[ia])\n\t\t\t) ||\n\t\t\t// highest density of match (least span)\n\t\t//\tspan[ia] - span[ib] ||\n\t\t\t// highest density of match (least term inter-fuzz)\n\t\t\tinterIns[ia] - interIns[ib] ||\n\t\t\t// earliest start of match\n\t\t\tstart[ia] - start[ib] ||\n\t\t\t// alphabetic\n\t\t\tcmp(haystack[idx[ia]], haystack[idx[ib]])\n\t\t));\n\t},\n};\n\nconst lazyRepeat = (chars, limit) => (\n\tlimit == 0 ? '' :\n\tlimit == 1 ? chars + '??' :\n\tlimit == inf ? chars + '*?' :\n\t chars + `{0,${limit}}?`\n);\n\nconst mode2Tpl = '(?:\\\\b|_)';\n\nfunction uFuzzy(opts) {\n\topts = Object.assign({}, OPTS, opts);\n\n\tlet {\n\t\tunicode,\n\t\tinterLft,\n\t\tinterRgt,\n\t\tintraMode,\n\t\tintraSlice,\n\t\tintraIns,\n\t\tintraSub,\n\t\tintraTrn,\n\t\tintraDel,\n\t\tintraContr,\n\t\tintraSplit: _intraSplit,\n\t\tinterSplit: _interSplit,\n\t\tintraBound: _intraBound,\n\t\tintraChars,\n\t} = opts;\n\n\tintraIns ??= intraMode;\n\tintraSub ??= intraMode;\n\tintraTrn ??= intraMode;\n\tintraDel ??= intraMode;\n\n\tlet alpha = opts.letters ?? opts.alpha;\n\n\tif (alpha != null) {\n\t\tlet upper = alpha.toLocaleUpperCase();\n\t\tlet lower = alpha.toLocaleLowerCase();\n\n\t\t_interSplit = swapAlpha(_interSplit, upper, lower);\n\t\t_intraSplit = swapAlpha(_intraSplit, upper, lower);\n\t\t_intraBound = swapAlpha(_intraBound, upper, lower);\n\t\tintraChars = swapAlpha(intraChars, upper, lower);\n\t\tintraContr = swapAlpha(intraContr, upper, lower);\n\t}\n\n\tlet uFlag = unicode ? 'u' : '';\n\n\tconst quotedAny = '\".+?\"';\n\tconst EXACTS_RE = new RegExp(quotedAny, 'gi' + uFlag);\n\tconst NEGS_RE = new RegExp(`(?:\\\\s+|^)-(?:${intraChars}+|${quotedAny})`, 'gi' + uFlag);\n\n\tlet { intraRules } = opts;\n\n\tif (intraRules == null) {\n\t\tintraRules = p => {\n\t\t\t// default is exact term matches only\n\t\t\tlet _intraSlice = OPTS.intraSlice, // requires first char\n\t\t\t\t_intraIns = 0,\n\t\t\t\t_intraSub = 0,\n\t\t\t\t_intraTrn = 0,\n\t\t\t\t_intraDel = 0;\n\n\t\t\t// only-digits strings should match exactly, else special rules for short strings\n\t\t\tif (/[^\\d]/.test(p)) {\n\t\t\t\tlet plen = p.length;\n\n\t\t\t\t// prevent junk matches by requiring stricter rules for short terms\n\t\t\t\tif (plen <= 4) {\n\t\t\t\t\tif (plen >= 3) {\n\t\t\t\t\t\t// one swap in non-first char when 3-4 chars\n\t\t\t\t\t\t_intraTrn = Math.min(intraTrn, 1);\n\n\t\t\t\t\t\t// or one insertion when 4 chars\n\t\t\t\t\t\tif (plen == 4)\n\t\t\t\t\t\t\t_intraIns = Math.min(intraIns, 1);\n\t\t\t\t\t}\n\t\t\t\t\t// else exact match when 1-2 chars\n\t\t\t\t}\n\t\t\t\t// use supplied opts\n\t\t\t\telse {\n\t\t\t\t\t_intraSlice = intraSlice;\n\t\t\t\t\t_intraIns = intraIns,\n\t\t\t\t\t_intraSub = intraSub,\n\t\t\t\t\t_intraTrn = intraTrn,\n\t\t\t\t\t_intraDel = intraDel;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tintraSlice: _intraSlice,\n\t\t\t\tintraIns: _intraIns,\n\t\t\t\tintraSub: _intraSub,\n\t\t\t\tintraTrn: _intraTrn,\n\t\t\t\tintraDel: _intraDel,\n\t\t\t};\n\t\t};\n\t}\n\n\tlet withIntraSplit = !!_intraSplit;\n\n\tlet intraSplit = new RegExp(_intraSplit, 'g' + uFlag);\n\tlet interSplit = new RegExp(_interSplit, 'g' + uFlag);\n\n\tlet trimRe = new RegExp('^' + _interSplit + '|' + _interSplit + '$', 'g' + uFlag);\n\tlet contrsRe = new RegExp(intraContr, 'gi' + uFlag);\n\n\tconst split = needle => {\n\t\tlet exacts = [];\n\n\t\tneedle = needle.replace(EXACTS_RE, m => {\n\t\t\texacts.push(m);\n\t\t\treturn EXACT_HERE;\n\t\t});\n\n\t\tneedle = needle.replace(trimRe, '').toLocaleLowerCase();\n\n\t\tif (withIntraSplit)\n\t\t\tneedle = needle.replace(intraSplit, m => m[0] + ' ' + m[1]);\n\n\t\tlet j = 0;\n\t\treturn needle.split(interSplit).filter(t => t != '').map(v => v === EXACT_HERE ? exacts[j++] : v);\n\t};\n\n\tconst NUM_OR_ALPHA_RE = /[^\\d]+|\\d+/g;\n\n\tconst prepQuery = (needle, capt = 0, interOR = false) => {\n\t\t// split on punct, whitespace, num-alpha, and upper-lower boundaries\n\t\tlet parts = split(needle);\n\n\t\tif (parts.length == 0)\n\t\t\treturn [];\n\n\t\t// split out any detected contractions for each term that become required suffixes\n\t\tlet contrs = Array(parts.length).fill('');\n\t\tparts = parts.map((p, pi) => p.replace(contrsRe, m => {\n\t\t\tcontrs[pi] = m;\n\t\t\treturn '';\n\t\t}));\n\n\t\t// array of regexp tpls for each term\n\t\tlet reTpl;\n\n\t\t// allows single mutations within each term\n\t\tif (intraMode == 1) {\n\t\t\treTpl = parts.map((p, pi) => {\n\t\t\t\tif (p[0] === '\"')\n\t\t\t\t\treturn escapeRegExp(p.slice(1, -1));\n\n\t\t\t\tlet reTpl = '';\n\n\t\t\t\t// split into numeric and alpha parts, so numbers are only matched as following punct or alpha boundaries, without swaps or insertions\n\t\t\t\tfor (let m of p.matchAll(NUM_OR_ALPHA_RE)) {\n\t\t\t\t\tlet p = m[0];\n\n\t\t\t\t\tlet {\n\t\t\t\t\t\tintraSlice,\n\t\t\t\t\t\tintraIns,\n\t\t\t\t\t\tintraSub,\n\t\t\t\t\t\tintraTrn,\n\t\t\t\t\t\tintraDel,\n\t\t\t\t\t} = intraRules(p);\n\n\t\t\t\t\tif (intraIns + intraSub + intraTrn + intraDel == 0)\n\t\t\t\t\t\treTpl += p + contrs[pi];\n\t\t\t\t\telse {\n\t\t\t\t\t\tlet [lftIdx, rgtIdx] = intraSlice;\n\t\t\t\t\t\tlet lftChar = p.slice(0, lftIdx); // prefix\n\t\t\t\t\t\tlet rgtChar = p.slice(rgtIdx); // suffix\n\n\t\t\t\t\t\tlet chars = p.slice(lftIdx, rgtIdx);\n\n\t\t\t\t\t\t// neg lookahead to prefer matching 'Test' instead of 'tTest' in ManifestTest or fittest\n\t\t\t\t\t\t// but skip when search term contains leading repetition (aardvark, aaa)\n\t\t\t\t\t\tif (intraIns == 1 && lftChar.length == 1 && lftChar != chars[0])\n\t\t\t\t\t\t\tlftChar += '(?!' + lftChar + ')';\n\n\t\t\t\t\t\tlet numChars = chars.length;\n\n\t\t\t\t\t\tlet variants = [p];\n\n\t\t\t\t\t\t// variants with single char substitutions\n\t\t\t\t\t\tif (intraSub) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + intraChars + chars.slice(i + 1) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single transpositions\n\t\t\t\t\t\tif (intraTrn) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars - 1; i++) {\n\t\t\t\t\t\t\t\tif (chars[i] != chars[i+1])\n\t\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + chars[i+1] + chars[i] + chars.slice(i + 2) + rgtChar);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single char omissions\n\t\t\t\t\t\tif (intraDel) {\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i + 1) + '?' + chars.slice(i + 1) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// variants with single char insertions\n\t\t\t\t\t\tif (intraIns) {\n\t\t\t\t\t\t\tlet intraInsTpl = lazyRepeat(intraChars, 1);\n\n\t\t\t\t\t\t\tfor (let i = 0; i < numChars; i++)\n\t\t\t\t\t\t\t\tvariants.push(lftChar + chars.slice(0, i) + intraInsTpl + chars.slice(i) + rgtChar);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treTpl += '(?:' + variants.join('|') + ')' + contrs[pi];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t//\tconsole.log(reTpl);\n\n\t\t\t\treturn reTpl;\n\t\t\t});\n\t\t}\n\t\telse {\n\t\t\tlet intraInsTpl = lazyRepeat(intraChars, intraIns);\n\n\t\t\t// capture at char level\n\t\t\tif (capt == 2 && intraIns > 0) {\n\t\t\t\t// sadly, we also have to capture the inter-term junk via parenth-wrapping .*?\n\t\t\t\t// to accum other capture groups' indices for \\b boosting during scoring\n\t\t\t\tintraInsTpl = ')(' + intraInsTpl + ')(';\n\t\t\t}\n\n\t\t\treTpl = parts.map((p, pi) => p[0] === '\"' ? escapeRegExp(p.slice(1, -1)) : p.split('').map((c, i, chars) => {\n\t\t\t\t// neg lookahead to prefer matching 'Test' instead of 'tTest' in ManifestTest or fittest\n\t\t\t\t// but skip when search term contains leading repetition (aardvark, aaa)\n\t\t\t\tif (intraIns == 1 && i == 0 && chars.length > 1 && c != chars[i+1])\n\t\t\t\t\tc += '(?!' + c + ')';\n\n\t\t\t\treturn c;\n\t\t\t}).join(intraInsTpl) + contrs[pi]);\n\t\t}\n\n\t//\tconsole.log(reTpl);\n\n\t\t// this only helps to reduce initial matches early when they can be detected\n\t\t// TODO: might want a mode 3 that excludes _\n\t\tlet preTpl = interLft == 2 ? mode2Tpl : '';\n\t\tlet sufTpl = interRgt == 2 ? mode2Tpl : '';\n\n\t\tlet interCharsTpl = sufTpl + lazyRepeat(opts.interChars, opts.interIns) + preTpl;\n\n\t\t// capture at word level\n\t\tif (capt > 0) {\n\t\t\tif (interOR) {\n\t\t\t\t// this is basically for doing .matchAll() occurence counting and highlighting without needing permuted ooo needles\n\t\t\t\treTpl = preTpl + '(' + reTpl.join(')' + sufTpl + '|' + preTpl + '(') + ')' + sufTpl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// sadly, we also have to capture the inter-term junk via parenth-wrapping .*?\n\t\t\t\t// to accum other capture groups' indices for \\b boosting during scoring\n\t\t\t\treTpl = '(' + reTpl.join(')(' + interCharsTpl + ')(') + ')';\n\t\t\t\treTpl = '(.??' + preTpl + ')' + reTpl + '(' + sufTpl + '.*)'; // nit: trailing capture here assumes interIns = Inf\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\treTpl = reTpl.join(interCharsTpl);\n\t\t\treTpl = preTpl + reTpl + sufTpl;\n\t\t}\n\n\t//\tconsole.log(reTpl);\n\n\t\treturn [new RegExp(reTpl, 'i' + uFlag), parts, contrs];\n\t};\n\n\tconst filter = (haystack, needle, idxs) => {\n\n\t\tlet [query] = prepQuery(needle);\n\n\t\tif (query == null)\n\t\t\treturn null;\n\n\t\tlet out = [];\n\n\t\tif (idxs != null) {\n\t\t\tfor (let i = 0; i < idxs.length; i++) {\n\t\t\t\tlet idx = idxs[i];\n\t\t\t\tquery.test(haystack[idx]) && out.push(idx);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (let i = 0; i < haystack.length; i++)\n\t\t\t\tquery.test(haystack[i]) && out.push(i);\n\t\t}\n\n\t\treturn out;\n\t};\n\n\tlet withIntraBound = !!_intraBound;\n\n\tlet interBound = new RegExp(_interSplit, uFlag);\n\tlet intraBound = new RegExp(_intraBound, uFlag);\n\n\tconst info = (idxs, haystack, needle) => {\n\n\t\tlet [query, parts, contrs] = prepQuery(needle, 1);\n\t\tlet [queryR] = prepQuery(needle, 2);\n\t\tlet partsLen = parts.length;\n\n\t\tlet len = idxs.length;\n\n\t\tlet field = Array(len).fill(0);\n\n\t\tlet info = {\n\t\t\t// idx in haystack\n\t\t\tidx: Array(len),\n\n\t\t\t// start of match\n\t\t\tstart: field.slice(),\n\t\t\t// length of match\n\t\t//\tspan: field.slice(),\n\n\t\t\t// contiguous chars matched\n\t\t\tchars: field.slice(),\n\n\t\t\t// contiguous (no fuzz) and bounded terms (intra=0, lft2/1, rgt2/1)\n\t\t\t// excludes terms that are contiguous but have < 2 bounds (substrings)\n\t\t\tterms: field.slice(),\n\n\t\t\t// cumulative length of unmatched chars (fuzz) within span\n\t\t\tinterIns: field.slice(), // between terms\n\t\t\tintraIns: field.slice(), // within terms\n\n\t\t\t// interLft/interRgt counters\n\t\t\tinterLft2: field.slice(),\n\t\t\tinterRgt2: field.slice(),\n\t\t\tinterLft1: field.slice(),\n\t\t\tinterRgt1: field.slice(),\n\n\t\t\tranges: Array(len),\n\t\t};\n\n\t\t// might discard idxs based on bounds checks\n\t\tlet mayDiscard = interLft == 1 || interRgt == 1;\n\n\t\tlet ii = 0;\n\n\t\tfor (let i = 0; i < idxs.length; i++) {\n\t\t\tlet mhstr = haystack[idxs[i]];\n\n\t\t\t// the matched parts are [full, junk, term, junk, term, junk]\n\t\t\tlet m = mhstr.match(query);\n\n\t\t\t// leading junk\n\t\t\tlet start = m.index + m[1].length;\n\n\t\t\tlet idxAcc = start;\n\t\t//\tlet span = m[0].length;\n\n\t\t\tlet disc = false;\n\t\t\tlet lft2 = 0;\n\t\t\tlet lft1 = 0;\n\t\t\tlet rgt2 = 0;\n\t\t\tlet rgt1 = 0;\n\t\t\tlet chars = 0;\n\t\t\tlet terms = 0;\n\t\t\tlet inter = 0;\n\t\t\tlet intra = 0;\n\n\t\t\tlet refine = [];\n\n\t\t\tfor (let j = 0, k = 2; j < partsLen; j++, k+=2) {\n\t\t\t\tlet group = m[k].toLocaleLowerCase();\n\t\t\t\tlet part = parts[j];\n\t\t\t\tlet term = part[0] == '\"' ? part.slice(1, -1) : part + contrs[j];\n\t\t\t\tlet termLen = term.length;\n\t\t\t\tlet groupLen = group.length;\n\t\t\t\tlet fullMatch = group == term;\n\n\t\t\t\t// this won't handle the case when an exact match exists across the boundary of the current group and the next junk\n\t\t\t\t// e.g. blob,ob when searching for 'bob' but finding the earlier `blob` (with extra insertion)\n\t\t\t\tif (!fullMatch && m[k+1].length >= termLen) {\n\t\t\t\t\t// probe for exact match in inter junk (TODO: maybe even in this matched part?)\n\t\t\t\t\tlet idxOf = m[k+1].toLocaleLowerCase().indexOf(term);\n\n\t\t\t\t\tif (idxOf > -1) {\n\t\t\t\t\t\trefine.push(idxAcc, groupLen, idxOf, termLen);\n\t\t\t\t\t\tidxAcc += refineMatch(m, k, idxOf, termLen);\n\t\t\t\t\t\tgroup = term;\n\t\t\t\t\t\tgroupLen = termLen;\n\t\t\t\t\t\tfullMatch = true;\n\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tstart = idxAcc;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (mayDiscard || fullMatch) {\n\t\t\t\t\t// does group's left and/or right land on \\b\n\t\t\t\t\tlet lftCharIdx = idxAcc - 1;\n\t\t\t\t\tlet rgtCharIdx = idxAcc + groupLen;\n\n\t\t\t\t\tlet isPre = false;\n\t\t\t\t\tlet isSuf = false;\n\n\t\t\t\t\t// prefix info\n\t\t\t\t\tif (lftCharIdx == -1 || interBound.test(mhstr[lftCharIdx])) {\n\t\t\t\t\t\tfullMatch && lft2++;\n\t\t\t\t\t\tisPre = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (interLft == 2) {\n\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (withIntraBound && intraBound.test(mhstr[lftCharIdx] + mhstr[lftCharIdx + 1])) {\n\t\t\t\t\t\t\tfullMatch && lft1++;\n\t\t\t\t\t\t\tisPre = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (interLft == 1) {\n\t\t\t\t\t\t\t\t// regexps are eager, so try to improve the match by probing forward inter junk for exact match at a boundary\n\t\t\t\t\t\t\t\tlet junk = m[k+1];\n\t\t\t\t\t\t\t\tlet junkIdx = idxAcc + groupLen;\n\n\t\t\t\t\t\t\t\tif (junk.length >= termLen) {\n\t\t\t\t\t\t\t\t\tlet idxOf = 0;\n\t\t\t\t\t\t\t\t\tlet found = false;\n\t\t\t\t\t\t\t\t\tlet re = new RegExp(term, 'ig' + uFlag);\n\n\t\t\t\t\t\t\t\t\tlet m2;\n\t\t\t\t\t\t\t\t\twhile (m2 = re.exec(junk)) {\n\t\t\t\t\t\t\t\t\t\tidxOf = m2.index;\n\n\t\t\t\t\t\t\t\t\t\tlet charIdx = junkIdx + idxOf;\n\t\t\t\t\t\t\t\t\t\tlet lftCharIdx = charIdx - 1;\n\n\t\t\t\t\t\t\t\t\t\tif (lftCharIdx == -1 || interBound.test(mhstr[lftCharIdx])) {\n\t\t\t\t\t\t\t\t\t\t\tlft2++;\n\t\t\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\telse if (intraBound.test(mhstr[lftCharIdx] + mhstr[charIdx])) {\n\t\t\t\t\t\t\t\t\t\t\tlft1++;\n\t\t\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tif (found) {\n\t\t\t\t\t\t\t\t\t\tisPre = true;\n\n\t\t\t\t\t\t\t\t\t\t// identical to exact term refinement pass above\n\t\t\t\t\t\t\t\t\t\trefine.push(idxAcc, groupLen, idxOf, termLen);\n\t\t\t\t\t\t\t\t\t\tidxAcc += refineMatch(m, k, idxOf, termLen);\n\t\t\t\t\t\t\t\t\t\tgroup = term;\n\t\t\t\t\t\t\t\t\t\tgroupLen = termLen;\n\t\t\t\t\t\t\t\t\t\tfullMatch = true;\n\n\t\t\t\t\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\t\t\t\t\tstart = idxAcc;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (!isPre) {\n\t\t\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// suffix info\n\t\t\t\t\tif (rgtCharIdx == mhstr.length || interBound.test(mhstr[rgtCharIdx])) {\n\t\t\t\t\t\tfullMatch && rgt2++;\n\t\t\t\t\t\tisSuf = true;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (interRgt == 2) {\n\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (withIntraBound && intraBound.test(mhstr[rgtCharIdx - 1] + mhstr[rgtCharIdx])) {\n\t\t\t\t\t\t\tfullMatch && rgt1++;\n\t\t\t\t\t\t\tisSuf = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tif (interRgt == 1) {\n\t\t\t\t\t\t\t\tdisc = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (fullMatch) {\n\t\t\t\t\t\tchars += termLen;\n\n\t\t\t\t\t\tif (isPre && isSuf)\n\t\t\t\t\t\t\tterms++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (groupLen > termLen)\n\t\t\t\t\tintra += groupLen - termLen; // intraFuzz\n\n\t\t\t\tif (j > 0)\n\t\t\t\t\tinter += m[k-1].length; // interFuzz\n\n\t\t\t\t// TODO: group here is lowercased, which is okay for length cmp, but not more case-sensitive filts\n\t\t\t\tif (!opts.intraFilt(term, group, idxAcc)) {\n\t\t\t\t\tdisc = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (j < partsLen - 1)\n\t\t\t\t\tidxAcc += groupLen + m[k+1].length;\n\t\t\t}\n\n\t\t\tif (!disc) {\n\t\t\t\tinfo.idx[ii] = idxs[i];\n\t\t\t\tinfo.interLft2[ii] = lft2;\n\t\t\t\tinfo.interLft1[ii] = lft1;\n\t\t\t\tinfo.interRgt2[ii] = rgt2;\n\t\t\t\tinfo.interRgt1[ii] = rgt1;\n\t\t\t\tinfo.chars[ii] = chars;\n\t\t\t\tinfo.terms[ii] = terms;\n\t\t\t\tinfo.interIns[ii] = inter;\n\t\t\t\tinfo.intraIns[ii] = intra;\n\n\t\t\t\tinfo.start[ii] = start;\n\t\t\t//\tinfo.span[ii] = span;\n\n\t\t\t\t// ranges\n\t\t\t\tlet m = mhstr.match(queryR);\n\n\t\t\t\tlet idxAcc = m.index + m[1].length;\n\n\t\t\t\tlet refLen = refine.length;\n\t\t\t\tlet ri = refLen > 0 ? 0 : Infinity;\n\t\t\t\tlet lastRi = refLen - 4;\n\n\t\t\t\tfor (let i = 2; i < m.length;) {\n\t\t\t\t\tlet len = m[i].length;\n\n\t\t\t\t\tif (ri <= lastRi && refine[ri] == idxAcc) {\n\t\t\t\t\t\tlet groupLen = refine[ri+1];\n\t\t\t\t\t\tlet idxOf = refine[ri+2];\n\t\t\t\t\t\tlet termLen = refine[ri+3];\n\n\t\t\t\t\t\t// advance to end of original (full) group match that includes intra-junk\n\t\t\t\t\t\tlet j = i;\n\t\t\t\t\t\tlet v = '';\n\t\t\t\t\t\tfor (let _len = 0; _len < groupLen; j++) {\n\t\t\t\t\t\t\tv += m[j];\n\t\t\t\t\t\t\t_len += m[j].length;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tm.splice(i, j - i, v);\n\n\t\t\t\t\t\tidxAcc += refineMatch(m, i, idxOf, termLen);\n\n\t\t\t\t\t\tri += 4;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tidxAcc += len;\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tidxAcc = m.index + m[1].length;\n\n\t\t\t\tlet ranges = info.ranges[ii] = [];\n\t\t\t\tlet from = idxAcc;\n\t\t\t\tlet to = idxAcc;\n\n\t\t\t\tfor (let i = 2; i < m.length; i++) {\n\t\t\t\t\tlet len = m[i].length;\n\n\t\t\t\t\tidxAcc += len;\n\n\t\t\t\t\tif (i % 2 == 0)\n\t\t\t\t\t\tto = idxAcc;\n\t\t\t\t\telse if (len > 0) {\n\t\t\t\t\t\tranges.push(from, to);\n\t\t\t\t\t\tfrom = to = idxAcc;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (to > from)\n\t\t\t\t\tranges.push(from, to);\n\n\t\t\t\tii++;\n\t\t\t}\n\t\t}\n\n\t\t// trim arrays\n\t\tif (ii < idxs.length) {\n\t\t\tfor (let k in info)\n\t\t\t\tinfo[k] = info[k].slice(0, ii);\n\t\t}\n\n\t\treturn info;\n\t};\n\n\tconst refineMatch = (m, k, idxInNext, termLen) => {\n\t\t// shift the current group into the prior junk\n\t\tlet prepend = m[k] + m[k+1].slice(0, idxInNext);\n\t\tm[k-1] += prepend;\n\t\tm[k] = m[k+1].slice(idxInNext, idxInNext + termLen);\n\t\tm[k+1] = m[k+1].slice(idxInNext + termLen);\n\t\treturn prepend.length;\n\t};\n\n\tconst OOO_TERMS_LIMIT = 5;\n\n\t// returns [idxs, info, order]\n\tconst _search = (haystack, needle, outOfOrder, infoThresh = 1e3, preFiltered) => {\n\t\toutOfOrder = !outOfOrder ? 0 : outOfOrder === true ? OOO_TERMS_LIMIT : outOfOrder;\n\n\t\tlet needles = null;\n\t\tlet matches = null;\n\n\t\tlet negs = [];\n\n\t\tneedle = needle.replace(NEGS_RE, m => {\n\t\t\tlet neg = m.trim().slice(1);\n\n\t\t\tif (neg[0] === '\"')\n\t\t\t\tneg = escapeRegExp(neg.slice(1,-1));\n\n\t\t\tnegs.push(neg);\n\t\t\treturn '';\n\t\t});\n\n\t\tlet terms = split(needle);\n\n\t\tlet negsRe;\n\n\t\tif (negs.length > 0) {\n\t\t\tnegsRe = new RegExp(negs.join('|'), 'i' + uFlag);\n\n\t\t\tif (terms.length == 0) {\n\t\t\t\tlet idxs = [];\n\n\t\t\t\tfor (let i = 0; i < haystack.length; i++) {\n\t\t\t\t\tif (!negsRe.test(haystack[i]))\n\t\t\t\t\t\tidxs.push(i);\n\t\t\t\t}\n\n\t\t\t\treturn [idxs, null, null];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// abort search (needle is empty after pre-processing, e.g. no alpha-numeric chars)\n\t\t\tif (terms.length == 0)\n\t\t\t\treturn [null, null, null];\n\t\t}\n\n\t//\tconsole.log(negs);\n\t//\tconsole.log(needle);\n\n\t\tif (outOfOrder > 0) {\n\t\t\t// since uFuzzy is an AND-based search, we can iteratively pre-reduce the haystack by searching\n\t\t\t// for each term in isolation before running permutations on what's left.\n\t\t\t// this is a major perf win. e.g. searching \"test man ger pp a\" goes from 570ms -> 14ms\n\t\t\tlet terms = split(needle);\n\n\t\t\tif (terms.length > 1) {\n\t\t\t\t// longest -> shortest\n\t\t\t\tlet terms2 = terms.slice().sort((a, b) => b.length - a.length);\n\n\t\t\t\tfor (let ti = 0; ti < terms2.length; ti++) {\n\t\t\t\t\t// no haystack item contained all terms\n\t\t\t\t\tif (preFiltered?.length == 0)\n\t\t\t\t\t\treturn [[], null, null];\n\n\t\t\t\t\tpreFiltered = filter(haystack, terms2[ti], preFiltered);\n\t\t\t\t}\n\n\t\t\t\t// avoid combinatorial explosion by limiting outOfOrder to 5 terms (120 max searches)\n\t\t\t\t// fall back to just filter() otherwise\n\t\t\t\tif (terms.length > outOfOrder)\n\t\t\t\t\treturn [preFiltered, null, null];\n\n\t\t\t\tneedles = permute(terms).map(perm => perm.join(' '));\n\n\t\t\t\t// filtered matches for each needle excluding same matches for prior needles\n\t\t\t\tmatches = [];\n\n\t\t\t\t// keeps track of already-matched idxs to skip in follow-up permutations\n\t\t\t\tlet matchedIdxs = new Set();\n\n\t\t\t\tfor (let ni = 0; ni < needles.length; ni++) {\n\t\t\t\t\tif (matchedIdxs.size < preFiltered.length) {\n\t\t\t\t\t\t// filter further for this needle, exclude already-matched\n\t\t\t\t\t\tlet preFiltered2 = preFiltered.filter(idx => !matchedIdxs.has(idx));\n\n\t\t\t\t\t\tlet matched = filter(haystack, needles[ni], preFiltered2);\n\n\t\t\t\t\t\tfor (let j = 0; j < matched.length; j++)\n\t\t\t\t\t\t\tmatchedIdxs.add(matched[j]);\n\n\t\t\t\t\t\tmatches.push(matched);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tmatches.push([]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// interOR\n\t//\tconsole.log(prepQuery(needle, 1, null, true));\n\n\t\t// non-ooo or ooo w/single term\n\t\tif (needles == null) {\n\t\t\tneedles = [needle];\n\t\t\tmatches = [preFiltered?.length > 0 ? preFiltered : filter(haystack, needle)];\n\t\t}\n\n\t\tlet retInfo = null;\n\t\tlet retOrder = null;\n\n\t\tif (negs.length > 0)\n\t\t\tmatches = matches.map(idxs => idxs.filter(idx => !negsRe.test(haystack[idx])));\n\n\t\tlet matchCount = matches.reduce((acc, idxs) => acc + idxs.length, 0);\n\n\t\t// rank, sort, concat\n\t\tif (matchCount <= infoThresh) {\n\t\t\tretInfo = {};\n\t\t\tretOrder = [];\n\n\t\t\tfor (let ni = 0; ni < matches.length; ni++) {\n\t\t\t\tlet idxs = matches[ni];\n\n\t\t\t\tif (idxs == null || idxs.length == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tlet needle = needles[ni];\n\t\t\t\tlet _info = info(idxs, haystack, needle);\n\t\t\t\tlet order = opts.sort(_info, haystack, needle);\n\n\t\t\t\t// offset idxs for concat'ing infos\n\t\t\t\tif (ni > 0) {\n\t\t\t\t\tfor (let i = 0; i < order.length; i++)\n\t\t\t\t\t\torder[i] += retOrder.length;\n\t\t\t\t}\n\n\t\t\t\tfor (let k in _info)\n\t\t\t\t\tretInfo[k] = (retInfo[k] ?? []).concat(_info[k]);\n\n\t\t\t\tretOrder = retOrder.concat(order);\n\t\t\t}\n\t\t}\n\n\t\treturn [\n\t\t\t[].concat(...matches),\n\t\t\tretInfo,\n\t\t\tretOrder,\n\t\t];\n\t};\n\n\treturn {\n\t\tsearch: (...args) => {\n\t\t\tlet out = _search(...args);\n\t\t\treturn out;\n\t\t},\n\t\tsplit,\n\t\tfilter,\n\t\tinfo,\n\t\tsort: opts.sort,\n\t};\n}\n\nconst latinize = (() => {\n\tlet accents = {\n\t\tA: 'ÁÀÃÂÄĄ',\n\t\ta: 'áàãâäą',\n\t\tE: 'ÉÈÊËĖ',\n\t\te: 'éèêëę',\n\t\tI: 'ÍÌÎÏĮ',\n\t\ti: 'íìîïį',\n\t\tO: 'ÓÒÔÕÖ',\n\t\to: 'óòôõö',\n\t\tU: 'ÚÙÛÜŪŲ',\n\t\tu: 'úùûüūų',\n\t\tC: 'ÇČĆ',\n\t\tc: 'çčć',\n\t\tL: 'Ł',\n\t\tl: 'ł',\n\t\tN: 'ÑŃ',\n\t\tn: 'ñń',\n\t\tS: 'ŠŚ',\n\t\ts: 'šś',\n\t\tZ: 'ŻŹ',\n\t\tz: 'żź'\n\t};\n\n\tlet accentsMap = new Map();\n\tlet accentsTpl = '';\n\n\tfor (let r in accents) {\n\t\taccents[r].split('').forEach(a => {\n\t\t\taccentsTpl += a;\n\t\t\taccentsMap.set(a, r);\n\t\t});\n\t}\n\n\tlet accentsRe = new RegExp(`[${accentsTpl}]`, 'g');\n\tlet replacer = m => accentsMap.get(m);\n\n\treturn strings => {\n\t\tif (typeof strings == 'string')\n\t\t\treturn strings.replace(accentsRe, replacer);\n\n\t\tlet out = Array(strings.length);\n\t\tfor (let i = 0; i < strings.length; i++)\n\t\t\tout[i] = strings[i].replace(accentsRe, replacer);\n\t\treturn out;\n\t};\n})();\n\n// https://stackoverflow.com/questions/9960908/permutations-in-javascript/37580979#37580979\nfunction permute(arr) {\n\tarr = arr.slice();\n\n\tlet length = arr.length,\n\t\tresult = [arr.slice()],\n\t\tc = new Array(length).fill(0),\n\t\ti = 1, k, p;\n\n\twhile (i < length) {\n\t\tif (c[i] < i) {\n\t\t\tk = i % 2 && c[i];\n\t\t\tp = arr[i];\n\t\t\tarr[i] = arr[k];\n\t\t\tarr[k] = p;\n\t\t\t++c[i];\n\t\t\ti = 1;\n\t\t\tresult.push(arr.slice());\n\t\t} else {\n\t\t\tc[i] = 0;\n\t\t\t++i;\n\t\t}\n\t}\n\n\treturn result;\n}\n\nconst _mark = (part, matched) => matched ? `
${part}` : part;\nconst _append = (acc, part) => acc + part;\n\nfunction highlight(str, ranges, mark = _mark, accum = '', append = _append) {\n\taccum = append(accum, mark(str.substring(0, ranges[0]), false)) ?? accum;\n\n\tfor (let i = 0; i < ranges.length; i+=2) {\n\t\tlet fr = ranges[i];\n\t\tlet to = ranges[i+1];\n\n\t\taccum = append(accum, mark(str.substring(fr, to), true)) ?? accum;\n\n\t\tif (i < ranges.length - 3)\n\t\t\taccum = append(accum, mark(str.substring(ranges[i+1], ranges[i+2]), false)) ?? accum;\n\t}\n\n\taccum = append(accum, mark(str.substring(ranges[ranges.length - 1]), false)) ?? accum;\n\n\treturn accum;\n}\n\nuFuzzy.latinize = latinize;\nuFuzzy.permute = arr => {\n\tlet idxs = permute([...Array(arr.length).keys()]).sort((a,b) => {\n\t\tfor (let i = 0; i < a.length; i++) {\n\t\t\tif (a[i] != b[i])\n\t\t\t\treturn a[i] - b[i];\n\t\t}\n\t\treturn 0;\n\t});\n\n\treturn idxs.map(pi => pi.map(i => arr[i]));\n};\nuFuzzy.highlight = highlight;\n\nexport { uFuzzy as default };\n","function r(e){var o,t,f=\"\";if(\"string\"==typeof e||\"number\"==typeof e)f+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var n=e.length;for(o=0;o
0) {\r\n if (!isEqual(a[index], b[index], index, index, a, b, meta)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n /**\r\n * Whether the arrays are equal in value, including circular references.\r\n */\r\n var areArraysEqualCircular = createIsCircular(areArraysEqual);\n\n /**\r\n * Whether the dates passed are equal in value.\r\n *\r\n * @NOTE\r\n * This is a standalone function instead of done inline in the comparator\r\n * to allow for overrides.\r\n */\r\n function areDatesEqual(a, b) {\r\n return sameValueZeroEqual(a.valueOf(), b.valueOf());\r\n }\n\n /**\r\n * Whether the `Map`s are equal in value.\r\n */\r\n function areMapsEqual(a, b, isEqual, meta) {\r\n var isValueEqual = a.size === b.size;\r\n if (!isValueEqual) {\r\n return false;\r\n }\r\n if (!a.size) {\r\n return true;\r\n }\r\n // The use of `forEach()` is to avoid the transpilation cost of `for...of` comparisons, and\r\n // the inability to control the performance of the resulting code. It also avoids excessive\r\n // iteration compared to doing comparisons of `keys()` and `values()`. As a result, though,\r\n // we cannot short-circuit the iterations; bookkeeping must be done to short-circuit the\r\n // equality checks themselves.\r\n var matchedIndices = {};\r\n var indexA = 0;\r\n a.forEach(function (aValue, aKey) {\r\n if (!isValueEqual) {\r\n return;\r\n }\r\n var hasMatch = false;\r\n var matchIndexB = 0;\r\n b.forEach(function (bValue, bKey) {\r\n if (!hasMatch &&\r\n !matchedIndices[matchIndexB] &&\r\n (hasMatch =\r\n isEqual(aKey, bKey, indexA, matchIndexB, a, b, meta) &&\r\n isEqual(aValue, bValue, aKey, bKey, a, b, meta))) {\r\n matchedIndices[matchIndexB] = true;\r\n }\r\n matchIndexB++;\r\n });\r\n indexA++;\r\n isValueEqual = hasMatch;\r\n });\r\n return isValueEqual;\r\n }\r\n /**\r\n * Whether the `Map`s are equal in value, including circular references.\r\n */\r\n var areMapsEqualCircular = createIsCircular(areMapsEqual);\n\n var OWNER = '_owner';\r\n var hasOwnProperty = Object.prototype.hasOwnProperty;\r\n /**\r\n * Whether the objects are equal in value.\r\n */\r\n function areObjectsEqual(a, b, isEqual, meta) {\r\n var keysA = Object.keys(a);\r\n var index = keysA.length;\r\n if (Object.keys(b).length !== index) {\r\n return false;\r\n }\r\n var key;\r\n // Decrementing `while` showed faster results than either incrementing or\r\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\r\n // methods like `some` / `every` were not used to avoid incurring the garbage\r\n // cost of anonymous callbacks.\r\n while (index-- > 0) {\r\n key = keysA[index];\r\n if (key === OWNER) {\r\n var reactElementA = !!a.$$typeof;\r\n var reactElementB = !!b.$$typeof;\r\n if ((reactElementA || reactElementB) && reactElementA !== reactElementB) {\r\n return false;\r\n }\r\n }\r\n if (!hasOwnProperty.call(b, key) ||\r\n !isEqual(a[key], b[key], key, key, a, b, meta)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n /**\r\n * Whether the objects are equal in value, including circular references.\r\n */\r\n var areObjectsEqualCircular = createIsCircular(areObjectsEqual);\n\n /**\r\n * Whether the regexps passed are equal in value.\r\n *\r\n * @NOTE\r\n * This is a standalone function instead of done inline in the comparator\r\n * to allow for overrides. An example of this would be supporting a\r\n * pre-ES2015 environment where the `flags` property is not available.\r\n */\r\n function areRegExpsEqual(a, b) {\r\n return a.source === b.source && a.flags === b.flags;\r\n }\n\n /**\r\n * Whether the `Set`s are equal in value.\r\n */\r\n function areSetsEqual(a, b, isEqual, meta) {\r\n var isValueEqual = a.size === b.size;\r\n if (!isValueEqual) {\r\n return false;\r\n }\r\n if (!a.size) {\r\n return true;\r\n }\r\n // The use of `forEach()` is to avoid the transpilation cost of `for...of` comparisons, and\r\n // the inability to control the performance of the resulting code. It also avoids excessive\r\n // iteration compared to doing comparisons of `keys()` and `values()`. As a result, though,\r\n // we cannot short-circuit the iterations; bookkeeping must be done to short-circuit the\r\n // equality checks themselves.\r\n var matchedIndices = {};\r\n a.forEach(function (aValue, aKey) {\r\n if (!isValueEqual) {\r\n return;\r\n }\r\n var hasMatch = false;\r\n var matchIndex = 0;\r\n b.forEach(function (bValue, bKey) {\r\n if (!hasMatch &&\r\n !matchedIndices[matchIndex] &&\r\n (hasMatch = isEqual(aValue, bValue, aKey, bKey, a, b, meta))) {\r\n matchedIndices[matchIndex] = true;\r\n }\r\n matchIndex++;\r\n });\r\n isValueEqual = hasMatch;\r\n });\r\n return isValueEqual;\r\n }\r\n /**\r\n * Whether the `Set`s are equal in value, including circular references.\r\n */\r\n var areSetsEqualCircular = createIsCircular(areSetsEqual);\n\n var DEFAULT_CONFIG = Object.freeze({\r\n areArraysEqual: areArraysEqual,\r\n areDatesEqual: areDatesEqual,\r\n areMapsEqual: areMapsEqual,\r\n areObjectsEqual: areObjectsEqual,\r\n areRegExpsEqual: areRegExpsEqual,\r\n areSetsEqual: areSetsEqual,\r\n createIsNestedEqual: createDefaultIsNestedEqual,\r\n });\r\n var DEFAULT_CIRCULAR_CONFIG = Object.freeze({\r\n areArraysEqual: areArraysEqualCircular,\r\n areDatesEqual: areDatesEqual,\r\n areMapsEqual: areMapsEqualCircular,\r\n areObjectsEqual: areObjectsEqualCircular,\r\n areRegExpsEqual: areRegExpsEqual,\r\n areSetsEqual: areSetsEqualCircular,\r\n createIsNestedEqual: createDefaultIsNestedEqual,\r\n });\r\n var isDeepEqual = createComparator(DEFAULT_CONFIG);\r\n /**\r\n * Whether the items passed are deeply-equal in value.\r\n */\r\n function deepEqual(a, b) {\r\n return isDeepEqual(a, b, undefined);\r\n }\r\n var isShallowEqual = createComparator(merge(DEFAULT_CONFIG, { createIsNestedEqual: function () { return sameValueZeroEqual; } }));\r\n /**\r\n * Whether the items passed are shallowly-equal in value.\r\n */\r\n function shallowEqual(a, b) {\r\n return isShallowEqual(a, b, undefined);\r\n }\r\n var isCircularDeepEqual = createComparator(DEFAULT_CIRCULAR_CONFIG);\r\n /**\r\n * Whether the items passed are deeply-equal in value, including circular references.\r\n */\r\n function circularDeepEqual(a, b) {\r\n return isCircularDeepEqual(a, b, new WeakMap());\r\n }\r\n var isCircularShallowEqual = createComparator(merge(DEFAULT_CIRCULAR_CONFIG, {\r\n createIsNestedEqual: function () { return sameValueZeroEqual; },\r\n }));\r\n /**\r\n * Whether the items passed are shallowly-equal in value, including circular references.\r\n */\r\n function circularShallowEqual(a, b) {\r\n return isCircularShallowEqual(a, b, new WeakMap());\r\n }\r\n /**\r\n * Create a custom equality comparison method.\r\n *\r\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\r\n * where the standard methods are not performant enough, but can also be used to provide\r\n * support for legacy environments that do not support expected features like\r\n * `RegExp.prototype.flags` out of the box.\r\n */\r\n function createCustomEqual(getComparatorOptions) {\r\n return createComparator(merge(DEFAULT_CONFIG, getComparatorOptions(DEFAULT_CONFIG)));\r\n }\r\n /**\r\n * Create a custom equality comparison method that handles circular references. This is very\r\n * similar to `createCustomEqual`, with the only difference being that `meta` expects to be\r\n * populated with a `WeakMap`-like contract.\r\n *\r\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\r\n * where the standard methods are not performant enough, but can also be used to provide\r\n * support for legacy environments that do not support expected features like\r\n * `WeakMap` out of the box.\r\n */\r\n function createCustomCircularEqual(getComparatorOptions) {\r\n var comparator = createComparator(merge(DEFAULT_CIRCULAR_CONFIG, getComparatorOptions(DEFAULT_CIRCULAR_CONFIG)));\r\n return (function (a, b, meta) {\r\n if (meta === void 0) { meta = new WeakMap(); }\r\n return comparator(a, b, meta);\r\n });\r\n }\n\n exports.circularDeepEqual = circularDeepEqual;\n exports.circularShallowEqual = circularShallowEqual;\n exports.createCustomCircularEqual = createCustomCircularEqual;\n exports.createCustomEqual = createCustomEqual;\n exports.deepEqual = deepEqual;\n exports.sameValueZeroEqual = sameValueZeroEqual;\n exports.shallowEqual = shallowEqual;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n}));\n//# sourceMappingURL=fast-equals.js.map\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var root = require('./_root');\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nmodule.exports = now;\n","var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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\nvar ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');\n\nfunction emptyFunction() {}\nfunction emptyFunctionWithReset() {}\nemptyFunctionWithReset.resetWarningCache = emptyFunction;\n\nmodule.exports = function() {\n function shim(props, propName, componentName, location, propFullName, secret) {\n if (secret === ReactPropTypesSecret) {\n // It is still safe when called from React.\n return;\n }\n var err = new Error(\n 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +\n 'Use PropTypes.checkPropTypes() to call them. ' +\n 'Read more at http://fb.me/use-check-prop-types'\n );\n err.name = 'Invariant Violation';\n throw err;\n };\n shim.isRequired = shim;\n function getShim() {\n return shim;\n };\n // Important!\n // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.\n var ReactPropTypes = {\n array: shim,\n bigint: shim,\n bool: shim,\n func: shim,\n number: shim,\n object: shim,\n string: shim,\n symbol: shim,\n\n any: shim,\n arrayOf: getShim,\n element: shim,\n elementType: shim,\n instanceOf: getShim,\n node: shim,\n objectOf: getShim,\n oneOf: getShim,\n oneOfType: getShim,\n shape: getShim,\n exact: getShim,\n\n checkPropTypes: emptyFunctionWithReset,\n resetWarningCache: emptyFunction\n };\n\n ReactPropTypes.PropTypes = ReactPropTypes;\n\n return ReactPropTypes;\n};\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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\nif (process.env.NODE_ENV !== 'production') {\n var ReactIs = require('react-is');\n\n // By explicitly using `prop-types` you are opting into new development behavior.\n // http://fb.me/prop-types-in-prod\n var throwOnDirectAccess = true;\n module.exports = require('./factoryWithTypeCheckers')(ReactIs.isElement, throwOnDirectAccess);\n} else {\n // By explicitly using `prop-types` you are opting into new production behavior.\n // http://fb.me/prop-types-in-prod\n module.exports = require('./factoryWithThrowingShims')();\n}\n","/**\n * Copyright (c) 2013-present, Facebook, Inc.\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\nvar ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';\n\nmodule.exports = ReactPropTypesSecret;\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"DraggableCore\", {\n enumerable: true,\n get: function () {\n return _DraggableCore.default;\n }\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _reactDom = _interopRequireDefault(require(\"react-dom\"));\nvar _clsx = _interopRequireDefault(require(\"clsx\"));\nvar _domFns = require(\"./utils/domFns\");\nvar _positionFns = require(\"./utils/positionFns\");\nvar _shims = require(\"./utils/shims\");\nvar _DraggableCore = _interopRequireDefault(require(\"./DraggableCore\"));\nvar _log = _interopRequireDefault(require(\"./utils/log\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); } /*:: import type {ControlPosition, PositionOffsetControlPosition, DraggableCoreProps, DraggableCoreDefaultProps} from './DraggableCore';*/\n/*:: import type {Bounds, DraggableEventHandler} from './utils/types';*/\n/*:: import type {Element as ReactElement} from 'react';*/\n/*:: type DraggableState = {\n dragging: boolean,\n dragged: boolean,\n x: number, y: number,\n slackX: number, slackY: number,\n isElementSVG: boolean,\n prevPropsPosition: ?ControlPosition,\n};*/\n/*:: export type DraggableDefaultProps = {\n ...DraggableCoreDefaultProps,\n axis: 'both' | 'x' | 'y' | 'none',\n bounds: Bounds | string | false,\n defaultClassName: string,\n defaultClassNameDragging: string,\n defaultClassNameDragged: string,\n defaultPosition: ControlPosition,\n scale: number,\n};*/\n/*:: export type DraggableProps = {\n ...DraggableCoreProps,\n ...DraggableDefaultProps,\n positionOffset: PositionOffsetControlPosition,\n position: ControlPosition,\n};*/\n//\n// Define \n//\nclass Draggable extends React.Component /*:: */{\n // React 16.3+\n // Arity (props, state)\n static getDerivedStateFromProps(_ref /*:: */, _ref2 /*:: */) /*: ?Partial*/{\n let {\n position\n } /*: DraggableProps*/ = _ref /*: DraggableProps*/;\n let {\n prevPropsPosition\n } /*: DraggableState*/ = _ref2 /*: DraggableState*/;\n // Set x/y if a new position is provided in props that is different than the previous.\n if (position && (!prevPropsPosition || position.x !== prevPropsPosition.x || position.y !== prevPropsPosition.y)) {\n (0, _log.default)('Draggable: getDerivedStateFromProps %j', {\n position,\n prevPropsPosition\n });\n return {\n x: position.x,\n y: position.y,\n prevPropsPosition: {\n ...position\n }\n };\n }\n return null;\n }\n constructor(props /*: DraggableProps*/) {\n super(props);\n _defineProperty(this, \"onDragStart\", (e, coreData) => {\n (0, _log.default)('Draggable: onDragStart: %j', coreData);\n\n // Short-circuit if user's callback killed it.\n const shouldStart = this.props.onStart(e, (0, _positionFns.createDraggableData)(this, coreData));\n // Kills start event on core as well, so move handlers are never bound.\n if (shouldStart === false) return false;\n this.setState({\n dragging: true,\n dragged: true\n });\n });\n _defineProperty(this, \"onDrag\", (e, coreData) => {\n if (!this.state.dragging) return false;\n (0, _log.default)('Draggable: onDrag: %j', coreData);\n const uiData = (0, _positionFns.createDraggableData)(this, coreData);\n const newState = {\n x: uiData.x,\n y: uiData.y,\n slackX: 0,\n slackY: 0\n };\n\n // Keep within bounds.\n if (this.props.bounds) {\n // Save original x and y.\n const {\n x,\n y\n } = newState;\n\n // Add slack to the values used to calculate bound position. This will ensure that if\n // we start removing slack, the element won't react to it right away until it's been\n // completely removed.\n newState.x += this.state.slackX;\n newState.y += this.state.slackY;\n\n // Get bound position. This will ceil/floor the x and y within the boundaries.\n const [newStateX, newStateY] = (0, _positionFns.getBoundPosition)(this, newState.x, newState.y);\n newState.x = newStateX;\n newState.y = newStateY;\n\n // Recalculate slack by noting how much was shaved by the boundPosition handler.\n newState.slackX = this.state.slackX + (x - newState.x);\n newState.slackY = this.state.slackY + (y - newState.y);\n\n // Update the event we fire to reflect what really happened after bounds took effect.\n uiData.x = newState.x;\n uiData.y = newState.y;\n uiData.deltaX = newState.x - this.state.x;\n uiData.deltaY = newState.y - this.state.y;\n }\n\n // Short-circuit if user's callback killed it.\n const shouldUpdate = this.props.onDrag(e, uiData);\n if (shouldUpdate === false) return false;\n this.setState(newState);\n });\n _defineProperty(this, \"onDragStop\", (e, coreData) => {\n if (!this.state.dragging) return false;\n\n // Short-circuit if user's callback killed it.\n const shouldContinue = this.props.onStop(e, (0, _positionFns.createDraggableData)(this, coreData));\n if (shouldContinue === false) return false;\n (0, _log.default)('Draggable: onDragStop: %j', coreData);\n const newState /*: Partial*/ = {\n dragging: false,\n slackX: 0,\n slackY: 0\n };\n\n // If this is a controlled component, the result of this operation will be to\n // revert back to the old position. We expect a handler on `onDragStop`, at the least.\n const controlled = Boolean(this.props.position);\n if (controlled) {\n const {\n x,\n y\n } = this.props.position;\n newState.x = x;\n newState.y = y;\n }\n this.setState(newState);\n });\n this.state = {\n // Whether or not we are currently dragging.\n dragging: false,\n // Whether or not we have been dragged before.\n dragged: false,\n // Current transform x and y.\n x: props.position ? props.position.x : props.defaultPosition.x,\n y: props.position ? props.position.y : props.defaultPosition.y,\n prevPropsPosition: {\n ...props.position\n },\n // Used for compensating for out-of-bounds drags\n slackX: 0,\n slackY: 0,\n // Can only determine if SVG after mounting\n isElementSVG: false\n };\n if (props.position && !(props.onDrag || props.onStop)) {\n // eslint-disable-next-line no-console\n console.warn('A `position` was applied to this , without drag handlers. This will make this ' + 'component effectively undraggable. Please attach `onDrag` or `onStop` handlers so you can adjust the ' + '`position` of this element.');\n }\n }\n componentDidMount() {\n // Check to see if the element passed is an instanceof SVGElement\n if (typeof window.SVGElement !== 'undefined' && this.findDOMNode() instanceof window.SVGElement) {\n this.setState({\n isElementSVG: true\n });\n }\n }\n componentWillUnmount() {\n this.setState({\n dragging: false\n }); // prevents invariant if unmounted while dragging\n }\n\n // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find\n // the underlying DOM node ourselves. See the README for more information.\n findDOMNode() /*: ?HTMLElement*/{\n var _this$props$nodeRef$c, _this$props;\n return (_this$props$nodeRef$c = (_this$props = this.props) === null || _this$props === void 0 || (_this$props = _this$props.nodeRef) === null || _this$props === void 0 ? void 0 : _this$props.current) !== null && _this$props$nodeRef$c !== void 0 ? _this$props$nodeRef$c : _reactDom.default.findDOMNode(this);\n }\n render() /*: ReactElement*/{\n const {\n axis,\n bounds,\n children,\n defaultPosition,\n defaultClassName,\n defaultClassNameDragging,\n defaultClassNameDragged,\n position,\n positionOffset,\n scale,\n ...draggableCoreProps\n } = this.props;\n let style = {};\n let svgTransform = null;\n\n // If this is controlled, we don't want to move it - unless it's dragging.\n const controlled = Boolean(position);\n const draggable = !controlled || this.state.dragging;\n const validPosition = position || defaultPosition;\n const transformOpts = {\n // Set left if horizontal drag is enabled\n x: (0, _positionFns.canDragX)(this) && draggable ? this.state.x : validPosition.x,\n // Set top if vertical drag is enabled\n y: (0, _positionFns.canDragY)(this) && draggable ? this.state.y : validPosition.y\n };\n\n // If this element was SVG, we use the `transform` attribute.\n if (this.state.isElementSVG) {\n svgTransform = (0, _domFns.createSVGTransform)(transformOpts, positionOffset);\n } else {\n // Add a CSS transform to move the element around. This allows us to move the element around\n // without worrying about whether or not it is relatively or absolutely positioned.\n // If the item you are dragging already has a transform set, wrap it in a so \n // has a clean slate.\n style = (0, _domFns.createCSSTransform)(transformOpts, positionOffset);\n }\n\n // Mark with class while dragging\n const className = (0, _clsx.default)(children.props.className || '', defaultClassName, {\n [defaultClassNameDragging]: this.state.dragging,\n [defaultClassNameDragged]: this.state.dragged\n });\n\n // Reuse the child provided\n // This makes it flexible to use whatever element is wanted (div, ul, etc)\n return /*#__PURE__*/React.createElement(_DraggableCore.default, _extends({}, draggableCoreProps, {\n onStart: this.onDragStart,\n onDrag: this.onDrag,\n onStop: this.onDragStop\n }), /*#__PURE__*/React.cloneElement(React.Children.only(children), {\n className: className,\n style: {\n ...children.props.style,\n ...style\n },\n transform: svgTransform\n }));\n }\n}\nexports.default = Draggable;\n_defineProperty(Draggable, \"displayName\", 'Draggable');\n_defineProperty(Draggable, \"propTypes\", {\n // Accepts all props accepts.\n ..._DraggableCore.default.propTypes,\n /**\n * `axis` determines which axis the draggable can move.\n *\n * Note that all callbacks will still return data as normal. This only\n * controls flushing to the DOM.\n *\n * 'both' allows movement horizontally and vertically.\n * 'x' limits movement to horizontal axis.\n * 'y' limits movement to vertical axis.\n * 'none' limits all movement.\n *\n * Defaults to 'both'.\n */\n axis: _propTypes.default.oneOf(['both', 'x', 'y', 'none']),\n /**\n * `bounds` determines the range of movement available to the element.\n * Available values are:\n *\n * 'parent' restricts movement within the Draggable's parent node.\n *\n * Alternatively, pass an object with the following properties, all of which are optional:\n *\n * {left: LEFT_BOUND, right: RIGHT_BOUND, bottom: BOTTOM_BOUND, top: TOP_BOUND}\n *\n * All values are in px.\n *\n * Example:\n *\n * ```jsx\n * let App = React.createClass({\n * render: function () {\n * return (\n * \n * Content
\n * \n * );\n * }\n * });\n * ```\n */\n bounds: _propTypes.default.oneOfType([_propTypes.default.shape({\n left: _propTypes.default.number,\n right: _propTypes.default.number,\n top: _propTypes.default.number,\n bottom: _propTypes.default.number\n }), _propTypes.default.string, _propTypes.default.oneOf([false])]),\n defaultClassName: _propTypes.default.string,\n defaultClassNameDragging: _propTypes.default.string,\n defaultClassNameDragged: _propTypes.default.string,\n /**\n * `defaultPosition` specifies the x and y that the dragged item should start at\n *\n * Example:\n *\n * ```jsx\n * let App = React.createClass({\n * render: function () {\n * return (\n * \n * I start with transformX: 25px and transformY: 25px;
\n * \n * );\n * }\n * });\n * ```\n */\n defaultPosition: _propTypes.default.shape({\n x: _propTypes.default.number,\n y: _propTypes.default.number\n }),\n positionOffset: _propTypes.default.shape({\n x: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string]),\n y: _propTypes.default.oneOfType([_propTypes.default.number, _propTypes.default.string])\n }),\n /**\n * `position`, if present, defines the current position of the element.\n *\n * This is similar to how form elements in React work - if no `position` is supplied, the component\n * is uncontrolled.\n *\n * Example:\n *\n * ```jsx\n * let App = React.createClass({\n * render: function () {\n * return (\n * \n * I start with transformX: 25px and transformY: 25px;
\n * \n * );\n * }\n * });\n * ```\n */\n position: _propTypes.default.shape({\n x: _propTypes.default.number,\n y: _propTypes.default.number\n }),\n /**\n * These properties should be defined on the child, not here.\n */\n className: _shims.dontSetMe,\n style: _shims.dontSetMe,\n transform: _shims.dontSetMe\n});\n_defineProperty(Draggable, \"defaultProps\", {\n ..._DraggableCore.default.defaultProps,\n axis: 'both',\n bounds: false,\n defaultClassName: 'react-draggable',\n defaultClassNameDragging: 'react-draggable-dragging',\n defaultClassNameDragged: 'react-draggable-dragged',\n defaultPosition: {\n x: 0,\n y: 0\n },\n scale: 1\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _reactDom = _interopRequireDefault(require(\"react-dom\"));\nvar _domFns = require(\"./utils/domFns\");\nvar _positionFns = require(\"./utils/positionFns\");\nvar _shims = require(\"./utils/shims\");\nvar _log = _interopRequireDefault(require(\"./utils/log\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*:: import type {EventHandler, MouseTouchEvent} from './utils/types';*/\n/*:: import type {Element as ReactElement} from 'react';*/\n// Simple abstraction for dragging events names.\nconst eventsFor = {\n touch: {\n start: 'touchstart',\n move: 'touchmove',\n stop: 'touchend'\n },\n mouse: {\n start: 'mousedown',\n move: 'mousemove',\n stop: 'mouseup'\n }\n};\n\n// Default to mouse events.\nlet dragEventFor = eventsFor.mouse;\n/*:: export type DraggableData = {\n node: HTMLElement,\n x: number, y: number,\n deltaX: number, deltaY: number,\n lastX: number, lastY: number,\n};*/\n/*:: export type DraggableEventHandler = (e: MouseEvent, data: DraggableData) => void | false;*/\n/*:: export type ControlPosition = {x: number, y: number};*/\n/*:: export type PositionOffsetControlPosition = {x: number|string, y: number|string};*/\n/*:: export type DraggableCoreDefaultProps = {\n allowAnyClick: boolean,\n disabled: boolean,\n enableUserSelectHack: boolean,\n onStart: DraggableEventHandler,\n onDrag: DraggableEventHandler,\n onStop: DraggableEventHandler,\n onMouseDown: (e: MouseEvent) => void,\n scale: number,\n};*/\n/*:: export type DraggableCoreProps = {\n ...DraggableCoreDefaultProps,\n cancel: string,\n children: ReactElement,\n offsetParent: HTMLElement,\n grid: [number, number],\n handle: string,\n nodeRef?: ?React.ElementRef,\n};*/\n//\n// Define .\n//\n// is for advanced usage of . It maintains minimal internal state so it can\n// work well with libraries that require more control over the element.\n//\n\nclass DraggableCore extends React.Component /*:: */{\n constructor() {\n super(...arguments);\n _defineProperty(this, \"dragging\", false);\n // Used while dragging to determine deltas.\n _defineProperty(this, \"lastX\", NaN);\n _defineProperty(this, \"lastY\", NaN);\n _defineProperty(this, \"touchIdentifier\", null);\n _defineProperty(this, \"mounted\", false);\n _defineProperty(this, \"handleDragStart\", e => {\n // Make it possible to attach event handlers on top of this one.\n this.props.onMouseDown(e);\n\n // Only accept left-clicks.\n if (!this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) return false;\n\n // Get nodes. Be sure to grab relative document (could be iframed)\n const thisNode = this.findDOMNode();\n if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) {\n throw new Error(' not mounted on DragStart!');\n }\n const {\n ownerDocument\n } = thisNode;\n\n // Short circuit if handle or cancel prop was provided and selector doesn't match.\n if (this.props.disabled || !(e.target instanceof ownerDocument.defaultView.Node) || this.props.handle && !(0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.handle, thisNode) || this.props.cancel && (0, _domFns.matchesSelectorAndParentsTo)(e.target, this.props.cancel, thisNode)) {\n return;\n }\n\n // Prevent scrolling on mobile devices, like ipad/iphone.\n // Important that this is after handle/cancel.\n if (e.type === 'touchstart') e.preventDefault();\n\n // Set touch identifier in component state if this is a touch event. This allows us to\n // distinguish between individual touches on multitouch screens by identifying which\n // touchpoint was set to this element.\n const touchIdentifier = (0, _domFns.getTouchIdentifier)(e);\n this.touchIdentifier = touchIdentifier;\n\n // Get the current drag point from the event. This is used as the offset.\n const position = (0, _positionFns.getControlPosition)(e, touchIdentifier, this);\n if (position == null) return; // not possible but satisfies flow\n const {\n x,\n y\n } = position;\n\n // Create an event object with all the data parents need to make a decision here.\n const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n (0, _log.default)('DraggableCore: handleDragStart: %j', coreEvent);\n\n // Call event handler. If it returns explicit false, cancel.\n (0, _log.default)('calling', this.props.onStart);\n const shouldUpdate = this.props.onStart(e, coreEvent);\n if (shouldUpdate === false || this.mounted === false) return;\n\n // Add a style to the body to disable user-select. This prevents text from\n // being selected all over the page.\n if (this.props.enableUserSelectHack) (0, _domFns.addUserSelectStyles)(ownerDocument);\n\n // Initiate dragging. Set the current x and y as offsets\n // so we know how much we've moved during the drag. This allows us\n // to drag elements around even if they have been moved, without issue.\n this.dragging = true;\n this.lastX = x;\n this.lastY = y;\n\n // Add events to the document directly so we catch when the user's mouse/touch moves outside of\n // this element. We use different events depending on whether or not we have detected that this\n // is a touch-capable device.\n (0, _domFns.addEvent)(ownerDocument, dragEventFor.move, this.handleDrag);\n (0, _domFns.addEvent)(ownerDocument, dragEventFor.stop, this.handleDragStop);\n });\n _defineProperty(this, \"handleDrag\", e => {\n // Get the current drag point from the event. This is used as the offset.\n const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);\n if (position == null) return;\n let {\n x,\n y\n } = position;\n\n // Snap to grid if prop has been provided\n if (Array.isArray(this.props.grid)) {\n let deltaX = x - this.lastX,\n deltaY = y - this.lastY;\n [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);\n if (!deltaX && !deltaY) return; // skip useless drag\n x = this.lastX + deltaX, y = this.lastY + deltaY;\n }\n const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n (0, _log.default)('DraggableCore: handleDrag: %j', coreEvent);\n\n // Call event handler. If it returns explicit false, trigger end.\n const shouldUpdate = this.props.onDrag(e, coreEvent);\n if (shouldUpdate === false || this.mounted === false) {\n try {\n // $FlowIgnore\n this.handleDragStop(new MouseEvent('mouseup'));\n } catch (err) {\n // Old browsers\n const event = ((document.createEvent('MouseEvents') /*: any*/) /*: MouseTouchEvent*/);\n // I see why this insanity was deprecated\n // $FlowIgnore\n event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n this.handleDragStop(event);\n }\n return;\n }\n this.lastX = x;\n this.lastY = y;\n });\n _defineProperty(this, \"handleDragStop\", e => {\n if (!this.dragging) return;\n const position = (0, _positionFns.getControlPosition)(e, this.touchIdentifier, this);\n if (position == null) return;\n let {\n x,\n y\n } = position;\n\n // Snap to grid if prop has been provided\n if (Array.isArray(this.props.grid)) {\n let deltaX = x - this.lastX || 0;\n let deltaY = y - this.lastY || 0;\n [deltaX, deltaY] = (0, _positionFns.snapToGrid)(this.props.grid, deltaX, deltaY);\n x = this.lastX + deltaX, y = this.lastY + deltaY;\n }\n const coreEvent = (0, _positionFns.createCoreData)(this, x, y);\n\n // Call event handler\n const shouldContinue = this.props.onStop(e, coreEvent);\n if (shouldContinue === false || this.mounted === false) return false;\n const thisNode = this.findDOMNode();\n if (thisNode) {\n // Remove user-select hack\n if (this.props.enableUserSelectHack) (0, _domFns.removeUserSelectStyles)(thisNode.ownerDocument);\n }\n (0, _log.default)('DraggableCore: handleDragStop: %j', coreEvent);\n\n // Reset the el.\n this.dragging = false;\n this.lastX = NaN;\n this.lastY = NaN;\n if (thisNode) {\n // Remove event handlers\n (0, _log.default)('DraggableCore: Removing handlers');\n (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.move, this.handleDrag);\n (0, _domFns.removeEvent)(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop);\n }\n });\n _defineProperty(this, \"onMouseDown\", e => {\n dragEventFor = eventsFor.mouse; // on touchscreen laptops we could switch back to mouse\n\n return this.handleDragStart(e);\n });\n _defineProperty(this, \"onMouseUp\", e => {\n dragEventFor = eventsFor.mouse;\n return this.handleDragStop(e);\n });\n // Same as onMouseDown (start drag), but now consider this a touch device.\n _defineProperty(this, \"onTouchStart\", e => {\n // We're on a touch device now, so change the event handlers\n dragEventFor = eventsFor.touch;\n return this.handleDragStart(e);\n });\n _defineProperty(this, \"onTouchEnd\", e => {\n // We're on a touch device now, so change the event handlers\n dragEventFor = eventsFor.touch;\n return this.handleDragStop(e);\n });\n }\n componentDidMount() {\n this.mounted = true;\n // Touch handlers must be added with {passive: false} to be cancelable.\n // https://developers.google.com/web/updates/2017/01/scrolling-intervention\n const thisNode = this.findDOMNode();\n if (thisNode) {\n (0, _domFns.addEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {\n passive: false\n });\n }\n }\n componentWillUnmount() {\n this.mounted = false;\n // Remove any leftover event handlers. Remove both touch and mouse handlers in case\n // some browser quirk caused a touch event to fire during a mouse move, or vice versa.\n const thisNode = this.findDOMNode();\n if (thisNode) {\n const {\n ownerDocument\n } = thisNode;\n (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.move, this.handleDrag);\n (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.move, this.handleDrag);\n (0, _domFns.removeEvent)(ownerDocument, eventsFor.mouse.stop, this.handleDragStop);\n (0, _domFns.removeEvent)(ownerDocument, eventsFor.touch.stop, this.handleDragStop);\n (0, _domFns.removeEvent)(thisNode, eventsFor.touch.start, this.onTouchStart, {\n passive: false\n });\n if (this.props.enableUserSelectHack) (0, _domFns.removeUserSelectStyles)(ownerDocument);\n }\n }\n\n // React Strict Mode compatibility: if `nodeRef` is passed, we will use it instead of trying to find\n // the underlying DOM node ourselves. See the README for more information.\n findDOMNode() /*: ?HTMLElement*/{\n var _this$props, _this$props2;\n return (_this$props = this.props) !== null && _this$props !== void 0 && _this$props.nodeRef ? (_this$props2 = this.props) === null || _this$props2 === void 0 || (_this$props2 = _this$props2.nodeRef) === null || _this$props2 === void 0 ? void 0 : _this$props2.current : _reactDom.default.findDOMNode(this);\n }\n render() /*: React.Element*/{\n // Reuse the child provided\n // This makes it flexible to use whatever element is wanted (div, ul, etc)\n return /*#__PURE__*/React.cloneElement(React.Children.only(this.props.children), {\n // Note: mouseMove handler is attached to document so it will still function\n // when the user drags quickly and leaves the bounds of the element.\n onMouseDown: this.onMouseDown,\n onMouseUp: this.onMouseUp,\n // onTouchStart is added on `componentDidMount` so they can be added with\n // {passive: false}, which allows it to cancel. See\n // https://developers.google.com/web/updates/2017/01/scrolling-intervention\n onTouchEnd: this.onTouchEnd\n });\n }\n}\nexports.default = DraggableCore;\n_defineProperty(DraggableCore, \"displayName\", 'DraggableCore');\n_defineProperty(DraggableCore, \"propTypes\", {\n /**\n * `allowAnyClick` allows dragging using any mouse button.\n * By default, we only accept the left button.\n *\n * Defaults to `false`.\n */\n allowAnyClick: _propTypes.default.bool,\n children: _propTypes.default.node.isRequired,\n /**\n * `disabled`, if true, stops the from dragging. All handlers,\n * with the exception of `onMouseDown`, will not fire.\n */\n disabled: _propTypes.default.bool,\n /**\n * By default, we add 'user-select:none' attributes to the document body\n * to prevent ugly text selection during drag. If this is causing problems\n * for your app, set this to `false`.\n */\n enableUserSelectHack: _propTypes.default.bool,\n /**\n * `offsetParent`, if set, uses the passed DOM node to compute drag offsets\n * instead of using the parent node.\n */\n offsetParent: function (props /*: DraggableCoreProps*/, propName /*: $Keys*/) {\n if (props[propName] && props[propName].nodeType !== 1) {\n throw new Error('Draggable\\'s offsetParent must be a DOM Node.');\n }\n },\n /**\n * `grid` specifies the x and y that dragging should snap to.\n */\n grid: _propTypes.default.arrayOf(_propTypes.default.number),\n /**\n * `handle` specifies a selector to be used as the handle that initiates drag.\n *\n * Example:\n *\n * ```jsx\n * let App = React.createClass({\n * render: function () {\n * return (\n * \n * \n *
Click me to drag
\n *
This is some other content
\n *
\n * \n * );\n * }\n * });\n * ```\n */\n handle: _propTypes.default.string,\n /**\n * `cancel` specifies a selector to be used to prevent drag initialization.\n *\n * Example:\n *\n * ```jsx\n * let App = React.createClass({\n * render: function () {\n * return(\n * \n * \n *
You can't drag from here
\n *
Dragging here works fine
\n *
\n * \n * );\n * }\n * });\n * ```\n */\n cancel: _propTypes.default.string,\n /* If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.\n * Unfortunately, in order for to work properly, we need raw access\n * to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`\n * as in this example:\n *\n * function MyComponent() {\n * const nodeRef = React.useRef(null);\n * return (\n * \n * Example Target
\n * \n * );\n * }\n *\n * This can be used for arbitrarily nested components, so long as the ref ends up\n * pointing to the actual child DOM node and not a custom component.\n */\n nodeRef: _propTypes.default.object,\n /**\n * Called when dragging starts.\n * If this function returns the boolean false, dragging will be canceled.\n */\n onStart: _propTypes.default.func,\n /**\n * Called while dragging.\n * If this function returns the boolean false, dragging will be canceled.\n */\n onDrag: _propTypes.default.func,\n /**\n * Called when dragging stops.\n * If this function returns the boolean false, the drag will remain active.\n */\n onStop: _propTypes.default.func,\n /**\n * A workaround option which can be passed if onMouseDown needs to be accessed,\n * since it'll always be blocked (as there is internal use of onMouseDown)\n */\n onMouseDown: _propTypes.default.func,\n /**\n * `scale`, if set, applies scaling while dragging an element\n */\n scale: _propTypes.default.number,\n /**\n * These properties should be defined on the child, not here.\n */\n className: _shims.dontSetMe,\n style: _shims.dontSetMe,\n transform: _shims.dontSetMe\n});\n_defineProperty(DraggableCore, \"defaultProps\", {\n allowAnyClick: false,\n // by default only accept left click\n disabled: false,\n enableUserSelectHack: true,\n onStart: function () {},\n onDrag: function () {},\n onStop: function () {},\n onMouseDown: function () {},\n scale: 1\n});","\"use strict\";\n\nconst {\n default: Draggable,\n DraggableCore\n} = require('./Draggable');\n\n// Previous versions of this lib exported as the root export. As to no-// them, or TypeScript, we export *both* as the root and as 'default'.\n// See https://github.com/mzabriskie/react-draggable/pull/254\n// and https://github.com/mzabriskie/react-draggable/issues/266\nmodule.exports = Draggable;\nmodule.exports.default = Draggable;\nmodule.exports.DraggableCore = DraggableCore;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.addClassName = addClassName;\nexports.addEvent = addEvent;\nexports.addUserSelectStyles = addUserSelectStyles;\nexports.createCSSTransform = createCSSTransform;\nexports.createSVGTransform = createSVGTransform;\nexports.getTouch = getTouch;\nexports.getTouchIdentifier = getTouchIdentifier;\nexports.getTranslation = getTranslation;\nexports.innerHeight = innerHeight;\nexports.innerWidth = innerWidth;\nexports.matchesSelector = matchesSelector;\nexports.matchesSelectorAndParentsTo = matchesSelectorAndParentsTo;\nexports.offsetXYFromParent = offsetXYFromParent;\nexports.outerHeight = outerHeight;\nexports.outerWidth = outerWidth;\nexports.removeClassName = removeClassName;\nexports.removeEvent = removeEvent;\nexports.removeUserSelectStyles = removeUserSelectStyles;\nvar _shims = require(\"./shims\");\nvar _getPrefix = _interopRequireWildcard(require(\"./getPrefix\"));\nfunction _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== \"function\") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }\nfunction _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }\n/*:: import type {ControlPosition, PositionOffsetControlPosition, MouseTouchEvent} from './types';*/\nlet matchesSelectorFunc = '';\nfunction matchesSelector(el /*: Node*/, selector /*: string*/) /*: boolean*/{\n if (!matchesSelectorFunc) {\n matchesSelectorFunc = (0, _shims.findInArray)(['matches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'], function (method) {\n // $FlowIgnore: Doesn't think elements are indexable\n return (0, _shims.isFunction)(el[method]);\n });\n }\n\n // Might not be found entirely (not an Element?) - in that case, bail\n // $FlowIgnore: Doesn't think elements are indexable\n if (!(0, _shims.isFunction)(el[matchesSelectorFunc])) return false;\n\n // $FlowIgnore: Doesn't think elements are indexable\n return el[matchesSelectorFunc](selector);\n}\n\n// Works up the tree to the draggable itself attempting to match selector.\nfunction matchesSelectorAndParentsTo(el /*: Node*/, selector /*: string*/, baseNode /*: Node*/) /*: boolean*/{\n let node = el;\n do {\n if (matchesSelector(node, selector)) return true;\n if (node === baseNode) return false;\n // $FlowIgnore[incompatible-type]\n node = node.parentNode;\n } while (node);\n return false;\n}\nfunction addEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/, inputOptions /*: Object*/) /*: void*/{\n if (!el) return;\n const options = {\n capture: true,\n ...inputOptions\n };\n // $FlowIgnore[method-unbinding]\n if (el.addEventListener) {\n el.addEventListener(event, handler, options);\n } else if (el.attachEvent) {\n el.attachEvent('on' + event, handler);\n } else {\n // $FlowIgnore: Doesn't think elements are indexable\n el['on' + event] = handler;\n }\n}\nfunction removeEvent(el /*: ?Node*/, event /*: string*/, handler /*: Function*/, inputOptions /*: Object*/) /*: void*/{\n if (!el) return;\n const options = {\n capture: true,\n ...inputOptions\n };\n // $FlowIgnore[method-unbinding]\n if (el.removeEventListener) {\n el.removeEventListener(event, handler, options);\n } else if (el.detachEvent) {\n el.detachEvent('on' + event, handler);\n } else {\n // $FlowIgnore: Doesn't think elements are indexable\n el['on' + event] = null;\n }\n}\nfunction outerHeight(node /*: HTMLElement*/) /*: number*/{\n // This is deliberately excluding margin for our calculations, since we are using\n // offsetTop which is including margin. See getBoundPosition\n let height = node.clientHeight;\n const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n height += (0, _shims.int)(computedStyle.borderTopWidth);\n height += (0, _shims.int)(computedStyle.borderBottomWidth);\n return height;\n}\nfunction outerWidth(node /*: HTMLElement*/) /*: number*/{\n // This is deliberately excluding margin for our calculations, since we are using\n // offsetLeft which is including margin. See getBoundPosition\n let width = node.clientWidth;\n const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n width += (0, _shims.int)(computedStyle.borderLeftWidth);\n width += (0, _shims.int)(computedStyle.borderRightWidth);\n return width;\n}\nfunction innerHeight(node /*: HTMLElement*/) /*: number*/{\n let height = node.clientHeight;\n const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n height -= (0, _shims.int)(computedStyle.paddingTop);\n height -= (0, _shims.int)(computedStyle.paddingBottom);\n return height;\n}\nfunction innerWidth(node /*: HTMLElement*/) /*: number*/{\n let width = node.clientWidth;\n const computedStyle = node.ownerDocument.defaultView.getComputedStyle(node);\n width -= (0, _shims.int)(computedStyle.paddingLeft);\n width -= (0, _shims.int)(computedStyle.paddingRight);\n return width;\n}\n/*:: interface EventWithOffset {\n clientX: number, clientY: number\n}*/\n// Get from offsetParent\nfunction offsetXYFromParent(evt /*: EventWithOffset*/, offsetParent /*: HTMLElement*/, scale /*: number*/) /*: ControlPosition*/{\n const isBody = offsetParent === offsetParent.ownerDocument.body;\n const offsetParentRect = isBody ? {\n left: 0,\n top: 0\n } : offsetParent.getBoundingClientRect();\n const x = (evt.clientX + offsetParent.scrollLeft - offsetParentRect.left) / scale;\n const y = (evt.clientY + offsetParent.scrollTop - offsetParentRect.top) / scale;\n return {\n x,\n y\n };\n}\nfunction createCSSTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: Object*/{\n const translation = getTranslation(controlPos, positionOffset, 'px');\n return {\n [(0, _getPrefix.browserPrefixToKey)('transform', _getPrefix.default)]: translation\n };\n}\nfunction createSVGTransform(controlPos /*: ControlPosition*/, positionOffset /*: PositionOffsetControlPosition*/) /*: string*/{\n const translation = getTranslation(controlPos, positionOffset, '');\n return translation;\n}\nfunction getTranslation(_ref /*:: */, positionOffset /*: PositionOffsetControlPosition*/, unitSuffix /*: string*/) /*: string*/{\n let {\n x,\n y\n } /*: ControlPosition*/ = _ref /*: ControlPosition*/;\n let translation = \"translate(\".concat(x).concat(unitSuffix, \",\").concat(y).concat(unitSuffix, \")\");\n if (positionOffset) {\n const defaultX = \"\".concat(typeof positionOffset.x === 'string' ? positionOffset.x : positionOffset.x + unitSuffix);\n const defaultY = \"\".concat(typeof positionOffset.y === 'string' ? positionOffset.y : positionOffset.y + unitSuffix);\n translation = \"translate(\".concat(defaultX, \", \").concat(defaultY, \")\") + translation;\n }\n return translation;\n}\nfunction getTouch(e /*: MouseTouchEvent*/, identifier /*: number*/) /*: ?{clientX: number, clientY: number}*/{\n return e.targetTouches && (0, _shims.findInArray)(e.targetTouches, t => identifier === t.identifier) || e.changedTouches && (0, _shims.findInArray)(e.changedTouches, t => identifier === t.identifier);\n}\nfunction getTouchIdentifier(e /*: MouseTouchEvent*/) /*: ?number*/{\n if (e.targetTouches && e.targetTouches[0]) return e.targetTouches[0].identifier;\n if (e.changedTouches && e.changedTouches[0]) return e.changedTouches[0].identifier;\n}\n\n// User-select Hacks:\n//\n// Useful for preventing blue highlights all over everything when dragging.\n\n// Note we're passing `document` b/c we could be iframed\nfunction addUserSelectStyles(doc /*: ?Document*/) {\n if (!doc) return;\n let styleEl = doc.getElementById('react-draggable-style-el');\n if (!styleEl) {\n styleEl = doc.createElement('style');\n styleEl.type = 'text/css';\n styleEl.id = 'react-draggable-style-el';\n styleEl.innerHTML = '.react-draggable-transparent-selection *::-moz-selection {all: inherit;}\\n';\n styleEl.innerHTML += '.react-draggable-transparent-selection *::selection {all: inherit;}\\n';\n doc.getElementsByTagName('head')[0].appendChild(styleEl);\n }\n if (doc.body) addClassName(doc.body, 'react-draggable-transparent-selection');\n}\nfunction removeUserSelectStyles(doc /*: ?Document*/) {\n if (!doc) return;\n try {\n if (doc.body) removeClassName(doc.body, 'react-draggable-transparent-selection');\n // $FlowIgnore: IE\n if (doc.selection) {\n // $FlowIgnore: IE\n doc.selection.empty();\n } else {\n // Remove selection caused by scroll, unless it's a focused input\n // (we use doc.defaultView in case we're in an iframe)\n const selection = (doc.defaultView || window).getSelection();\n if (selection && selection.type !== 'Caret') {\n selection.removeAllRanges();\n }\n }\n } catch (e) {\n // probably IE\n }\n}\nfunction addClassName(el /*: HTMLElement*/, className /*: string*/) {\n if (el.classList) {\n el.classList.add(className);\n } else {\n if (!el.className.match(new RegExp(\"(?:^|\\\\s)\".concat(className, \"(?!\\\\S)\")))) {\n el.className += \" \".concat(className);\n }\n }\n}\nfunction removeClassName(el /*: HTMLElement*/, className /*: string*/) {\n if (el.classList) {\n el.classList.remove(className);\n } else {\n el.className = el.className.replace(new RegExp(\"(?:^|\\\\s)\".concat(className, \"(?!\\\\S)\"), 'g'), '');\n }\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.browserPrefixToKey = browserPrefixToKey;\nexports.browserPrefixToStyle = browserPrefixToStyle;\nexports.default = void 0;\nexports.getPrefix = getPrefix;\nconst prefixes = ['Moz', 'Webkit', 'O', 'ms'];\nfunction getPrefix() /*: string*/{\n var _window$document;\n let prop /*: string*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';\n // Ensure we're running in an environment where there is actually a global\n // `window` obj\n if (typeof window === 'undefined') return '';\n\n // If we're in a pseudo-browser server-side environment, this access\n // path may not exist, so bail out if it doesn't.\n const style = (_window$document = window.document) === null || _window$document === void 0 || (_window$document = _window$document.documentElement) === null || _window$document === void 0 ? void 0 : _window$document.style;\n if (!style) return '';\n if (prop in style) return '';\n for (let i = 0; i < prefixes.length; i++) {\n if (browserPrefixToKey(prop, prefixes[i]) in style) return prefixes[i];\n }\n return '';\n}\nfunction browserPrefixToKey(prop /*: string*/, prefix /*: string*/) /*: string*/{\n return prefix ? \"\".concat(prefix).concat(kebabToTitleCase(prop)) : prop;\n}\nfunction browserPrefixToStyle(prop /*: string*/, prefix /*: string*/) /*: string*/{\n return prefix ? \"-\".concat(prefix.toLowerCase(), \"-\").concat(prop) : prop;\n}\nfunction kebabToTitleCase(str /*: string*/) /*: string*/{\n let out = '';\n let shouldCapitalize = true;\n for (let i = 0; i < str.length; i++) {\n if (shouldCapitalize) {\n out += str[i].toUpperCase();\n shouldCapitalize = false;\n } else if (str[i] === '-') {\n shouldCapitalize = true;\n } else {\n out += str[i];\n }\n }\n return out;\n}\n\n// Default export is the prefix itself, like 'Moz', 'Webkit', etc\n// Note that you may have to re-test for certain things; for instance, Chrome 50\n// can handle unprefixed `transform`, but not unprefixed `user-select`\nvar _default = exports.default = (getPrefix() /*: string*/);","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = log;\n/*eslint no-console:0*/\nfunction log() {\n if (undefined) console.log(...arguments);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.canDragX = canDragX;\nexports.canDragY = canDragY;\nexports.createCoreData = createCoreData;\nexports.createDraggableData = createDraggableData;\nexports.getBoundPosition = getBoundPosition;\nexports.getControlPosition = getControlPosition;\nexports.snapToGrid = snapToGrid;\nvar _shims = require(\"./shims\");\nvar _domFns = require(\"./domFns\");\n/*:: import type Draggable from '../Draggable';*/\n/*:: import type {Bounds, ControlPosition, DraggableData, MouseTouchEvent} from './types';*/\n/*:: import type DraggableCore from '../DraggableCore';*/\nfunction getBoundPosition(draggable /*: Draggable*/, x /*: number*/, y /*: number*/) /*: [number, number]*/{\n // If no bounds, short-circuit and move on\n if (!draggable.props.bounds) return [x, y];\n\n // Clone new bounds\n let {\n bounds\n } = draggable.props;\n bounds = typeof bounds === 'string' ? bounds : cloneBounds(bounds);\n const node = findDOMNode(draggable);\n if (typeof bounds === 'string') {\n const {\n ownerDocument\n } = node;\n const ownerWindow = ownerDocument.defaultView;\n let boundNode;\n if (bounds === 'parent') {\n boundNode = node.parentNode;\n } else {\n boundNode = ownerDocument.querySelector(bounds);\n }\n if (!(boundNode instanceof ownerWindow.HTMLElement)) {\n throw new Error('Bounds selector \"' + bounds + '\" could not find an element.');\n }\n const boundNodeEl /*: HTMLElement*/ = boundNode; // for Flow, can't seem to refine correctly\n const nodeStyle = ownerWindow.getComputedStyle(node);\n const boundNodeStyle = ownerWindow.getComputedStyle(boundNodeEl);\n // Compute bounds. This is a pain with padding and offsets but this gets it exactly right.\n bounds = {\n left: -node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingLeft) + (0, _shims.int)(nodeStyle.marginLeft),\n top: -node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingTop) + (0, _shims.int)(nodeStyle.marginTop),\n right: (0, _domFns.innerWidth)(boundNodeEl) - (0, _domFns.outerWidth)(node) - node.offsetLeft + (0, _shims.int)(boundNodeStyle.paddingRight) - (0, _shims.int)(nodeStyle.marginRight),\n bottom: (0, _domFns.innerHeight)(boundNodeEl) - (0, _domFns.outerHeight)(node) - node.offsetTop + (0, _shims.int)(boundNodeStyle.paddingBottom) - (0, _shims.int)(nodeStyle.marginBottom)\n };\n }\n\n // Keep x and y below right and bottom limits...\n if ((0, _shims.isNum)(bounds.right)) x = Math.min(x, bounds.right);\n if ((0, _shims.isNum)(bounds.bottom)) y = Math.min(y, bounds.bottom);\n\n // But above left and top limits.\n if ((0, _shims.isNum)(bounds.left)) x = Math.max(x, bounds.left);\n if ((0, _shims.isNum)(bounds.top)) y = Math.max(y, bounds.top);\n return [x, y];\n}\nfunction snapToGrid(grid /*: [number, number]*/, pendingX /*: number*/, pendingY /*: number*/) /*: [number, number]*/{\n const x = Math.round(pendingX / grid[0]) * grid[0];\n const y = Math.round(pendingY / grid[1]) * grid[1];\n return [x, y];\n}\nfunction canDragX(draggable /*: Draggable*/) /*: boolean*/{\n return draggable.props.axis === 'both' || draggable.props.axis === 'x';\n}\nfunction canDragY(draggable /*: Draggable*/) /*: boolean*/{\n return draggable.props.axis === 'both' || draggable.props.axis === 'y';\n}\n\n// Get {x, y} positions from event.\nfunction getControlPosition(e /*: MouseTouchEvent*/, touchIdentifier /*: ?number*/, draggableCore /*: DraggableCore*/) /*: ?ControlPosition*/{\n const touchObj = typeof touchIdentifier === 'number' ? (0, _domFns.getTouch)(e, touchIdentifier) : null;\n if (typeof touchIdentifier === 'number' && !touchObj) return null; // not the right touch\n const node = findDOMNode(draggableCore);\n // User can provide an offsetParent if desired.\n const offsetParent = draggableCore.props.offsetParent || node.offsetParent || node.ownerDocument.body;\n return (0, _domFns.offsetXYFromParent)(touchObj || e, offsetParent, draggableCore.props.scale);\n}\n\n// Create an data object exposed by 's events\nfunction createCoreData(draggable /*: DraggableCore*/, x /*: number*/, y /*: number*/) /*: DraggableData*/{\n const isStart = !(0, _shims.isNum)(draggable.lastX);\n const node = findDOMNode(draggable);\n if (isStart) {\n // If this is our first move, use the x and y as last coords.\n return {\n node,\n deltaX: 0,\n deltaY: 0,\n lastX: x,\n lastY: y,\n x,\n y\n };\n } else {\n // Otherwise calculate proper values.\n return {\n node,\n deltaX: x - draggable.lastX,\n deltaY: y - draggable.lastY,\n lastX: draggable.lastX,\n lastY: draggable.lastY,\n x,\n y\n };\n }\n}\n\n// Create an data exposed by 's events\nfunction createDraggableData(draggable /*: Draggable*/, coreData /*: DraggableData*/) /*: DraggableData*/{\n const scale = draggable.props.scale;\n return {\n node: coreData.node,\n x: draggable.state.x + coreData.deltaX / scale,\n y: draggable.state.y + coreData.deltaY / scale,\n deltaX: coreData.deltaX / scale,\n deltaY: coreData.deltaY / scale,\n lastX: draggable.state.x,\n lastY: draggable.state.y\n };\n}\n\n// A lot faster than stringify/parse\nfunction cloneBounds(bounds /*: Bounds*/) /*: Bounds*/{\n return {\n left: bounds.left,\n top: bounds.top,\n right: bounds.right,\n bottom: bounds.bottom\n };\n}\nfunction findDOMNode(draggable /*: Draggable | DraggableCore*/) /*: HTMLElement*/{\n const node = draggable.findDOMNode();\n if (!node) {\n throw new Error(': Unmounted during event!');\n }\n // $FlowIgnore we can't assert on HTMLElement due to tests... FIXME\n return node;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.dontSetMe = dontSetMe;\nexports.findInArray = findInArray;\nexports.int = int;\nexports.isFunction = isFunction;\nexports.isNum = isNum;\n// @credits https://gist.github.com/rogozhnikoff/a43cfed27c41e4e68cdc\nfunction findInArray(array /*: Array | TouchList*/, callback /*: Function*/) /*: any*/{\n for (let i = 0, length = array.length; i < length; i++) {\n if (callback.apply(callback, [array[i], i, array])) return array[i];\n }\n}\nfunction isFunction(func /*: any*/) /*: boolean %checks*/{\n // $FlowIgnore[method-unbinding]\n return typeof func === 'function' || Object.prototype.toString.call(func) === '[object Function]';\n}\nfunction isNum(num /*: any*/) /*: boolean %checks*/{\n return typeof num === 'number' && !isNaN(num);\n}\nfunction int(a /*: string*/) /*: number*/{\n return parseInt(a, 10);\n}\nfunction dontSetMe(props /*: Object*/, propName /*: string*/, componentName /*: string*/) /*: ?Error*/{\n if (props[propName]) {\n return new Error(\"Invalid prop \".concat(propName, \" passed to \").concat(componentName, \" - do not set this, set it on the child.\"));\n }\n}","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t = (\n i: string,\n w: number,\n h: number,\n Data\n) => void;*/\n/*:: type ResizeCallbackData = {\n node: HTMLElement,\n size: Position,\n handle: ResizeHandleAxis\n};*/\n/*:: type GridItemResizeCallback = (\n e: Event,\n data: ResizeCallbackData,\n position: Position\n) => void;*/\n/*:: type State = {\n resizing: ?{ top: number, left: number, width: number, height: number },\n dragging: ?{ top: number, left: number },\n className: string\n};*/\n/*:: type Props = {\n children: ReactElement,\n cols: number,\n containerWidth: number,\n margin: [number, number],\n containerPadding: [number, number],\n rowHeight: number,\n maxRows: number,\n isDraggable: boolean,\n isResizable: boolean,\n isBounded: boolean,\n static?: boolean,\n useCSSTransforms?: boolean,\n usePercentages?: boolean,\n transformScale: number,\n droppingPosition?: DroppingPosition,\n\n className: string,\n style?: Object,\n // Draggability\n cancel: string,\n handle: string,\n\n x: number,\n y: number,\n w: number,\n h: number,\n\n minW: number,\n maxW: number,\n minH: number,\n maxH: number,\n i: string,\n\n resizeHandles?: ResizeHandleAxis[],\n resizeHandle?: ResizeHandle,\n\n onDrag?: GridItemCallback,\n onDragStart?: GridItemCallback,\n onDragStop?: GridItemCallback,\n onResize?: GridItemCallback,\n onResizeStart?: GridItemCallback,\n onResizeStop?: GridItemCallback\n};*/\n/*:: type DefaultProps = {\n className: string,\n cancel: string,\n handle: string,\n minH: number,\n minW: number,\n maxH: number,\n maxW: number,\n transformScale: number\n};*/\n/**\n * An individual item within a ReactGridLayout.\n */\nclass GridItem extends _react.default.Component /*:: */{\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n resizing: null,\n dragging: null,\n className: \"\"\n });\n _defineProperty(this, \"elementRef\", /*#__PURE__*/_react.default.createRef());\n /**\n * onDragStart event handler\n * @param {Event} e event data\n * @param {Object} callbackData an object with node, delta and position information\n */\n _defineProperty(this, \"onDragStart\", (e, _ref) => {\n let {\n node\n } = _ref;\n const {\n onDragStart,\n transformScale\n } = this.props;\n if (!onDragStart) return;\n const newPosition /*: PartialPosition*/ = {\n top: 0,\n left: 0\n };\n\n // TODO: this wont work on nested parents\n const {\n offsetParent\n } = node;\n if (!offsetParent) return;\n const parentRect = offsetParent.getBoundingClientRect();\n const clientRect = node.getBoundingClientRect();\n const cLeft = clientRect.left / transformScale;\n const pLeft = parentRect.left / transformScale;\n const cTop = clientRect.top / transformScale;\n const pTop = parentRect.top / transformScale;\n newPosition.left = cLeft - pLeft + offsetParent.scrollLeft;\n newPosition.top = cTop - pTop + offsetParent.scrollTop;\n this.setState({\n dragging: newPosition\n });\n\n // Call callback with this data\n const {\n x,\n y\n } = (0, _calculateUtils.calcXY)(this.getPositionParams(), newPosition.top, newPosition.left, this.props.w, this.props.h);\n return onDragStart.call(this, this.props.i, x, y, {\n e,\n node,\n newPosition\n });\n });\n /**\n * onDrag event handler\n * @param {Event} e event data\n * @param {Object} callbackData an object with node, delta and position information\n */\n _defineProperty(this, \"onDrag\", (e, _ref2) => {\n let {\n node,\n deltaX,\n deltaY\n } = _ref2;\n const {\n onDrag\n } = this.props;\n if (!onDrag) return;\n if (!this.state.dragging) {\n throw new Error(\"onDrag called before onDragStart.\");\n }\n let top = this.state.dragging.top + deltaY;\n let left = this.state.dragging.left + deltaX;\n const {\n isBounded,\n i,\n w,\n h,\n containerWidth\n } = this.props;\n const positionParams = this.getPositionParams();\n\n // Boundary calculations; keeps items within the grid\n if (isBounded) {\n const {\n offsetParent\n } = node;\n if (offsetParent) {\n const {\n margin,\n rowHeight,\n containerPadding\n } = this.props;\n const bottomBoundary = offsetParent.clientHeight - (0, _calculateUtils.calcGridItemWHPx)(h, rowHeight, margin[1]);\n top = (0, _calculateUtils.clamp)(top - containerPadding[1], 0, bottomBoundary);\n const colWidth = (0, _calculateUtils.calcGridColWidth)(positionParams);\n const rightBoundary = containerWidth - (0, _calculateUtils.calcGridItemWHPx)(w, colWidth, margin[0]);\n left = (0, _calculateUtils.clamp)(left - containerPadding[0], 0, rightBoundary);\n }\n }\n const newPosition /*: PartialPosition*/ = {\n top,\n left\n };\n this.setState({\n dragging: newPosition\n });\n\n // Call callback with this data\n const {\n x,\n y\n } = (0, _calculateUtils.calcXY)(positionParams, top, left, w, h);\n return onDrag.call(this, i, x, y, {\n e,\n node,\n newPosition\n });\n });\n /**\n * onDragStop event handler\n * @param {Event} e event data\n * @param {Object} callbackData an object with node, delta and position information\n */\n _defineProperty(this, \"onDragStop\", (e, _ref3) => {\n let {\n node\n } = _ref3;\n const {\n onDragStop\n } = this.props;\n if (!onDragStop) return;\n if (!this.state.dragging) {\n throw new Error(\"onDragEnd called before onDragStart.\");\n }\n const {\n w,\n h,\n i\n } = this.props;\n const {\n left,\n top\n } = this.state.dragging;\n const newPosition /*: PartialPosition*/ = {\n top,\n left\n };\n this.setState({\n dragging: null\n });\n const {\n x,\n y\n } = (0, _calculateUtils.calcXY)(this.getPositionParams(), top, left, w, h);\n return onDragStop.call(this, i, x, y, {\n e,\n node,\n newPosition\n });\n });\n /**\n * onResizeStop event handler\n * @param {Event} e event data\n * @param {Object} callbackData an object with node and size information\n */\n _defineProperty(this, \"onResizeStop\", (e, callbackData, position) => this.onResizeHandler(e, callbackData, position, \"onResizeStop\"));\n // onResizeStart event handler\n _defineProperty(this, \"onResizeStart\", (e, callbackData, position) => this.onResizeHandler(e, callbackData, position, \"onResizeStart\"));\n // onResize event handler\n _defineProperty(this, \"onResize\", (e, callbackData, position) => this.onResizeHandler(e, callbackData, position, \"onResize\"));\n }\n shouldComponentUpdate(nextProps /*: Props*/, nextState /*: State*/) /*: boolean*/{\n // We can't deeply compare children. If the developer memoizes them, we can\n // use this optimization.\n if (this.props.children !== nextProps.children) return true;\n if (this.props.droppingPosition !== nextProps.droppingPosition) return true;\n // TODO memoize these calculations so they don't take so long?\n const oldPosition = (0, _calculateUtils.calcGridItemPosition)(this.getPositionParams(this.props), this.props.x, this.props.y, this.props.w, this.props.h, this.state);\n const newPosition = (0, _calculateUtils.calcGridItemPosition)(this.getPositionParams(nextProps), nextProps.x, nextProps.y, nextProps.w, nextProps.h, nextState);\n return !(0, _utils.fastPositionEqual)(oldPosition, newPosition) || this.props.useCSSTransforms !== nextProps.useCSSTransforms;\n }\n componentDidMount() {\n this.moveDroppingItem({});\n }\n componentDidUpdate(prevProps /*: Props*/) {\n this.moveDroppingItem(prevProps);\n }\n\n // When a droppingPosition is present, this means we should fire a move event, as if we had moved\n // this element by `x, y` pixels.\n moveDroppingItem(prevProps /*: Props*/) {\n const {\n droppingPosition\n } = this.props;\n if (!droppingPosition) return;\n const node = this.elementRef.current;\n // Can't find DOM node (are we unmounted?)\n if (!node) return;\n const prevDroppingPosition = prevProps.droppingPosition || {\n left: 0,\n top: 0\n };\n const {\n dragging\n } = this.state;\n const shouldDrag = dragging && droppingPosition.left !== prevDroppingPosition.left || droppingPosition.top !== prevDroppingPosition.top;\n if (!dragging) {\n this.onDragStart(droppingPosition.e, {\n node,\n deltaX: droppingPosition.left,\n deltaY: droppingPosition.top\n });\n } else if (shouldDrag) {\n const deltaX = droppingPosition.left - dragging.left;\n const deltaY = droppingPosition.top - dragging.top;\n this.onDrag(droppingPosition.e, {\n node,\n deltaX,\n deltaY\n });\n }\n }\n getPositionParams() /*: PositionParams*/{\n let props /*: Props*/ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props;\n return {\n cols: props.cols,\n containerPadding: props.containerPadding,\n containerWidth: props.containerWidth,\n margin: props.margin,\n maxRows: props.maxRows,\n rowHeight: props.rowHeight\n };\n }\n\n /**\n * This is where we set the grid item's absolute placement. It gets a little tricky because we want to do it\n * well when server rendering, and the only way to do that properly is to use percentage width/left because\n * we don't know exactly what the browser viewport is.\n * Unfortunately, CSS Transforms, which are great for performance, break in this instance because a percentage\n * left is relative to the item itself, not its container! So we cannot use them on the server rendering pass.\n *\n * @param {Object} pos Position object with width, height, left, top.\n * @return {Object} Style object.\n */\n createStyle(pos /*: Position*/) /*: { [key: string]: ?string }*/{\n const {\n usePercentages,\n containerWidth,\n useCSSTransforms\n } = this.props;\n let style;\n // CSS Transforms support (default)\n if (useCSSTransforms) {\n style = (0, _utils.setTransform)(pos);\n } else {\n // top,left (slow)\n style = (0, _utils.setTopLeft)(pos);\n\n // This is used for server rendering.\n if (usePercentages) {\n style.left = (0, _utils.perc)(pos.left / containerWidth);\n style.width = (0, _utils.perc)(pos.width / containerWidth);\n }\n }\n return style;\n }\n\n /**\n * Mix a Draggable instance into a child.\n * @param {Element} child Child element.\n * @return {Element} Child wrapped in Draggable.\n */\n mixinDraggable(child /*: ReactElement*/, isDraggable /*: boolean*/) /*: ReactElement*/{\n return /*#__PURE__*/_react.default.createElement(_reactDraggable.DraggableCore, {\n disabled: !isDraggable,\n onStart: this.onDragStart,\n onDrag: this.onDrag,\n onStop: this.onDragStop,\n handle: this.props.handle,\n cancel: \".react-resizable-handle\" + (this.props.cancel ? \",\" + this.props.cancel : \"\"),\n scale: this.props.transformScale,\n nodeRef: this.elementRef\n }, child);\n }\n\n /**\n * Utility function to setup callback handler definitions for\n * similarily structured resize events.\n */\n curryResizeHandler(position /*: Position*/, handler /*: Function*/) /*: Function*/{\n return (e /*: Event*/, data /*: ResizeCallbackData*/) => /*: Function*/handler(e, data, position);\n }\n\n /**\n * Mix a Resizable instance into a child.\n * @param {Element} child Child element.\n * @param {Object} position Position object (pixel values)\n * @return {Element} Child wrapped in Resizable.\n */\n mixinResizable(child /*: ReactElement*/, position /*: Position*/, isResizable /*: boolean*/) /*: ReactElement*/{\n const {\n cols,\n minW,\n minH,\n maxW,\n maxH,\n transformScale,\n resizeHandles,\n resizeHandle\n } = this.props;\n const positionParams = this.getPositionParams();\n\n // This is the max possible width - doesn't go to infinity because of the width of the window\n const maxWidth = (0, _calculateUtils.calcGridItemPosition)(positionParams, 0, 0, cols, 0).width;\n\n // Calculate min/max constraints using our min & maxes\n const mins = (0, _calculateUtils.calcGridItemPosition)(positionParams, 0, 0, minW, minH);\n const maxes = (0, _calculateUtils.calcGridItemPosition)(positionParams, 0, 0, maxW, maxH);\n const minConstraints = [mins.width, mins.height];\n const maxConstraints = [Math.min(maxes.width, maxWidth), Math.min(maxes.height, Infinity)];\n return /*#__PURE__*/_react.default.createElement(_reactResizable.Resizable\n // These are opts for the resize handle itself\n , {\n draggableOpts: {\n disabled: !isResizable\n },\n className: isResizable ? undefined : \"react-resizable-hide\",\n width: position.width,\n height: position.height,\n minConstraints: minConstraints,\n maxConstraints: maxConstraints,\n onResizeStop: this.curryResizeHandler(position, this.onResizeStop),\n onResizeStart: this.curryResizeHandler(position, this.onResizeStart),\n onResize: this.curryResizeHandler(position, this.onResize),\n transformScale: transformScale,\n resizeHandles: resizeHandles,\n handle: resizeHandle\n }, child);\n }\n /**\n * Wrapper around resize events to provide more useful data.\n */\n onResizeHandler(e /*: Event*/, _ref4 /*:: */,\n // 'size' is updated position\n position /*: Position*/,\n // existing position\n handlerName /*: string*/) /*: void*/{\n let {\n node,\n size,\n handle\n } /*: ResizeCallbackData*/ = _ref4 /*: ResizeCallbackData*/;\n const handler = this.props[handlerName];\n if (!handler) return;\n const {\n x,\n y,\n i,\n maxH,\n minH,\n containerWidth\n } = this.props;\n const {\n minW,\n maxW\n } = this.props;\n\n // Clamping of dimensions based on resize direction\n let updatedSize = size;\n if (node) {\n updatedSize = (0, _utils.resizeItemInDirection)(handle, position, size, containerWidth);\n this.setState({\n resizing: handlerName === \"onResizeStop\" ? null : updatedSize\n });\n }\n\n // Get new XY based on pixel size\n let {\n w,\n h\n } = (0, _calculateUtils.calcWH)(this.getPositionParams(), updatedSize.width, updatedSize.height, x, y, handle);\n\n // Min/max capping.\n // minW should be at least 1 (TODO propTypes validation?)\n w = (0, _calculateUtils.clamp)(w, Math.max(minW, 1), maxW);\n h = (0, _calculateUtils.clamp)(h, minH, maxH);\n handler.call(this, i, w, h, {\n e,\n node,\n size: updatedSize,\n handle\n });\n }\n render() /*: ReactNode*/{\n const {\n x,\n y,\n w,\n h,\n isDraggable,\n isResizable,\n droppingPosition,\n useCSSTransforms\n } = this.props;\n const pos = (0, _calculateUtils.calcGridItemPosition)(this.getPositionParams(), x, y, w, h, this.state);\n const child = _react.default.Children.only(this.props.children);\n\n // Create the child element. We clone the existing element but modify its className and style.\n let newChild = /*#__PURE__*/_react.default.cloneElement(child, {\n ref: this.elementRef,\n className: (0, _clsx.default)(\"react-grid-item\", child.props.className, this.props.className, {\n static: this.props.static,\n resizing: Boolean(this.state.resizing),\n \"react-draggable\": isDraggable,\n \"react-draggable-dragging\": Boolean(this.state.dragging),\n dropping: Boolean(droppingPosition),\n cssTransforms: useCSSTransforms\n }),\n // We can set the width and height on the child, but unfortunately we can't set the position.\n style: {\n ...this.props.style,\n ...child.props.style,\n ...this.createStyle(pos)\n }\n });\n\n // Resizable support. This is usually on but the user can toggle it off.\n newChild = this.mixinResizable(newChild, pos, isResizable);\n\n // Draggable support. This is always on, except for with placeholders.\n newChild = this.mixinDraggable(newChild, isDraggable);\n return newChild;\n }\n}\nexports.default = GridItem;\n_defineProperty(GridItem, \"propTypes\", {\n // Children must be only a single element\n children: _propTypes.default.element,\n // General grid attributes\n cols: _propTypes.default.number.isRequired,\n containerWidth: _propTypes.default.number.isRequired,\n rowHeight: _propTypes.default.number.isRequired,\n margin: _propTypes.default.array.isRequired,\n maxRows: _propTypes.default.number.isRequired,\n containerPadding: _propTypes.default.array.isRequired,\n // These are all in grid units\n x: _propTypes.default.number.isRequired,\n y: _propTypes.default.number.isRequired,\n w: _propTypes.default.number.isRequired,\n h: _propTypes.default.number.isRequired,\n // All optional\n minW: function (props /*: Props*/, propName /*: string*/) {\n const value = props[propName];\n if (typeof value !== \"number\") return new Error(\"minWidth not Number\");\n if (value > props.w || value > props.maxW) return new Error(\"minWidth larger than item width/maxWidth\");\n },\n maxW: function (props /*: Props*/, propName /*: string*/) {\n const value = props[propName];\n if (typeof value !== \"number\") return new Error(\"maxWidth not Number\");\n if (value < props.w || value < props.minW) return new Error(\"maxWidth smaller than item width/minWidth\");\n },\n minH: function (props /*: Props*/, propName /*: string*/) {\n const value = props[propName];\n if (typeof value !== \"number\") return new Error(\"minHeight not Number\");\n if (value > props.h || value > props.maxH) return new Error(\"minHeight larger than item height/maxHeight\");\n },\n maxH: function (props /*: Props*/, propName /*: string*/) {\n const value = props[propName];\n if (typeof value !== \"number\") return new Error(\"maxHeight not Number\");\n if (value < props.h || value < props.minH) return new Error(\"maxHeight smaller than item height/minHeight\");\n },\n // ID is nice to have for callbacks\n i: _propTypes.default.string.isRequired,\n // Resize handle options\n resizeHandles: _ReactGridLayoutPropTypes.resizeHandleAxesType,\n resizeHandle: _ReactGridLayoutPropTypes.resizeHandleType,\n // Functions\n onDragStop: _propTypes.default.func,\n onDragStart: _propTypes.default.func,\n onDrag: _propTypes.default.func,\n onResizeStop: _propTypes.default.func,\n onResizeStart: _propTypes.default.func,\n onResize: _propTypes.default.func,\n // Flags\n isDraggable: _propTypes.default.bool.isRequired,\n isResizable: _propTypes.default.bool.isRequired,\n isBounded: _propTypes.default.bool.isRequired,\n static: _propTypes.default.bool,\n // Use CSS transforms instead of top/left\n useCSSTransforms: _propTypes.default.bool.isRequired,\n transformScale: _propTypes.default.number,\n // Others\n className: _propTypes.default.string,\n // Selector for draggable handle\n handle: _propTypes.default.string,\n // Selector for draggable cancel (see react-draggable)\n cancel: _propTypes.default.string,\n // Current position of a dropping element\n droppingPosition: _propTypes.default.shape({\n e: _propTypes.default.object.isRequired,\n left: _propTypes.default.number.isRequired,\n top: _propTypes.default.number.isRequired\n })\n});\n_defineProperty(GridItem, \"defaultProps\", {\n className: \"\",\n cancel: \"\",\n handle: \"\",\n minH: 1,\n minW: 1,\n maxH: Infinity,\n maxW: Infinity,\n transformScale: 1\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _fastEquals = require(\"fast-equals\");\nvar _clsx = _interopRequireDefault(require(\"clsx\"));\nvar _utils = require(\"./utils\");\nvar _calculateUtils = require(\"./calculateUtils\");\nvar _GridItem = _interopRequireDefault(require(\"./GridItem\"));\nvar _ReactGridLayoutPropTypes = _interopRequireDefault(require(\"./ReactGridLayoutPropTypes\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*:: import type {\n ChildrenArray as ReactChildrenArray,\n Element as ReactElement\n} from \"react\";*/\n/*:: import type {\n CompactType,\n GridResizeEvent,\n GridDragEvent,\n DragOverEvent,\n Layout,\n DroppingPosition,\n LayoutItem\n} from \"./utils\";*/\n// Types\n/*:: import type { PositionParams } from \"./calculateUtils\";*/\n/*:: type State = {\n activeDrag: ?LayoutItem,\n layout: Layout,\n mounted: boolean,\n oldDragItem: ?LayoutItem,\n oldLayout: ?Layout,\n oldResizeItem: ?LayoutItem,\n resizing: boolean,\n droppingDOMNode: ?ReactElement,\n droppingPosition?: DroppingPosition,\n // Mirrored props\n children: ReactChildrenArray>,\n compactType?: CompactType,\n propsLayout?: Layout\n};*/\n/*:: import type { Props, DefaultProps } from \"./ReactGridLayoutPropTypes\";*/\n// End Types\nconst layoutClassName = \"react-grid-layout\";\nlet isFirefox = false;\n// Try...catch will protect from navigator not existing (e.g. node) or a bad implementation of navigator\ntry {\n isFirefox = /firefox/i.test(navigator.userAgent);\n} catch (e) {\n /* Ignore */\n}\n\n/**\n * A reactive, fluid grid layout with draggable, resizable components.\n */\n\nclass ReactGridLayout extends React.Component /*:: */{\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n activeDrag: null,\n layout: (0, _utils.synchronizeLayoutWithChildren)(this.props.layout, this.props.children, this.props.cols,\n // Legacy support for verticalCompact: false\n (0, _utils.compactType)(this.props), this.props.allowOverlap),\n mounted: false,\n oldDragItem: null,\n oldLayout: null,\n oldResizeItem: null,\n resizing: false,\n droppingDOMNode: null,\n children: []\n });\n _defineProperty(this, \"dragEnterCounter\", 0);\n /**\n * When dragging starts\n * @param {String} i Id of the child\n * @param {Number} x X position of the move\n * @param {Number} y Y position of the move\n * @param {Event} e The mousedown event\n * @param {Element} node The current dragging DOM element\n */\n _defineProperty(this, \"onDragStart\", (i /*: string*/, x /*: number*/, y /*: number*/, _ref /*:: */) => {\n let {\n e,\n node\n } /*: GridDragEvent*/ = _ref /*: GridDragEvent*/;\n const {\n layout\n } = this.state;\n const l = (0, _utils.getLayoutItem)(layout, i);\n if (!l) return;\n\n // Create placeholder (display only)\n const placeholder = {\n w: l.w,\n h: l.h,\n x: l.x,\n y: l.y,\n placeholder: true,\n i: i\n };\n this.setState({\n oldDragItem: (0, _utils.cloneLayoutItem)(l),\n oldLayout: layout,\n activeDrag: placeholder\n });\n return this.props.onDragStart(layout, l, l, null, e, node);\n });\n /**\n * Each drag movement create a new dragelement and move the element to the dragged location\n * @param {String} i Id of the child\n * @param {Number} x X position of the move\n * @param {Number} y Y position of the move\n * @param {Event} e The mousedown event\n * @param {Element} node The current dragging DOM element\n */\n _defineProperty(this, \"onDrag\", (i, x, y, _ref2) => {\n let {\n e,\n node\n } = _ref2;\n const {\n oldDragItem\n } = this.state;\n let {\n layout\n } = this.state;\n const {\n cols,\n allowOverlap,\n preventCollision\n } = this.props;\n const l = (0, _utils.getLayoutItem)(layout, i);\n if (!l) return;\n\n // Create placeholder (display only)\n const placeholder = {\n w: l.w,\n h: l.h,\n x: l.x,\n y: l.y,\n placeholder: true,\n i: i\n };\n\n // Move the element to the dragged location.\n const isUserAction = true;\n layout = (0, _utils.moveElement)(layout, l, x, y, isUserAction, preventCollision, (0, _utils.compactType)(this.props), cols, allowOverlap);\n this.props.onDrag(layout, oldDragItem, l, placeholder, e, node);\n this.setState({\n layout: allowOverlap ? layout : (0, _utils.compact)(layout, (0, _utils.compactType)(this.props), cols),\n activeDrag: placeholder\n });\n });\n /**\n * When dragging stops, figure out which position the element is closest to and update its x and y.\n * @param {String} i Index of the child.\n * @param {Number} x X position of the move\n * @param {Number} y Y position of the move\n * @param {Event} e The mousedown event\n * @param {Element} node The current dragging DOM element\n */\n _defineProperty(this, \"onDragStop\", (i, x, y, _ref3) => {\n let {\n e,\n node\n } = _ref3;\n if (!this.state.activeDrag) return;\n const {\n oldDragItem\n } = this.state;\n let {\n layout\n } = this.state;\n const {\n cols,\n preventCollision,\n allowOverlap\n } = this.props;\n const l = (0, _utils.getLayoutItem)(layout, i);\n if (!l) return;\n\n // Move the element here\n const isUserAction = true;\n layout = (0, _utils.moveElement)(layout, l, x, y, isUserAction, preventCollision, (0, _utils.compactType)(this.props), cols, allowOverlap);\n\n // Set state\n const newLayout = allowOverlap ? layout : (0, _utils.compact)(layout, (0, _utils.compactType)(this.props), cols);\n this.props.onDragStop(newLayout, oldDragItem, l, null, e, node);\n const {\n oldLayout\n } = this.state;\n this.setState({\n activeDrag: null,\n layout: newLayout,\n oldDragItem: null,\n oldLayout: null\n });\n this.onLayoutMaybeChanged(newLayout, oldLayout);\n });\n _defineProperty(this, \"onResizeStart\", (i, w, h, _ref4) => {\n let {\n e,\n node\n } = _ref4;\n const {\n layout\n } = this.state;\n const l = (0, _utils.getLayoutItem)(layout, i);\n if (!l) return;\n this.setState({\n oldResizeItem: (0, _utils.cloneLayoutItem)(l),\n oldLayout: this.state.layout,\n resizing: true\n });\n this.props.onResizeStart(layout, l, l, null, e, node);\n });\n _defineProperty(this, \"onResize\", (i, w, h, _ref5) => {\n let {\n e,\n node,\n size,\n handle\n } = _ref5;\n const {\n oldResizeItem\n } = this.state;\n const {\n layout\n } = this.state;\n const {\n cols,\n preventCollision,\n allowOverlap\n } = this.props;\n let shouldMoveItem = false;\n let finalLayout;\n let x;\n let y;\n const [newLayout, l] = (0, _utils.withLayoutItem)(layout, i, l => {\n let hasCollisions;\n x = l.x;\n y = l.y;\n if ([\"sw\", \"w\", \"nw\", \"n\", \"ne\"].indexOf(handle) !== -1) {\n if ([\"sw\", \"nw\", \"w\"].indexOf(handle) !== -1) {\n x = l.x + (l.w - w);\n w = l.x !== x && x < 0 ? l.w : w;\n x = x < 0 ? 0 : x;\n }\n if ([\"ne\", \"n\", \"nw\"].indexOf(handle) !== -1) {\n y = l.y + (l.h - h);\n h = l.y !== y && y < 0 ? l.h : h;\n y = y < 0 ? 0 : y;\n }\n shouldMoveItem = true;\n }\n\n // Something like quad tree should be used\n // to find collisions faster\n if (preventCollision && !allowOverlap) {\n const collisions = (0, _utils.getAllCollisions)(layout, {\n ...l,\n w,\n h,\n x,\n y\n }).filter(layoutItem => layoutItem.i !== l.i);\n hasCollisions = collisions.length > 0;\n\n // If we're colliding, we need adjust the placeholder.\n if (hasCollisions) {\n // Reset layoutItem dimensions if there were collisions\n y = l.y;\n h = l.h;\n x = l.x;\n w = l.w;\n shouldMoveItem = false;\n }\n }\n l.w = w;\n l.h = h;\n return l;\n });\n\n // Shouldn't ever happen, but typechecking makes it necessary\n if (!l) return;\n finalLayout = newLayout;\n if (shouldMoveItem) {\n // Move the element to the new position.\n const isUserAction = true;\n finalLayout = (0, _utils.moveElement)(newLayout, l, x, y, isUserAction, this.props.preventCollision, (0, _utils.compactType)(this.props), cols, allowOverlap);\n }\n\n // Create placeholder element (display only)\n const placeholder = {\n w: l.w,\n h: l.h,\n x: l.x,\n y: l.y,\n static: true,\n i: i\n };\n this.props.onResize(finalLayout, oldResizeItem, l, placeholder, e, node);\n\n // Re-compact the newLayout and set the drag placeholder.\n this.setState({\n layout: allowOverlap ? finalLayout : (0, _utils.compact)(finalLayout, (0, _utils.compactType)(this.props), cols),\n activeDrag: placeholder\n });\n });\n _defineProperty(this, \"onResizeStop\", (i, w, h, _ref6) => {\n let {\n e,\n node\n } = _ref6;\n const {\n layout,\n oldResizeItem\n } = this.state;\n const {\n cols,\n allowOverlap\n } = this.props;\n const l = (0, _utils.getLayoutItem)(layout, i);\n\n // Set state\n const newLayout = allowOverlap ? layout : (0, _utils.compact)(layout, (0, _utils.compactType)(this.props), cols);\n this.props.onResizeStop(newLayout, oldResizeItem, l, null, e, node);\n const {\n oldLayout\n } = this.state;\n this.setState({\n activeDrag: null,\n layout: newLayout,\n oldResizeItem: null,\n oldLayout: null,\n resizing: false\n });\n this.onLayoutMaybeChanged(newLayout, oldLayout);\n });\n // Called while dragging an element. Part of browser native drag/drop API.\n // Native event target might be the layout itself, or an element within the layout.\n _defineProperty(this, \"onDragOver\", e => {\n e.preventDefault(); // Prevent any browser native action\n e.stopPropagation();\n\n // we should ignore events from layout's children in Firefox\n // to avoid unpredictable jumping of a dropping placeholder\n // FIXME remove this hack\n if (isFirefox &&\n // $FlowIgnore can't figure this out\n !e.nativeEvent.target?.classList.contains(layoutClassName)) {\n return false;\n }\n const {\n droppingItem,\n onDropDragOver,\n margin,\n cols,\n rowHeight,\n maxRows,\n width,\n containerPadding,\n transformScale\n } = this.props;\n // Allow user to customize the dropping item or short-circuit the drop based on the results\n // of the `onDragOver(e: Event)` callback.\n const onDragOverResult = onDropDragOver?.(e);\n if (onDragOverResult === false) {\n if (this.state.droppingDOMNode) {\n this.removeDroppingPlaceholder();\n }\n return false;\n }\n const finalDroppingItem = {\n ...droppingItem,\n ...onDragOverResult\n };\n const {\n layout\n } = this.state;\n\n // $FlowIgnore missing def\n const gridRect = e.currentTarget.getBoundingClientRect(); // The grid's position in the viewport\n\n // Calculate the mouse position relative to the grid\n const layerX = e.clientX - gridRect.left;\n const layerY = e.clientY - gridRect.top;\n const droppingPosition = {\n left: layerX / transformScale,\n top: layerY / transformScale,\n e\n };\n if (!this.state.droppingDOMNode) {\n const positionParams /*: PositionParams*/ = {\n cols,\n margin,\n maxRows,\n rowHeight,\n containerWidth: width,\n containerPadding: containerPadding || margin\n };\n const calculatedPosition = (0, _calculateUtils.calcXY)(positionParams, layerY, layerX, finalDroppingItem.w, finalDroppingItem.h);\n this.setState({\n droppingDOMNode: /*#__PURE__*/React.createElement(\"div\", {\n key: finalDroppingItem.i\n }),\n droppingPosition,\n layout: [...layout, {\n ...finalDroppingItem,\n x: calculatedPosition.x,\n y: calculatedPosition.y,\n static: false,\n isDraggable: true\n }]\n });\n } else if (this.state.droppingPosition) {\n const {\n left,\n top\n } = this.state.droppingPosition;\n const shouldUpdatePosition = left != layerX || top != layerY;\n if (shouldUpdatePosition) {\n this.setState({\n droppingPosition\n });\n }\n }\n });\n _defineProperty(this, \"removeDroppingPlaceholder\", () => {\n const {\n droppingItem,\n cols\n } = this.props;\n const {\n layout\n } = this.state;\n const newLayout = (0, _utils.compact)(layout.filter(l => l.i !== droppingItem.i), (0, _utils.compactType)(this.props), cols, this.props.allowOverlap);\n this.setState({\n layout: newLayout,\n droppingDOMNode: null,\n activeDrag: null,\n droppingPosition: undefined\n });\n });\n _defineProperty(this, \"onDragLeave\", e => {\n e.preventDefault(); // Prevent any browser native action\n e.stopPropagation();\n this.dragEnterCounter--;\n\n // onDragLeave can be triggered on each layout's child.\n // But we know that count of dragEnter and dragLeave events\n // will be balanced after leaving the layout's container\n // so we can increase and decrease count of dragEnter and\n // when it'll be equal to 0 we'll remove the placeholder\n if (this.dragEnterCounter === 0) {\n this.removeDroppingPlaceholder();\n }\n });\n _defineProperty(this, \"onDragEnter\", e => {\n e.preventDefault(); // Prevent any browser native action\n e.stopPropagation();\n this.dragEnterCounter++;\n });\n _defineProperty(this, \"onDrop\", (e /*: Event*/) => {\n e.preventDefault(); // Prevent any browser native action\n e.stopPropagation();\n const {\n droppingItem\n } = this.props;\n const {\n layout\n } = this.state;\n const item = layout.find(l => l.i === droppingItem.i);\n\n // reset dragEnter counter on drop\n this.dragEnterCounter = 0;\n this.removeDroppingPlaceholder();\n this.props.onDrop(layout, item, e);\n });\n }\n componentDidMount() {\n this.setState({\n mounted: true\n });\n // Possibly call back with layout on mount. This should be done after correcting the layout width\n // to ensure we don't rerender with the wrong width.\n this.onLayoutMaybeChanged(this.state.layout, this.props.layout);\n }\n static getDerivedStateFromProps(nextProps /*: Props*/, prevState /*: State*/) /*: $Shape | null*/{\n let newLayoutBase;\n if (prevState.activeDrag) {\n return null;\n }\n\n // Legacy support for compactType\n // Allow parent to set layout directly.\n if (!(0, _fastEquals.deepEqual)(nextProps.layout, prevState.propsLayout) || nextProps.compactType !== prevState.compactType) {\n newLayoutBase = nextProps.layout;\n } else if (!(0, _utils.childrenEqual)(nextProps.children, prevState.children)) {\n // If children change, also regenerate the layout. Use our state\n // as the base in case because it may be more up to date than\n // what is in props.\n newLayoutBase = prevState.layout;\n }\n\n // We need to regenerate the layout.\n if (newLayoutBase) {\n const newLayout = (0, _utils.synchronizeLayoutWithChildren)(newLayoutBase, nextProps.children, nextProps.cols, (0, _utils.compactType)(nextProps), nextProps.allowOverlap);\n return {\n layout: newLayout,\n // We need to save these props to state for using\n // getDerivedStateFromProps instead of componentDidMount (in which we would get extra rerender)\n compactType: nextProps.compactType,\n children: nextProps.children,\n propsLayout: nextProps.layout\n };\n }\n return null;\n }\n shouldComponentUpdate(nextProps /*: Props*/, nextState /*: State*/) /*: boolean*/{\n return (\n // NOTE: this is almost always unequal. Therefore the only way to get better performance\n // from SCU is if the user intentionally memoizes children. If they do, and they can\n // handle changes properly, performance will increase.\n this.props.children !== nextProps.children || !(0, _utils.fastRGLPropsEqual)(this.props, nextProps, _fastEquals.deepEqual) || this.state.activeDrag !== nextState.activeDrag || this.state.mounted !== nextState.mounted || this.state.droppingPosition !== nextState.droppingPosition\n );\n }\n componentDidUpdate(prevProps /*: Props*/, prevState /*: State*/) {\n if (!this.state.activeDrag) {\n const newLayout = this.state.layout;\n const oldLayout = prevState.layout;\n this.onLayoutMaybeChanged(newLayout, oldLayout);\n }\n }\n\n /**\n * Calculates a pixel value for the container.\n * @return {String} Container height in pixels.\n */\n containerHeight() /*: ?string*/{\n if (!this.props.autoSize) return;\n const nbRow = (0, _utils.bottom)(this.state.layout);\n const containerPaddingY = this.props.containerPadding ? this.props.containerPadding[1] : this.props.margin[1];\n return nbRow * this.props.rowHeight + (nbRow - 1) * this.props.margin[1] + containerPaddingY * 2 + \"px\";\n }\n onLayoutMaybeChanged(newLayout /*: Layout*/, oldLayout /*: ?Layout*/) {\n if (!oldLayout) oldLayout = this.state.layout;\n if (!(0, _fastEquals.deepEqual)(oldLayout, newLayout)) {\n this.props.onLayoutChange(newLayout);\n }\n }\n /**\n * Create a placeholder object.\n * @return {Element} Placeholder div.\n */\n placeholder() /*: ?ReactElement*/{\n const {\n activeDrag\n } = this.state;\n if (!activeDrag) return null;\n const {\n width,\n cols,\n margin,\n containerPadding,\n rowHeight,\n maxRows,\n useCSSTransforms,\n transformScale\n } = this.props;\n\n // {...this.state.activeDrag} is pretty slow, actually\n return /*#__PURE__*/React.createElement(_GridItem.default, {\n w: activeDrag.w,\n h: activeDrag.h,\n x: activeDrag.x,\n y: activeDrag.y,\n i: activeDrag.i,\n className: `react-grid-placeholder ${this.state.resizing ? \"placeholder-resizing\" : \"\"}`,\n containerWidth: width,\n cols: cols,\n margin: margin,\n containerPadding: containerPadding || margin,\n maxRows: maxRows,\n rowHeight: rowHeight,\n isDraggable: false,\n isResizable: false,\n isBounded: false,\n useCSSTransforms: useCSSTransforms,\n transformScale: transformScale\n }, /*#__PURE__*/React.createElement(\"div\", null));\n }\n\n /**\n * Given a grid item, set its style attributes & surround in a .\n * @param {Element} child React element.\n * @return {Element} Element wrapped in draggable and properly placed.\n */\n processGridItem(child /*: ReactElement*/, isDroppingItem /*: boolean*/) /*: ?ReactElement*/{\n if (!child || !child.key) return;\n const l = (0, _utils.getLayoutItem)(this.state.layout, String(child.key));\n if (!l) return null;\n const {\n width,\n cols,\n margin,\n containerPadding,\n rowHeight,\n maxRows,\n isDraggable,\n isResizable,\n isBounded,\n useCSSTransforms,\n transformScale,\n draggableCancel,\n draggableHandle,\n resizeHandles,\n resizeHandle\n } = this.props;\n const {\n mounted,\n droppingPosition\n } = this.state;\n\n // Determine user manipulations possible.\n // If an item is static, it can't be manipulated by default.\n // Any properties defined directly on the grid item will take precedence.\n const draggable = typeof l.isDraggable === \"boolean\" ? l.isDraggable : !l.static && isDraggable;\n const resizable = typeof l.isResizable === \"boolean\" ? l.isResizable : !l.static && isResizable;\n const resizeHandlesOptions = l.resizeHandles || resizeHandles;\n\n // isBounded set on child if set on parent, and child is not explicitly false\n const bounded = draggable && isBounded && l.isBounded !== false;\n return /*#__PURE__*/React.createElement(_GridItem.default, {\n containerWidth: width,\n cols: cols,\n margin: margin,\n containerPadding: containerPadding || margin,\n maxRows: maxRows,\n rowHeight: rowHeight,\n cancel: draggableCancel,\n handle: draggableHandle,\n onDragStop: this.onDragStop,\n onDragStart: this.onDragStart,\n onDrag: this.onDrag,\n onResizeStart: this.onResizeStart,\n onResize: this.onResize,\n onResizeStop: this.onResizeStop,\n isDraggable: draggable,\n isResizable: resizable,\n isBounded: bounded,\n useCSSTransforms: useCSSTransforms && mounted,\n usePercentages: !mounted,\n transformScale: transformScale,\n w: l.w,\n h: l.h,\n x: l.x,\n y: l.y,\n i: l.i,\n minH: l.minH,\n minW: l.minW,\n maxH: l.maxH,\n maxW: l.maxW,\n static: l.static,\n droppingPosition: isDroppingItem ? droppingPosition : undefined,\n resizeHandles: resizeHandlesOptions,\n resizeHandle: resizeHandle\n }, child);\n }\n render() /*: React.Element<\"div\">*/{\n const {\n className,\n style,\n isDroppable,\n innerRef\n } = this.props;\n const mergedClassName = (0, _clsx.default)(layoutClassName, className);\n const mergedStyle = {\n height: this.containerHeight(),\n ...style\n };\n return /*#__PURE__*/React.createElement(\"div\", {\n ref: innerRef,\n className: mergedClassName,\n style: mergedStyle,\n onDrop: isDroppable ? this.onDrop : _utils.noop,\n onDragLeave: isDroppable ? this.onDragLeave : _utils.noop,\n onDragEnter: isDroppable ? this.onDragEnter : _utils.noop,\n onDragOver: isDroppable ? this.onDragOver : _utils.noop\n }, React.Children.map(this.props.children, child => this.processGridItem(child)), isDroppable && this.state.droppingDOMNode && this.processGridItem(this.state.droppingDOMNode, true), this.placeholder());\n }\n}\nexports.default = ReactGridLayout;\n// TODO publish internal ReactClass displayName transform\n_defineProperty(ReactGridLayout, \"displayName\", \"ReactGridLayout\");\n// Refactored to another module to make way for preval\n_defineProperty(ReactGridLayout, \"propTypes\", _ReactGridLayoutPropTypes.default);\n_defineProperty(ReactGridLayout, \"defaultProps\", {\n autoSize: true,\n cols: 12,\n className: \"\",\n style: {},\n draggableHandle: \"\",\n draggableCancel: \"\",\n containerPadding: null,\n rowHeight: 150,\n maxRows: Infinity,\n // infinite vertical growth\n layout: [],\n margin: [10, 10],\n isBounded: false,\n isDraggable: true,\n isResizable: true,\n allowOverlap: false,\n isDroppable: false,\n useCSSTransforms: true,\n transformScale: 1,\n verticalCompact: true,\n compactType: \"vertical\",\n preventCollision: false,\n droppingItem: {\n i: \"__dropping-elem__\",\n h: 1,\n w: 1\n },\n resizeHandles: [\"se\"],\n onLayoutChange: _utils.noop,\n onDragStart: _utils.noop,\n onDrag: _utils.noop,\n onDragStop: _utils.noop,\n onResizeStart: _utils.noop,\n onResize: _utils.noop,\n onResizeStop: _utils.noop,\n onDrop: _utils.noop,\n onDropDragOver: _utils.noop\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.resizeHandleType = exports.resizeHandleAxesType = exports.default = void 0;\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _react = _interopRequireDefault(require(\"react\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n/*:: import type {\n Ref,\n ChildrenArray as ReactChildrenArray,\n Element as ReactElement\n} from \"react\";*/\n/*:: import type {\n DragOverEvent,\n EventCallback,\n CompactType,\n Layout,\n LayoutItem,\n ResizeHandleAxis\n} from \"./utils\";*/\n/*:: export type ReactRef = {|\n +current: T | null\n|};*/\n// util\n/*:: export type ResizeHandle =\n | ReactElement\n | ((\n resizeHandleAxis: ResizeHandleAxis,\n ref: ReactRef\n ) => ReactElement);*/\n// Defines which resize handles should be rendered (default: 'se')\n// Allows for any combination of:\n// 's' - South handle (bottom-center)\n// 'w' - West handle (left-center)\n// 'e' - East handle (right-center)\n// 'n' - North handle (top-center)\n// 'sw' - Southwest handle (bottom-left)\n// 'nw' - Northwest handle (top-left)\n// 'se' - Southeast handle (bottom-right)\n// 'ne' - Northeast handle (top-right)\nconst resizeHandleAxesType /*: ReactPropsChainableTypeChecker*/ = exports.resizeHandleAxesType = _propTypes.default.arrayOf(_propTypes.default.oneOf([\"s\", \"w\", \"e\", \"n\", \"sw\", \"nw\", \"se\", \"ne\"]));\n// Custom component for resize handles\nconst resizeHandleType /*: ReactPropsChainableTypeChecker*/ = exports.resizeHandleType = _propTypes.default.oneOfType([_propTypes.default.node, _propTypes.default.func]);\n/*:: export type Props = {|\n className: string,\n style: Object,\n width: number,\n autoSize: boolean,\n cols: number,\n draggableCancel: string,\n draggableHandle: string,\n verticalCompact: boolean,\n compactType: CompactType,\n layout: Layout,\n margin: [number, number],\n containerPadding: ?[number, number],\n rowHeight: number,\n maxRows: number,\n isBounded: boolean,\n isDraggable: boolean,\n isResizable: boolean,\n isDroppable: boolean,\n preventCollision: boolean,\n useCSSTransforms: boolean,\n transformScale: number,\n droppingItem: $Shape,\n resizeHandles: ResizeHandleAxis[],\n resizeHandle?: ResizeHandle,\n allowOverlap: boolean,\n\n // Callbacks\n onLayoutChange: Layout => void,\n onDrag: EventCallback,\n onDragStart: EventCallback,\n onDragStop: EventCallback,\n onResize: EventCallback,\n onResizeStart: EventCallback,\n onResizeStop: EventCallback,\n onDropDragOver: (e: DragOverEvent) => ?({| w?: number, h?: number |} | false),\n onDrop: (layout: Layout, item: ?LayoutItem, e: Event) => void,\n children: ReactChildrenArray>,\n innerRef?: Ref<\"div\">\n|};*/\n/*:: export type DefaultProps = $Diff<\n Props,\n {\n children: ReactChildrenArray>,\n width: number\n }\n>;*/\nvar _default = exports.default = {\n //\n // Basic props\n //\n className: _propTypes.default.string,\n style: _propTypes.default.object,\n // This can be set explicitly. If it is not set, it will automatically\n // be set to the container width. Note that resizes will *not* cause this to adjust.\n // If you need that behavior, use WidthProvider.\n width: _propTypes.default.number,\n // If true, the container height swells and contracts to fit contents\n autoSize: _propTypes.default.bool,\n // # of cols.\n cols: _propTypes.default.number,\n // A selector that will not be draggable.\n draggableCancel: _propTypes.default.string,\n // A selector for the draggable handler\n draggableHandle: _propTypes.default.string,\n // Deprecated\n verticalCompact: function (props /*: Props*/) {\n if (props.verticalCompact === false && process.env.NODE_ENV !== \"production\") {\n console.warn(\n // eslint-disable-line no-console\n \"`verticalCompact` on is deprecated and will be removed soon. \" + 'Use `compactType`: \"horizontal\" | \"vertical\" | null.');\n }\n },\n // Choose vertical or hotizontal compaction\n compactType: (_propTypes.default.oneOf([\"vertical\", \"horizontal\"]) /*: ReactPropsChainableTypeChecker*/),\n // layout is an array of object with the format:\n // {x: Number, y: Number, w: Number, h: Number, i: String}\n layout: function (props /*: Props*/) {\n var layout = props.layout;\n // I hope you're setting the data-grid property on the grid items\n if (layout === undefined) return;\n require(\"./utils\").validateLayout(layout, \"layout\");\n },\n //\n // Grid Dimensions\n //\n\n // Margin between items [x, y] in px\n margin: (_propTypes.default.arrayOf(_propTypes.default.number) /*: ReactPropsChainableTypeChecker*/),\n // Padding inside the container [x, y] in px\n containerPadding: (_propTypes.default.arrayOf(_propTypes.default.number) /*: ReactPropsChainableTypeChecker*/),\n // Rows have a static height, but you can change this based on breakpoints if you like\n rowHeight: _propTypes.default.number,\n // Default Infinity, but you can specify a max here if you like.\n // Note that this isn't fully fleshed out and won't error if you specify a layout that\n // extends beyond the row capacity. It will, however, not allow users to drag/resize\n // an item past the barrier. They can push items beyond the barrier, though.\n // Intentionally not documented for this reason.\n maxRows: _propTypes.default.number,\n //\n // Flags\n //\n isBounded: _propTypes.default.bool,\n isDraggable: _propTypes.default.bool,\n isResizable: _propTypes.default.bool,\n // If true, grid can be placed one over the other.\n allowOverlap: _propTypes.default.bool,\n // If true, grid items won't change position when being dragged over.\n preventCollision: _propTypes.default.bool,\n // Use CSS transforms instead of top/left\n useCSSTransforms: _propTypes.default.bool,\n // parent layout transform scale\n transformScale: _propTypes.default.number,\n // If true, an external element can trigger onDrop callback with a specific grid position as a parameter\n isDroppable: _propTypes.default.bool,\n // Resize handle options\n resizeHandles: resizeHandleAxesType,\n resizeHandle: resizeHandleType,\n //\n // Callbacks\n //\n\n // Callback so you can save the layout. Calls after each drag & resize stops.\n onLayoutChange: _propTypes.default.func,\n // Calls when drag starts. Callback is of the signature (layout, oldItem, newItem, placeholder, e, ?node).\n // All callbacks below have the same signature. 'start' and 'stop' callbacks omit the 'placeholder'.\n onDragStart: _propTypes.default.func,\n // Calls on each drag movement.\n onDrag: _propTypes.default.func,\n // Calls when drag is complete.\n onDragStop: _propTypes.default.func,\n //Calls when resize starts.\n onResizeStart: _propTypes.default.func,\n // Calls when resize movement happens.\n onResize: _propTypes.default.func,\n // Calls when resize is complete.\n onResizeStop: _propTypes.default.func,\n // Calls when some element is dropped.\n onDrop: _propTypes.default.func,\n //\n // Other validations\n //\n\n droppingItem: (_propTypes.default.shape({\n i: _propTypes.default.string.isRequired,\n w: _propTypes.default.number.isRequired,\n h: _propTypes.default.number.isRequired\n }) /*: ReactPropsChainableTypeChecker*/),\n // Children must not have duplicate keys.\n children: function (props /*: Props*/, propName /*: string*/) {\n const children = props[propName];\n\n // Check children keys for duplicates. Throw if found.\n const keys = {};\n _react.default.Children.forEach(children, function (child) {\n if (child?.key == null) return;\n if (keys[child.key]) {\n throw new Error('Duplicate child key \"' + child.key + '\" found! This will cause problems in ReactGridLayout.');\n }\n keys[child.key] = true;\n });\n },\n // Optional ref for getting a reference for the wrapping div.\n innerRef: _propTypes.default.any\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _fastEquals = require(\"fast-equals\");\nvar _utils = require(\"./utils\");\nvar _responsiveUtils = require(\"./responsiveUtils\");\nvar _ReactGridLayout = _interopRequireDefault(require(\"./ReactGridLayout\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); } /*:: import { type Layout, type Pick } from \"./utils\";*/ /*:: import { type ResponsiveLayout, type OnLayoutChangeCallback, type Breakpoints } from \"./responsiveUtils\";*/\n// $FlowFixMe[method-unbinding]\nconst type = obj => Object.prototype.toString.call(obj);\n\n/**\n * Get a value of margin or containerPadding.\n *\n * @param {Array | Object} param Margin | containerPadding, e.g. [10, 10] | {lg: [10, 10], ...}.\n * @param {String} breakpoint Breakpoint: lg, md, sm, xs and etc.\n * @return {Array}\n */\nfunction getIndentationValue /*:: */(param /*: { [key: string]: T } | T*/, breakpoint /*: string*/) /*: T*/{\n // $FlowIgnore TODO fix this typedef\n if (param == null) return null;\n // $FlowIgnore TODO fix this typedef\n return Array.isArray(param) ? param : param[breakpoint];\n}\n/*:: type State = {\n layout: Layout,\n breakpoint: string,\n cols: number,\n layouts?: ResponsiveLayout\n};*/\n/*:: type Props = {|\n ...React.ElementConfig,\n\n // Responsive config\n breakpoint?: ?Breakpoint,\n breakpoints: Breakpoints,\n cols: { [key: Breakpoint]: number },\n layouts: ResponsiveLayout,\n width: number,\n margin: { [key: Breakpoint]: [number, number] } | [number, number],\n /* prettier-ignore *-/\n containerPadding: { [key: Breakpoint]: ?[number, number] } | ?[number, number],\n\n // Callbacks\n onBreakpointChange: (Breakpoint, cols: number) => void,\n onLayoutChange: OnLayoutChangeCallback,\n onWidthChange: (\n containerWidth: number,\n margin: [number, number],\n cols: number,\n containerPadding: ?[number, number]\n ) => void\n|};*/\n/*:: type DefaultProps = Pick<\n Props<>,\n {|\n allowOverlap: 0,\n breakpoints: 0,\n cols: 0,\n containerPadding: 0,\n layouts: 0,\n margin: 0,\n onBreakpointChange: 0,\n onLayoutChange: 0,\n onWidthChange: 0\n |}\n>;*/\nclass ResponsiveReactGridLayout extends React.Component\n/*:: <\n Props<>,\n State\n>*/\n{\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", this.generateInitialState());\n // wrap layouts so we do not need to pass layouts to child\n _defineProperty(this, \"onLayoutChange\", (layout /*: Layout*/) => {\n this.props.onLayoutChange(layout, {\n ...this.props.layouts,\n [this.state.breakpoint]: layout\n });\n });\n }\n generateInitialState() /*: State*/{\n const {\n width,\n breakpoints,\n layouts,\n cols\n } = this.props;\n const breakpoint = (0, _responsiveUtils.getBreakpointFromWidth)(breakpoints, width);\n const colNo = (0, _responsiveUtils.getColsFromBreakpoint)(breakpoint, cols);\n // verticalCompact compatibility, now deprecated\n const compactType = this.props.verticalCompact === false ? null : this.props.compactType;\n // Get the initial layout. This can tricky; we try to generate one however possible if one doesn't exist\n // for this layout.\n const initialLayout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(layouts, breakpoints, breakpoint, breakpoint, colNo, compactType);\n return {\n layout: initialLayout,\n breakpoint: breakpoint,\n cols: colNo\n };\n }\n static getDerivedStateFromProps(nextProps /*: Props<*>*/, prevState /*: State*/) /*: ?$Shape*/{\n if (!(0, _fastEquals.deepEqual)(nextProps.layouts, prevState.layouts)) {\n // Allow parent to set layouts directly.\n const {\n breakpoint,\n cols\n } = prevState;\n\n // Since we're setting an entirely new layout object, we must generate a new responsive layout\n // if one does not exist.\n const newLayout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(nextProps.layouts, nextProps.breakpoints, breakpoint, breakpoint, cols, nextProps.compactType);\n return {\n layout: newLayout,\n layouts: nextProps.layouts\n };\n }\n return null;\n }\n componentDidUpdate(prevProps /*: Props<*>*/) {\n // Allow parent to set width or breakpoint directly.\n if (this.props.width != prevProps.width || this.props.breakpoint !== prevProps.breakpoint || !(0, _fastEquals.deepEqual)(this.props.breakpoints, prevProps.breakpoints) || !(0, _fastEquals.deepEqual)(this.props.cols, prevProps.cols)) {\n this.onWidthChange(prevProps);\n }\n }\n /**\n * When the width changes work through breakpoints and reset state with the new width & breakpoint.\n * Width changes are necessary to figure out the widget widths.\n */\n onWidthChange(prevProps /*: Props<*>*/) {\n const {\n breakpoints,\n cols,\n layouts,\n compactType\n } = this.props;\n const newBreakpoint = this.props.breakpoint || (0, _responsiveUtils.getBreakpointFromWidth)(this.props.breakpoints, this.props.width);\n const lastBreakpoint = this.state.breakpoint;\n const newCols /*: number*/ = (0, _responsiveUtils.getColsFromBreakpoint)(newBreakpoint, cols);\n const newLayouts = {\n ...layouts\n };\n\n // Breakpoint change\n if (lastBreakpoint !== newBreakpoint || prevProps.breakpoints !== breakpoints || prevProps.cols !== cols) {\n // Preserve the current layout if the current breakpoint is not present in the next layouts.\n if (!(lastBreakpoint in newLayouts)) newLayouts[lastBreakpoint] = (0, _utils.cloneLayout)(this.state.layout);\n\n // Find or generate a new layout.\n let layout = (0, _responsiveUtils.findOrGenerateResponsiveLayout)(newLayouts, breakpoints, newBreakpoint, lastBreakpoint, newCols, compactType);\n\n // This adds missing items.\n layout = (0, _utils.synchronizeLayoutWithChildren)(layout, this.props.children, newCols, compactType, this.props.allowOverlap);\n\n // Store the new layout.\n newLayouts[newBreakpoint] = layout;\n\n // callbacks\n this.props.onBreakpointChange(newBreakpoint, newCols);\n this.props.onLayoutChange(layout, newLayouts);\n this.setState({\n breakpoint: newBreakpoint,\n layout: layout,\n cols: newCols\n });\n }\n const margin = getIndentationValue(this.props.margin, newBreakpoint);\n const containerPadding = getIndentationValue(this.props.containerPadding, newBreakpoint);\n\n //call onWidthChange on every change of width, not only on breakpoint changes\n this.props.onWidthChange(this.props.width, margin, newCols, containerPadding);\n }\n render() /*: React.Element*/{\n /* eslint-disable no-unused-vars */\n const {\n breakpoint,\n breakpoints,\n cols,\n layouts,\n margin,\n containerPadding,\n onBreakpointChange,\n onLayoutChange,\n onWidthChange,\n ...other\n } = this.props;\n /* eslint-enable no-unused-vars */\n\n return /*#__PURE__*/React.createElement(_ReactGridLayout.default, _extends({}, other, {\n // $FlowIgnore should allow nullable here due to DefaultProps\n margin: getIndentationValue(margin, this.state.breakpoint),\n containerPadding: getIndentationValue(containerPadding, this.state.breakpoint),\n onLayoutChange: this.onLayoutChange,\n layout: this.state.layout,\n cols: this.state.cols\n }));\n }\n}\nexports.default = ResponsiveReactGridLayout;\n// This should only include propTypes needed in this code; RGL itself\n// will do validation of the rest props passed to it.\n_defineProperty(ResponsiveReactGridLayout, \"propTypes\", {\n //\n // Basic props\n //\n\n // Optional, but if you are managing width yourself you may want to set the breakpoint\n // yourself as well.\n breakpoint: _propTypes.default.string,\n // {name: pxVal}, e.g. {lg: 1200, md: 996, sm: 768, xs: 480}\n breakpoints: _propTypes.default.object,\n allowOverlap: _propTypes.default.bool,\n // # of cols. This is a breakpoint -> cols map\n cols: _propTypes.default.object,\n // # of margin. This is a breakpoint -> margin map\n // e.g. { lg: [5, 5], md: [10, 10], sm: [15, 15] }\n // Margin between items [x, y] in px\n // e.g. [10, 10]\n margin: _propTypes.default.oneOfType([_propTypes.default.array, _propTypes.default.object]),\n // # of containerPadding. This is a breakpoint -> containerPadding map\n // e.g. { lg: [5, 5], md: [10, 10], sm: [15, 15] }\n // Padding inside the container [x, y] in px\n // e.g. [10, 10]\n containerPadding: _propTypes.default.oneOfType([_propTypes.default.array, _propTypes.default.object]),\n // layouts is an object mapping breakpoints to layouts.\n // e.g. {lg: Layout, md: Layout, ...}\n layouts(props /*: Props<>*/, propName /*: string*/) {\n if (type(props[propName]) !== \"[object Object]\") {\n throw new Error(\"Layout property must be an object. Received: \" + type(props[propName]));\n }\n Object.keys(props[propName]).forEach(key => {\n if (!(key in props.breakpoints)) {\n throw new Error(\"Each key in layouts must align with a key in breakpoints.\");\n }\n (0, _utils.validateLayout)(props.layouts[key], \"layouts.\" + key);\n });\n },\n // The width of this component.\n // Required in this propTypes stanza because generateInitialState() will fail without it.\n width: _propTypes.default.number.isRequired,\n //\n // Callbacks\n //\n\n // Calls back with breakpoint and new # cols\n onBreakpointChange: _propTypes.default.func,\n // Callback so you can save the layout.\n // Calls back with (currentLayout, allLayouts). allLayouts are keyed by breakpoint.\n onLayoutChange: _propTypes.default.func,\n // Calls back with (containerWidth, margin, cols, containerPadding)\n onWidthChange: _propTypes.default.func\n});\n_defineProperty(ResponsiveReactGridLayout, \"defaultProps\", {\n breakpoints: {\n lg: 1200,\n md: 996,\n sm: 768,\n xs: 480,\n xxs: 0\n },\n cols: {\n lg: 12,\n md: 10,\n sm: 6,\n xs: 4,\n xxs: 2\n },\n containerPadding: {\n lg: null,\n md: null,\n sm: null,\n xs: null,\n xxs: null\n },\n layouts: {},\n margin: [10, 10],\n allowOverlap: false,\n onBreakpointChange: _utils.noop,\n onLayoutChange: _utils.noop,\n onWidthChange: _utils.noop\n});","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.calcGridColWidth = calcGridColWidth;\nexports.calcGridItemPosition = calcGridItemPosition;\nexports.calcGridItemWHPx = calcGridItemWHPx;\nexports.calcWH = calcWH;\nexports.calcXY = calcXY;\nexports.clamp = clamp;\n/*:: import type { Position } from \"./utils\";*/\n/*:: export type PositionParams = {\n margin: [number, number],\n containerPadding: [number, number],\n containerWidth: number,\n cols: number,\n rowHeight: number,\n maxRows: number\n};*/\n// Helper for generating column width\nfunction calcGridColWidth(positionParams /*: PositionParams*/) /*: number*/{\n const {\n margin,\n containerPadding,\n containerWidth,\n cols\n } = positionParams;\n return (containerWidth - margin[0] * (cols - 1) - containerPadding[0] * 2) / cols;\n}\n\n// This can either be called:\n// calcGridItemWHPx(w, colWidth, margin[0])\n// or\n// calcGridItemWHPx(h, rowHeight, margin[1])\nfunction calcGridItemWHPx(gridUnits /*: number*/, colOrRowSize /*: number*/, marginPx /*: number*/) /*: number*/{\n // 0 * Infinity === NaN, which causes problems with resize contraints\n if (!Number.isFinite(gridUnits)) return gridUnits;\n return Math.round(colOrRowSize * gridUnits + Math.max(0, gridUnits - 1) * marginPx);\n}\n\n/**\n * Return position on the page given an x, y, w, h.\n * left, top, width, height are all in pixels.\n * @param {PositionParams} positionParams Parameters of grid needed for coordinates calculations.\n * @param {Number} x X coordinate in grid units.\n * @param {Number} y Y coordinate in grid units.\n * @param {Number} w W coordinate in grid units.\n * @param {Number} h H coordinate in grid units.\n * @return {Position} Object containing coords.\n */\nfunction calcGridItemPosition(positionParams /*: PositionParams*/, x /*: number*/, y /*: number*/, w /*: number*/, h /*: number*/, state /*: ?Object*/) /*: Position*/{\n const {\n margin,\n containerPadding,\n rowHeight\n } = positionParams;\n const colWidth = calcGridColWidth(positionParams);\n const out = {};\n\n // If resizing, use the exact width and height as returned from resizing callbacks.\n if (state && state.resizing) {\n out.width = Math.round(state.resizing.width);\n out.height = Math.round(state.resizing.height);\n }\n // Otherwise, calculate from grid units.\n else {\n out.width = calcGridItemWHPx(w, colWidth, margin[0]);\n out.height = calcGridItemWHPx(h, rowHeight, margin[1]);\n }\n\n // If dragging, use the exact width and height as returned from dragging callbacks.\n if (state && state.dragging) {\n out.top = Math.round(state.dragging.top);\n out.left = Math.round(state.dragging.left);\n } else if (state && state.resizing && typeof state.resizing.top === \"number\" && typeof state.resizing.left === \"number\") {\n out.top = Math.round(state.resizing.top);\n out.left = Math.round(state.resizing.left);\n }\n // Otherwise, calculate from grid units.\n else {\n out.top = Math.round((rowHeight + margin[1]) * y + containerPadding[1]);\n out.left = Math.round((colWidth + margin[0]) * x + containerPadding[0]);\n }\n return out;\n}\n\n/**\n * Translate x and y coordinates from pixels to grid units.\n * @param {PositionParams} positionParams Parameters of grid needed for coordinates calculations.\n * @param {Number} top Top position (relative to parent) in pixels.\n * @param {Number} left Left position (relative to parent) in pixels.\n * @param {Number} w W coordinate in grid units.\n * @param {Number} h H coordinate in grid units.\n * @return {Object} x and y in grid units.\n */\nfunction calcXY(positionParams /*: PositionParams*/, top /*: number*/, left /*: number*/, w /*: number*/, h /*: number*/) /*: { x: number, y: number }*/{\n const {\n margin,\n containerPadding,\n cols,\n rowHeight,\n maxRows\n } = positionParams;\n const colWidth = calcGridColWidth(positionParams);\n\n // left = containerPaddingX + x * (colWidth + marginX)\n // x * (colWidth + marginX) = left - containerPaddingX\n // x = (left - containerPaddingX) / (colWidth + marginX)\n let x = Math.round((left - containerPadding[0]) / (colWidth + margin[0]));\n let y = Math.round((top - containerPadding[1]) / (rowHeight + margin[1]));\n\n // Capping\n x = clamp(x, 0, cols - w);\n y = clamp(y, 0, maxRows - h);\n return {\n x,\n y\n };\n}\n\n/**\n * Given a height and width in pixel values, calculate grid units.\n * @param {PositionParams} positionParams Parameters of grid needed for coordinates calcluations.\n * @param {Number} height Height in pixels.\n * @param {Number} width Width in pixels.\n * @param {Number} x X coordinate in grid units.\n * @param {Number} y Y coordinate in grid units.\n * @param {String} handle Resize Handle.\n * @return {Object} w, h as grid units.\n */\nfunction calcWH(positionParams /*: PositionParams*/, width /*: number*/, height /*: number*/, x /*: number*/, y /*: number*/, handle /*: string*/) /*: { w: number, h: number }*/{\n const {\n margin,\n maxRows,\n cols,\n rowHeight\n } = positionParams;\n const colWidth = calcGridColWidth(positionParams);\n\n // width = colWidth * w - (margin * (w - 1))\n // ...\n // w = (width + margin) / (colWidth + margin)\n let w = Math.round((width + margin[0]) / (colWidth + margin[0]));\n let h = Math.round((height + margin[1]) / (rowHeight + margin[1]));\n\n // Capping\n let _w = clamp(w, 0, cols - x);\n let _h = clamp(h, 0, maxRows - y);\n if ([\"sw\", \"w\", \"nw\"].indexOf(handle) !== -1) {\n _w = clamp(w, 0, cols);\n }\n if ([\"nw\", \"n\", \"ne\"].indexOf(handle) !== -1) {\n _h = clamp(h, 0, maxRows);\n }\n return {\n w: _w,\n h: _h\n };\n}\n\n// Similar to _.clamp\nfunction clamp(num /*: number*/, lowerBound /*: number*/, upperBound /*: number*/) /*: number*/{\n return Math.max(Math.min(num, upperBound), lowerBound);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = WidthProvideRGL;\nvar React = _interopRequireWildcard(require(\"react\"));\nvar _propTypes = _interopRequireDefault(require(\"prop-types\"));\nvar _resizeObserverPolyfill = _interopRequireDefault(require(\"resize-observer-polyfill\"));\nvar _clsx = _interopRequireDefault(require(\"clsx\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\nfunction _getRequireWildcardCache(e) { if (\"function\" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }\nfunction _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || \"object\" != typeof e && \"function\" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if (\"default\" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }\nfunction _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*:: import type { ReactRef } from \"../ReactGridLayoutPropTypes\";*/\n/*:: type WPDefaultProps = {|\n measureBeforeMount: boolean\n|};*/\n/*:: type WPProps = {|\n className?: string,\n style?: Object,\n ...WPDefaultProps\n|};*/\n// eslint-disable-next-line no-unused-vars\n/*:: type WPState = {|\n width: number\n|};*/\n/*:: type ComposedProps = {|\n ...Config,\n measureBeforeMount?: boolean,\n className?: string,\n style?: Object,\n width?: number\n|};*/\nconst layoutClassName = \"react-grid-layout\";\n\n/*\n * A simple HOC that provides facility for listening to container resizes.\n *\n * The Flow type is pretty janky here. I can't just spread `WPProps` into this returned object - I wish I could - but it triggers\n * a flow bug of some sort that causes it to stop typechecking.\n */\nfunction WidthProvideRGL /*:: */(ComposedComponent /*: React.AbstractComponent*/) /*: React.AbstractComponent>*/{\n var _class;\n return _class = class WidthProvider extends React.Component\n /*:: <\n ComposedProps,\n WPState\n >*/\n {\n constructor() {\n super(...arguments);\n _defineProperty(this, \"state\", {\n width: 1280\n });\n _defineProperty(this, \"elementRef\", /*#__PURE__*/React.createRef());\n _defineProperty(this, \"mounted\", false);\n _defineProperty(this, \"resizeObserver\", void 0);\n }\n componentDidMount() {\n this.mounted = true;\n this.resizeObserver = new _resizeObserverPolyfill.default(entries => {\n const node = this.elementRef.current;\n if (node instanceof HTMLElement) {\n const width = entries[0].contentRect.width;\n this.setState({\n width\n });\n }\n });\n const node = this.elementRef.current;\n if (node instanceof HTMLElement) {\n this.resizeObserver.observe(node);\n }\n }\n componentWillUnmount() {\n this.mounted = false;\n const node = this.elementRef.current;\n if (node instanceof HTMLElement) {\n this.resizeObserver.unobserve(node);\n }\n this.resizeObserver.disconnect();\n }\n render() {\n const {\n measureBeforeMount,\n ...rest\n } = this.props;\n if (measureBeforeMount && !this.mounted) {\n return /*#__PURE__*/React.createElement(\"div\", {\n className: (0, _clsx.default)(this.props.className, layoutClassName),\n style: this.props.style\n // $FlowIgnore ref types\n ,\n ref: this.elementRef\n });\n }\n return /*#__PURE__*/React.createElement(ComposedComponent, _extends({\n innerRef: this.elementRef\n }, rest, this.state));\n }\n }, _defineProperty(_class, \"defaultProps\", {\n measureBeforeMount: false\n }), _defineProperty(_class, \"propTypes\", {\n // If true, will not render children until mounted. Useful for getting the exact width before\n // rendering, to prevent any unsightly resizing.\n measureBeforeMount: _propTypes.default.bool\n }), _class;\n}","// this file was prevaled\nmodule.exports = function fastRGLPropsEqual(a, b, isEqualImpl) {\n if (a === b) return true;\n return a.className === b.className && isEqualImpl(a.style, b.style) && a.width === b.width && a.autoSize === b.autoSize && a.cols === b.cols && a.draggableCancel === b.draggableCancel && a.draggableHandle === b.draggableHandle && isEqualImpl(a.verticalCompact, b.verticalCompact) && isEqualImpl(a.compactType, b.compactType) && isEqualImpl(a.layout, b.layout) && isEqualImpl(a.margin, b.margin) && isEqualImpl(a.containerPadding, b.containerPadding) && a.rowHeight === b.rowHeight && a.maxRows === b.maxRows && a.isBounded === b.isBounded && a.isDraggable === b.isDraggable && a.isResizable === b.isResizable && a.allowOverlap === b.allowOverlap && a.preventCollision === b.preventCollision && a.useCSSTransforms === b.useCSSTransforms && a.transformScale === b.transformScale && a.isDroppable === b.isDroppable && isEqualImpl(a.resizeHandles, b.resizeHandles) && isEqualImpl(a.resizeHandle, b.resizeHandle) && a.onLayoutChange === b.onLayoutChange && a.onDragStart === b.onDragStart && a.onDrag === b.onDrag && a.onDragStop === b.onDragStop && a.onResizeStart === b.onResizeStart && a.onResize === b.onResize && a.onResizeStop === b.onResizeStop && a.onDrop === b.onDrop && isEqualImpl(a.droppingItem, b.droppingItem) && isEqualImpl(a.innerRef, b.innerRef);\n};","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.findOrGenerateResponsiveLayout = findOrGenerateResponsiveLayout;\nexports.getBreakpointFromWidth = getBreakpointFromWidth;\nexports.getColsFromBreakpoint = getColsFromBreakpoint;\nexports.sortBreakpoints = sortBreakpoints;\nvar _utils = require(\"./utils\");\n/*:: import type { CompactType, Layout } from \"./utils\";*/\n/*:: export type Breakpoint = string;*/\n/*:: export type DefaultBreakpoints = \"lg\" | \"md\" | \"sm\" | \"xs\" | \"xxs\";*/\n/*:: export type ResponsiveLayout = {\n +[breakpoint: T]: Layout\n};*/\n// + indicates read-only\n/*:: export type Breakpoints = {\n +[breakpoint: T]: number\n};*/\n/*:: export type OnLayoutChangeCallback = (\n Layout,\n { [key: Breakpoint]: Layout }\n) => void;*/\n/**\n * Given a width, find the highest breakpoint that matches is valid for it (width > breakpoint).\n *\n * @param {Object} breakpoints Breakpoints object (e.g. {lg: 1200, md: 960, ...})\n * @param {Number} width Screen width.\n * @return {String} Highest breakpoint that is less than width.\n */\nfunction getBreakpointFromWidth(breakpoints /*: Breakpoints*/, width /*: number*/) /*: Breakpoint*/{\n const sorted = sortBreakpoints(breakpoints);\n let matching = sorted[0];\n for (let i = 1, len = sorted.length; i < len; i++) {\n const breakpointName = sorted[i];\n if (width > breakpoints[breakpointName]) matching = breakpointName;\n }\n return matching;\n}\n\n/**\n * Given a breakpoint, get the # of cols set for it.\n * @param {String} breakpoint Breakpoint name.\n * @param {Object} cols Map of breakpoints to cols.\n * @return {Number} Number of cols.\n */\nfunction getColsFromBreakpoint(breakpoint /*: Breakpoint*/, cols /*: Breakpoints*/) /*: number*/{\n if (!cols[breakpoint]) {\n throw new Error(\"ResponsiveReactGridLayout: `cols` entry for breakpoint \" + breakpoint + \" is missing!\");\n }\n return cols[breakpoint];\n}\n\n/**\n * Given existing layouts and a new breakpoint, find or generate a new layout.\n *\n * This finds the layout above the new one and generates from it, if it exists.\n *\n * @param {Object} layouts Existing layouts.\n * @param {Array} breakpoints All breakpoints.\n * @param {String} breakpoint New breakpoint.\n * @param {String} breakpoint Last breakpoint (for fallback).\n * @param {Number} cols Column count at new breakpoint.\n * @param {Boolean} verticalCompact Whether or not to compact the layout\n * vertically.\n * @return {Array} New layout.\n */\nfunction findOrGenerateResponsiveLayout(layouts /*: ResponsiveLayout*/, breakpoints /*: Breakpoints*/, breakpoint /*: Breakpoint*/, lastBreakpoint /*: Breakpoint*/, cols /*: number*/, compactType /*: CompactType*/) /*: Layout*/{\n // If it already exists, just return it.\n if (layouts[breakpoint]) return (0, _utils.cloneLayout)(layouts[breakpoint]);\n // Find or generate the next layout\n let layout = layouts[lastBreakpoint];\n const breakpointsSorted = sortBreakpoints(breakpoints);\n const breakpointsAbove = breakpointsSorted.slice(breakpointsSorted.indexOf(breakpoint));\n for (let i = 0, len = breakpointsAbove.length; i < len; i++) {\n const b = breakpointsAbove[i];\n if (layouts[b]) {\n layout = layouts[b];\n break;\n }\n }\n layout = (0, _utils.cloneLayout)(layout || []); // clone layout so we don't modify existing items\n return (0, _utils.compact)((0, _utils.correctBounds)(layout, {\n cols: cols\n }), compactType, cols);\n}\n\n/**\n * Given breakpoints, return an array of breakpoints sorted by width. This is usually\n * e.g. ['xxs', 'xs', 'sm', ...]\n *\n * @param {Object} breakpoints Key/value pair of breakpoint names to widths.\n * @return {Array} Sorted breakpoints.\n */\nfunction sortBreakpoints(breakpoints /*: Breakpoints*/) /*: Array*/{\n const keys /*: Array*/ = Object.keys(breakpoints);\n return keys.sort(function (a, b) {\n return breakpoints[a] - breakpoints[b];\n });\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.bottom = bottom;\nexports.childrenEqual = childrenEqual;\nexports.cloneLayout = cloneLayout;\nexports.cloneLayoutItem = cloneLayoutItem;\nexports.collides = collides;\nexports.compact = compact;\nexports.compactItem = compactItem;\nexports.compactType = compactType;\nexports.correctBounds = correctBounds;\nexports.fastPositionEqual = fastPositionEqual;\nexports.fastRGLPropsEqual = void 0;\nexports.getAllCollisions = getAllCollisions;\nexports.getFirstCollision = getFirstCollision;\nexports.getLayoutItem = getLayoutItem;\nexports.getStatics = getStatics;\nexports.modifyLayout = modifyLayout;\nexports.moveElement = moveElement;\nexports.moveElementAwayFromCollision = moveElementAwayFromCollision;\nexports.noop = void 0;\nexports.perc = perc;\nexports.resizeItemInDirection = resizeItemInDirection;\nexports.setTopLeft = setTopLeft;\nexports.setTransform = setTransform;\nexports.sortLayoutItems = sortLayoutItems;\nexports.sortLayoutItemsByColRow = sortLayoutItemsByColRow;\nexports.sortLayoutItemsByRowCol = sortLayoutItemsByRowCol;\nexports.synchronizeLayoutWithChildren = synchronizeLayoutWithChildren;\nexports.validateLayout = validateLayout;\nexports.withLayoutItem = withLayoutItem;\nvar _fastEquals = require(\"fast-equals\");\nvar _react = _interopRequireDefault(require(\"react\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n/*:: import type {\n ChildrenArray as ReactChildrenArray,\n Element as ReactElement\n} from \"react\";*/\n/*:: export type ResizeHandleAxis =\n | \"s\"\n | \"w\"\n | \"e\"\n | \"n\"\n | \"sw\"\n | \"nw\"\n | \"se\"\n | \"ne\";*/\n/*:: export type LayoutItem = {\n w: number,\n h: number,\n x: number,\n y: number,\n i: string,\n minW?: number,\n minH?: number,\n maxW?: number,\n maxH?: number,\n moved?: boolean,\n static?: boolean,\n isDraggable?: ?boolean,\n isResizable?: ?boolean,\n resizeHandles?: Array,\n isBounded?: ?boolean\n};*/\n/*:: export type Layout = $ReadOnlyArray;*/\n/*:: export type Position = {\n left: number,\n top: number,\n width: number,\n height: number\n};*/\n/*:: export type ReactDraggableCallbackData = {\n node: HTMLElement,\n x?: number,\n y?: number,\n deltaX: number,\n deltaY: number,\n lastX?: number,\n lastY?: number\n};*/\n/*:: export type PartialPosition = { left: number, top: number };*/\n/*:: export type DroppingPosition = { left: number, top: number, e: Event };*/\n/*:: export type Size = { width: number, height: number };*/\n/*:: export type GridDragEvent = {\n e: Event,\n node: HTMLElement,\n newPosition: PartialPosition\n};*/\n/*:: export type GridResizeEvent = {\n e: Event,\n node: HTMLElement,\n size: Size,\n handle: string\n};*/\n/*:: export type DragOverEvent = MouseEvent & {\n nativeEvent: {\n layerX: number,\n layerY: number,\n ...Event\n }\n};*/\n/*:: export type Pick = $Exact<\n $ObjMapi(k: K, v: V) => $ElementType>\n>;*/\n// Helpful port from TS\n/*:: type REl = ReactElement;*/\n/*:: export type ReactChildren = ReactChildrenArray;*/\n/*:: export type EventCallback = (\n Layout,\n oldItem: ?LayoutItem,\n newItem: ?LayoutItem,\n placeholder: ?LayoutItem,\n Event,\n ?HTMLElement\n) => void;*/\n// All callbacks are of the signature (layout, oldItem, newItem, placeholder, e).\n/*:: export type CompactType = ?(\"horizontal\" | \"vertical\");*/\nconst isProduction = process.env.NODE_ENV === \"production\";\nconst DEBUG = false;\n\n/**\n * Return the bottom coordinate of the layout.\n *\n * @param {Array} layout Layout array.\n * @return {Number} Bottom coordinate.\n */\nfunction bottom(layout /*: Layout*/) /*: number*/{\n let max = 0,\n bottomY;\n for (let i = 0, len = layout.length; i < len; i++) {\n bottomY = layout[i].y + layout[i].h;\n if (bottomY > max) max = bottomY;\n }\n return max;\n}\nfunction cloneLayout(layout /*: Layout*/) /*: Layout*/{\n const newLayout = Array(layout.length);\n for (let i = 0, len = layout.length; i < len; i++) {\n newLayout[i] = cloneLayoutItem(layout[i]);\n }\n return newLayout;\n}\n\n// Modify a layoutItem inside a layout. Returns a new Layout,\n// does not mutate. Carries over all other LayoutItems unmodified.\nfunction modifyLayout(layout /*: Layout*/, layoutItem /*: LayoutItem*/) /*: Layout*/{\n const newLayout = Array(layout.length);\n for (let i = 0, len = layout.length; i < len; i++) {\n if (layoutItem.i === layout[i].i) {\n newLayout[i] = layoutItem;\n } else {\n newLayout[i] = layout[i];\n }\n }\n return newLayout;\n}\n\n// Function to be called to modify a layout item.\n// Does defensive clones to ensure the layout is not modified.\nfunction withLayoutItem(layout /*: Layout*/, itemKey /*: string*/, cb /*: LayoutItem => LayoutItem*/) /*: [Layout, ?LayoutItem]*/{\n let item = getLayoutItem(layout, itemKey);\n if (!item) return [layout, null];\n item = cb(cloneLayoutItem(item)); // defensive clone then modify\n // FIXME could do this faster if we already knew the index\n layout = modifyLayout(layout, item);\n return [layout, item];\n}\n\n// Fast path to cloning, since this is monomorphic\nfunction cloneLayoutItem(layoutItem /*: LayoutItem*/) /*: LayoutItem*/{\n return {\n w: layoutItem.w,\n h: layoutItem.h,\n x: layoutItem.x,\n y: layoutItem.y,\n i: layoutItem.i,\n minW: layoutItem.minW,\n maxW: layoutItem.maxW,\n minH: layoutItem.minH,\n maxH: layoutItem.maxH,\n moved: Boolean(layoutItem.moved),\n static: Boolean(layoutItem.static),\n // These can be null/undefined\n isDraggable: layoutItem.isDraggable,\n isResizable: layoutItem.isResizable,\n resizeHandles: layoutItem.resizeHandles,\n isBounded: layoutItem.isBounded\n };\n}\n\n/**\n * Comparing React `children` is a bit difficult. This is a good way to compare them.\n * This will catch differences in keys, order, and length.\n */\nfunction childrenEqual(a /*: ReactChildren*/, b /*: ReactChildren*/) /*: boolean*/{\n return (0, _fastEquals.deepEqual)(_react.default.Children.map(a, c => c?.key), _react.default.Children.map(b, c => c?.key)) && (0, _fastEquals.deepEqual)(_react.default.Children.map(a, c => c?.props[\"data-grid\"]), _react.default.Children.map(b, c => c?.props[\"data-grid\"]));\n}\n\n/**\n * See `fastRGLPropsEqual.js`.\n * We want this to run as fast as possible - it is called often - and to be\n * resilient to new props that we add. So rather than call lodash.isEqual,\n * which isn't suited to comparing props very well, we use this specialized\n * function in conjunction with preval to generate the fastest possible comparison\n * function, tuned for exactly our props.\n */\n/*:: type FastRGLPropsEqual = (Object, Object, Function) => boolean;*/\nconst fastRGLPropsEqual /*: FastRGLPropsEqual*/ = exports.fastRGLPropsEqual = require(\"./fastRGLPropsEqual\");\n\n// Like the above, but a lot simpler.\nfunction fastPositionEqual(a /*: Position*/, b /*: Position*/) /*: boolean*/{\n return a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;\n}\n\n/**\n * Given two layoutitems, check if they collide.\n */\nfunction collides(l1 /*: LayoutItem*/, l2 /*: LayoutItem*/) /*: boolean*/{\n if (l1.i === l2.i) return false; // same element\n if (l1.x + l1.w <= l2.x) return false; // l1 is left of l2\n if (l1.x >= l2.x + l2.w) return false; // l1 is right of l2\n if (l1.y + l1.h <= l2.y) return false; // l1 is above l2\n if (l1.y >= l2.y + l2.h) return false; // l1 is below l2\n return true; // boxes overlap\n}\n\n/**\n * Given a layout, compact it. This involves going down each y coordinate and removing gaps\n * between items.\n *\n * Does not modify layout items (clones). Creates a new layout array.\n *\n * @param {Array} layout Layout.\n * @param {Boolean} verticalCompact Whether or not to compact the layout\n * vertically.\n * @param {Boolean} allowOverlap When `true`, allows overlapping grid items.\n * @return {Array} Compacted Layout.\n */\nfunction compact(layout /*: Layout*/, compactType /*: CompactType*/, cols /*: number*/, allowOverlap /*: ?boolean*/) /*: Layout*/{\n // Statics go in the compareWith array right away so items flow around them.\n const compareWith = getStatics(layout);\n // We go through the items by row and column.\n const sorted = sortLayoutItems(layout, compactType);\n // Holding for new items.\n const out = Array(layout.length);\n for (let i = 0, len = sorted.length; i < len; i++) {\n let l = cloneLayoutItem(sorted[i]);\n\n // Don't move static elements\n if (!l.static) {\n l = compactItem(compareWith, l, compactType, cols, sorted, allowOverlap);\n\n // Add to comparison array. We only collide with items before this one.\n // Statics are already in this array.\n compareWith.push(l);\n }\n\n // Add to output array to make sure they still come out in the right order.\n out[layout.indexOf(sorted[i])] = l;\n\n // Clear moved flag, if it exists.\n l.moved = false;\n }\n return out;\n}\nconst heightWidth = {\n x: \"w\",\n y: \"h\"\n};\n/**\n * Before moving item down, it will check if the movement will cause collisions and move those items down before.\n */\nfunction resolveCompactionCollision(layout /*: Layout*/, item /*: LayoutItem*/, moveToCoord /*: number*/, axis /*: \"x\" | \"y\"*/) {\n const sizeProp = heightWidth[axis];\n item[axis] += 1;\n const itemIndex = layout.map(layoutItem => {\n return layoutItem.i;\n }).indexOf(item.i);\n\n // Go through each item we collide with.\n for (let i = itemIndex + 1; i < layout.length; i++) {\n const otherItem = layout[i];\n // Ignore static items\n if (otherItem.static) continue;\n\n // Optimization: we can break early if we know we're past this el\n // We can do this b/c it's a sorted layout\n if (otherItem.y > item.y + item.h) break;\n if (collides(item, otherItem)) {\n resolveCompactionCollision(layout, otherItem, moveToCoord + item[sizeProp], axis);\n }\n }\n item[axis] = moveToCoord;\n}\n\n/**\n * Compact an item in the layout.\n *\n * Modifies item.\n *\n */\nfunction compactItem(compareWith /*: Layout*/, l /*: LayoutItem*/, compactType /*: CompactType*/, cols /*: number*/, fullLayout /*: Layout*/, allowOverlap /*: ?boolean*/) /*: LayoutItem*/{\n const compactV = compactType === \"vertical\";\n const compactH = compactType === \"horizontal\";\n if (compactV) {\n // Bottom 'y' possible is the bottom of the layout.\n // This allows you to do nice stuff like specify {y: Infinity}\n // This is here because the layout must be sorted in order to get the correct bottom `y`.\n l.y = Math.min(bottom(compareWith), l.y);\n // Move the element up as far as it can go without colliding.\n while (l.y > 0 && !getFirstCollision(compareWith, l)) {\n l.y--;\n }\n } else if (compactH) {\n // Move the element left as far as it can go without colliding.\n while (l.x > 0 && !getFirstCollision(compareWith, l)) {\n l.x--;\n }\n }\n\n // Move it down, and keep moving it down if it's colliding.\n let collides;\n // Checking the compactType null value to avoid breaking the layout when overlapping is allowed.\n while ((collides = getFirstCollision(compareWith, l)) && !(compactType === null && allowOverlap)) {\n if (compactH) {\n resolveCompactionCollision(fullLayout, l, collides.x + collides.w, \"x\");\n } else {\n resolveCompactionCollision(fullLayout, l, collides.y + collides.h, \"y\");\n }\n // Since we can't grow without bounds horizontally, if we've overflown, let's move it down and try again.\n if (compactH && l.x + l.w > cols) {\n l.x = cols - l.w;\n l.y++;\n // ALso move element as left as we can\n while (l.x > 0 && !getFirstCollision(compareWith, l)) {\n l.x--;\n }\n }\n }\n\n // Ensure that there are no negative positions\n l.y = Math.max(l.y, 0);\n l.x = Math.max(l.x, 0);\n return l;\n}\n\n/**\n * Given a layout, make sure all elements fit within its bounds.\n *\n * Modifies layout items.\n *\n * @param {Array} layout Layout array.\n * @param {Number} bounds Number of columns.\n */\nfunction correctBounds(layout /*: Layout*/, bounds /*: { cols: number }*/) /*: Layout*/{\n const collidesWith = getStatics(layout);\n for (let i = 0, len = layout.length; i < len; i++) {\n const l = layout[i];\n // Overflows right\n if (l.x + l.w > bounds.cols) l.x = bounds.cols - l.w;\n // Overflows left\n if (l.x < 0) {\n l.x = 0;\n l.w = bounds.cols;\n }\n if (!l.static) collidesWith.push(l);else {\n // If this is static and collides with other statics, we must move it down.\n // We have to do something nicer than just letting them overlap.\n while (getFirstCollision(collidesWith, l)) {\n l.y++;\n }\n }\n }\n return layout;\n}\n\n/**\n * Get a layout item by ID. Used so we can override later on if necessary.\n *\n * @param {Array} layout Layout array.\n * @param {String} id ID\n * @return {LayoutItem} Item at ID.\n */\nfunction getLayoutItem(layout /*: Layout*/, id /*: string*/) /*: ?LayoutItem*/{\n for (let i = 0, len = layout.length; i < len; i++) {\n if (layout[i].i === id) return layout[i];\n }\n}\n\n/**\n * Returns the first item this layout collides with.\n * It doesn't appear to matter which order we approach this from, although\n * perhaps that is the wrong thing to do.\n *\n * @param {Object} layoutItem Layout item.\n * @return {Object|undefined} A colliding layout item, or undefined.\n */\nfunction getFirstCollision(layout /*: Layout*/, layoutItem /*: LayoutItem*/) /*: ?LayoutItem*/{\n for (let i = 0, len = layout.length; i < len; i++) {\n if (collides(layout[i], layoutItem)) return layout[i];\n }\n}\nfunction getAllCollisions(layout /*: Layout*/, layoutItem /*: LayoutItem*/) /*: Array*/{\n return layout.filter(l => collides(l, layoutItem));\n}\n\n/**\n * Get all static elements.\n * @param {Array} layout Array of layout objects.\n * @return {Array} Array of static layout items..\n */\nfunction getStatics(layout /*: Layout*/) /*: Array*/{\n return layout.filter(l => l.static);\n}\n\n/**\n * Move an element. Responsible for doing cascading movements of other elements.\n *\n * Modifies layout items.\n *\n * @param {Array} layout Full layout to modify.\n * @param {LayoutItem} l element to move.\n * @param {Number} [x] X position in grid units.\n * @param {Number} [y] Y position in grid units.\n */\nfunction moveElement(layout /*: Layout*/, l /*: LayoutItem*/, x /*: ?number*/, y /*: ?number*/, isUserAction /*: ?boolean*/, preventCollision /*: ?boolean*/, compactType /*: CompactType*/, cols /*: number*/, allowOverlap /*: ?boolean*/) /*: Layout*/{\n // If this is static and not explicitly enabled as draggable,\n // no move is possible, so we can short-circuit this immediately.\n if (l.static && l.isDraggable !== true) return layout;\n\n // Short-circuit if nothing to do.\n if (l.y === y && l.x === x) return layout;\n log(`Moving element ${l.i} to [${String(x)},${String(y)}] from [${l.x},${l.y}]`);\n const oldX = l.x;\n const oldY = l.y;\n\n // This is quite a bit faster than extending the object\n if (typeof x === \"number\") l.x = x;\n if (typeof y === \"number\") l.y = y;\n l.moved = true;\n\n // If this collides with anything, move it.\n // When doing this comparison, we have to sort the items we compare with\n // to ensure, in the case of multiple collisions, that we're getting the\n // nearest collision.\n let sorted = sortLayoutItems(layout, compactType);\n const movingUp = compactType === \"vertical\" && typeof y === \"number\" ? oldY >= y : compactType === \"horizontal\" && typeof x === \"number\" ? oldX >= x : false;\n // $FlowIgnore acceptable modification of read-only array as it was recently cloned\n if (movingUp) sorted = sorted.reverse();\n const collisions = getAllCollisions(sorted, l);\n const hasCollisions = collisions.length > 0;\n\n // We may have collisions. We can short-circuit if we've turned off collisions or\n // allowed overlap.\n if (hasCollisions && allowOverlap) {\n // Easy, we don't need to resolve collisions. But we *did* change the layout,\n // so clone it on the way out.\n return cloneLayout(layout);\n } else if (hasCollisions && preventCollision) {\n // If we are preventing collision but not allowing overlap, we need to\n // revert the position of this element so it goes to where it came from, rather\n // than the user's desired location.\n log(`Collision prevented on ${l.i}, reverting.`);\n l.x = oldX;\n l.y = oldY;\n l.moved = false;\n return layout; // did not change so don't clone\n }\n\n // Move each item that collides away from this element.\n for (let i = 0, len = collisions.length; i < len; i++) {\n const collision = collisions[i];\n log(`Resolving collision between ${l.i} at [${l.x},${l.y}] and ${collision.i} at [${collision.x},${collision.y}]`);\n\n // Short circuit so we can't infinite loop\n if (collision.moved) continue;\n\n // Don't move static items - we have to move *this* element away\n if (collision.static) {\n layout = moveElementAwayFromCollision(layout, collision, l, isUserAction, compactType, cols);\n } else {\n layout = moveElementAwayFromCollision(layout, l, collision, isUserAction, compactType, cols);\n }\n }\n return layout;\n}\n\n/**\n * This is where the magic needs to happen - given a collision, move an element away from the collision.\n * We attempt to move it up if there's room, otherwise it goes below.\n *\n * @param {Array} layout Full layout to modify.\n * @param {LayoutItem} collidesWith Layout item we're colliding with.\n * @param {LayoutItem} itemToMove Layout item we're moving.\n */\nfunction moveElementAwayFromCollision(layout /*: Layout*/, collidesWith /*: LayoutItem*/, itemToMove /*: LayoutItem*/, isUserAction /*: ?boolean*/, compactType /*: CompactType*/, cols /*: number*/) /*: Layout*/{\n const compactH = compactType === \"horizontal\";\n // Compact vertically if not set to horizontal\n const compactV = compactType === \"vertical\";\n const preventCollision = collidesWith.static; // we're already colliding (not for static items)\n\n // If there is enough space above the collision to put this element, move it there.\n // We only do this on the main collision as this can get funky in cascades and cause\n // unwanted swapping behavior.\n if (isUserAction) {\n // Reset isUserAction flag because we're not in the main collision anymore.\n isUserAction = false;\n\n // Make a mock item so we don't modify the item here, only modify in moveElement.\n const fakeItem /*: LayoutItem*/ = {\n x: compactH ? Math.max(collidesWith.x - itemToMove.w, 0) : itemToMove.x,\n y: compactV ? Math.max(collidesWith.y - itemToMove.h, 0) : itemToMove.y,\n w: itemToMove.w,\n h: itemToMove.h,\n i: \"-1\"\n };\n const firstCollision = getFirstCollision(layout, fakeItem);\n const collisionNorth = firstCollision && firstCollision.y + firstCollision.h > collidesWith.y;\n const collisionWest = firstCollision && collidesWith.x + collidesWith.w > firstCollision.x;\n\n // No collision? If so, we can go up there; otherwise, we'll end up moving down as normal\n if (!firstCollision) {\n log(`Doing reverse collision on ${itemToMove.i} up to [${fakeItem.x},${fakeItem.y}].`);\n return moveElement(layout, itemToMove, compactH ? fakeItem.x : undefined, compactV ? fakeItem.y : undefined, isUserAction, preventCollision, compactType, cols);\n } else if (collisionNorth && compactV) {\n return moveElement(layout, itemToMove, undefined, collidesWith.y + 1, isUserAction, preventCollision, compactType, cols);\n } else if (collisionNorth && compactType == null) {\n collidesWith.y = itemToMove.y;\n itemToMove.y = itemToMove.y + itemToMove.h;\n return layout;\n } else if (collisionWest && compactH) {\n return moveElement(layout, collidesWith, itemToMove.x, undefined, isUserAction, preventCollision, compactType, cols);\n }\n }\n const newX = compactH ? itemToMove.x + 1 : undefined;\n const newY = compactV ? itemToMove.y + 1 : undefined;\n if (newX == null && newY == null) {\n return layout;\n }\n return moveElement(layout, itemToMove, compactH ? itemToMove.x + 1 : undefined, compactV ? itemToMove.y + 1 : undefined, isUserAction, preventCollision, compactType, cols);\n}\n\n/**\n * Helper to convert a number to a percentage string.\n *\n * @param {Number} num Any number\n * @return {String} That number as a percentage.\n */\nfunction perc(num /*: number*/) /*: string*/{\n return num * 100 + \"%\";\n}\n\n/**\n * Helper functions to constrain dimensions of a GridItem\n */\nconst constrainWidth = (left /*: number*/, currentWidth /*: number*/, newWidth /*: number*/, containerWidth /*: number*/) => {\n return left + newWidth > containerWidth ? currentWidth : newWidth;\n};\nconst constrainHeight = (top /*: number*/, currentHeight /*: number*/, newHeight /*: number*/) => {\n return top < 0 ? currentHeight : newHeight;\n};\nconst constrainLeft = (left /*: number*/) => Math.max(0, left);\nconst constrainTop = (top /*: number*/) => Math.max(0, top);\nconst resizeNorth = (currentSize, _ref, _containerWidth) => {\n let {\n left,\n height,\n width\n } = _ref;\n const top = currentSize.top - (height - currentSize.height);\n return {\n left,\n width,\n height: constrainHeight(top, currentSize.height, height),\n top: constrainTop(top)\n };\n};\nconst resizeEast = (currentSize, _ref2, containerWidth) => {\n let {\n top,\n left,\n height,\n width\n } = _ref2;\n return {\n top,\n height,\n width: constrainWidth(currentSize.left, currentSize.width, width, containerWidth),\n left: constrainLeft(left)\n };\n};\nconst resizeWest = (currentSize, _ref3, containerWidth) => {\n let {\n top,\n height,\n width\n } = _ref3;\n const left = currentSize.left - (width - currentSize.width);\n return {\n height,\n width: left < 0 ? currentSize.width : constrainWidth(currentSize.left, currentSize.width, width, containerWidth),\n top: constrainTop(top),\n left: constrainLeft(left)\n };\n};\nconst resizeSouth = (currentSize, _ref4, containerWidth) => {\n let {\n top,\n left,\n height,\n width\n } = _ref4;\n return {\n width,\n left,\n height: constrainHeight(top, currentSize.height, height),\n top: constrainTop(top)\n };\n};\nconst resizeNorthEast = function () {\n return resizeNorth(arguments.length <= 0 ? undefined : arguments[0], resizeEast(...arguments), arguments.length <= 2 ? undefined : arguments[2]);\n};\nconst resizeNorthWest = function () {\n return resizeNorth(arguments.length <= 0 ? undefined : arguments[0], resizeWest(...arguments), arguments.length <= 2 ? undefined : arguments[2]);\n};\nconst resizeSouthEast = function () {\n return resizeSouth(arguments.length <= 0 ? undefined : arguments[0], resizeEast(...arguments), arguments.length <= 2 ? undefined : arguments[2]);\n};\nconst resizeSouthWest = function () {\n return resizeSouth(arguments.length <= 0 ? undefined : arguments[0], resizeWest(...arguments), arguments.length <= 2 ? undefined : arguments[2]);\n};\nconst ordinalResizeHandlerMap = {\n n: resizeNorth,\n ne: resizeNorthEast,\n e: resizeEast,\n se: resizeSouthEast,\n s: resizeSouth,\n sw: resizeSouthWest,\n w: resizeWest,\n nw: resizeNorthWest\n};\n\n/**\n * Helper for clamping width and position when resizing an item.\n */\nfunction resizeItemInDirection(direction /*: ResizeHandleAxis*/, currentSize /*: Position*/, newSize /*: Position*/, containerWidth /*: number*/) /*: Position*/{\n const ordinalHandler = ordinalResizeHandlerMap[direction];\n // Shouldn't be possible given types; that said, don't fail hard\n if (!ordinalHandler) return newSize;\n return ordinalHandler(currentSize, {\n ...currentSize,\n ...newSize\n }, containerWidth);\n}\nfunction setTransform(_ref5 /*:: */) /*: Object*/{\n let {\n top,\n left,\n width,\n height\n } /*: Position*/ = _ref5 /*: Position*/;\n // Replace unitless items with px\n const translate = `translate(${left}px,${top}px)`;\n return {\n transform: translate,\n WebkitTransform: translate,\n MozTransform: translate,\n msTransform: translate,\n OTransform: translate,\n width: `${width}px`,\n height: `${height}px`,\n position: \"absolute\"\n };\n}\nfunction setTopLeft(_ref6 /*:: */) /*: Object*/{\n let {\n top,\n left,\n width,\n height\n } /*: Position*/ = _ref6 /*: Position*/;\n return {\n top: `${top}px`,\n left: `${left}px`,\n width: `${width}px`,\n height: `${height}px`,\n position: \"absolute\"\n };\n}\n\n/**\n * Get layout items sorted from top left to right and down.\n *\n * @return {Array} Array of layout objects.\n * @return {Array} Layout, sorted static items first.\n */\nfunction sortLayoutItems(layout /*: Layout*/, compactType /*: CompactType*/) /*: Layout*/{\n if (compactType === \"horizontal\") return sortLayoutItemsByColRow(layout);\n if (compactType === \"vertical\") return sortLayoutItemsByRowCol(layout);else return layout;\n}\n\n/**\n * Sort layout items by row ascending and column ascending.\n *\n * Does not modify Layout.\n */\nfunction sortLayoutItemsByRowCol(layout /*: Layout*/) /*: Layout*/{\n // Slice to clone array as sort modifies\n return layout.slice(0).sort(function (a, b) {\n if (a.y > b.y || a.y === b.y && a.x > b.x) {\n return 1;\n } else if (a.y === b.y && a.x === b.x) {\n // Without this, we can get different sort results in IE vs. Chrome/FF\n return 0;\n }\n return -1;\n });\n}\n\n/**\n * Sort layout items by column ascending then row ascending.\n *\n * Does not modify Layout.\n */\nfunction sortLayoutItemsByColRow(layout /*: Layout*/) /*: Layout*/{\n return layout.slice(0).sort(function (a, b) {\n if (a.x > b.x || a.x === b.x && a.y > b.y) {\n return 1;\n }\n return -1;\n });\n}\n\n/**\n * Generate a layout using the initialLayout and children as a template.\n * Missing entries will be added, extraneous ones will be truncated.\n *\n * Does not modify initialLayout.\n *\n * @param {Array} initialLayout Layout passed in through props.\n * @param {String} breakpoint Current responsive breakpoint.\n * @param {?String} compact Compaction option.\n * @return {Array} Working layout.\n */\nfunction synchronizeLayoutWithChildren(initialLayout /*: Layout*/, children /*: ReactChildren*/, cols /*: number*/, compactType /*: CompactType*/, allowOverlap /*: ?boolean*/) /*: Layout*/{\n initialLayout = initialLayout || [];\n\n // Generate one layout item per child.\n const layout /*: LayoutItem[]*/ = [];\n _react.default.Children.forEach(children, (child /*: ReactElement*/) => {\n // Child may not exist\n if (child?.key == null) return;\n const exists = getLayoutItem(initialLayout, String(child.key));\n const g = child.props[\"data-grid\"];\n // Don't overwrite the layout item if it's already in the initial layout.\n // If it has a `data-grid` property, prefer that over what's in the layout.\n if (exists && g == null) {\n layout.push(cloneLayoutItem(exists));\n } else {\n // Hey, this item has a data-grid property, use it.\n if (g) {\n if (!isProduction) {\n validateLayout([g], \"ReactGridLayout.children\");\n }\n // FIXME clone not really necessary here\n layout.push(cloneLayoutItem({\n ...g,\n i: child.key\n }));\n } else {\n // Nothing provided: ensure this is added to the bottom\n // FIXME clone not really necessary here\n layout.push(cloneLayoutItem({\n w: 1,\n h: 1,\n x: 0,\n y: bottom(layout),\n i: String(child.key)\n }));\n }\n }\n });\n\n // Correct the layout.\n const correctedLayout = correctBounds(layout, {\n cols: cols\n });\n return allowOverlap ? correctedLayout : compact(correctedLayout, compactType, cols);\n}\n\n/**\n * Validate a layout. Throws errors.\n *\n * @param {Array} layout Array of layout items.\n * @param {String} [contextName] Context name for errors.\n * @throw {Error} Validation error.\n */\nfunction validateLayout(layout /*: Layout*/) /*: void*/{\n let contextName /*: string*/ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : \"Layout\";\n const subProps = [\"x\", \"y\", \"w\", \"h\"];\n if (!Array.isArray(layout)) throw new Error(contextName + \" must be an array!\");\n for (let i = 0, len = layout.length; i < len; i++) {\n const item = layout[i];\n for (let j = 0; j < subProps.length; j++) {\n const key = subProps[j];\n const value = item[key];\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n throw new Error(`ReactGridLayout: ${contextName}[${i}].${key} must be a number! Received: ${value} (${typeof value})`);\n }\n }\n if (typeof item.i !== \"undefined\" && typeof item.i !== \"string\") {\n throw new Error(`ReactGridLayout: ${contextName}[${i}].i must be a string! Received: ${item.i} (${typeof item.i})`);\n }\n }\n}\n\n// Legacy support for verticalCompact: false\nfunction compactType(props /*: ?{ verticalCompact: boolean, compactType: CompactType }*/) /*: CompactType*/{\n const {\n verticalCompact,\n compactType\n } = props || {};\n return verticalCompact === false ? null : compactType;\n}\nfunction log() {\n if (!DEBUG) return;\n // eslint-disable-next-line no-console\n console.log(...arguments);\n}\nconst noop = () => {};\nexports.noop = noop;","module.exports = require(\"./build/ReactGridLayout\").default;\nmodule.exports.utils = require(\"./build/utils\");\nmodule.exports.calculateUtils = require(\"./build/calculateUtils\");\nmodule.exports.Responsive =\n require(\"./build/ResponsiveReactGridLayout\").default;\nmodule.exports.Responsive.utils = require(\"./build/responsiveUtils\");\nmodule.exports.WidthProvider =\n require(\"./build/components/WidthProvider\").default;\n","var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nexport var styleToObject = function (input) {\n var attributes = input.split(/ ?; ?/);\n return attributes.reduce(function (acc, d) {\n var _a = __read(d.split(/ ?: ?/), 2), key = _a[0], value = _a[1];\n if (key && value) {\n acc[key.replace(/-(\\w)/g, function (_$0, $1) { return $1.toUpperCase(); })] = Number.isNaN(Number(value))\n ? value\n : Number(value);\n }\n return acc;\n }, {});\n};\n/* istanbul ignore next */\nexport function randomString(length) {\n if (length === void 0) { length = 6; }\n var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n var result = '';\n for (var index = length; index > 0; --index) {\n result += characters[Math.round(Math.random() * (characters.length - 1))];\n }\n return result;\n}\nexport var noTextChildNodes = [\n 'br',\n 'col',\n 'colgroup',\n 'dl',\n 'hr',\n 'iframe',\n 'img',\n 'input',\n 'link',\n 'menuitem',\n 'meta',\n 'ol',\n 'param',\n 'select',\n 'table',\n 'tbody',\n 'tfoot',\n 'thead',\n 'tr',\n 'ul',\n 'wbr',\n];\n/**\n * Copyright (c) 2013-present, Facebook, Inc.\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// Taken from https://raw.githubusercontent.com/facebook/react/baff5cc2f69d30589a5dc65b089e47765437294b/packages/react-dom/src/shared/possibleStandardNames.js\n// tslint:disable:object-literal-sort-keys\nexport var possibleStandardNames = {\n // HTML\n 'accept-charset': 'acceptCharset',\n acceptcharset: 'acceptCharset',\n accesskey: 'accessKey',\n allowfullscreen: 'allowFullScreen',\n autocapitalize: 'autoCapitalize',\n autocomplete: 'autoComplete',\n autocorrect: 'autoCorrect',\n autofocus: 'autoFocus',\n autoplay: 'autoPlay',\n autosave: 'autoSave',\n cellpadding: 'cellPadding',\n cellspacing: 'cellSpacing',\n charset: 'charSet',\n class: 'className',\n classid: 'classID',\n classname: 'className',\n colspan: 'colSpan',\n contenteditable: 'contentEditable',\n contextmenu: 'contextMenu',\n controlslist: 'controlsList',\n crossorigin: 'crossOrigin',\n dangerouslysetinnerhtml: 'dangerouslySetInnerHTML',\n datetime: 'dateTime',\n defaultchecked: 'defaultChecked',\n defaultvalue: 'defaultValue',\n enctype: 'encType',\n for: 'htmlFor',\n formmethod: 'formMethod',\n formaction: 'formAction',\n formenctype: 'formEncType',\n formnovalidate: 'formNoValidate',\n formtarget: 'formTarget',\n frameborder: 'frameBorder',\n hreflang: 'hrefLang',\n htmlfor: 'htmlFor',\n httpequiv: 'httpEquiv',\n 'http-equiv': 'httpEquiv',\n icon: 'icon',\n innerhtml: 'innerHTML',\n inputmode: 'inputMode',\n itemid: 'itemID',\n itemprop: 'itemProp',\n itemref: 'itemRef',\n itemscope: 'itemScope',\n itemtype: 'itemType',\n keyparams: 'keyParams',\n keytype: 'keyType',\n marginwidth: 'marginWidth',\n marginheight: 'marginHeight',\n maxlength: 'maxLength',\n mediagroup: 'mediaGroup',\n minlength: 'minLength',\n nomodule: 'noModule',\n novalidate: 'noValidate',\n playsinline: 'playsInline',\n radiogroup: 'radioGroup',\n readonly: 'readOnly',\n referrerpolicy: 'referrerPolicy',\n rowspan: 'rowSpan',\n spellcheck: 'spellCheck',\n srcdoc: 'srcDoc',\n srclang: 'srcLang',\n srcset: 'srcSet',\n tabindex: 'tabIndex',\n typemustmatch: 'typeMustMatch',\n usemap: 'useMap',\n // SVG\n accentheight: 'accentHeight',\n 'accent-height': 'accentHeight',\n alignmentbaseline: 'alignmentBaseline',\n 'alignment-baseline': 'alignmentBaseline',\n allowreorder: 'allowReorder',\n arabicform: 'arabicForm',\n 'arabic-form': 'arabicForm',\n attributename: 'attributeName',\n attributetype: 'attributeType',\n autoreverse: 'autoReverse',\n basefrequency: 'baseFrequency',\n baselineshift: 'baselineShift',\n 'baseline-shift': 'baselineShift',\n baseprofile: 'baseProfile',\n calcmode: 'calcMode',\n capheight: 'capHeight',\n 'cap-height': 'capHeight',\n clippath: 'clipPath',\n 'clip-path': 'clipPath',\n clippathunits: 'clipPathUnits',\n cliprule: 'clipRule',\n 'clip-rule': 'clipRule',\n colorinterpolation: 'colorInterpolation',\n 'color-interpolation': 'colorInterpolation',\n colorinterpolationfilters: 'colorInterpolationFilters',\n 'color-interpolation-filters': 'colorInterpolationFilters',\n colorprofile: 'colorProfile',\n 'color-profile': 'colorProfile',\n colorrendering: 'colorRendering',\n 'color-rendering': 'colorRendering',\n contentscripttype: 'contentScriptType',\n contentstyletype: 'contentStyleType',\n diffuseconstant: 'diffuseConstant',\n dominantbaseline: 'dominantBaseline',\n 'dominant-baseline': 'dominantBaseline',\n edgemode: 'edgeMode',\n enablebackground: 'enableBackground',\n 'enable-background': 'enableBackground',\n externalresourcesrequired: 'externalResourcesRequired',\n fillopacity: 'fillOpacity',\n 'fill-opacity': 'fillOpacity',\n fillrule: 'fillRule',\n 'fill-rule': 'fillRule',\n filterres: 'filterRes',\n filterunits: 'filterUnits',\n floodopacity: 'floodOpacity',\n 'flood-opacity': 'floodOpacity',\n floodcolor: 'floodColor',\n 'flood-color': 'floodColor',\n fontfamily: 'fontFamily',\n 'font-family': 'fontFamily',\n fontsize: 'fontSize',\n 'font-size': 'fontSize',\n fontsizeadjust: 'fontSizeAdjust',\n 'font-size-adjust': 'fontSizeAdjust',\n fontstretch: 'fontStretch',\n 'font-stretch': 'fontStretch',\n fontstyle: 'fontStyle',\n 'font-style': 'fontStyle',\n fontvariant: 'fontVariant',\n 'font-variant': 'fontVariant',\n fontweight: 'fontWeight',\n 'font-weight': 'fontWeight',\n glyphname: 'glyphName',\n 'glyph-name': 'glyphName',\n glyphorientationhorizontal: 'glyphOrientationHorizontal',\n 'glyph-orientation-horizontal': 'glyphOrientationHorizontal',\n glyphorientationvertical: 'glyphOrientationVertical',\n 'glyph-orientation-vertical': 'glyphOrientationVertical',\n glyphref: 'glyphRef',\n gradienttransform: 'gradientTransform',\n gradientunits: 'gradientUnits',\n horizadvx: 'horizAdvX',\n 'horiz-adv-x': 'horizAdvX',\n horizoriginx: 'horizOriginX',\n 'horiz-origin-x': 'horizOriginX',\n imagerendering: 'imageRendering',\n 'image-rendering': 'imageRendering',\n kernelmatrix: 'kernelMatrix',\n kernelunitlength: 'kernelUnitLength',\n keypoints: 'keyPoints',\n keysplines: 'keySplines',\n keytimes: 'keyTimes',\n lengthadjust: 'lengthAdjust',\n letterspacing: 'letterSpacing',\n 'letter-spacing': 'letterSpacing',\n lightingcolor: 'lightingColor',\n 'lighting-color': 'lightingColor',\n limitingconeangle: 'limitingConeAngle',\n markerend: 'markerEnd',\n 'marker-end': 'markerEnd',\n markerheight: 'markerHeight',\n markermid: 'markerMid',\n 'marker-mid': 'markerMid',\n markerstart: 'markerStart',\n 'marker-start': 'markerStart',\n markerunits: 'markerUnits',\n markerwidth: 'markerWidth',\n maskcontentunits: 'maskContentUnits',\n maskunits: 'maskUnits',\n numoctaves: 'numOctaves',\n overlineposition: 'overlinePosition',\n 'overline-position': 'overlinePosition',\n overlinethickness: 'overlineThickness',\n 'overline-thickness': 'overlineThickness',\n paintorder: 'paintOrder',\n 'paint-order': 'paintOrder',\n 'panose-1': 'panose1',\n pathlength: 'pathLength',\n patterncontentunits: 'patternContentUnits',\n patterntransform: 'patternTransform',\n patternunits: 'patternUnits',\n pointerevents: 'pointerEvents',\n 'pointer-events': 'pointerEvents',\n pointsatx: 'pointsAtX',\n pointsaty: 'pointsAtY',\n pointsatz: 'pointsAtZ',\n preservealpha: 'preserveAlpha',\n preserveaspectratio: 'preserveAspectRatio',\n primitiveunits: 'primitiveUnits',\n refx: 'refX',\n refy: 'refY',\n renderingintent: 'renderingIntent',\n 'rendering-intent': 'renderingIntent',\n repeatcount: 'repeatCount',\n repeatdur: 'repeatDur',\n requiredextensions: 'requiredExtensions',\n requiredfeatures: 'requiredFeatures',\n shaperendering: 'shapeRendering',\n 'shape-rendering': 'shapeRendering',\n specularconstant: 'specularConstant',\n specularexponent: 'specularExponent',\n spreadmethod: 'spreadMethod',\n startoffset: 'startOffset',\n stddeviation: 'stdDeviation',\n stitchtiles: 'stitchTiles',\n stopcolor: 'stopColor',\n 'stop-color': 'stopColor',\n stopopacity: 'stopOpacity',\n 'stop-opacity': 'stopOpacity',\n strikethroughposition: 'strikethroughPosition',\n 'strikethrough-position': 'strikethroughPosition',\n strikethroughthickness: 'strikethroughThickness',\n 'strikethrough-thickness': 'strikethroughThickness',\n strokedasharray: 'strokeDasharray',\n 'stroke-dasharray': 'strokeDasharray',\n strokedashoffset: 'strokeDashoffset',\n 'stroke-dashoffset': 'strokeDashoffset',\n strokelinecap: 'strokeLinecap',\n 'stroke-linecap': 'strokeLinecap',\n strokelinejoin: 'strokeLinejoin',\n 'stroke-linejoin': 'strokeLinejoin',\n strokemiterlimit: 'strokeMiterlimit',\n 'stroke-miterlimit': 'strokeMiterlimit',\n strokewidth: 'strokeWidth',\n 'stroke-width': 'strokeWidth',\n strokeopacity: 'strokeOpacity',\n 'stroke-opacity': 'strokeOpacity',\n suppresscontenteditablewarning: 'suppressContentEditableWarning',\n suppresshydrationwarning: 'suppressHydrationWarning',\n surfacescale: 'surfaceScale',\n systemlanguage: 'systemLanguage',\n tablevalues: 'tableValues',\n targetx: 'targetX',\n targety: 'targetY',\n textanchor: 'textAnchor',\n 'text-anchor': 'textAnchor',\n textdecoration: 'textDecoration',\n 'text-decoration': 'textDecoration',\n textlength: 'textLength',\n textrendering: 'textRendering',\n 'text-rendering': 'textRendering',\n underlineposition: 'underlinePosition',\n 'underline-position': 'underlinePosition',\n underlinethickness: 'underlineThickness',\n 'underline-thickness': 'underlineThickness',\n unicodebidi: 'unicodeBidi',\n 'unicode-bidi': 'unicodeBidi',\n unicoderange: 'unicodeRange',\n 'unicode-range': 'unicodeRange',\n unitsperem: 'unitsPerEm',\n 'units-per-em': 'unitsPerEm',\n unselectable: 'unselectable',\n valphabetic: 'vAlphabetic',\n 'v-alphabetic': 'vAlphabetic',\n vectoreffect: 'vectorEffect',\n 'vector-effect': 'vectorEffect',\n vertadvy: 'vertAdvY',\n 'vert-adv-y': 'vertAdvY',\n vertoriginx: 'vertOriginX',\n 'vert-origin-x': 'vertOriginX',\n vertoriginy: 'vertOriginY',\n 'vert-origin-y': 'vertOriginY',\n vhanging: 'vHanging',\n 'v-hanging': 'vHanging',\n videographic: 'vIdeographic',\n 'v-ideographic': 'vIdeographic',\n viewbox: 'viewBox',\n viewtarget: 'viewTarget',\n vmathematical: 'vMathematical',\n 'v-mathematical': 'vMathematical',\n wordspacing: 'wordSpacing',\n 'word-spacing': 'wordSpacing',\n writingmode: 'writingMode',\n 'writing-mode': 'writingMode',\n xchannelselector: 'xChannelSelector',\n xheight: 'xHeight',\n 'x-height': 'xHeight',\n xlinkactuate: 'xlinkActuate',\n 'xlink:actuate': 'xlinkActuate',\n xlinkarcrole: 'xlinkArcrole',\n 'xlink:arcrole': 'xlinkArcrole',\n xlinkhref: 'xlinkHref',\n 'xlink:href': 'xlinkHref',\n xlinkrole: 'xlinkRole',\n 'xlink:role': 'xlinkRole',\n xlinkshow: 'xlinkShow',\n 'xlink:show': 'xlinkShow',\n xlinktitle: 'xlinkTitle',\n 'xlink:title': 'xlinkTitle',\n xlinktype: 'xlinkType',\n 'xlink:type': 'xlinkType',\n xmlbase: 'xmlBase',\n 'xml:base': 'xmlBase',\n xmllang: 'xmlLang',\n 'xml:lang': 'xmlLang',\n 'xml:space': 'xmlSpace',\n xmlnsxlink: 'xmlnsXlink',\n 'xmlns:xlink': 'xmlnsXlink',\n xmlspace: 'xmlSpace',\n ychannelselector: 'yChannelSelector',\n zoomandpan: 'zoomAndPan',\n // event handlers\n onblur: 'onBlur',\n onchange: 'onChange',\n onclick: 'onClick',\n oncontextmenu: 'onContextMenu',\n ondoubleclick: 'onDoubleClick',\n ondrag: 'onDrag',\n ondragend: 'onDragEnd',\n ondragenter: 'onDragEnter',\n ondragexit: 'onDragExit',\n ondragleave: 'onDragLeave',\n ondragover: 'onDragOver',\n ondragstart: 'onDragStart',\n ondrop: 'onDrop',\n onerror: 'onError',\n onfocus: 'onFocus',\n oninput: 'onInput',\n oninvalid: 'onInvalid',\n onkeydown: 'onKeyDown',\n onkeypress: 'onKeyPress',\n onkeyup: 'onKeyUp',\n onload: 'onLoad',\n onmousedown: 'onMouseDown',\n onmouseenter: 'onMouseEnter',\n onmouseleave: 'onMouseLeave',\n onmousemove: 'onMouseMove',\n onmouseout: 'onMouseOut',\n onmouseover: 'onMouseOver',\n onmouseup: 'onMouseUp',\n onscroll: 'onScroll',\n onsubmit: 'onSubmit',\n ontouchcancel: 'onTouchCancel',\n ontouchend: 'onTouchEnd',\n ontouchmove: 'onTouchMove',\n ontouchstart: 'onTouchStart',\n onwheel: 'onWheel',\n};\n//# sourceMappingURL=helpers.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\n/* eslint-disable @typescript-eslint/no-use-before-define */\nimport * as React from 'react';\nimport { noTextChildNodes, possibleStandardNames, randomString, styleToObject } from './helpers';\nfunction parseAttributes(node, reactKey) {\n var attributes = {\n key: reactKey,\n };\n /* istanbul ignore else */\n if (node instanceof Element) {\n var nodeClassNames = node.getAttribute('class');\n if (nodeClassNames) {\n attributes.className = nodeClassNames;\n }\n __spreadArray([], __read(node.attributes), false).forEach(function (d) {\n switch (d.name) {\n // this is manually handled above, so break;\n case 'class':\n break;\n case 'style':\n attributes[d.name] = styleToObject(d.value);\n break;\n case 'allowfullscreen':\n case 'allowpaymentrequest':\n case 'async':\n case 'autofocus':\n case 'autoplay':\n case 'checked':\n case 'controls':\n case 'default':\n case 'defer':\n case 'disabled':\n case 'formnovalidate':\n case 'hidden':\n case 'ismap':\n case 'itemscope':\n case 'loop':\n case 'multiple':\n case 'muted':\n case 'nomodule':\n case 'novalidate':\n case 'open':\n case 'readonly':\n case 'required':\n case 'reversed':\n case 'selected':\n case 'typemustmatch':\n attributes[possibleStandardNames[d.name] || d.name] = true;\n break;\n default:\n attributes[possibleStandardNames[d.name] || d.name] = d.value;\n }\n });\n }\n return attributes;\n}\nfunction parseChildren(childNodeList, level, options) {\n var children = __spreadArray([], __read(childNodeList), false).map(function (node, index) {\n return convertFromNode(node, __assign(__assign({}, options), { index: index, level: level + 1 }));\n })\n .filter(Boolean);\n if (!children.length) {\n return null;\n }\n return children;\n}\nfunction parseName(nodeName) {\n if (/[a-z]+[A-Z]+[a-z]+/.test(nodeName)) {\n return nodeName;\n }\n return nodeName.toLowerCase();\n}\nexport function convertFromNode(input, options) {\n var _a;\n if (options === void 0) { options = {}; }\n if (!input || !(input instanceof Node)) {\n return null;\n }\n var _b = options.actions, actions = _b === void 0 ? [] : _b, _c = options.index, index = _c === void 0 ? 0 : _c, _d = options.level, level = _d === void 0 ? 0 : _d, randomKey = options.randomKey;\n var node = input;\n var key = \"\".concat(level, \"-\").concat(index);\n var result = [];\n if (randomKey && level === 0) {\n key = \"\".concat(randomString(), \"-\").concat(key);\n }\n /* istanbul ignore else */\n if (Array.isArray(actions)) {\n actions.forEach(function (action) {\n if (action.condition(node, key, level)) {\n if (typeof action.pre === 'function') {\n node = action.pre(node, key, level);\n if (!(node instanceof Node)) {\n node = input;\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('The `pre` method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `post` method instead)');\n }\n }\n }\n if (typeof action.post === 'function') {\n result.push(action.post(node, key, level));\n }\n }\n });\n }\n if (result.length) {\n return result;\n }\n switch (node.nodeType) {\n case 1: {\n // regular dom-node\n return React.createElement(parseName(node.nodeName), parseAttributes(node, key), parseChildren(node.childNodes, level, options));\n }\n case 3: {\n // textnode\n var nodeText = ((_a = node.nodeValue) === null || _a === void 0 ? void 0 : _a.toString()) || '';\n /* istanbul ignore else */\n if (/^\\s+$/.test(nodeText) && !/[\\u00A0\\u202F]/.test(nodeText)) {\n return null;\n }\n /* istanbul ignore next */\n if (!node.parentNode) {\n return nodeText;\n }\n var parentNodeName = node.parentNode.nodeName.toLowerCase();\n if (noTextChildNodes.includes(parentNodeName)) {\n /* istanbul ignore else */\n if (/\\S/.test(nodeText)) {\n // eslint-disable-next-line no-console\n console.warn(\"A textNode is not allowed inside '\".concat(parentNodeName, \"'. Your text \\\"\").concat(nodeText, \"\\\" will be ignored\"));\n }\n return null;\n }\n return nodeText;\n }\n case 8: {\n // html-comment\n return null;\n }\n /* istanbul ignore next */\n default: {\n return null;\n }\n }\n}\nexport function convertFromString(input, options) {\n if (options === void 0) { options = {}; }\n if (!input || typeof input !== 'string') {\n return null;\n }\n var _a = options.nodeOnly, nodeOnly = _a === void 0 ? false : _a, _b = options.selector, selector = _b === void 0 ? 'body > *' : _b, _c = options.type, type = _c === void 0 ? 'text/html' : _c;\n try {\n var parser = new DOMParser();\n var document_1 = parser.parseFromString(input, type);\n var node = document_1.querySelector(selector);\n if (!(node instanceof Node)) {\n throw new TypeError('Error parsing input');\n }\n if (nodeOnly) {\n return node;\n }\n return convertFromNode(node, options);\n }\n catch (error) {\n /* istanbul ignore else */\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.error(error);\n }\n }\n return null;\n}\nexport default function convert(input, options) {\n if (options === void 0) { options = {}; }\n if (typeof input === 'string') {\n return convertFromString(input, options);\n }\n if (input instanceof Node) {\n return convertFromNode(input, options);\n }\n return null;\n}\n//# sourceMappingURL=index.js.map","import { canUseDOM as canUseDOMFlag } from 'exenv';\nexport var STATUS = {\n FAILED: 'failed',\n LOADED: 'loaded',\n LOADING: 'loading',\n PENDING: 'pending',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n};\nexport function canUseDOM() {\n return canUseDOMFlag;\n}\nexport function isSupportedEnvironment() {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\nexport function supportsInlineSVG() {\n /* istanbul ignore next */\n if (!document) {\n return false;\n }\n var div = document.createElement('div');\n div.innerHTML = '';\n var svg = div.firstChild;\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\nfunction randomCharacter(character) {\n return character[Math.floor(Math.random() * character.length)];\n}\nexport function randomString(length) {\n var letters = 'abcdefghijklmnopqrstuvwxyz';\n var numbers = '1234567890';\n var charset = \"\".concat(letters).concat(letters.toUpperCase()).concat(numbers);\n var R = '';\n for (var index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n return R;\n}\n/**\n * Remove properties from an object\n */\nexport function omit(input) {\n var filter = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n filter[_i - 1] = arguments[_i];\n }\n var output = {};\n for (var key in input) {\n /* istanbul ignore else */\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key)) {\n output[key] = input[key];\n }\n }\n }\n return output;\n}\n//# sourceMappingURL=helpers.js.map","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport * as React from 'react';\nimport convert from 'react-from-dom';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, STATUS } from './helpers';\nexport var cacheStore = Object.create(null);\nvar InlineSVG = /** @class */ (function (_super) {\n __extends(InlineSVG, _super);\n function InlineSVG(props) {\n var _this = _super.call(this, props) || this;\n Object.defineProperty(_this, \"isInitialized\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(_this, \"isActive\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: false\n });\n Object.defineProperty(_this, \"hash\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(_this, \"handleLoad\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (content, hasCache) {\n if (hasCache === void 0) { hasCache = false; }\n /* istanbul ignore else */\n if (_this.isActive) {\n _this.setState({\n content: content,\n hasCache: hasCache,\n status: STATUS.LOADED,\n }, _this.getElement);\n }\n }\n });\n Object.defineProperty(_this, \"handleError\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function (error) {\n var onError = _this.props.onError;\n var status = error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;\n /* istanbul ignore else */\n if (_this.isActive) {\n _this.setState({ status: status }, function () {\n /* istanbul ignore else */\n if (typeof onError === 'function') {\n onError(error);\n }\n });\n }\n }\n });\n Object.defineProperty(_this, \"request\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: function () {\n var _a = _this.props, cacheRequests = _a.cacheRequests, fetchOptions = _a.fetchOptions, src = _a.src;\n try {\n if (cacheRequests) {\n cacheStore[src] = { content: '', status: STATUS.LOADING };\n }\n return fetch(src, fetchOptions)\n .then(function (response) {\n var contentType = response.headers.get('content-type');\n var _a = __read((contentType || '').split(/ ?; ?/), 1), fileType = _a[0];\n if (response.status > 299) {\n throw new Error('Not found');\n }\n if (!['image/svg+xml', 'text/plain'].some(function (d) { return fileType.includes(d); })) {\n throw new Error(\"Content type isn't valid: \".concat(fileType));\n }\n return response.text();\n })\n .then(function (content) {\n var currentSrc = _this.props.src;\n // the current src don't match the previous one, skipping...\n if (src !== currentSrc) {\n if (cacheStore[src].status === STATUS.LOADING) {\n delete cacheStore[src];\n }\n return;\n }\n _this.handleLoad(content);\n /* istanbul ignore else */\n if (cacheRequests) {\n var cache = cacheStore[src];\n /* istanbul ignore else */\n if (cache) {\n cache.content = content;\n cache.status = STATUS.LOADED;\n }\n }\n })\n .catch(function (error) {\n _this.handleError(error);\n /* istanbul ignore else */\n if (cacheRequests) {\n var cache = cacheStore[src];\n /* istanbul ignore else */\n if (cache) {\n delete cacheStore[src];\n }\n }\n });\n }\n catch (error) {\n return _this.handleError(new Error(error.message));\n }\n }\n });\n _this.state = {\n content: '',\n element: null,\n hasCache: !!props.cacheRequests && !!cacheStore[props.src],\n status: STATUS.PENDING,\n };\n _this.hash = props.uniqueHash || randomString(8);\n return _this;\n }\n Object.defineProperty(InlineSVG.prototype, \"componentDidMount\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.isActive = true;\n if (!canUseDOM() || this.isInitialized) {\n return;\n }\n var status = this.state.status;\n var src = this.props.src;\n try {\n /* istanbul ignore else */\n if (status === STATUS.PENDING) {\n /* istanbul ignore else */\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n /* istanbul ignore else */\n if (!src) {\n throw new Error('Missing src');\n }\n this.load();\n }\n }\n catch (error) {\n this.handleError(error);\n }\n this.isInitialized = true;\n }\n });\n Object.defineProperty(InlineSVG.prototype, \"componentDidUpdate\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function (previousProps, previousState) {\n if (!canUseDOM()) {\n return;\n }\n var _a = this.state, hasCache = _a.hasCache, status = _a.status;\n var _b = this.props, onLoad = _b.onLoad, src = _b.src;\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n /* istanbul ignore else */\n if (onLoad) {\n onLoad(src, hasCache);\n }\n }\n if (previousProps.src !== src) {\n if (!src) {\n this.handleError(new Error('Missing src'));\n return;\n }\n this.load();\n }\n }\n });\n Object.defineProperty(InlineSVG.prototype, \"componentWillUnmount\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n this.isActive = false;\n }\n });\n Object.defineProperty(InlineSVG.prototype, \"getNode\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var _a = this.props, description = _a.description, title = _a.title;\n try {\n var svgText = this.processSVG();\n var node = convert(svgText, { nodeOnly: true });\n if (!node || !(node instanceof SVGSVGElement)) {\n throw new Error('Could not convert the src to a DOM Node');\n }\n var svg = this.updateSVGAttributes(node);\n if (description) {\n var originalDesc = svg.querySelector('desc');\n if (originalDesc && originalDesc.parentNode) {\n originalDesc.parentNode.removeChild(originalDesc);\n }\n var descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');\n descElement.innerHTML = description;\n svg.prepend(descElement);\n }\n if (typeof title !== 'undefined') {\n var originalTitle = svg.querySelector('title');\n if (originalTitle && originalTitle.parentNode) {\n originalTitle.parentNode.removeChild(originalTitle);\n }\n if (title) {\n var titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');\n titleElement.innerHTML = title;\n svg.prepend(titleElement);\n }\n }\n return svg;\n }\n catch (error) {\n return this.handleError(error);\n }\n }\n });\n Object.defineProperty(InlineSVG.prototype, \"getElement\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n try {\n var node = this.getNode();\n var element = convert(node);\n if (!element || !React.isValidElement(element)) {\n throw new Error('Could not convert the src to a React element');\n }\n this.setState({\n element: element,\n status: STATUS.READY,\n });\n }\n catch (error) {\n this.handleError(new Error(error.message));\n }\n }\n });\n Object.defineProperty(InlineSVG.prototype, \"load\", {\n enumerable: false,\n configurable: true,\n writable: true,\n value: function () {\n var _this = this;\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState({\n content: '',\n element: null,\n hasCache: false,\n status: STATUS.LOADING,\n }, function () {\n var _a = _this.props, cacheRequests = _a.cacheRequests, src = _a.src;\n var cache = cacheRequests && cacheStore[src];\n if (cache && cache.status === STATUS.LOADED) {\n _this.handleLoad(cache.content, true);\n return;\n }\n var dataURI = src.match(/data:image\\/svg[^,]*?(;base64)?,(.*)/);\n var inlineSrc;\n if (dataURI) {\n inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);\n }\n else if (src.includes('