{"version":3,"file":"SpotlightProvider.mjs","names":[],"sources":["../../../src/spotlight/SpotlightProvider.tsx"],"sourcesContent":["/*!\n *\n *  Copyright (c) \"Neo4j\"\n *  Neo4j Sweden AB [http://neo4j.com]\n *\n *  This file is part of Neo4j.\n *\n *  Neo4j is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  This program is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\nimport { FloatingOverlay, FloatingPortal } from '@floating-ui/react';\nimport classNames from 'classnames';\nimport type React from 'react';\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n} from 'react';\n\ntype SpotlightProviderProps = {\n  /** The app/screen content to wrap */\n  children: React.ReactNode;\n  /** A boolean that decides if there is a gray overlay when a spotlight is open. */\n  hasOverlay?: boolean;\n  /** If the overlay should be transparent */\n  isOverlayTransparent?: boolean;\n};\n\ntype SpotlightContextType = {\n  /** A boolean that indicates if a spotlight is open */\n  isOpen: boolean;\n  /** A function that can be used to close or open the spotlight */\n  setIsOpen: (arg: boolean) => void;\n  /** A function that can be used to check if a spotlight is active. It takes a target id as an argument */\n  isActiveSpotlight: (target: string) => boolean;\n  /** A function that can be used to set a spotlight as active. It takes a target id as an argument, or null to clear the active spotlight */\n  setActiveSpotlight: (target: string | null) => void;\n  /** A function that can be used to register a target. It takes a target id, and a ref to the target element as arguments */\n  registerTarget: (id: string, ref: React.RefObject<HTMLElement>) => void;\n  /** A function that can be used to unregister a target. It takes a target id as an argument */\n  unregisterTarget: (id: string) => void;\n  /** An object that contains all registered targets. The keys are the target ids, and the values are the refs to the target elements */\n  registeredTargets: Record<string, React.RefObject<HTMLElement>>;\n  /** A boolean that decides if there is a gray overlay when a spotlight is open */\n  hasOverlay?: boolean;\n};\n\nconst SpotlightContext = createContext<SpotlightContextType | null>(null);\n\nexport const SpotlightProvider = ({\n  children,\n  hasOverlay = true,\n  isOverlayTransparent = false,\n}: SpotlightProviderProps) => {\n  const [active, setActive] = useState<string | null>(null);\n  const [isOpen, setIsOpen] = useState<boolean>(false);\n  const [targets, setTargets] = useState<\n    Record<string, React.RefObject<HTMLElement>>\n  >({});\n  const [targetRect, setTargetRect] = useState<DOMRect | null>(null);\n\n  const registerTarget = useCallback(\n    (id: string, ref: React.RefObject<HTMLElement>) => {\n      setTargets((prev) => ({ ...prev, [id]: ref }));\n    },\n    [],\n  );\n\n  const unregisterTarget = useCallback((id: string) => {\n    setTargets((prev) => {\n      const newTargets = { ...prev };\n      delete newTargets[id];\n      return newTargets;\n    });\n  }, []);\n\n  // Calculate target element position and size for mask\n  useEffect(() => {\n    if (\n      active !== null &&\n      targets[active] !== undefined &&\n      targets[active]?.current !== null\n    ) {\n      const element = targets[active].current;\n      const rect = element.getBoundingClientRect();\n      setTargetRect(rect);\n    } else {\n      setTargetRect(null);\n    }\n  }, [active, targets]);\n\n  const contextValue: SpotlightContextType = {\n    hasOverlay,\n    isActiveSpotlight: useCallback(\n      (target: string) => target === active,\n      [active],\n    ),\n    isOpen,\n    registerTarget,\n    registeredTargets: targets,\n    setActiveSpotlight: useCallback(\n      (target: string | null) => setActive(target),\n      [],\n    ),\n    setIsOpen: useCallback((open: boolean) => setIsOpen(open), []),\n    unregisterTarget,\n  };\n\n  const overlayClasses = classNames('ndl-spotlight-overlay', {\n    'ndl-spotlight-overlay-opaque': !isOverlayTransparent,\n    'ndl-spotlight-overlay-open': isOpen && active !== null,\n  });\n\n  const overlayRootRef = useRef<HTMLElement | null>(null);\n\n  if (active !== null) {\n    overlayRootRef.current = document.getElementById(active);\n  }\n\n  // Get the border radius from the target element\n  const getHoleRadius = useCallback(() => {\n    if (\n      active !== null &&\n      targets[active] !== undefined &&\n      targets[active]?.current !== null\n    ) {\n      const element = targets[active].current;\n      const computedStyle = window.getComputedStyle(element);\n      const borderRadius = computedStyle.borderRadius;\n\n      // Parse the border radius value (handle px, rem, em, etc.)\n      const radiusValue = parseFloat(borderRadius);\n      return isNaN(radiusValue) ? 0 : radiusValue;\n    }\n    return 0;\n  }, [active, targets]);\n\n  const getMaskStyle = () => {\n    if (!targetRect || isOverlayTransparent) {\n      return {};\n    }\n\n    const { left, top, width, height } = targetRect;\n\n    const xPos = Math.max(0, left);\n    const yPos = Math.max(0, top);\n    const holeWidth = Math.max(0, width);\n    const holeHeight = Math.max(0, height);\n    const radius = Math.max(\n      0,\n      Math.min(getHoleRadius(), Math.min(holeWidth, holeHeight) / 2),\n    );\n\n    const vw = window.innerWidth;\n    const vh = window.innerHeight;\n\n    // SVG mask: white = visible overlay, black = hole (transparent)\n    const svg = `\n      <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${vw}\" height=\"${vh}\" viewBox=\"0 0 ${vw} ${vh}\">\n        <defs>\n          <mask id=\"spotlightMask\" maskUnits=\"userSpaceOnUse\">\n            <rect x=\"0\" y=\"0\" width=\"${vw}\" height=\"${vh}\" fill=\"white\"/>\n            <rect x=\"${xPos}\" y=\"${yPos}\" width=\"${holeWidth}\" height=\"${holeHeight}\" rx=\"${radius}\" ry=\"${radius}\" fill=\"black\"/>\n          </mask>\n        </defs>\n        <rect x=\"0\" y=\"0\" width=\"${vw}\" height=\"${vh}\" fill=\"black\" mask=\"url(#spotlightMask)\"/>\n      </svg>`.trim();\n\n    const encoded = `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;\n\n    return {\n      WebkitMaskImage: `url(\"${encoded}\")`,\n      WebkitMaskRepeat: 'no-repeat',\n      WebkitMaskSize: `${vw}px ${vh}px`,\n      maskImage: `url(\"${encoded}\")`,\n      maskRepeat: 'no-repeat',\n      maskSize: `${vw}px ${vh}px`,\n    } as React.CSSProperties;\n  };\n\n  /** useEffect to update the target rect, so that the mask tracks the target element */\n  useEffect(() => {\n    if (active === null) {\n      return;\n    }\n\n    const el = targets[active]?.current;\n    if (el === null || el === undefined) {\n      return;\n    }\n\n    const update = () => setTargetRect(el.getBoundingClientRect());\n    update();\n\n    const ro = new ResizeObserver(update);\n    ro.observe(el);\n\n    window.addEventListener('scroll', update, true);\n    window.addEventListener('resize', update);\n\n    return () => {\n      ro.disconnect();\n      window.removeEventListener('scroll', update, true);\n      window.removeEventListener('resize', update);\n    };\n  }, [active, targets]);\n\n  return (\n    <SpotlightContext.Provider value={contextValue}>\n      {hasOverlay && active !== null && isOpen && (\n        <FloatingPortal>\n          <FloatingOverlay\n            lockScroll={true}\n            className={overlayClasses}\n            style={getMaskStyle()}\n            data-testid=\"ndl-spotlight-overlay\"\n          />\n        </FloatingPortal>\n      )}\n      {children}\n    </SpotlightContext.Provider>\n  );\n};\n\nexport const useSpotlightContext = (): SpotlightContextType => {\n  const context = useContext(SpotlightContext);\n\n  if (context === null) {\n    throw new Error(\n      'Spotlight components must be wrapped in <SpotlightProvider />',\n    );\n  }\n\n  return context;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,MAAM,mBAAmB,cAA2C,IAAI;AAExE,MAAa,qBAAqB,EAChC,UACA,aAAa,MACb,uBAAuB,YACK;CAC5B,MAAM,CAAC,QAAQ,aAAa,SAAwB,IAAI;CACxD,MAAM,CAAC,QAAQ,aAAa,SAAkB,KAAK;CACnD,MAAM,CAAC,SAAS,cAAc,SAE5B,CAAC,CAAC;CACJ,MAAM,CAAC,YAAY,iBAAiB,SAAyB,IAAI;CAEjE,MAAM,iBAAiB,aACpB,IAAY,QAAsC;EACjD,YAAY,SAAA,eAAA,eAAA,CAAA,GAAe,IAAA,GAAA,CAAA,GAAA,GAAO,KAAK,IAAA,CAAI,CAAE;CAC/C,GACA,CAAC,CACH;CAEA,MAAM,mBAAmB,aAAa,OAAe;EACnD,YAAY,SAAS;GACnB,MAAM,aAAA,eA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