Remove client-side isLoggedIn value
[ProtonMail-WebClient.git] / packages / drive-store / components / useSpotlight.tsx
blob4f6012aada7c9ae7d390e606326d892b8b6b9a96
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 = {
16     searchSpotlight: {
17         isOpen: boolean;
18         onDisplayed: () => void;
19         close: () => void;
20     };
23 interface Props {
24     children?: ReactNode;
27 const SpotlightContext = createContext<SpotlightContextFunctions | null>(null);
29 const useSearchSpotlight = () => {
30     const [rootFolder, setRootFolder] = useState<DriveFolder>();
31     const { getDefaultShare } = useDefaultShare();
32     const { getCachedChildrenCount } = useLinksListing();
34     useEffect(() => {
35         getDefaultShare()
36             .then(({ shareId, rootLinkId }) => {
37                 setRootFolder({ shareId, linkId: rootLinkId });
38             })
39             .catch(sendErrorReport);
40     }, []);
42     const storedItemsCount = useMemo(() => {
43         if (!rootFolder?.linkId || !rootFolder?.shareId) {
44             return 0;
45         }
46         return getCachedChildrenCount(rootFolder.shareId, rootFolder.linkId);
47     }, [rootFolder, getCachedChildrenCount]);
49     const enoughItemsStored = storedItemsCount > SEARCH_DISCOVERY_FILES_THRESHOLD;
51     const {
52         show: showSpotlight,
53         onDisplayed,
54         onClose,
55     } = useSpotlightOnFeature(FeatureCode.DriveSearchSpotlight, enoughItemsStored);
56     const shouldShowSpotlight = useSpotlightShow(showSpotlight);
58     return {
59         isOpen: shouldShowSpotlight,
60         onDisplayed,
61         close: onClose,
62     };
65 export const SpotlightProvider = ({ children }: Props) => {
66     const searchSpotlight = useSearchSpotlight();
68     const value = {
69         searchSpotlight,
70     };
72     return <SpotlightContext.Provider value={value}>{children}</SpotlightContext.Provider>;
75 export function useSpotlight() {
76     const state = useContext(SpotlightContext);
77     if (!state) {
78         throw new Error('Trying to use uninitialized SearchLibraryProvider');
79     }
80     return state;