Merge branch 'INDA-330-pii-update' into 'main'
[ProtonMail-WebClient.git] / applications / drive / src / app / components / useSpotlight.tsx
blob83b5b9b9e3df705600203ca8ebddd8ea8a11e28c
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 = {
15     searchSpotlight: {
16         isOpen: boolean;
17         onDisplayed: () => void;
18         close: () => void;
19     };
22 interface Props {
23     children?: ReactNode;
26 const SpotlightContext = createContext<SpotlightContextFunctions | null>(null);
28 const useSearchSpotlight = () => {
29     const [rootFolder, setRootFolder] = useState<DriveFolder>();
30     const { getDefaultShare } = useDefaultShare();
31     const { getCachedChildrenCount } = useLinksListing();
33     useEffect(() => {
34         getDefaultShare()
35             .then(({ shareId, rootLinkId }) => {
36                 setRootFolder({ shareId, linkId: rootLinkId });
37             })
38             .catch(sendErrorReport);
39     }, []);
41     const storedItemsCount = useMemo(() => {
42         if (!rootFolder?.linkId || !rootFolder?.shareId) {
43             return 0;
44         }
45         return getCachedChildrenCount(rootFolder.shareId, rootFolder.linkId);
46     }, [rootFolder, getCachedChildrenCount]);
48     const enoughItemsStored = storedItemsCount > SEARCH_DISCOVERY_FILES_THRESHOLD;
50     const {
51         show: showSpotlight,
52         onDisplayed,
53         onClose,
54     } = useSpotlightOnFeature(FeatureCode.DriveSearchSpotlight, enoughItemsStored);
55     const shouldShowSpotlight = useSpotlightShow(showSpotlight);
57     return {
58         isOpen: shouldShowSpotlight,
59         onDisplayed,
60         close: onClose,
61     };
64 export const SpotlightProvider = ({ children }: Props) => {
65     const searchSpotlight = useSearchSpotlight();
67     const value = {
68         searchSpotlight,
69     };
71     return <SpotlightContext.Provider value={value}>{children}</SpotlightContext.Provider>;
74 export function useSpotlight() {
75     const state = useContext(SpotlightContext);
76     if (!state) {
77         throw new Error('Trying to use uninitialized SearchLibraryProvider');
78     }
79     return state;