1 import type { ReactNode } from 'react';
2 import { createContext, useContext, useEffect, useMemo, useState } from 'react';
4 import { useSpotlightOnFeature, useSpotlightShow } from '@proton/components';
5 import { FeatureCode } from '@proton/features';
7 import type { DriveFolder } from '../hooks/drive/useActiveShare';
8 import { useLinksListing } from '../store/_links';
9 import { useDefaultShare } from '../store/_shares';
10 import { sendErrorReport } from '../utils/errorHandling';
12 const SEARCH_DISCOVERY_FILES_THRESHOLD = 5;
14 type SpotlightContextFunctions = {
17 onDisplayed: () => void;
26 const SpotlightContext = createContext<SpotlightContextFunctions | null>(null);
28 const useSearchSpotlight = () => {
29 const [rootFolder, setRootFolder] = useState<DriveFolder>();
30 const { getDefaultShare } = useDefaultShare();
31 const { getCachedChildrenCount } = useLinksListing();
35 .then(({ shareId, rootLinkId }) => {
36 setRootFolder({ shareId, linkId: rootLinkId });
38 .catch(sendErrorReport);
41 const storedItemsCount = useMemo(() => {
42 if (!rootFolder?.linkId || !rootFolder?.shareId) {
45 return getCachedChildrenCount(rootFolder.shareId, rootFolder.linkId);
46 }, [rootFolder, getCachedChildrenCount]);
48 const enoughItemsStored = storedItemsCount > SEARCH_DISCOVERY_FILES_THRESHOLD;
54 } = useSpotlightOnFeature(FeatureCode.DriveSearchSpotlight, enoughItemsStored);
55 const shouldShowSpotlight = useSpotlightShow(showSpotlight);
58 isOpen: shouldShowSpotlight,
64 export const SpotlightProvider = ({ children }: Props) => {
65 const searchSpotlight = useSearchSpotlight();
71 return <SpotlightContext.Provider value={value}>{children}</SpotlightContext.Provider>;
74 export function useSpotlight() {
75 const state = useContext(SpotlightContext);
77 throw new Error('Trying to use uninitialized SearchLibraryProvider');