Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / applications / drive / src / app / store / _views / utils / useIsActiveLinkReadOnly.ts
blob23b9d9270262aeddbfc5f17142dba85f8efe6127
1 import { useEffect, useRef, useState } from 'react';
3 import { ShareType } from '../..';
4 import { useActiveShare } from '../../../hooks/drive/useActiveShare';
5 import { isIgnoredError, sendErrorReport } from '../../../utils/errorHandling';
6 import type { DecryptedLink } from '../../_links';
7 import { useLink } from '../../_links';
8 import { useShareType } from './useShareType';
10 export const isLinkReadOnly = (link: DecryptedLink, shareType: ShareType) => {
11     const isRootLink = !link.parentLinkId;
12     return shareType === ShareType.device && isRootLink;
15 export const useIsActiveLinkReadOnly = () => {
16     const { activeFolder } = useActiveShare();
17     const { shareId, linkId } = activeFolder;
18     const shareType = useShareType(shareId);
19     const link = useLink();
21     const [isReadOnly, setIsReadOnly] = useState<boolean | undefined>(undefined);
22     const ongoingRequestAc = useRef<AbortController>();
24     useEffect(() => {
25         const ac = new AbortController();
27         // Abort ongoing request to avoid fast meaningless shareType change
28         ongoingRequestAc.current?.abort();
29         ongoingRequestAc.current = ac;
30         setIsReadOnly(undefined);
32         if (shareType) {
33             link.getLink(ac.signal, shareId, linkId)
34                 .then((link) => {
35                     setIsReadOnly(isLinkReadOnly(link, shareType));
36                 })
37                 .catch((e) => {
38                     sendErrorReport(e);
40                     // Ignore errors caused by .abort()
41                     if (!isIgnoredError(e)) {
42                         // Assume that a link isn't read-only,
43                         // as it's the majority of all cases.
44                         setIsReadOnly(false);
45                     }
46                 })
47                 .finally(() => {
48                     ongoingRequestAc.current = undefined;
49                 });
50         } else if (shareType === null) {
51             // Couldn't load share info, assuming it isn't read-only
52             setIsReadOnly(false);
53         }
54     }, [linkId, shareType]);
56     return {
57         isLoading: isReadOnly === undefined,
58         isReadOnly,
59     };