1 import type { ReactNode } from 'react';
2 import { createContext, useContext, useEffect, useMemo, useState } from 'react';
4 import { useSpotlightShow } from '@proton/components';
5 import useSpotlightOnFeature from '@proton/components/hooks/useSpotlightOnFeature';
6 import { FeatureCode } from '@proton/features';
8 import type { DriveFolder } from '../hooks/drive/useActiveShare';
9 import { useLinksListing } from '../store/_links';
10 import { useDefaultShare } from '../store/_shares';
11 import { sendErrorReport } from '../utils/errorHandling';
13 const SEARCH_DISCOVERY_FILES_THRESHOLD = 5;
15 type SpotlightContextFunctions = {
18 onDisplayed: () => void;
27 const SpotlightContext = createContext<SpotlightContextFunctions | null>(null);
29 const useSearchSpotlight = () => {
30 const [rootFolder, setRootFolder] = useState<DriveFolder>();
31 const { getDefaultShare } = useDefaultShare();
32 const { getCachedChildrenCount } = useLinksListing();
36 .then(({ shareId, rootLinkId }) => {
37 setRootFolder({ shareId, linkId: rootLinkId });
39 .catch(sendErrorReport);
42 const storedItemsCount = useMemo(() => {
43 if (!rootFolder?.linkId || !rootFolder?.shareId) {
46 return getCachedChildrenCount(rootFolder.shareId, rootFolder.linkId);
47 }, [rootFolder, getCachedChildrenCount]);
49 const enoughItemsStored = storedItemsCount > SEARCH_DISCOVERY_FILES_THRESHOLD;
55 } = useSpotlightOnFeature(FeatureCode.DriveSearchSpotlight, enoughItemsStored);
56 const shouldShowSpotlight = useSpotlightShow(showSpotlight);
59 isOpen: shouldShowSpotlight,
65 export const SpotlightProvider = ({ children }: Props) => {
66 const searchSpotlight = useSearchSpotlight();
72 return <SpotlightContext.Provider value={value}>{children}</SpotlightContext.Provider>;
75 export function useSpotlight() {
76 const state = useContext(SpotlightContext);
78 throw new Error('Trying to use uninitialized SearchLibraryProvider');