UNPKG

@neo4j-ndl/react

Version:

React implementation of Neo4j Design System

67 lines 3.01 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; /** * * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import { FloatingOverlay, FloatingPortal } from '@floating-ui/react'; import classNames from 'classnames'; import { createContext, useCallback, useContext, useRef, useState, } from 'react'; const SpotlightContext = createContext(null); export const useSpotlightContext = () => { const context = useContext(SpotlightContext); if (context === null) { throw new Error('Spotlight components must be wrapped in <SpotlightProvider />'); } return context; }; export const SpotlightProvider = ({ children, hasOverlay = true, isOverlayTransparent = false, }) => { const [active, setActive] = useState(null); const [isOpen, setIsOpen] = useState(false); const [targets, setTargets] = useState({}); const registerTarget = useCallback((id, ref) => { setTargets((prev) => (Object.assign(Object.assign({}, prev), { [id]: ref }))); }, []); const unregisterTarget = useCallback((id) => { setTargets((prev) => { const newTargets = Object.assign({}, prev); delete newTargets[id]; return newTargets; }); }, []); const contextValue = { hasOverlay, isActiveSpotlight: useCallback((target) => target === active, [active]), isOpen, registerTarget, registeredTargets: targets, setActiveSpotlight: useCallback((target) => setActive(target), []), setIsOpen: useCallback((open) => setIsOpen(open), []), unregisterTarget, }; const overlayClasses = classNames('ndl-spotlight-overlay', { 'ndl-spotlight-overlay-opaque': !isOverlayTransparent, 'ndl-spotlight-overlay-open': isOpen && active !== null, }); const overlayRootRef = useRef(null); if (active !== null) { overlayRootRef.current = document.getElementById(active); } return (_jsxs(SpotlightContext.Provider, { value: contextValue, children: [hasOverlay && active !== null && isOpen && (_jsx(FloatingPortal, { root: overlayRootRef.current, children: _jsx(FloatingOverlay, { lockScroll: true, className: overlayClasses, "data-testid": "ndl-spotlight-overlay" }) })), children] })); }; //# sourceMappingURL=SpotlightProvider.js.map