index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsProtonUserCookie.ts
import { useEffect } from 'react'; import { getCookie, setCookie } from '@proton/shared/lib/helpers/cookies'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; export const IS_PROTON_USER_COOKIE_NAME = 'is-proton-user'; const today = new Date(); const lastDayOfTheYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59); const cookieDomain = `.${getSecondLevelDomain(window.location.hostname)}`; // Set a cookie for Proton users, used by proton.me website // Also use in Drive download page to show/hide some marketing info const useIsProtonUserCookie = () => { useEffect(() => { const cookie = getCookie(IS_PROTON_USER_COOKIE_NAME); if (cookie !== '1') { setCookie({ cookieName: IS_PROTON_USER_COOKIE_NAME, cookieValue: '1', cookieDomain, expirationDate: lastDayOfTheYear.toUTCString(), path: '/', }); } }, []); }; export default useIsProtonUserCookie;
7,100
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsRecoveryFileAvailable.ts
import { getIsRecoveryFileAvailable } from '@proton/shared/lib/recoveryFile/recoveryFile'; import useAddresses from './useAddresses'; import useConfig from './useConfig'; import useUser from './useUser'; import { useUserKeys } from './useUserKeys'; const useIsRecoveryFileAvailable = () => { const [user, loadingUser] = useUser(); const [addresses = [], loadingAddresses] = useAddresses(); const [userKeys = [], loadingUserKeys] = useUserKeys(); const { APP_NAME } = useConfig(); const isRecoveryFileAvailable = getIsRecoveryFileAvailable({ user, addresses, userKeys, appName: APP_NAME, }); return [isRecoveryFileAvailable, loadingUserKeys || loadingAddresses || loadingUser] as const; }; export default useIsRecoveryFileAvailable;
7,101
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useKeyPress.ts
import { DependencyList, useCallback, useEffect } from 'react'; const useKeyPress = (cb: (e: KeyboardEvent) => void, deps: DependencyList = [], el = document) => { const callback = useCallback(cb, deps); useEffect(() => { el.addEventListener('keydown', callback); return () => { el.removeEventListener('keydown', cb); }; }, deps); }; export default useKeyPress;
7,102
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useKeyTransparencyNotification.ts
import { ThemeColor } from '@proton/colors/types'; import { AddressAuditStatus, AddressAuditWarningReason, SelfAuditResult } from '@proton/key-transparency/lib'; import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces'; import { useKeyTransparencyContext } from '../containers'; const getHasSelfAuditFailure = (selfAuditResult: SelfAuditResult) => { const addressAuditFailed = selfAuditResult.addressAuditResults.some( ({ status }) => status === AddressAuditStatus.Failure ); if (addressAuditFailed) { return true; } const lsAuditOwnFailed = selfAuditResult.localStorageAuditResultsOwnAddress.some(({ success }) => !success); if (lsAuditOwnFailed) { return true; } const lsAuditOtherFailed = selfAuditResult.localStorageAuditResultsOtherAddress.some(({ success }) => !success); return lsAuditOtherFailed; }; const getHasSelfAuditWarning = (selfAuditResult: SelfAuditResult) => { if (selfAuditResult?.error?.tooManyRetries) { return true; } const addressAuditWarning = selfAuditResult.addressAuditResults.some( ({ status, warningDetails }) => status === AddressAuditStatus.Warning && !( warningDetails?.reason === AddressAuditWarningReason.UnverifiableHistory && !warningDetails.addressWasDisabled ) ); if (addressAuditWarning) { return true; } }; const useKeyTransparencyNotification = (): ThemeColor | undefined => { const { ktState: { selfAuditResult }, ktActivation, } = useKeyTransparencyContext(); const showNotification = ktActivation === KeyTransparencyActivation.SHOW_UI && selfAuditResult; if (!showNotification) { return; } if (getHasSelfAuditFailure(selfAuditResult)) { return ThemeColor.Danger; } if (getHasSelfAuditWarning(selfAuditResult)) { return ThemeColor.Warning; } }; export default useKeyTransparencyNotification;
7,103
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLastSubscriptionEnd.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { getLastCancelledSubscription } from '@proton/shared/lib/api/payments'; import { LatestSubscription } from '../payments/core'; import useApi from './useApi'; import useUser from './useUser'; let promise: Promise<LatestSubscription> | undefined; const useLastSubscriptionEnd = (): [latestSubscription: number, loading: boolean] => { const api = useApi(); const [loading, withLoading] = useLoading(); const [{ isPaid }] = useUser(); const [latestSubscription, setLatestSubscription] = useState<number>(0); const isMounted = useIsMounted(); useEffect(() => { if (isPaid) { setLatestSubscription(0); return; } const run = async () => { try { if (!promise) { promise = api<LatestSubscription>(getLastCancelledSubscription()); } const { LastSubscriptionEnd = 0 } = await promise; if (isMounted()) { setLatestSubscription(LastSubscriptionEnd || 0); } } catch (e) { // Ignore } finally { // Reset promise to allow a new request promise = undefined; } }; void withLoading(run()); }, [isPaid]); return [latestSubscription, loading]; }; export default useLastSubscriptionEnd;
7,104
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLinkHandler.tsx
import { ReactNode, RefObject, useEffect, useState } from 'react'; import { c } from 'ttag'; import { PROTON_DOMAINS } from '@proton/shared/lib/constants'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { CONFIRM_LINK } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import { useModalState } from '../components'; import LinkConfirmationModal from '../components/notifications/LinkConfirmationModal/LinkConfirmationModal'; import { getHostname, isExternal, isSubDomain, punycodeUrl } from '../helpers/url'; import { useHandler, useNotifications } from './index'; // Reference : Angular/src/app/utils/directives/linkHandler.js interface UseLinkHandlerOptions { onMailTo?: (src: string) => void; startListening?: boolean; isOutside?: boolean; isPhishingAttempt?: boolean; } type UseLinkHandler = ( wrapperRef: RefObject<HTMLDivElement | undefined>, mailSettings?: MailSettings, options?: UseLinkHandlerOptions ) => { modal: ReactNode }; const defaultOptions: UseLinkHandlerOptions = { startListening: true, }; const getSrc = (target: Element) => { const extract = () => { try { return { encoded: target.toString() || '', raw: target.getAttribute('href') || '' }; } catch (e: any) { /* Because for Edge/IE11 <a href="http://xn--rotonmail-4sg.com" rel="noreferrer nofollow noopener">Protonmail.com</a> will crash --> Unspecified error. ¯\_(ツ)_/¯ Don't worry, target.href/getAttribute will crash too ¯\_(ツ)_/¯ */ const attr = Array.from(target.attributes).find((attr) => (attr || {}).name === 'href'); return { raw: attr?.nodeValue || '' }; } }; // Because even the fallback can crash on IE11/Edge try { return extract(); } catch (e: any) { return { raw: '' }; } }; export const useLinkHandler: UseLinkHandler = ( wrapperRef, mailSettings, { onMailTo, startListening, isOutside, isPhishingAttempt } = defaultOptions ) => { const { createNotification } = useNotifications(); const [link, setLink] = useState<string>(); const [linkConfirmationModalProps, setLinkConfirmationModalOpen, renderLinkConfirmationModal] = useModalState(); // eslint-disable-next-line @typescript-eslint/no-misused-promises const handleClick = useHandler(async (event: Event) => { const originalTarget = event.target as Element; const target = originalTarget.closest('a') || originalTarget.closest('area'); if (!target) { return; } const src = getSrc(target); if (!src.raw) { createNotification({ text: c('Error') .t`This message may contain some links URL that cannot be properly opened by your current browser.`, type: 'error', }); } // IE11 and Edge random env bug... (╯°□°)╯︵ ┻━┻ if (!src) { event.preventDefault(); return false; } // We only handle anchor that begins with `mailto:` if (src.raw.toLowerCase().startsWith('mailto:') && onMailTo) { event.preventDefault(); event.stopPropagation(); // Required for Safari /* * Open the composer with the given mailto address * position isAfter true as the user can choose to set a body */ onMailTo(src.raw); } const askForConfirmation = mailSettings?.ConfirmLink ?? CONFIRM_LINK.CONFIRM; const hostname = getHostname(src.raw); const currentDomain = getSecondLevelDomain(window.location.hostname); /* * If the modal is already active --- do nothing * ex: click on a link, open the modal, inside the continue button is an anchor with the same link. */ if (linkConfirmationModalProps.open) { return; } /* * If dealing with anchors, we need to treat them separately because we use URLs with # for searching elements */ if (src.raw.startsWith('#')) { const id = src.raw.replace('#', ''); if (wrapperRef.current) { const elementInMail = wrapperRef.current.querySelector(`a[name="${id}"], a[id="${id}"]`); if (elementInMail) { elementInMail.scrollIntoView({ behavior: 'smooth', block: 'start' }); } } event.preventDefault(); event.stopPropagation(); return; } if ( (askForConfirmation || isPhishingAttempt) && isExternal(src.raw) && ![...PROTON_DOMAINS, currentDomain] .filter(isTruthy) // currentDomain can be null .some((domain) => isSubDomain(hostname, domain)) ) { event.preventDefault(); event.stopPropagation(); // Required for Safari const link = punycodeUrl(src.encoded || src.raw); setLink(link); setLinkConfirmationModalOpen(true); } }); useEffect(() => { if (startListening === false) { return; } // eslint-disable-next-line @typescript-eslint/no-misused-promises wrapperRef.current?.addEventListener('click', handleClick, false); return () => { // eslint-disable-next-line @typescript-eslint/no-misused-promises wrapperRef.current?.removeEventListener('click', handleClick, false); }; }, [startListening, wrapperRef.current]); const modal = renderLinkConfirmationModal ? ( <LinkConfirmationModal link={link} isOutside={isOutside} isPhishingAttempt={isPhishingAttempt} modalProps={linkConfirmationModalProps} /> ) : null; return { modal }; };
7,105
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLoad.ts
import { useEffect } from 'react'; import { formatURLForAjaxRequest } from '@proton/shared/lib/helpers/url'; import noop from '@proton/utils/noop'; const useLoad = () => { useEffect(() => { const url = formatURLForAjaxRequest(); fetch(url).catch(noop); }, []); }; export default useLoad;
7,106
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLoadContactImage.ts
import { useEffect, useState } from 'react'; import { useAuthentication, useConfig, useMailSettings } from '@proton/components/hooks/index'; import { useLoading } from '@proton/hooks'; import { CONTACT_IMG_SIZE } from '@proton/shared/lib/contacts/constants'; import { getContactImageSource } from '@proton/shared/lib/helpers/contacts'; import { resizeImage, toImage } from '@proton/shared/lib/helpers/image'; import { isBase64Image } from '@proton/shared/lib/helpers/validators'; import { hasShowEmbedded, hasShowRemote } from '@proton/shared/lib/mail/images'; import noop from '@proton/utils/noop'; type ImageModel = { src: string; width?: number; height?: number; isSmall?: boolean; }; interface Props { photo: string; needsResize?: boolean; onToggleLoadDirectBanner?: (show: boolean) => void; } const useLoadContactImage = ({ photo, onToggleLoadDirectBanner, needsResize = false }: Props) => { const authentication = useAuthentication(); const { API_URL } = useConfig(); const [mailSettings, loadingMailSettings] = useMailSettings(); const [image, setImage] = useState<ImageModel>({ src: '' }); const [loadingResize, withLoadingResize] = useLoading(true); const [needsLoadDirect, setNeedsLoadDirect] = useState(false); const [showAnyway, setShowAnyway] = useState(false); const [loadDirectFailed, setLoadDirectFailed] = useState(false); const loading = loadingMailSettings || loadingResize; const hasShowRemoteImages = hasShowRemote(mailSettings); const hasShowEmbeddedImages = hasShowEmbedded(mailSettings); const isBase64 = isBase64Image(photo); // Show image when : // - User requested by clicking on the load button // - Both Auto show settings are ON // - If image is embedded, check embedded setting // - If image is remote, check remote setting const shouldShow = showAnyway || (hasShowEmbeddedImages && hasShowRemoteImages) || (isBase64 ? hasShowRemoteImages : hasShowRemoteImages); /** * How image loading works: * 1. If shouldShow = false (e.g. Auto show setting is OFF) * => Nothing is done, we should display a "Load" button on the component calling this hook * 2. Load is possible (Auto show ON or user clicked on load) * a. User is using the proxy OR the image is b64 * => We pass in loadImage function. We will try to load the image using the Proton image proxy * b. User is not using the proxy * => We pass in loadImageDirect. We will try to load the image using the default URL * 3. Loading failed * a. Loading with proxy failed * A banner should be displayed to the user (from the component calling this hook) * informing that the image could not be loaded using Proton image proxy. * The user has the possibility to load the image with its default url * => We pass in loadImageDirect * b. Loading without proxy failed * => A placeholder should be displayed in the component calling this hook to inform * the user that the image could not be loaded (+ potential load direct banner is removed) */ const handleResizeImage = async (src: string, width: number, height: number, useProxy: boolean) => { if (width <= CONTACT_IMG_SIZE && height <= CONTACT_IMG_SIZE) { setImage({ src, width, height, isSmall: true }); } else { const resized = await resizeImage({ original: src, maxWidth: CONTACT_IMG_SIZE, maxHeight: CONTACT_IMG_SIZE, bigResize: true, crossOrigin: useProxy, }); setImage({ src: resized }); } }; const loadImage = async () => { try { const uid = authentication.getUID(); const imageURL = getContactImageSource(API_URL, photo, uid, !!mailSettings?.ImageProxy); const { src, width, height } = await toImage(imageURL); if (needsResize) { await handleResizeImage(src, width, height, !!mailSettings?.ImageProxy); } else { setImage({ src }); } } catch (e) { if (!!mailSettings?.ImageProxy) { onToggleLoadDirectBanner?.(true); setNeedsLoadDirect(true); } throw new Error('Get image failed'); } }; const loadImageDirect = async () => { try { const { src, width, height } = await toImage(photo, false); if (needsResize) { // In some cases resizing the image will not work (e.g. images using .ppm formats) // So the loading from handleResizeImage will fail. // In this case, we catch the error and set the Image using the image src // At this point if the image necessarily loaded, // otherwise we would have passed in the function catch block where we set loadDirectFailed try { await handleResizeImage(src, width, height, false); } catch (e) { setImage({ src }); } } else { setImage({ src }); } setNeedsLoadDirect(false); onToggleLoadDirectBanner?.(false); } catch (e) { setLoadDirectFailed(true); onToggleLoadDirectBanner?.(false); throw new Error('Get image failed'); } }; const handleLoadImageDirect = async () => { void withLoadingResize(loadImageDirect()); }; useEffect(() => { if (!photo || !shouldShow) { return; } if (mailSettings?.ImageProxy || isBase64) { // if resize fails (e.g. toImage will throw if the requested resource hasn't specified a CORS policy), // fallback to the original src void withLoadingResize(loadImage().catch(noop)); } else { void withLoadingResize(loadImageDirect().catch(noop)); } }, [photo, shouldShow]); const display: 'loading' | 'loadDirectFailed' | 'needsLoadDirect' | 'smallImageLoaded' | 'loaded' | 'askLoading' = (() => { if (shouldShow) { if (loading) { return 'loading'; } if (loadDirectFailed) { return 'loadDirectFailed'; } if (needsLoadDirect) { return 'needsLoadDirect'; } if (needsResize && image.isSmall) { return 'smallImageLoaded'; } return 'loaded'; } return 'askLoading'; })(); return { loadImage, loadImageDirect, handleLoadImageDirect, image, needsLoadDirect, setShowAnyway, loading, shouldShow, loadDirectFailed, display, }; }; export default useLoadContactImage;
7,107
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLoadFeature.ts
import { useContext } from 'react'; import { FeaturesLoadContext } from '../containers/features'; const useLoadFeature = () => { return useContext(FeaturesLoadContext); }; export default useLoadFeature;
7,108
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useLocalState.ts
import { useEffect, useState } from 'react'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; const useLocalState = <T>(defaultValue: T, key: string) => { const [value, setValue] = useState<T>(() => { try { const localStorageValue = getItem(key); if (typeof localStorageValue !== 'string') { return defaultValue; } return JSON.parse(localStorageValue); } catch (e: any) { return defaultValue; } }); useEffect(() => { setItem(key, JSON.stringify(value)); }, [key, value]); return [value, setValue] as const; }; export default useLocalState;
7,109
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMailSettings.ts
import { useCallback } from 'react'; import { MailSettings as tsMailSettings } from '@proton/shared/lib/interfaces'; import { MailSettingsModel } from '@proton/shared/lib/models'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetMailSettings = (): (() => Promise<tsMailSettings>) => { const api = useApi(); const cache = useCache(); return useCallback(() => { return getPromiseValue(cache, MailSettingsModel.key, () => MailSettingsModel.get(api)); }, [cache, api]); }; export const useMailSettings = (): [tsMailSettings | undefined, boolean, any] => { const cache = useCache(); const miss = useGetMailSettings(); return useCachedModelResult(cache, MailSettingsModel.key, miss); };
7,110
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMainArea.ts
import { RefObject, createContext, useContext } from 'react'; export const MainAreaContext = createContext<RefObject<HTMLElement> | null>(null); export const useMainArea = () => { const mainArea = useContext(MainAreaContext); if (mainArea === null) { throw new Error('Trying to use uninitialized MainAreaContext'); } return mainArea; }; export default useMainArea;
7,111
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMemberAddresses.ts
import { getAllMemberAddresses } from '@proton/shared/lib/api/members'; import { Address, Member, PartialMemberAddress } from '@proton/shared/lib/interfaces'; import { cachedPromise } from './helpers/cachedPromise'; import { useAddresses } from './useAddresses'; import useApi from './useApi'; import useCache from './useCache'; import usePromiseResult from './usePromiseResult'; export function useMemberAddresses( members: Member[], partial: true ): [{ [id: string]: PartialMemberAddress[] } | undefined, boolean, any]; export function useMemberAddresses( members: Member[], partial?: false ): [{ [id: string]: Address[] } | undefined, boolean, any]; export function useMemberAddresses(members: Member[], partial?: boolean) { const cache = useCache(); const api = useApi(); const [addresses] = useAddresses(); return usePromiseResult(async () => { if (!Array.isArray(members)) { return; } const memberAddresses = await Promise.all( members.map((member) => { const key = `member-addresses-${member.ID}`; if (member.Self) { return Promise.resolve(addresses); } // Prefer only addresses (partial) from member if the addresses haven't been fetched if (member.Addresses && partial && !cache.has(key)) { return Promise.resolve(member.Addresses); } return cachedPromise( cache, key, () => { return getAllMemberAddresses(api, member.ID); }, member ); }) ); return members.reduce<{ [id: string]: Address[] | PartialMemberAddress[] }>((acc, { ID }, i) => { return { ...acc, [ID]: memberAddresses[i], }; }, {}); }, [members, addresses]); }
7,112
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMembers.ts
import { useCallback } from 'react'; import { Member } from '@proton/shared/lib/interfaces'; import { MembersModel } from '@proton/shared/lib/models/membersModel'; import { UserModel } from '@proton/shared/lib/models/userModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const useMembers = (): [Member[], boolean, Error] => { const cache = useCache(); const api = useApi(); const miss = useCallback(() => { // Not using use user since it's better to read from the cache // It will be updated from the event manager. const user = cache.get(UserModel.key).value; if (user.isAdmin) { return MembersModel.get(api); } return Promise.resolve([]); }, [api, cache]); return useCachedModelResult(cache, MembersModel.key, miss); }; export default useMembers;
7,113
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMessageCounts.ts
import { useCallback } from 'react'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { MessageCountsModel } from '@proton/shared/lib/models/messageCountsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetMessageCounts = (): (() => Promise<LabelCount[]>) => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => MessageCountsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, MessageCountsModel.key, miss); }, [cache, miss]); }; export const useMessageCounts = (): [LabelCount[], boolean, any] => { const cache = useCache(); const miss = useGetMessageCounts(); return useCachedModelResult(cache, MessageCountsModel.key, miss); };
7,114
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useModals.ts
import { useContext } from 'react'; import ModalsContext from '../containers/modals/modalsContext'; /** * @deprecated Please use useModalTwo or useModalState instead */ const useModals = () => { return useContext(ModalsContext); }; export default useModals;
7,115
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useModalsMap.ts
import { useState } from 'react'; import { ModalWithProps } from '@proton/shared/lib/interfaces/Modal'; export const useModalsMap = <T extends Record<string, ModalWithProps<any>>>(map: T) => { const [modalsMap, setModalsMap] = useState<T>(map); const updateModal = <K extends keyof T>(key: K, newValue: T[K]) => setModalsMap((prevState) => ({ ...prevState, [key]: newValue, })); const closeModal = (key: keyof T) => setModalsMap((prevState) => ({ ...prevState, [key]: { isOpen: false, }, })); return { modalsMap, closeModal, setModalsMap, updateModal }; };
7,116
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMozillaCheck.spec.ts
import { renderHook } from '@testing-library/react-hooks'; import { FREE_SUBSCRIPTION } from '@proton/shared/lib/constants'; import useMozillaCheck from './useMozillaCheck'; import { useTypedSubscription } from './useSubscription'; jest.mock('./useSubscription'); it('should return false if subscription is still loading', () => { jest.mocked(useTypedSubscription).mockReturnValue([undefined, true]); const { result } = renderHook(() => useMozillaCheck()); expect(result.current).toEqual([false, true]); }); it('should return false if not managed by Mozilla', () => { jest.mocked(useTypedSubscription).mockReturnValue([{ isManagedByMozilla: false } as any, false]); const { result } = renderHook(() => useMozillaCheck()); expect(result.current).toEqual([false, false]); }); it('should return true if managed by Mozilla', () => { jest.mocked(useTypedSubscription).mockReturnValue([{ isManagedByMozilla: true } as any, false]); const { result } = renderHook(() => useMozillaCheck()); expect(result.current).toEqual([true, false]); }); it('should return false if subscription is free', () => { jest.mocked(useTypedSubscription).mockReturnValue([FREE_SUBSCRIPTION, false]); const { result } = renderHook(() => useMozillaCheck()); expect(result.current).toEqual([false, false]); });
7,117
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMozillaCheck.ts
import { isFreeSubscription } from '@proton/shared/lib/constants'; import { useTypedSubscription } from './useSubscription'; const useMozillaCheck = (): [isManagedByMozilla: boolean, loading: boolean] => { const [subscription, loading] = useTypedSubscription(); let isManagedByMozilla = false; if (!loading && !isFreeSubscription(subscription)) { isManagedByMozilla = subscription.isManagedByMozilla; } return [isManagedByMozilla, loading]; }; export default useMozillaCheck;
7,118
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMyCountry.test.ts
import { getCountryFromLanguage } from './useMyCountry'; describe('getCountryFromLanguage()', () => { beforeEach(() => { jest.clearAllMocks(); }); it('should prioritize languages as given by the browser', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['de-DE', 'en-EN'], }); expect(getCountryFromLanguage()).toEqual('de'); }); it('should prioritize languages with country code', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['fr', 'en_CA'], }); expect(getCountryFromLanguage()).toEqual('ca'); }); it('should return undefined when the browser language tags do not have country code', () => { const mockNavigator = jest.spyOn(window, 'navigator', 'get'); mockNavigator.mockReturnValue({ ...window.navigator, languages: ['fr', 'en'], }); expect(getCountryFromLanguage()).toBeUndefined(); }); });
7,119
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMyCountry.tsx
import { useCallback } from 'react'; import { findTimeZone } from '@protontech/timezone-support'; import { getLocation } from '@proton/shared/lib/api/vpn'; import { singleCountryTimezoneDatabase } from '@proton/shared/lib/date/singleCountryTimezoneDatabase'; import { manualFindTimeZone } from '@proton/shared/lib/date/timezoneDatabase'; import { getNaiveCountryCode } from '@proton/shared/lib/i18n/helper'; import { Api, MyLocationResponse } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const KEY = 'country'; const tryTimezone = (tz: string): string | undefined => singleCountryTimezoneDatabase[tz as keyof typeof singleCountryTimezoneDatabase]; const getCountryFromTimezone = () => { try { const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; if (timezone) { return tryTimezone(timezone) || tryTimezone(manualFindTimeZone(timezone) || findTimeZone(timezone).name); } } catch (e) { // undefined } }; export const getCountryFromLanguage = () => { return getNaiveCountryCode(navigator.languages.find((language) => /[_-]/.test(language))); }; const getMyCountry = async (api: Api) => { return ( getCountryFromTimezone() || getCountryFromLanguage() || // TODO: Have a non-VPN dedicated API for that purpose (await api<MyLocationResponse>(getLocation()).catch(noop))?.Country )?.toUpperCase(); }; const useMyCountry = (): [string | undefined, boolean, Error] => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => getMyCountry(api), [api]); return useCachedModelResult(cache, KEY, miss); }; export default useMyCountry;
7,120
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useMyLocation.tsx
import { useCallback } from 'react'; import { getLocation } from '@proton/shared/lib/api/vpn'; import { Api, MyLocationResponse } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const KEY = 'location'; const getMyLocationResponse = (api: Api) => { return api<MyLocationResponse>(getLocation()).catch(noop); }; /** * @deprecated Don't use VPN location API outside VPN context. * To get country, use useMyCountry() instead. * For other purpose, get dedicated API route from your BE team. */ const useMyLocation = (): [MyLocationResponse | undefined, boolean, Error] => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => getMyLocationResponse(api), [api]); return useCachedModelResult(cache, KEY, miss); }; export default useMyLocation;
7,121
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useNextSubscription.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { checkSubscription } from '@proton/shared/lib/api/payments'; import { getPlanIDs } from '@proton/shared/lib/helpers/subscription'; import { SubscriptionCheckResponse } from '@proton/shared/lib/interfaces/Subscription'; import useApi from './useApi'; import useSubscription from './useSubscription'; import { useUser } from './useUser'; const useNextSubscription = () => { const [user] = useUser(); const [nextSubscription, setNextSubscription] = useState<SubscriptionCheckResponse | undefined>(); const [loading, withLoading] = useLoading(user.isPaid); const api = useApi(); const [subscription] = useSubscription(); const getNextSubscription = async () => { // Without any coupon const next = await api<SubscriptionCheckResponse>( checkSubscription({ Plans: getPlanIDs(subscription), Currency: subscription.Currency, Cycle: subscription.Cycle, }) ); setNextSubscription(next); }; useEffect(() => { if (subscription && subscription.Plans) { withLoading(getNextSubscription()); } }, [subscription]); return [nextSubscription, loading]; }; export default useNextSubscription;
7,122
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useNotifications.tsx
import { useContext } from 'react'; import NotificationsContext from '../containers/notifications/notificationsContext'; const useNotifications = () => { const manager = useContext(NotificationsContext); if (!manager) { throw new Error('Trying to use uninitialized NotificationsContext'); } return manager; }; export default useNotifications;
7,123
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useOnline.ts
import { useEffect, useState } from 'react'; export const getOnlineStatus = () => { return typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true; }; const useOnline = () => { const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus()); useEffect(() => { const handleOnlineStatus = () => { setOnlineStatus(getOnlineStatus()); }; handleOnlineStatus(); window.addEventListener('online', handleOnlineStatus); window.addEventListener('offline', handleOnlineStatus); return () => { window.removeEventListener('online', handleOnlineStatus); window.removeEventListener('offline', handleOnlineStatus); }; }, []); return onlineStatus; }; export default useOnline;
7,124
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useOrganization.ts
import { useCallback } from 'react'; import { FREE_ORGANIZATION } from '@proton/shared/lib/constants'; import { Organization } from '@proton/shared/lib/interfaces'; import { OrganizationModel } from '@proton/shared/lib/models/organizationModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; import { useGetUser } from './useUser'; export const useGetOrganization = (): (() => Promise<Organization>) => { const api = useApi(); const cache = useCache(); const getUser = useGetUser(); const miss = useCallback(async () => { const user = await getUser(); if (user.isPaid) { return OrganizationModel.get(api); } return Promise.resolve(FREE_ORGANIZATION); }, [api, cache]); return useCallback(() => { return getPromiseValue(cache, OrganizationModel.key, miss); }, [cache, miss]); }; export const useOrganization = (): [Organization, boolean, any] => { const cache = useCache(); const miss = useGetOrganization(); return useCachedModelResult(cache, OrganizationModel.key, miss); };
7,125
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useOrganizationKey.ts
import { Organization } from '@proton/shared/lib/interfaces'; import { cachedPromise } from './helpers/cachedPromise'; import useCache from './useCache'; import { useGetOrganizationKeyRaw } from './useGetOrganizationKeyRaw'; import usePromiseResult from './usePromiseResult'; import { useUser } from './useUser'; export const KEY = 'ORGANIZATION_KEY'; const useOrganizationKey = (organization?: Organization) => { const cache = useCache(); const getOrganizationKeyRaw = useGetOrganizationKeyRaw(); const [user] = useUser(); return usePromiseResult(async () => { if (!user.isAdmin || !organization) { return; } // Warning: There is no event update coming for organization key changes, however, an update for the organization // is received as the keys are changed. So each time it changes, it will redo this. return cachedPromise( cache, KEY, async () => { return getOrganizationKeyRaw(); }, organization ); }, [user, organization]); }; export default useOrganizationKey;
7,126
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useOutgoingAddressForwardings.ts
import { OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import { OutgoingAddressForwardingModel } from '@proton/shared/lib/models/outgoingAddressForwardingModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const useOutgoingAddressForwardings = (): [OutgoingAddressForwarding[], boolean, Error] => { const cache = useCache(); const api = useApi(); const miss = () => OutgoingAddressForwardingModel.get(api); return useCachedModelResult(cache, OutgoingAddressForwardingModel.key, miss); }; export default useOutgoingAddressForwardings;
7,127
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePaymentMethods.ts
import { PaymentMethodsModel } from '@proton/shared/lib/models/paymentMethodsModel'; import { SavedPaymentMethod } from '../payments/core'; import createUseModelHook from './helpers/createModelHook'; export default createUseModelHook<SavedPaymentMethod[]>(PaymentMethodsModel);
7,128
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePendingUserInvitations.ts
import { useCallback } from 'react'; import { PendingInvitation as PendingUserInvitation } from '@proton/shared/lib/interfaces'; import { UserInvitationModel } from '@proton/shared/lib/models'; import { fetchPendingUserInvitations } from '@proton/shared/lib/models/userInvitationModelApi'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const usePendingUserInvitations = (): [PendingUserInvitation[] | undefined, boolean, Error] => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => fetchPendingUserInvitations(api), [api]); return useCachedModelResult(cache, UserInvitationModel.key, miss); }; export default usePendingUserInvitations;
7,129
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePlans.tsx
import { useCallback } from 'react'; import { queryPlans } from '@proton/shared/lib/api/payments'; import { Api, Currency, Plan } from '@proton/shared/lib/interfaces'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; export const KEY = 'plans'; const getPlans = (api: Api, Currency?: Currency) => api<{ Plans: Plan[] }>(queryPlans({ Currency })).then(({ Plans }) => Plans); /** * Requests available plans information */ const usePlans = (currency?: Currency): [Plan[] | undefined, boolean, Error] => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => getPlans(api, currency), [api, currency]); return useCachedModelResult(cache, KEY, miss); }; export default usePlans;
7,130
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePremiumDomains.js
import { useCallback } from 'react'; import { queryPremiumDomains } from '@proton/shared/lib/api/domains'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const getPremiumDomains = (api) => api(queryPremiumDomains()).then(({ Domains = [] }) => Domains); const usePremiumDomains = () => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => getPremiumDomains(api), [api]); return useCachedModelResult(cache, 'premiumDomains', miss); }; export default usePremiumDomains;
7,131
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePreventLeave.tsx
import { ReactNode, createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'; import useBeforeUnload from './useBeforeUnload'; const PreventLeaveContext = createContext<{ clearPendingTasks: () => void; preventLeave: <T>(task: Promise<T>) => Promise<T>; } | null>(null); export default function usePreventLeave() { const preventLeaveState = useContext(PreventLeaveContext); if (!preventLeaveState) { throw new Error('PreventLeaveContext is not initialized, wrap the app with PreventLeaveProvider'); } return preventLeaveState; } export const PreventLeaveProvider = ({ children }: { children: ReactNode }) => { const pendingTasks = useRef(new Set<Promise<any>>()); const [hasPendingTasks, setHasPendingTasks] = useState(false); const clearPendingTasks = useCallback(() => { pendingTasks.current.clear(); }, []); const preventLeave = useCallback( <T,>(task: Promise<T>) => { pendingTasks.current.add(task); if (!hasPendingTasks) { setHasPendingTasks(true); } const cleanup = () => { pendingTasks.current.delete(task); if (!pendingTasks.current.size) { setHasPendingTasks(false); } }; task.then(cleanup).catch(cleanup); return task; }, [hasPendingTasks] ); useBeforeUnload(hasPendingTasks); useEffect(() => { return () => clearPendingTasks(); }, []); return ( <PreventLeaveContext.Provider value={{ preventLeave, clearPendingTasks }}> {children} </PreventLeaveContext.Provider> ); };
7,132
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePrimaryRecoverySecret.ts
import { getPrimaryRecoverySecret } from '@proton/shared/lib/recoveryFile/recoveryFile'; import { useUser } from './useUser'; const usePrimaryRecoverySecret = () => { const [{ Keys }] = useUser(); return getPrimaryRecoverySecret(Keys); }; export default usePrimaryRecoverySecret;
7,133
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useProgressiveRollout.ts
import { useMemo } from 'react'; import { getUserByte } from '@proton/shared/lib/user/helpers'; import { FeatureCode } from '../containers'; import useFeature from './useFeature'; import useUser from './useUser'; const useProgressiveRollout = (code: FeatureCode) => { const [user] = useUser(); const { feature } = useFeature(code); const userID = user?.ID || ''; const userByte = useMemo(() => getUserByte(user), [userID]); const threshold = feature?.Value >= 0 && feature?.Value <= 100 ? feature?.Value : 0; return userByte < Math.floor((threshold / 100) * 255); }; export default useProgressiveRollout;
7,134
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/usePromiseResult.ts
import { DependencyList, Reducer, useEffect, useReducer, useRef } from 'react'; import { STATUS } from '@proton/shared/lib/models/cache'; type ResolvedRecord<T> = { status: STATUS.RESOLVED; value?: T; }; type PendingRecord<T> = { status: STATUS.PENDING; value?: any; promise?: Promise<T>; }; type RejectedRecord = { status: STATUS.REJECTED; value?: Error }; type Record<T> = ResolvedRecord<T> | PendingRecord<T> | RejectedRecord; type State<T> = [T | undefined, boolean, Error | undefined]; const getState = <T>(record: Record<T> = { status: STATUS.PENDING }): State<T> => { return [ record.status === STATUS.PENDING || record.status === STATUS.RESOLVED ? record.value : undefined, record.status === STATUS.PENDING || record.status === STATUS.REJECTED, record.status === STATUS.REJECTED ? record.value : undefined, ]; }; const reducer = <T>(oldValue: State<T>, record: Record<T> = { status: STATUS.PENDING }) => { const newValue = getState(record); if (newValue.every((value, i) => value === oldValue[i])) { return oldValue; } return newValue; }; /** * The difference with this hook vs `useCachedModelResult` is that this hook does not cache the result in the cache. * This hook stores it per component, which means the promise will always be re-run on initial mount. */ const usePromiseResult = <T>(miss: () => Promise<T>, dependencies: DependencyList) => { const ref = useRef<Record<T>>(); const unmountedRef = useRef(false); const [state, dispatch] = useReducer<Reducer<State<T>, Record<T>>, undefined>(reducer, undefined, getState); useEffect(() => { return () => { unmountedRef.current = true; }; }, []); useEffect(() => { const promise = miss(); const record = { status: STATUS.PENDING, value: ref.current ? ref.current.value : undefined, promise, } as const; ref.current = record; dispatch(record); promise .then((value): ResolvedRecord<T> => { return { status: STATUS.RESOLVED, value, }; }) .catch((error): RejectedRecord => { return { status: STATUS.REJECTED, value: error, }; }) .then((record) => { if (unmountedRef.current) { ref.current = undefined; return; } const oldRecord = ref.current; // Ensure it's the latest promise that is running if (!oldRecord || ('promise' in oldRecord && oldRecord.promise !== promise)) { return; } ref.current = record; dispatch(record); }); }, dependencies); return state; }; export default usePromiseResult;
7,135
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useRecoveryNotification.ts
import { c } from 'ttag'; import { ThemeColor } from '@proton/colors'; import { MNEMONIC_STATUS } from '@proton/shared/lib/interfaces'; import { FeatureCode } from '../containers/features/FeaturesContext'; import getLikelyHasKeysToReactivate from '../containers/keys/reactivateKeys/getLikelyHasKeysToReactivate'; import getOverallStatus from '../containers/recovery/getOverallStatus'; import useAddresses from './useAddresses'; import useFeature from './useFeature'; import useHasOutdatedRecoveryFile from './useHasOutdatedRecoveryFile'; import useIsDataRecoveryAvailable from './useIsDataRecoveryAvailable'; import useIsMnemonicAvailable from './useIsMnemonicAvailable'; import useIsRecoveryFileAvailable from './useIsRecoveryFileAvailable'; import useRecoveryStatus from './useRecoveryStatus'; import useUser from './useUser'; const useRecoveryNotification = ( isLessInvasive: boolean ): { path: string; text: string; color: ThemeColor } | undefined => { const [user] = useUser(); const [addresses, loadingAddresses] = useAddresses(); const [{ accountRecoveryStatus, dataRecoveryStatus, mnemonicIsSet }, loadingRecoveryStatus] = useRecoveryStatus(); const [isRecoveryFileAvailable, loadingIsRecoveryFileAvailable] = useIsRecoveryFileAvailable(); const [isMnemonicAvailable, loadingIsMnemonicAvailable] = useIsMnemonicAvailable(); const [isDataRecoveryAvailable, loadingIsDataRecoveryAvailable] = useIsDataRecoveryAvailable(); const hasOutdatedRecoveryFile = useHasOutdatedRecoveryFile(); const { feature: hasDismissedRecoverDataCard } = useFeature(FeatureCode.DismissedRecoverDataCard); const hasKeysToReactivate = getLikelyHasKeysToReactivate(user, addresses); const overallStatus = getOverallStatus({ accountRecoveryStatus, dataRecoveryStatus, isDataRecoveryAvailable }); const loading = loadingRecoveryStatus || loadingIsRecoveryFileAvailable || loadingIsMnemonicAvailable || loadingIsDataRecoveryAvailable || loadingAddresses; if (loading) { return; } if (!isDataRecoveryAvailable) { return; } const hasOutdatedMnemonic = user.MnemonicStatus === MNEMONIC_STATUS.OUTDATED; if (isMnemonicAvailable && hasOutdatedMnemonic) { return { path: '/recovery#data', text: c('Action').t`Update recovery phrase`, color: ThemeColor.Danger, }; } if (isRecoveryFileAvailable && hasOutdatedRecoveryFile) { return { path: '/recovery#data', text: c('Action').t`Update recovery file`, color: ThemeColor.Danger, }; } if (isLessInvasive) { return; } if (hasKeysToReactivate && hasDismissedRecoverDataCard?.Value === false) { return { path: '/recovery?action=recover-data', text: c('Action').t`Unlock data`, color: ThemeColor.Danger, }; } if (mnemonicIsSet || overallStatus === 'complete') { return; } const mnemonicCanBeSet = user.MnemonicStatus === MNEMONIC_STATUS.ENABLED || user.MnemonicStatus === MNEMONIC_STATUS.PROMPT; if (isMnemonicAvailable && mnemonicCanBeSet) { return { path: '/recovery?action=generate-recovery-phrase', text: c('Action').t`Set recovery phrase`, color: ThemeColor.Warning, }; } return { path: '/recovery', text: c('Action').t`Activate recovery`, color: ThemeColor.Warning, }; }; export default useRecoveryNotification;
7,136
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useRecoverySecrets.ts
import { getRecoverySecrets } from '@proton/shared/lib/recoveryFile/recoveryFile'; import { useUser } from './useUser'; const useRecoverySecrets = () => { const [{ Keys }] = useUser(); return getRecoverySecrets(Keys); }; export default useRecoverySecrets;
7,137
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useRecoveryStatus.ts
import { MNEMONIC_STATUS } from '@proton/shared/lib/interfaces'; import RecoveryStatus from '../containers/recovery/RecoveryStatus'; import usePrimaryRecoverySecret from './usePrimaryRecoverySecret'; import { useUser } from './useUser'; import useUserSettings from './useUserSettings'; const useRecoveryStatus = () => { const [user] = useUser(); const [userSettings, loadingUserSettings] = useUserSettings(); const hasVerifiedRecoveryEmailAddress = !!userSettings?.Email?.Reset && !!userSettings?.Email?.Value; const hasRecoveryPhoneNumber = !!userSettings?.Phone?.Reset && !!userSettings?.Phone?.Value; const primaryRecoverySecret = usePrimaryRecoverySecret(); const hasCurrentRecoveryFile = primaryRecoverySecret !== undefined; const accountRecoveryStatus: RecoveryStatus = hasVerifiedRecoveryEmailAddress || hasRecoveryPhoneNumber ? 'complete' : 'incomplete'; const mnemonicIsSet = user.MnemonicStatus === MNEMONIC_STATUS.SET; const dataRecoveryStatus: RecoveryStatus = mnemonicIsSet || hasCurrentRecoveryFile ? 'complete' : 'incomplete'; return [ { accountRecoveryStatus, dataRecoveryStatus, mnemonicIsSet, }, loadingUserSettings || !userSettings, ] as const; }; export default useRecoveryStatus;
7,138
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useRelocalizeText.ts
import { useCallback } from 'react'; import { relocalizeText } from '@proton/shared/lib/i18n/relocalize'; import useUserSettings from './useUserSettings'; const useRelocalizeText = () => { const [userSettings] = useUserSettings(); return useCallback( async ({ getLocalizedText, newLocaleCode, relocalizeDateFormat, }: { getLocalizedText: () => string; newLocaleCode?: string; relocalizeDateFormat?: boolean; }) => { return relocalizeText({ getLocalizedText, newLocaleCode, relocalizeDateFormat, userSettings, }); }, [userSettings] ); }; export default useRelocalizeText;
7,139
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useRevisionRetentionDays.tsx
import { FormEvent, useEffect, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { queryUpdateUserSettings, queryUserSettings } from '@proton/shared/lib/api/drive/userSettings'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import type { RevisionRetentionDaysSetting, UserSettingsResponse, } from '@proton/shared/lib/interfaces/drive/userSettings'; import { useConfirmActionModal } from '../components/confirmActionModal'; import { getRetentionLabel } from '../containers/drive/settings/retentionLabels'; import useApi from './useApi'; import useNotifications from './useNotifications'; const useRevisionRetentionDays = ( hasPaidDrive: boolean, showConfirmActionModal: ReturnType<typeof useConfirmActionModal>['1'] ) => { const api = useApi(); const [isLoading, withLoading] = useLoading(hasPaidDrive); const [isSubmitLoading, withSubmitLoading] = useLoading(); const { createNotification } = useNotifications(); const [originalRevisionRetentionDays, setOriginalRevisionRetentionDays] = useState<RevisionRetentionDaysSetting>(); const [revisionRetentionDays, setRevisionRetentionDay] = useState<RevisionRetentionDaysSetting>(); const hasValueChanged = originalRevisionRetentionDays !== revisionRetentionDays; useEffect(() => { void withLoading( api<UserSettingsResponse>(queryUserSettings()).then(({ UserSettings, Defaults }) => { if ( UserSettings.RevisionRetentionDays !== null && UserSettings.RevisionRetentionDays !== undefined && hasPaidDrive ) { setOriginalRevisionRetentionDays(UserSettings.RevisionRetentionDays); setRevisionRetentionDay(UserSettings.RevisionRetentionDays); } else { setOriginalRevisionRetentionDays(Defaults.RevisionRetentionDays); setRevisionRetentionDay(Defaults.RevisionRetentionDays); } return; }) ); }, [hasPaidDrive]); const handleChange = (newRevisionRetentionDay: RevisionRetentionDaysSetting) => { setRevisionRetentionDay(newRevisionRetentionDay); }; const updateRevisionRetentionDay = () => { return withSubmitLoading( api<UserSettingsResponse>( queryUpdateUserSettings({ RevisionRetentionDays: revisionRetentionDays, }) ) ) .then(() => { createNotification({ text: c('Info').t`Settings updated`, }); setOriginalRevisionRetentionDays(revisionRetentionDays); }) .catch((err) => { createNotification({ type: 'error', text: c('Info').t`Settings update failed`, }); setRevisionRetentionDay(originalRevisionRetentionDays); console.error('Settings update failed.', err); }); }; const handleSubmit = (e: FormEvent) => { e.preventDefault(); if (revisionRetentionDays === undefined) { return; } if (originalRevisionRetentionDays && originalRevisionRetentionDays > revisionRetentionDays) { const rententionLabel = getRetentionLabel(revisionRetentionDays); const message = revisionRetentionDays === 0 ? [ c('Info').t`This will delete all previous versions of your files.`, <br />, c('Info').jt`${DRIVE_APP_NAME} will no longer keep previous versions of your files.`, ] : c('Info').t`This will delete all previous versions of your files older than ${rententionLabel}.`; void showConfirmActionModal({ title: c('Title').t`Delete version history?`, onSubmit: updateRevisionRetentionDay, onCancel: () => setRevisionRetentionDay(originalRevisionRetentionDays), size: 'medium', message, submitText: c('Action').t`Delete and confirm`, }); } else { void updateRevisionRetentionDay(); } }; return { revisionRetentionDays, hasValueChanged, isLoading, isSubmitLoading, handleChange, handleSubmit, }; }; export default useRevisionRetentionDays;
7,140
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSearch.tsx
import { KeyboardEvent, MouseEvent, ReactNode, RefObject, useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { sanitizeString } from '@proton/shared/lib/sanitize'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { getMatch } from './helpers/search'; import useClickOutside from './useClickOutside'; // should result in an object that only has values from T that are assignable to string type SearchableObject<T> = { [Key in KeyOfUnion<T>]: T[KeyOfUnion<T>] extends string ? T[KeyOfUnion<T>] : undefined }; type KeyOfUnion<T> = T extends any ? keyof T : never; /** *useSearch hook * * @template T Type of entries, could be union * @param sources Array of functions returning entries * @param keys Array of entries' keys to search, all by default * @param mapFn Function that accepts a list of items collected from sources and returns a subset of that list, do sorting/filter here * @param highlightFn Function that accepts a string and wraps it with element you need, <mark /> by default * @param inputValue Search string * @param minSymbols Minimum symbols to start searching * @param resetField * @param onSelect */ function useSearch<T extends object, K = keyof SearchableObject<T>>({ inputValue = '', minSymbols = 1, mapFn, onSelect, onSubmit = noop, validate = () => true, resetField, sources, keys, highlightFn = (str: string) => <mark className="is-light">{str}</mark>, }: { inputValue?: string; minSymbols?: number; onSelect: (item: T) => void; onSubmit?: (input: string) => void; mapFn?: (items: SearchableObject<T>[]) => T[]; validate?: (inputValue: string) => boolean | undefined | void; resetField: () => void; sources: ((match: string) => T[])[]; keys?: K[]; highlightFn?: (a1: string) => JSX.Element; }) { const [isFocused, setIsFocused] = useState(false); const [error, setError] = useState(''); const [selectedSuggest, setSelectedSuggest] = useState<number>(0); const parentRef = useRef<HTMLDivElement>(null); const selectedSuggestRef = useRef<HTMLDivElement>(null); const [itemProps, setItemProps] = useState<({ ref: RefObject<HTMLDivElement> } | null)[]>([]); const searchSuggestions = useMemo(() => { const matchString = sanitizeString(inputValue).toLowerCase(); if (matchString.length < minSymbols) { return []; } let itemList = sources.flatMap((source) => source(matchString)); // theoretically, this is an error in types, but it's the only way to let typescript // typecheck keys and mapFn arguments without doing the work in runtime if (mapFn) { itemList = mapFn(itemList as unknown as SearchableObject<T>[]); } const results = itemList .map((item) => { const matchedProps: { [key in KeyOfUnion<T>]?: ReactNode } = {}; // when keys are not defined we still pick only searchable keys const keyList = (keys || Object.keys(item).filter( (key) => typeof item[key as KeyOfUnion<T>] === 'string' )) as KeyOfUnion<T>[]; for (const prop of keyList) { const content = item[prop]; const match = content && typeof content === 'string' && getMatch(content, matchString, highlightFn); if (match) { matchedProps[prop] = match; } } return { item, matchedProps }; }) .filter(({ matchedProps }) => Object.keys(matchedProps).length > 0) .map((item, key) => ({ ...item, key, onClick: (e: MouseEvent<HTMLButtonElement>) => { e.preventDefault(); e.stopPropagation(); resetField(); onSelect(item.item); }, })); return results; }, [inputValue]); const totalSuggestions = searchSuggestions.length; useEffect(() => setSelectedSuggest(0), [searchSuggestions]); useEffect(() => { setError(''); if (inputValue) { setIsFocused(true); } }, [inputValue]); useEffect(() => { setItemProps( searchSuggestions.map((_, index) => (index === selectedSuggest ? { ref: selectedSuggestRef } : null)) ); }, [selectedSuggest]); useEffect(() => { if (!isFocused) { return; } selectedSuggestRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, [itemProps, isFocused]); const selectNextItem = useCallback(() => { const newSelectedSuggest = (selectedSuggest + 1) % totalSuggestions; setSelectedSuggest(newSelectedSuggest); }, [selectedSuggest, setSelectedSuggest, totalSuggestions]); const selectPreviousItem = useCallback(() => { const newSelectedSuggest = (selectedSuggest + totalSuggestions - 1) % totalSuggestions; setSelectedSuggest(newSelectedSuggest); }, [selectedSuggest, setSelectedSuggest, totalSuggestions]); const trySubmit = useMemo( () => () => { try { // validate can implement validation through throwing or returning false const isValid = validate(inputValue); if (isValid !== false) { onSubmit(inputValue); resetField(); } } catch (e: any) { if (e.message) { setError(e.message); } } }, [validate, inputValue, onSubmit, resetField, setError] ); const onKeyDown = useCallback( (event: KeyboardEvent<HTMLInputElement>) => { switch (event.key) { case 'Escape': { event.preventDefault(); setIsFocused(false); break; } case 'Enter': { const firstSuggestion = searchSuggestions[selectedSuggest]?.item; if (firstSuggestion) { event.preventDefault(); onSelect(firstSuggestion); resetField(); } else { if (!inputValue) { return; } event.preventDefault(); trySubmit(); } break; } case 'Tab': { if (totalSuggestions) { event.preventDefault(); if (totalSuggestions === 1) { const firstSuggestion = searchSuggestions[selectedSuggest]?.item; onSelect(firstSuggestion); resetField(); } else if (event.shiftKey) { selectPreviousItem(); } else { selectNextItem(); } } else { if (!inputValue) { return; } event.preventDefault(); trySubmit(); } break; } case 'ArrowDown': { if (!totalSuggestions) { return; } event.preventDefault(); selectNextItem(); break; } case 'ArrowUp': { if (!totalSuggestions) { return; } event.preventDefault(); selectPreviousItem(); break; } default: } }, [selectedSuggest, setSelectedSuggest, searchSuggestions] ); const onFocus = useCallback(() => setIsFocused(true), [setIsFocused]); useClickOutside(parentRef, () => { setIsFocused(false); }); return { error, selectedSuggest, inputProps: { onKeyDown, onFocus }, searchSuggestions, datalistProps: { className: clsx([ 'autocomplete-suggestions', isFocused && searchSuggestions.length > 0 ? 'autocomplete-suggestions--open' : 'no-pointer-events', ]), }, parentProps: { className: clsx(['autocomplete-input relative']), ref: parentRef, }, itemProps, isFocused, }; } export default useSearch;
7,141
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSearchParamsEffect.ts
import { useEffect } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; const useSearchParamsEffect = (cb: (params: URLSearchParams) => URLSearchParams | undefined, deps: any[]) => { const history = useHistory(); const location = useLocation(); useEffect(() => { const params = new URLSearchParams(location.search); const result = cb(params); if (result) { history.replace({ ...location, search: result.toString() }); } }, [location.search, ...deps]); }; export default useSearchParamsEffect;
7,142
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSendIcs.ts
import { useCallback } from 'react'; import { sendMessageDirect } from '@proton/shared/lib/api/messages'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding'; import { pick } from '@proton/shared/lib/helpers/object'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import { SEND_MESSAGE_DIRECT_ACTION } from '@proton/shared/lib/interfaces/message'; import { RequireSome, SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { AUTO_SAVE_CONTACTS } from '@proton/shared/lib/mail/mailSettings'; import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments'; import generatePackages from '@proton/shared/lib/mail/send/generatePackages'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import isTruthy from '@proton/utils/isTruthy'; import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; import { useApi, useGetAddressKeys, useGetEncryptionPreferences, useGetMailSettings } from './index'; export interface SendIcsParams { method: ICAL_METHOD; ics: string; from: RequireSome<Recipient, 'Address' | 'Name'>; addressID: string; parentID?: string; to: RequireSome<Recipient, 'Address' | 'Name'>[]; subject: string; plainTextBody?: string; sendPreferencesMap?: SimpleMap<SendPreferences>; contactEmailsMap?: SimpleMap<ContactEmail>; } const useSendIcs = () => { const api = useApi(); const getAddressKeys = useGetAddressKeys(); const getMailSettings = useGetMailSettings(); const getEncryptionPreferences = useGetEncryptionPreferences(); const send = useCallback( async ({ method, ics, from, addressID, parentID, to, subject, plainTextBody = '', sendPreferencesMap = {}, contactEmailsMap, }: SendIcsParams) => { if (!to.length) { return; } if (!addressID) { throw new Error('Missing addressID'); } const { publicKeys: allPublicKeys, privateKeys: allPrivateKeys } = splitKeys( await getAddressKeys(addressID) ); const [publicKeys, privateKeys] = [allPublicKeys.slice(0, 1), allPrivateKeys.slice(0, 1)]; const { AutoSaveContacts, Sign } = await getMailSettings(); const inviteAttachment = new File([new Blob([ics])], 'invite.ics', { type: `text/calendar; method=${method}`, }); const packets = await encryptAttachment(ics, inviteAttachment, false, publicKeys, privateKeys); const concatenatedPackets = mergeUint8Arrays( [packets.data, packets.keys, packets.signature].filter(isTruthy) ); const emails = to.map(({ Address }) => Address); const attachment = { Filename: packets.Filename, MIMEType: packets.MIMEType, Contents: uint8ArrayToBase64String(concatenatedPackets), KeyPackets: uint8ArrayToBase64String(packets.keys), Signature: packets.signature ? uint8ArrayToBase64String(packets.signature) : undefined, }; const attachmentData = { attachment, data: ics, }; const directMessage = { ToList: to, CCList: [], BCCList: [], Subject: subject, Sender: from, Body: plainTextBody, MIMEType: MIME_TYPES.PLAINTEXT, Attachments: [pick(attachment, ['Filename', 'MIMEType', 'Contents'])], Flags: Sign ? MESSAGE_FLAGS.FLAG_SIGN : undefined, }; const sendPrefsMap: SimpleMap<SendPreferences> = {}; await Promise.all( emails.map(async (email) => { const existingSendPreferences = sendPreferencesMap[email]; if (existingSendPreferences) { sendPrefsMap[email] = existingSendPreferences; return; } const encryptionPreferences = await getEncryptionPreferences({ email, lifetime: 0, contactEmailsMap, }); const sendPreferences = getSendPreferences(encryptionPreferences, directMessage); sendPrefsMap[email] = sendPreferences; }) ); // throw if trying to send a reply to an organizer with send preferences error if (method === ICAL_METHOD.REPLY) { const sendPrefError = sendPrefsMap[to[0].Address]?.error; if (sendPrefError) { throw sendPrefError; } } const packages = await generatePackages({ message: directMessage, sendPreferencesMap: sendPrefsMap, attachmentData, attachments: [attachment], emails, publicKeys, privateKeys, }); const payload: any = { Message: directMessage, AttachmentKeys: uint8ArrayToBase64String(packets.keys), // do not save organizer address as contact on REPLY (it could be a calendar group address) AutoSaveContacts: method === ICAL_METHOD.REPLY ? AUTO_SAVE_CONTACTS.DISABLED : AutoSaveContacts, Packages: Object.values(packages), }; if (parentID) { // set the action to tell the API that this is a response to the message with ID = parentID payload.ParentID = parentID; payload.Action = SEND_MESSAGE_DIRECT_ACTION.REPLY; } await api({ ...sendMessageDirect(payload), silence: true }); }, [api, getMailSettings, getAddressKeys, getEncryptionPreferences] ); return send; }; export default useSendIcs;
7,143
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSessionRecovery.ts
import { APPS, DAY, HOUR } from '@proton/shared/lib/constants'; import { MNEMONIC_STATUS, SessionRecoveryState } from '@proton/shared/lib/interfaces'; import { getHasMigratedAddressKeys } from '@proton/shared/lib/keys'; import { useSessionRecoveryLocalStorage } from '../containers/account/sessionRecovery/SessionRecoveryLocalStorageManager'; import { useFlag } from '../containers/unleash'; import useAddresses from './useAddresses'; import useAuthentication from './useAuthentication'; import useConfig from './useConfig'; import useUser from './useUser'; import useUserSettings from './useUserSettings'; export const useIsSessionRecoveryInitiatedByCurrentSession = () => { const [user] = useUser(); const authentication = useAuthentication(); if (!user?.AccountRecovery) { return null; } return user.AccountRecovery.UID === authentication.getUID(); }; export const useSessionRecoveryState = () => { const [user] = useUser(); if (!user?.AccountRecovery) { return SessionRecoveryState.NONE; } return user.AccountRecovery.State; }; export const useIsSessionRecoveryEnabled = () => { const [userSettings] = useUserSettings(); return !!userSettings?.SessionAccountRecovery; }; export const useHasRecoveryMethod = () => { const [user] = useUser(); const [userSettings, loadingUserSettings] = useUserSettings(); const hasRecoveryEmail = !!userSettings?.Email.Reset && !!userSettings?.Email.Value; const hasRecoveryPhone = !!userSettings?.Phone.Reset && !!userSettings?.Phone.Value; const hasRecoveryPhrase = user.MnemonicStatus === MNEMONIC_STATUS.SET; const hasRecoveryMethod = hasRecoveryEmail || hasRecoveryPhone || hasRecoveryPhrase; return [hasRecoveryMethod, loadingUserSettings] as const; }; export const useIsSessionRecoveryAvailable = () => { const [user] = useUser(); const [addresses = [], loadingAddresses] = useAddresses(); const { APP_NAME } = useConfig(); const hasMigratedKeys = getHasMigratedAddressKeys(addresses); const feature = useFlag('SignedInAccountRecovery'); const isPrivateUser = user?.isPrivate; return [ APP_NAME !== APPS.PROTONVPN_SETTINGS && !loadingAddresses && hasMigratedKeys && feature && isPrivateUser, loadingAddresses, ]; }; export const useIsSessionRecoveryInitiationAvailable = () => { const [isSessionRecoveryAvailable] = useIsSessionRecoveryAvailable(); const isSessionRecoveryEnabled = useIsSessionRecoveryEnabled(); const sessionRecoveryState = useSessionRecoveryState(); const sessionRecoveryInitiated = sessionRecoveryState === SessionRecoveryState.GRACE_PERIOD || sessionRecoveryState === SessionRecoveryState.INSECURE; return isSessionRecoveryAvailable && isSessionRecoveryEnabled && !sessionRecoveryInitiated; }; /** * Determines whether applications should display session recovery in progress "notifications". * Notifications here means banners or modals and not the browser notifications. */ export const useShouldNotifySessionRecoveryInProgress = () => { const [isSessionRecoveryAvailable] = useIsSessionRecoveryAvailable(); const sessionRecoveryState = useSessionRecoveryState(); const isSessionRecoveryInitiatedByCurrentSession = useIsSessionRecoveryInitiatedByCurrentSession(); const { hasConfirmedSessionRecoveryInProgress } = useSessionRecoveryLocalStorage(); return ( isSessionRecoveryAvailable && sessionRecoveryState === SessionRecoveryState.GRACE_PERIOD && !hasConfirmedSessionRecoveryInProgress && !isSessionRecoveryInitiatedByCurrentSession ); }; /** * Determines whether applications should display password reset available "notifications". * Notifications here means banners or modals and not the browser notifications. */ export const useShouldNotifyPasswordResetAvailable = () => { const [isSessionRecoveryAvailable] = useIsSessionRecoveryAvailable(); const sessionRecoveryState = useSessionRecoveryState(); return isSessionRecoveryAvailable && sessionRecoveryState === SessionRecoveryState.INSECURE; }; export const useSessionRecoveryGracePeriodHoursRemaining = () => { const [user] = useUser(); if (!user.AccountRecovery || user.AccountRecovery.State !== SessionRecoveryState.GRACE_PERIOD) { return null; } const msRemaining = user.AccountRecovery.EndTime * 1000 - Date.now(); return Math.ceil(msRemaining / HOUR); }; export const useSessionRecoveryInsecureTimeRemaining = () => { const [user] = useUser(); if (!user.AccountRecovery || user.AccountRecovery.State !== SessionRecoveryState.INSECURE) { return null; } const msRemaining = user.AccountRecovery.EndTime * 1000 - Date.now(); const inHours = Math.floor(msRemaining / HOUR); const inDays = Math.floor(msRemaining / DAY); return { inHours, inDays, }; }; export const useShouldNotifySessionRecoveryCancelled = () => { const [isSessionRecoveryAvailable] = useIsSessionRecoveryAvailable(); const sessionRecoveryState = useSessionRecoveryState(); const { hasDismissedSessionRecoveryCancelled } = useSessionRecoveryLocalStorage(); return ( isSessionRecoveryAvailable && sessionRecoveryState === SessionRecoveryState.CANCELLED && !hasDismissedSessionRecoveryCancelled ); };
7,144
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSortedList.test.ts
import { act, renderHook } from '@testing-library/react-hooks'; import { SORT_DIRECTION } from '@proton/shared/lib/constants'; import useSortedList from './useSortedList'; describe('useSortedList hook', () => { it('should return sorted list initially if config is provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.DESC })); expect(result.current.sortedList).toEqual([{ t: 3 }, { t: 2 }, { t: 1 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.DESC }); }); it('should not sort initially if no config is provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list)); expect(result.current.sortedList).toEqual(list); expect(result.current.sortConfig).toBeUndefined(); }); it('should set initialize sorting config on sort when none was provided', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list)); act(() => result.current.toggleSort('t')); expect(result.current.sortedList).toEqual([{ t: 1 }, { t: 2 }, { t: 3 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); }); it('should toggle sort direction for the same key', () => { const list = [{ t: 2 }, { t: 3 }, { t: 1 }]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.ASC })); expect(result.current.sortedList).toEqual([{ t: 1 }, { t: 2 }, { t: 3 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); act(() => result.current.toggleSort('t')); expect(result.current.sortedList).toEqual([{ t: 3 }, { t: 2 }, { t: 1 }]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.DESC }); }); it('should change sort key and set direction to ascending for another key', () => { const list = [ { t: 2, k: 'c' }, { t: 3, k: 'b' }, { t: 1, k: 'a' }, ]; const { result } = renderHook(() => useSortedList(list, { key: 't', direction: SORT_DIRECTION.ASC })); expect(result.current.sortedList).toEqual([ { t: 1, k: 'a' }, { t: 2, k: 'c' }, { t: 3, k: 'b' }, ]); expect(result.current.sortConfig).toEqual({ key: 't', direction: SORT_DIRECTION.ASC }); act(() => result.current.toggleSort('k')); expect(result.current.sortedList).toEqual([ { t: 1, k: 'a' }, { t: 3, k: 'b' }, { t: 2, k: 'c' }, ]); expect(result.current.sortConfig).toEqual({ key: 'k', direction: SORT_DIRECTION.ASC }); }); });
7,145
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSortedList.ts
import { useMemo, useState } from 'react'; import { SORT_DIRECTION } from '@proton/shared/lib/constants'; export interface SortConfig<T> { key: keyof T; direction: SORT_DIRECTION; compare?: (a: any, b: any) => number; } /** * Handles multi-parameter sorting logic for lists */ export const useMultiSortedList = <T>(list: T[], initialConfig: SortConfig<T>[] = []) => { const [configs, setConfigs] = useState(initialConfig); const sortedList = useMemo(() => { if (!configs.length) { return list; } const comparator = (a: T, b: T) => { const defaultCompare = (a: T[keyof T], b: T[keyof T]) => { if (typeof a === 'string' && typeof b === 'string') { return a.localeCompare(b); } if (a < b) { return -1; } if (a > b) { return 1; } return 0; }; for (let i = 0; i < configs.length; i++) { const config = configs[i]; const { key } = config; const compare = ('compare' in config && config.compare) || defaultCompare; const result = config.direction === SORT_DIRECTION.ASC ? compare(a[key], b[key]) : compare(b[key], a[key]); if (result !== 0) { return result; } } return 0; }; return [...list].sort(comparator); }, [configs, list]); return { sortConfigs: configs, sortedList, setConfigs }; }; /** * Handles sorting logic for lists. */ const useSortedList = <T>(list: T[], initialConfig?: SortConfig<T>) => { const { setConfigs, sortConfigs, sortedList } = useMultiSortedList(list, initialConfig && [initialConfig]); const toggleSort = (key: keyof T) => { if (key === sortConfigs[0]?.key) { setConfigs((configs) => [ { key, direction: configs[0]?.direction === SORT_DIRECTION.ASC ? SORT_DIRECTION.DESC : SORT_DIRECTION.ASC, }, ]); } else { setConfigs([{ key, direction: SORT_DIRECTION.ASC }]); } }; const setSort = (key: keyof T, direction: SORT_DIRECTION) => { setConfigs([{ key, direction }]); }; return { sortConfig: sortConfigs[0], sortedList, setSort, toggleSort }; }; /** * Handles sorting logic, when data is async. */ export const useSortedListAsync = <T>(initialConfig: SortConfig<T>) => useSortedList([], initialConfig); export default useSortedList;
7,146
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSpotlightOnFeature.tsx
import { useCallback, useMemo, useState } from 'react'; import useEarlyAccess from '@proton/components/hooks/useEarlyAccess'; import useUser from '@proton/components/hooks/useUser'; import { SECOND } from '@proton/shared/lib/constants'; import { getEnvironmentDate } from '@proton/shared/lib/spotlight/helpers'; import { SpotlightDate } from '@proton/shared/lib/spotlight/interface'; import { FeatureCode } from '../containers/features/FeaturesContext'; import useFeature from './useFeature'; /** * This hook is used to leverage from our FeatureFlag system in order to display only once the spotlight to the user. * When/if the spotlight is getting displayed, `onDisplayed` callback should be called in order to turn the feature flag off. * Obviously, an additional FF should used rather than the highlighted feature's one itself * * @dev Pass releaseDates if you want to hide the spotlight for users created after the release date * @dev Pass expiration if you want to stop showing the spotlight after a certain date */ const useSpotlightOnFeature = ( code: FeatureCode, initialShow = true, releaseDates?: SpotlightDate, expirationDates?: SpotlightDate ) => { const [manualClose, setManualClose] = useState(false); const { feature, update, loading: loadingFeature } = useFeature(code); const [user, loadingUser] = useUser(); const { currentEnvironment, loading: loadingCurrentEnvironment } = useEarlyAccess(); const loading = loadingFeature || loadingUser || !user || loadingCurrentEnvironment; // If the feature flag value is changing right after the spotlight is displayed, we don't want it to be closed automatically const show = useMemo(() => { // Stop showing the spotlight after the expiration date if (expirationDates) { const expirationDate = getEnvironmentDate(currentEnvironment, expirationDates); if (Date.now() > expirationDate) { return false; } } const hideBecauseIsNewUser = releaseDates ? user.CreateTime * SECOND > getEnvironmentDate(currentEnvironment, releaseDates) : false; return initialShow && !loading && !!feature?.Value && !manualClose && !hideBecauseIsNewUser; }, [initialShow, loading, manualClose]); const onDisplayed = useCallback(() => { void update(false); }, []); const onClose = () => setManualClose(true); return { show, onDisplayed, onClose }; }; export default useSpotlightOnFeature;
7,147
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useStep.ts
import { useState } from 'react'; const useStep = (initialStep = 0) => { const [step, updateStep] = useState(initialStep); const next = () => updateStep((s) => s + 1); const previous = () => updateStep((s) => s - 1); const goTo = (s: number) => updateStep(s); return { step, next, previous, goTo, }; }; export default useStep;
7,148
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSubscribedCalendars.ts
import { useEffect, useMemo, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { getSubscriptionParameters } from '@proton/shared/lib/api/calendars'; import { getIsSubscribedCalendar, getVisualCalendars } from '@proton/shared/lib/calendar/calendar'; import { getIsCalendarSubscriptionEventManagerUpdate } from '@proton/shared/lib/calendar/subscribe/helpers'; import { findMemberIndices, getIsCalendarEventManagerCreate, getIsCalendarEventManagerDelete, getIsCalendarEventManagerUpdate, getIsCalendarMemberEventManagerCreate, getIsCalendarMemberEventManagerDelete, getIsCalendarMemberEventManagerUpdate, } from '@proton/shared/lib/eventManager/calendar/helpers'; import { Calendar, CalendarMember, CalendarSubscription, CalendarSubscriptionResponse, CalendarWithOwnMembers, SubscribedCalendar, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { CalendarEventManager, CalendarMemberEventManager, CalendarSubscriptionEventManager, } from '@proton/shared/lib/interfaces/calendar/EventManager'; import addItem from '@proton/utils/addItem'; import removeItem from '@proton/utils/removeIndex'; import updateItem from '@proton/utils/updateItem'; import { useCalendarModelEventManager } from '../containers/eventManager/calendar'; import useApi from './useApi'; import useEventManager from './useEventManager'; const useSubscribedCalendars = (calendars: VisualCalendar[], loadingCalendars = false) => { const [subscribedCalendars, setSubscribedCalendars] = useState<SubscribedCalendar[]>([]); const [loading, withLoading] = useLoading(true); const api = useApi(); const calendarIDs = useMemo(() => calendars.map(({ ID }) => ID), [calendars]); const { subscribe: coreSubscribe } = useEventManager(); const { subscribe: calendarSubscribe } = useCalendarModelEventManager(); const handleAddCalendar = async (calendar: CalendarWithOwnMembers) => { if (!getIsSubscribedCalendar(calendar)) { return; } const { CalendarSubscription } = await api<CalendarSubscriptionResponse>( getSubscriptionParameters(calendar.ID) ); setSubscribedCalendars((prevState = []) => getVisualCalendars([ ...prevState, { ...calendar, SubscriptionParameters: CalendarSubscription, }, ]) ); }; const handleDeleteCalendar = (calendarID: string) => { setSubscribedCalendars((subscribedCalendars) => { const index = subscribedCalendars?.findIndex((calendar) => calendar.ID === calendarID); return removeItem(subscribedCalendars, index); }); }; const handleUpdateCalendar = (calendar: Calendar) => { setSubscribedCalendars((subscribedCalendars) => { const { ID } = calendar; const index = subscribedCalendars?.findIndex((calendar) => calendar.ID === ID); return updateItem(subscribedCalendars, index, { ...subscribedCalendars[index], ...calendar, }); }); }; const handleDeleteMember = (memberID: string) => { setSubscribedCalendars((subscribedCalendars) => { const [calendarIndex, memberIndex] = findMemberIndices(memberID, subscribedCalendars); if (calendarIndex === -1 || memberIndex === -1) { return subscribedCalendars; } const oldCalendar = subscribedCalendars[calendarIndex]; return updateItem(subscribedCalendars, calendarIndex, { ...oldCalendar, Members: removeItem(oldCalendar.Members, memberIndex), }); }); }; const handleCreateMember = (member: CalendarMember) => { setSubscribedCalendars((subscribedCalendars) => { const { ID: memberID, CalendarID } = member; const [calendarIndex, memberIndex] = findMemberIndices(memberID, subscribedCalendars, CalendarID); if (calendarIndex === -1 || memberIndex !== -1) { return subscribedCalendars; } const oldCalendar = subscribedCalendars[calendarIndex]; return updateItem(subscribedCalendars, calendarIndex, { ...oldCalendar, Members: addItem(oldCalendar.Members, member), }); }); }; const handleUpdateMember = (member: CalendarMember) => { setSubscribedCalendars((subscribedCalendars) => { const { ID: memberID, CalendarID } = member; const [calendarIndex, memberIndex] = findMemberIndices(memberID, subscribedCalendars, CalendarID); if (calendarIndex === -1 || memberIndex === -1) { return subscribedCalendars; } const oldCalendar = subscribedCalendars[calendarIndex]; return getVisualCalendars( updateItem(subscribedCalendars, calendarIndex, { ...oldCalendar, Members: updateItem(oldCalendar.Members, memberIndex, member), }) ); }); }; const handleUpdateSubscription = (calendarID: string, subscription: CalendarSubscription) => { setSubscribedCalendars((subscribedCalendars) => { const index = subscribedCalendars?.findIndex((calendar) => calendar.ID === calendarID); const oldCalendar = subscribedCalendars[index]; return updateItem(subscribedCalendars, index, { ...oldCalendar, SubscriptionParameters: { ...oldCalendar.SubscriptionParameters, ...subscription, }, }); }); }; useEffect(() => { if (loadingCalendars) { return; } return coreSubscribe( ({ Calendars: CalendarEvents = [], CalendarMembers: CalendarMembersEvents = [], }: { Calendars?: CalendarEventManager[]; CalendarMembers?: CalendarMemberEventManager[]; }) => { CalendarEvents.forEach((event) => { if (getIsCalendarEventManagerDelete(event)) { handleDeleteCalendar(event.ID); } if (getIsCalendarEventManagerCreate(event)) { // TODO: The code below is prone to race conditions. Namely if a new event manager update // comes before this promise is resolved. void handleAddCalendar(event.Calendar); } if (getIsCalendarEventManagerUpdate(event)) { // TODO: The code below is prone to race conditions. Namely if a new event manager update // comes before this promise is resolved. void handleUpdateCalendar(event.Calendar); } }); CalendarMembersEvents.forEach((event) => { if (getIsCalendarMemberEventManagerDelete(event)) { handleDeleteMember(event.ID); } else if (getIsCalendarMemberEventManagerCreate(event)) { handleCreateMember(event.Member); } else if (getIsCalendarMemberEventManagerUpdate(event)) { handleUpdateMember(event.Member); } }); } ); }, [loadingCalendars]); useEffect(() => { if (loadingCalendars) { return; } return calendarSubscribe( calendarIDs, ({ CalendarSubscriptions: CalendarSubscriptionEvents = [], }: { CalendarSubscriptions?: CalendarSubscriptionEventManager[]; }) => { CalendarSubscriptionEvents.forEach((calendarSubscriptionChange) => { if (getIsCalendarSubscriptionEventManagerUpdate(calendarSubscriptionChange)) { const { ID, CalendarSubscription } = calendarSubscriptionChange; handleUpdateSubscription(ID, CalendarSubscription); } }); } ); }, [calendarIDs, loadingCalendars]); useEffect(() => { const run = async () => { const newSubscribedCalendars = await Promise.all( calendars.map(async (calendar) => { const { CalendarSubscription } = await api<CalendarSubscriptionResponse>( getSubscriptionParameters(calendar.ID) ); return { ...calendar, SubscriptionParameters: CalendarSubscription, }; }) ); void setSubscribedCalendars(newSubscribedCalendars); }; if (loadingCalendars) { return; } void withLoading(run()); }, [loadingCalendars]); return { subscribedCalendars, loading }; }; export default useSubscribedCalendars;
7,149
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSubscription.ts
import { useCallback } from 'react'; import { FREE_SUBSCRIPTION } from '@proton/shared/lib/constants'; import { SubscriptionModel as tsSubscriptionModel } from '@proton/shared/lib/interfaces'; import { SubscriptionModel } from '@proton/shared/lib/models/subscriptionModel'; import { UserModel } from '@proton/shared/lib/models/userModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const useSubscription = (): [tsSubscriptionModel, boolean, Error] => { const cache = useCache(); const api = useApi(); const miss = useCallback(() => { const { value: user = {} } = cache.get(UserModel.key) || {}; if (user.isAdmin && Boolean(user.Subscribed)) { return SubscriptionModel.get(api); } // Member cannot fetch subscription return Promise.resolve(FREE_SUBSCRIPTION); }, [api, cache]); return useCachedModelResult(cache, SubscriptionModel.key, miss); }; /** * Unlike the return type of {@link useSubscription}, it doesn't have the third element in the array. That's because * {@link useCachedModelResult} never actually returns 3-element arrays. */ export type SubscriptionResult = | [subscription: tsSubscriptionModel | typeof FREE_SUBSCRIPTION, loading: false] | [subscription: undefined, loading: true]; /** * Same as {@link useSubscription} but *better*. In a sense of type-safety. */ export const useTypedSubscription = (): SubscriptionResult => { return useSubscription() as any; }; export default useSubscription;
7,150
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useSvgGraphicsBbox.ts
import { RefObject, useLayoutEffect, useState } from 'react'; // These defaults do not matter const DEFAULT = { y: 0, x: 0, width: 100, height: 100, }; const useSvgGraphicsBbox = (ref: RefObject<SVGGraphicsElement>, deps: any[] = []) => { const [bbox, setBbox] = useState(DEFAULT); useLayoutEffect(() => { if (!ref.current) { setBbox(DEFAULT); return; } setBbox(ref.current.getBBox()); }, [ref.current, ...deps]); return bbox; }; export default useSvgGraphicsBbox;
7,151
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useToggle.ts
import { useEffect, useState } from 'react'; const useToggle = (initialState = false) => { const [state, setState] = useState(initialState); const toggle = () => setState(!state); useEffect(() => { setState(initialState); }, [initialState]); return { state, toggle, set: setState, }; }; export default useToggle;
7,152
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useTraceUpdate.tsx
import { MutableRefObject, useEffect, useRef } from 'react'; const traceChanges = (componentName: string, typeName: string, current: any, previousRef: MutableRefObject<any>) => { const changedProps = Object.entries(current).reduce<any>((acc, [key, value]) => { if (previousRef.current[key] !== value) { acc[key] = [previousRef.current[key], value]; } return acc; }, {}); if (Object.keys(changedProps).length > 0) { // eslint-disable-next-line no-console console.log(componentName, typeName, 'Changes:', changedProps); } previousRef.current = current; }; /** * Debugging hook helper to trace rendering and changes of component */ const useTraceUpdate = (componentName: string, props: any = {}, states: any = {}) => { const renderCounter = useRef(0); const previousProps = useRef(props); const previousStates = useRef(states); useEffect(() => { // eslint-disable-next-line no-console console.log('Render', componentName, renderCounter.current++); traceChanges(componentName, 'Props', props, previousProps); traceChanges(componentName, 'States', states, previousStates); }); }; export default useTraceUpdate;
7,153
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUid.ts
import useInstance from '@proton/hooks/useInstance'; import generateUID from '@proton/shared/lib/helpers/generateUID'; /* Persists same uid accross component lifetime. */ const useUid = (prefix?: string) => { return useInstance(() => generateUID(prefix)); }; export default useUid;
7,154
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUser.ts
import { useCallback } from 'react'; import { UserModel as tsUserModel } from '@proton/shared/lib/interfaces'; import { UserModel } from '@proton/shared/lib/models/userModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetUser = (): (() => Promise<tsUserModel>) => { const api = useApi(); const cache = useCache(); return useCallback(() => { return getPromiseValue(cache, UserModel.key, () => UserModel.get(api)); }, [cache, api]); }; export const useUser = (): [tsUserModel, boolean, any] => { const cache = useCache(); const miss = useGetUser(); return useCachedModelResult(cache, UserModel.key, miss); }; export default useUser;
7,155
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUserKeys.ts
import { useCallback } from 'react'; import { DecryptedKey } from '@proton/shared/lib/interfaces'; import { Unwrap } from '@proton/shared/lib/interfaces/utils'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; import { useGetUserKeysRaw } from './useGetUserKeysRaw'; export const KEY = 'USER_KEYS'; export const useGetUserKeys = (): (() => Promise<DecryptedKey[]>) => { const cache = useCache(); const miss = useGetUserKeysRaw(); return useCallback(() => getPromiseValue(cache, KEY, miss), [miss]); }; export const useUserKeys = (): [Unwrap<ReturnType<typeof useGetUserKeys>>, boolean, any] => { const cache = useCache(); const getUserKeysAsync = useGetUserKeys(); return useCachedModelResult(cache, KEY, getUserKeysAsync); };
7,156
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUserScopes.ts
import { useCallback } from 'react'; import { queryScopes } from '@proton/shared/lib/api/auth'; import { Api } from '@proton/shared/lib/interfaces'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const KEY = 'userScopes'; const getUserScopes = (api: Api) => api(queryScopes()).then((result: any = {}) => result.Scope); export const useUserScopes = () => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => getUserScopes(api), [api]); return useCachedModelResult(cache, KEY, miss); }; export default useUserScopes;
7,157
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUserSettings.ts
import { UserSettings } from '@proton/shared/lib/interfaces/UserSettings'; import { UserSettingsModel } from '@proton/shared/lib/models/userSettingsModel'; import createUseModelHook from './helpers/createModelHook'; export default createUseModelHook<UserSettings>(UserSettingsModel);
7,158
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useUserVPN.ts
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { getClientVPNInfo } from '@proton/shared/lib/api/vpn'; import { Currency } from '@proton/shared/lib/interfaces'; import useApi from './useApi'; import useCache from './useCache'; export interface VPNUserInfo { VPN: { ExpirationTime: number; Name: string; Password: string; GroupID: string; Status: number; PlanName: string | null; PlanTitle: string | null; MaxTier: number | null; MaxConnect: number; Groups: string[]; NeedConnectionAllocation: boolean; }; Warnings: any[]; Services: number; Subscribed: number; Delinquent: number; HasPaymentMethod: number; Credit: number; Currency: Currency; } const useUserVPN = () => { const api = useApi(); const mountedRef = useRef(true); const cache = useCache(); const [state, setState] = useState<{ error?: Error; result?: VPNUserInfo; loading: boolean; }>(() => ({ result: cache.get('vpn')?.result, loading: false })); const fetch = useCallback(async (maxAge = 0) => { try { const cachedValue = cache.get('vpn'); const time = new Date().getTime(); if (cachedValue?.time + maxAge >= time) { setState({ result: cachedValue?.result, loading: false }); return; } if (cachedValue?.promise) { const result = await cachedValue?.promise; setState({ result, loading: false }); return; } const promise = api(getClientVPNInfo()) as Promise<VPNUserInfo>; cache.set('vpn', { promise }); const result = await promise; cache.set('vpn', { result, time, }); if (mountedRef.current) { setState({ result, loading: false }); } } catch (e) { cache.delete('vpn'); if (mountedRef.current) { setState({ error: e as Error, loading: false }); } } }, []); useEffect(() => { fetch(30_000); return () => { mountedRef.current = false; }; }, []); return useMemo( () => ({ ...state, fetch, }), [state] ); }; export default useUserVPN;
7,159
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useVPNLogicals.ts
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { queryVPNLogicalServerInfo } from '@proton/shared/lib/api/vpn'; import { Logical } from '../containers/vpn/Logical'; import useApi from './useApi'; import useCache from './useCache'; const useVPNLogicals = () => { const api = useApi(); const mountedRef = useRef(true); const cache = useCache(); const [state, setState] = useState<{ error?: Error; result?: { LogicalServers: Logical[]; }; loading: boolean; }>(() => ({ result: cache.get('vpn-logicals')?.result, loading: false })); const fetch = useCallback(async (maxAge = 0) => { try { const cachedValue = cache.get('vpn-logicals'); const time = new Date().getTime(); if (cachedValue?.time + maxAge >= time) { setState({ result: cachedValue?.result, loading: false }); return; } if (cachedValue?.promise) { const result = await cachedValue?.promise; setState({ result, loading: false }); return; } const promise = api(queryVPNLogicalServerInfo()) as Promise<{ LogicalServers: Logical[] }>; cache.set('vpn-logicals', { promise }); const result = await promise; cache.set('vpn-logicals', { result, time, }); if (mountedRef.current) { setState({ result, loading: false }); } } catch (e) { cache.delete('vpn-logicals'); if (mountedRef.current) { setState({ error: e as Error, loading: false }); } } }, []); useEffect(() => { if (!cache.has('vpn-logicals')) { fetch(); } return () => { mountedRef.current = false; }; }, []); return useMemo( () => ({ ...state, fetch, }), [state] ); }; export default useVPNLogicals;
7,160
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useVPNServersCount.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { queryVPNCountriesCount, queryVPNLogicalServerInfoCount, queryVPNServersCount, } from '@proton/shared/lib/api/vpn'; import { VPNCountriesCount, VPNLogicalsCount, VPNServersCount, VPNServersCountData, } from '@proton/shared/lib/interfaces'; import useApi from './useApi'; const DEFAULT_RESULT: VPNServersCountData = { free: { countries: 3, servers: 150 }, paid: { countries: 190, servers: 1900 }, }; let cache: Promise<[VPNServersCount, VPNCountriesCount, VPNLogicalsCount]> | undefined; const useVPNServersCount = (): [VPNServersCountData, boolean] => { const api = useApi(); const [loading, withLoading] = useLoading(); const [result, setResult] = useState<VPNServersCountData>(DEFAULT_RESULT); useEffect(() => { const query = async () => { if (!cache) { cache = Promise.all([ api<VPNServersCount>(queryVPNServersCount()), api<VPNCountriesCount>(queryVPNCountriesCount()), api<VPNLogicalsCount>(queryVPNLogicalServerInfoCount()), ]); } const promise = cache; const [serversCount, countriesCount, logicalsCount] = await promise; const countFreeVPNCountries = countriesCount.Counts.find((count) => count.MaxTier === 0)?.Count || DEFAULT_RESULT.free.countries; const countFreeVpnServers = logicalsCount.Counts['0']; const countPaidVPNServers = Math.floor(serversCount.Servers / 50) * 50; const countPaidVPNCountries = Math.floor(serversCount.Countries / 5) * 5; const updatedResult: VPNServersCountData = { free: { servers: countFreeVpnServers, countries: countFreeVPNCountries, }, paid: { servers: countPaidVPNServers, countries: countPaidVPNCountries, }, }; setResult(updatedResult); }; void withLoading(query()); }, []); return [result, loading]; }; export default useVPNServersCount;
7,161
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useWelcomeFlags.ts
import { useCallback, useEffect, useState } from 'react'; import { UserSettings } from '@proton/shared/lib/interfaces'; import useCache from './useCache'; export const WELCOME_FLAGS_CACHE_KEY = 'welcome-flags'; export interface WelcomeFlagsState { hasGenericWelcomeStep: boolean; isWelcomeFlow: boolean; isDone: boolean; } export const getWelcomeFlagsValue = (userSettings: Pick<UserSettings, 'WelcomeFlag' | 'Flags'>): WelcomeFlagsState => { const hasProductWelcomeStep = userSettings.WelcomeFlag === 0; const hasGenericWelcomeStep = userSettings.Flags.Welcomed === 0; const isWelcomeFlow = hasGenericWelcomeStep || hasProductWelcomeStep; return { hasGenericWelcomeStep, isWelcomeFlow, isDone: !isWelcomeFlow, }; }; const defaultValue: WelcomeFlagsState = { hasGenericWelcomeStep: false, isWelcomeFlow: false, isDone: true, }; const useWelcomeFlags = (): [WelcomeFlagsState, () => void] => { const cache = useCache(); const [state, setState] = useState<WelcomeFlagsState>(() => { return cache.get(WELCOME_FLAGS_CACHE_KEY) || defaultValue; }); useEffect(() => { const cacheListener = (key: string) => { if (key !== WELCOME_FLAGS_CACHE_KEY) { return; } setState(cache.get(key)); }; return cache.subscribe(cacheListener); }, []); const setDone = useCallback(() => { const newValue: WelcomeFlagsState = { ...state, isDone: true }; cache.set(WELCOME_FLAGS_CACHE_KEY, newValue); }, []); return [state, setDone]; }; export default useWelcomeFlags;
7,162
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useWindowSize.ts
import { useEffect, useState } from 'react'; import debounce from '@proton/utils/debounce'; const getWindowSize = (): [width: number, height: number] => { return [window.innerWidth, window.innerHeight]; }; const useWindowSize = () => { const [windowSize, setWindowSize] = useState(() => getWindowSize()); useEffect(() => { const reducer = (oldValue: [number, number], newValue: [number, number]) => { if (oldValue[0] === newValue[0] && oldValue[1] === newValue[1]) { return oldValue; } return newValue; }; const onResize = debounce(() => { setWindowSize((old) => reducer(old, getWindowSize())); }, 100); window.addEventListener('resize', onResize); setWindowSize((old) => reducer(old, getWindowSize())); return () => { window.removeEventListener('resize', onResize); }; }, []); return windowSize; }; export default useWindowSize;
7,163
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/__mocks__/useModals.ts
export default jest.fn().mockReturnValue({ createModal: jest.fn(), });
7,164
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/index.ts
export { default as useDrawer } from './useDrawer'; export { default as useDrawerLocalStorage } from './useDrawerLocalStorage'; export { default as useDrawerParent } from './useDrawerParent'; export { default as useDrawerWidth } from './useDrawerWidth'; export { default as useObserveDrawerIframeAppLocation } from './useObserveDrawerIframeAppLocation'; export { default as useOpenDrawerOnLoad } from './useOpenDrawerOnLoad'; export { default as useToggleDrawerApp } from './useToggleDrawerApp';
7,165
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useDrawer.tsx
import { Dispatch, ReactNode, SetStateAction, createContext, useCallback, useContext, useEffect, useRef, useState, } from 'react'; import { useApi, useAuthentication, useDrawerLocalStorage, useGetUser, useToggleDrawerApp, } from '@proton/components/hooks'; import { versionCookieAtLoad } from '@proton/components/hooks/useEarlyAccess'; import { serverTime } from '@proton/crypto'; import { getClientID } from '@proton/shared/lib/apps/helper'; import { getAppFromHostname } from '@proton/shared/lib/apps/slugHelper'; import { APP_NAMES, DAY, MINUTE } from '@proton/shared/lib/constants'; import { getIsDrawerPostMessage, getIsIframedDrawerApp, postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_APPS, DRAWER_EVENTS, IframeSrcMap } from '@proton/shared/lib/drawer/interfaces'; import { ApiError, serializeApiErrorData } from '@proton/shared/lib/fetch/ApiError'; import { getAppVersionHeaders } from '@proton/shared/lib/fetch/headers'; import { getIsIframe } from '@proton/shared/lib/helpers/browser'; export const DrawerContext = createContext<{ /** * App currently opened in the Drawer */ appInView: DRAWER_APPS | undefined; setAppInView: Dispatch<SetStateAction<DRAWER_APPS | undefined>>; /** * Map of the srcs we use on the iframe to open it */ iframeSrcMap: IframeSrcMap; setIframeSrcMap: Dispatch<SetStateAction<IframeSrcMap>>; /** * Map we use to store urls of all apps opened inside the iframe */ iframeURLMap: IframeSrcMap; setIframeURLMap: Dispatch<SetStateAction<IframeSrcMap>>; /** * Is the drawer sidebar hidden (from a setting perspective) */ showDrawerSidebar?: boolean; setShowDrawerSidebar: Dispatch<SetStateAction<boolean | undefined>>; /** * Is the drawer sidebar already mounted, so that we can perform actions on it */ drawerSidebarMounted: boolean; setDrawerSidebarMounted: Dispatch<SetStateAction<boolean>>; /** * Child specific, on which "parent" app the "child" app is opened */ parentApp?: APP_NAMES; setParentApp: Dispatch<SetStateAction<APP_NAMES | undefined>>; } | null>(null); export default function useDrawer() { const drawerContext = useContext(DrawerContext); if (!drawerContext) { throw new Error('Drawer provider not initialized'); } const { appInView, setAppInView, iframeSrcMap, setIframeSrcMap, iframeURLMap, setIframeURLMap, showDrawerSidebar, setShowDrawerSidebar, parentApp, drawerSidebarMounted, setDrawerSidebarMounted, } = drawerContext; const toggleDrawerApp = useToggleDrawerApp({ appInView, setAppInView, iframeSrcMap, setIframeSrcMap, }); const isIframe = getIsIframe(); // If app is inside an iframe and it has a parent, then it's a drawer app const isDrawerApp = !!parentApp && isIframe; return { appInView, setAppInView, iframeSrcMap, setIframeSrcMap, iframeURLMap, setIframeURLMap, toggleDrawerApp, parentApp, isDrawerApp, showDrawerSidebar, setShowDrawerSidebar, drawerSidebarMounted, setDrawerSidebarMounted, }; } export const DrawerProvider = ({ children }: { children: ReactNode }) => { const { getUID, getPersistent, getPassword, getTrusted } = useAuthentication(); const api = useApi(); const getUser = useGetUser(); // App currently in view in the drawer const [appInView, setAppInView] = useState<DRAWER_APPS | undefined>(); // Iframe src's for all apps opened in the drawer => Map of the src we use on the iframe to open it const [iframeSrcMap, setIframeSrcMap] = useState<IframeSrcMap>({}); // Iframe urls for all apps opened in the drawer => Map we use to store the url of the app opened inside the iframe const [iframeURLMap, setIframeURLMap] = useState<IframeSrcMap>({}); // Parent app of the app embedded into the drawer const [parentApp, setParentApp] = useState<APP_NAMES>(); // Is the sidebar mounted, we need this to get the drawer width const [drawerSidebarMounted, setDrawerSidebarMounted] = useState(false); // Is the DrawerSidebar displayed or not (we can hide the drawer with a setting) const [showDrawerSidebar, setShowDrawerSidebar] = useState<boolean | undefined>(undefined); const [requestsAbortControllers, setRequestsAbortControllers] = useState< { id: string; abortController: AbortController }[] >([]); const { setDrawerLocalStorageKey } = useDrawerLocalStorage(iframeSrcMap, drawerSidebarMounted, appInView); const removeAbortController = (id: string) => { setRequestsAbortControllers((requestsAbortControllers) => requestsAbortControllers.filter((controller) => controller.id === id) ); }; const handleReceived = useCallback( async (event: MessageEvent) => { if (!getIsDrawerPostMessage(event)) { return; } switch (event.data.type) { case DRAWER_EVENTS.CLOSE: { setAppInView(undefined); if (event.data.payload) { const { app, closeDefinitely } = event.data.payload; if (closeDefinitely) { setIframeSrcMap((map) => ({ ...map, [app]: undefined, })); } } } break; case DRAWER_EVENTS.SWITCH: { const { nextUrl } = event.data.payload; const nextApp = getAppFromHostname(nextUrl); if (!nextApp || !getIsIframedDrawerApp(nextApp)) { throw new Error('Invalid nextUrl'); } setAppInView(nextApp); setIframeSrcMap((map) => ({ ...map, [nextApp]: nextUrl, })); } break; case DRAWER_EVENTS.READY: { if (appInView) { const user = await getUser(); postMessageToIframe( { type: DRAWER_EVENTS.SESSION, payload: { UID: getUID(), keyPassword: getPassword(), persistent: getPersistent(), trusted: getTrusted(), User: user, tag: versionCookieAtLoad, }, }, appInView ); } } break; case DRAWER_EVENTS.API_REQUEST: { if (!appInView || !getIsIframedDrawerApp(appInView)) { return; } const { arg, id, appVersion, hasAbortController } = event.data.payload; try { let updatedArgs: any = arg; if (hasAbortController) { const abortController = new AbortController(); setRequestsAbortControllers((requestsAbortControllers) => [ ...requestsAbortControllers, { id, abortController }, ]); updatedArgs = { ...arg, signal: abortController.signal, }; } let res = await api({ ...updatedArgs, headers: { ...updatedArgs.headers, ...getAppVersionHeaders(getClientID(appInView), appVersion), 'x-pm-source': 'drawer', }, }); // Once the request is finished, remove the controller from the array if (hasAbortController) { removeAbortController(id); } if (updatedArgs.output === 'raw') { res = { ok: res.ok, status: res.status, json: await res.json(), headers: Object.fromEntries(res.headers.entries()), }; } postMessageToIframe( { type: DRAWER_EVENTS.API_RESPONSE, payload: { id, success: true, data: res, serverTime: serverTime(), output: updatedArgs.output, }, }, appInView ); } catch (err: any) { // If the request failed, remove the controller from the array if (hasAbortController) { removeAbortController(id); } const isApiError = err instanceof ApiError; postMessageToIframe( { type: DRAWER_EVENTS.API_RESPONSE, payload: { id, success: false, isApiError, data: isApiError ? serializeApiErrorData(err) : err, serverTime: serverTime(), }, }, appInView ); } } break; case DRAWER_EVENTS.ABORT_REQUEST: const { id } = event.data.payload; const controller = requestsAbortControllers.find( (controller) => controller.id === id )?.abortController; if (controller) { controller.abort(); // Once the request is aborted, remove the controller from the array removeAbortController(id); } break; case DRAWER_EVENTS.CHILD_URL_UPDATE: const user = await getUser(); const { url, app } = event.data.payload; setDrawerLocalStorageKey({ app, url }, user.ID); setIframeURLMap((iframeURLMap) => ({ ...iframeURLMap, [app]: url, })); break; default: break; } }, [appInView] ); useEffect(() => { window.addEventListener('message', handleReceived); return () => { window.removeEventListener('message', handleReceived); }; }, [handleReceived]); // We close definitely cached drawer apps if unused for a certain period of time (3 days) const hideAtMapRef = useRef<Partial<Record<DRAWER_APPS, number>>>({}); const intervalMapRef = useRef<Partial<Record<DRAWER_APPS, number>>>({}); useEffect(() => { // forced to use this workaround for iframeSrcMap key types due to https://github.com/microsoft/TypeScript/issues/50096 let key: keyof typeof iframeSrcMap; for (key in iframeSrcMap) { const app = key; const isAppCached = iframeSrcMap[app] && appInView !== app; if (isAppCached) { let hidePanelAt = hideAtMapRef.current[app]; if (hidePanelAt === undefined) { hidePanelAt = Date.now(); hideAtMapRef.current[app] = hidePanelAt; } const maxDate = hidePanelAt + 3 * DAY; intervalMapRef.current[app] = window.setInterval(() => { if (Date.now() > maxDate) { setIframeSrcMap((iframeSrcMap) => ({ ...iframeSrcMap, [app]: undefined, })); hideAtMapRef.current[app] = undefined; } }, 5 * MINUTE); } } return () => { let app: keyof typeof iframeSrcMap; for (app in iframeSrcMap) { if (intervalMapRef.current[app]) { clearInterval(intervalMapRef.current[app]); } } }; }, [appInView, iframeSrcMap]); return ( <DrawerContext.Provider value={{ appInView, setAppInView, iframeSrcMap, setIframeSrcMap, iframeURLMap, setIframeURLMap, showDrawerSidebar, setShowDrawerSidebar, parentApp, setParentApp, drawerSidebarMounted, setDrawerSidebarMounted, }} > {children} </DrawerContext.Provider> ); };
7,166
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useDrawerLocalStorage.ts
import { useEffect, useRef } from 'react'; import { useGetUser } from '@proton/components/hooks'; import { getLocalStorageUserDrawerKey } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_APPS, DrawerLocalStorageValue, IframeSrcMap } from '@proton/shared/lib/drawer/interfaces'; import { removeItem, setItem } from '@proton/shared/lib/helpers/storage'; const useDrawerLocalStorage = (iframeSrcMap: IframeSrcMap, drawerIsReady: boolean, appInView?: DRAWER_APPS) => { const getUser = useGetUser(); /** * Use a ref to allow deletion of the localStorage value only if we opened an app during the session. * Otherwise, when loading the app, no app is opened in the drawer, and we would delete the value stored. * By deleting this value directly, we would not be able to open the previously opened app */ const hasSetAppInView = useRef(false); const setDrawerLocalStorageKey = (item: DrawerLocalStorageValue, userID: string) => { setItem(getLocalStorageUserDrawerKey(userID), JSON.stringify(item)); }; const handleSetLocalStorage = async () => { // Only perform these actions when drawer can be shown // Otherwise it can trigger /users request when not authenticated if (drawerIsReady) { const { ID } = await getUser(); if (appInView) { const url = iframeSrcMap[appInView]; hasSetAppInView.current = true; const item = { app: appInView, url } as DrawerLocalStorageValue; setDrawerLocalStorageKey(item, ID); } else if (hasSetAppInView.current) { // When closing the drawer, clean up the value from the drawer local storage item removeItem(getLocalStorageUserDrawerKey(ID)); } } }; useEffect(() => { void handleSetLocalStorage(); }, [appInView, drawerIsReady]); return { setDrawerLocalStorageKey }; }; export default useDrawerLocalStorage;
7,167
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useDrawerParent.ts
import { useContext, useEffect } from 'react'; import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { getIsAuthorizedApp } from '@proton/shared/lib/drawer/helpers'; import { DrawerContext } from './useDrawer'; export default function useDrawerParent() { const drawerContext = useContext(DrawerContext); if (!drawerContext) { throw new Error('DrawerContext should be initialised in parent component'); } const { setParentApp } = drawerContext; useEffect(() => { const parentApp = getAppFromPathnameSafe(window.location.pathname); if (parentApp && getIsAuthorizedApp(parentApp)) { setParentApp?.(parentApp); } }, []); }
7,168
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useDrawerWidth.ts
import { useEffect, useState } from 'react'; import { useDrawer } from '@proton/components/hooks'; const useDrawerWidth = () => { const [sidebarWidth, setSidebarWidth] = useState(0); const [appWidth, setAppWidth] = useState(0); const { showDrawerSidebar, drawerSidebarMounted, appInView } = useDrawer(); useEffect(() => { if (!showDrawerSidebar || !drawerSidebarMounted) { setSidebarWidth(0); return; } const sidebarElement = window.document.querySelector('.drawer-sidebar'); if (!sidebarElement) { return; } const sidebarResizeObserver = new ResizeObserver((entries) => { setSidebarWidth(entries[0].contentRect.width); }); // Only checks iframe root div widths changes (window resize or inner resize when column mailbox layout is set) sidebarResizeObserver.observe(sidebarElement); return () => { sidebarResizeObserver.disconnect(); }; }, [showDrawerSidebar, drawerSidebarMounted]); useEffect(() => { if (!appInView) { setAppWidth(0); } const appElement = window.document.querySelector('.drawer-app'); if (!appElement) { return; } const appResizeObserver = new ResizeObserver((entries) => { setAppWidth(entries[0].contentRect.width); }); appResizeObserver.observe(appElement); return () => { appResizeObserver.disconnect(); }; }, [appInView]); return appWidth + sidebarWidth; }; export default useDrawerWidth;
7,169
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useObserveDrawerIframeAppLocation.ts
import { useEffect } from 'react'; import { useConfig, useDrawer } from '@proton/components/hooks'; import { postMessageFromIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_APPS, DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; const useObserveDrawerIframeAppLocation = () => { const { APP_NAME } = useConfig(); const { parentApp } = useDrawer(); useEffect(() => { if (parentApp) { postMessageFromIframe( { type: DRAWER_EVENTS.CHILD_URL_UPDATE, payload: { url: window.location.href, app: APP_NAME as DRAWER_APPS, }, }, parentApp ); } }, [window.location.href]); }; export default useObserveDrawerIframeAppLocation;
7,170
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useOpenDrawerOnLoad.ts
import { useEffect } from 'react'; import { useConfig, useDrawer, useOnline, useUser } from '@proton/components/hooks'; import useApiStatus from '@proton/components/hooks/useApiStatus'; import { getAppHref } from '@proton/shared/lib/apps/helper'; import { getLocalIDFromPathname } from '@proton/shared/lib/authentication/pathnameHelper'; import { addParentAppToUrl, getDisplayDrawerApp, getIsDrawerApp, getIsIframedDrawerApp, getLocalStorageUserDrawerKey, } from '@proton/shared/lib/drawer/helpers'; import { DrawerLocalStorageValue } from '@proton/shared/lib/drawer/interfaces'; import { getItem } from '@proton/shared/lib/helpers/storage'; const useOpenDrawerOnLoad = () => { const [user] = useUser(); const { APP_NAME } = useConfig(); const { offline } = useApiStatus(); const onlineStatus = useOnline(); const { setIframeSrcMap, setIframeURLMap, setAppInView } = useDrawer(); const isAppReachable = !offline && onlineStatus; useEffect(() => { const itemFromStorage = getItem(getLocalStorageUserDrawerKey(user.ID)); if (itemFromStorage) { // Surround JSON.parse by try/catch in case the value cannot be parsed try { const { app, url } = JSON.parse(itemFromStorage) as DrawerLocalStorageValue; if (app && isAppReachable) { const isValidApp = getIsDrawerApp(app); const canDisplayDrawerApp = getDisplayDrawerApp(APP_NAME, app); if (!isValidApp || !canDisplayDrawerApp) { return; } if (getIsIframedDrawerApp(app)) { if (url) { setIframeSrcMap((map) => ({ ...map, [app]: url, })); setIframeURLMap((map) => ({ ...map, [app]: url, })); } else { /** * Normally, this case should never happen. * In case there is an iframed app reference stored in the localStorage without url, * we will try to open the drawer app on parent app load, without any url. * * However, if we try to open an iframed app without url, * it will result as a blank space in the drawer on which the user has no control. * To avoid that, we will use en the default child app url. */ // If no url is set, load the iframe on the default child app url const localID = getLocalIDFromPathname(window.location.pathname); const appHref = getAppHref('/', app, localID); const defaultUrl = addParentAppToUrl(appHref, APP_NAME); setIframeSrcMap((map) => ({ ...map, [app]: defaultUrl, })); setIframeURLMap((map) => ({ ...map, [app]: defaultUrl, })); } } setAppInView(app); } } catch (e: any) { console.error(e); } } }, []); }; export default useOpenDrawerOnLoad;
7,171
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useQuickSettingsReminders.tsx
import { ReactNode, createContext, useContext } from 'react'; import { ThemeColor } from '@proton/colors/types'; import MailQuickSettingsReminderContextProvider from '@proton/components/containers/drawer/MailQuickSettingsReminderContextProvider'; import { useConfig, useRecoveryNotification } from '@proton/components/hooks'; import { APPS } from '@proton/shared/lib/constants'; import isTruthy from '@proton/utils/isTruthy'; /** * Quick settings are now part of the drawer. * Some elements might trigger the display of a dot on the quick settings button. * Once the notification has been seen by the user, the dot needs to disappear on the button. * The role of this context is keep track of these values correctly across the application, * because the value might change after a user action within the drawer, involving a change on the setting button */ export const QuickSettingsRemindersContext = createContext<{ reminders: ThemeColor[]; } | null>(null); export default function useQuickSettingsReminders() { const quickSettingsNotificationContext = useContext(QuickSettingsRemindersContext); if (!quickSettingsNotificationContext) { throw new Error('Quick Settings reminders provider not initialized'); } const { reminders } = quickSettingsNotificationContext; return reminders; } export const QuickSettingsRemindersProvider = ({ children }: { children: ReactNode }) => { const { APP_NAME } = useConfig(); const recoveryNotification = useRecoveryNotification(false); const reminders: ThemeColor[] = [recoveryNotification?.color].filter(isTruthy); /** * Need to create a different context per app if some reminders are app specific */ if (APP_NAME === APPS.PROTONMAIL) { return ( <MailQuickSettingsReminderContextProvider defaultReminders={reminders}> {children} </MailQuickSettingsReminderContextProvider> ); } return ( <QuickSettingsRemindersContext.Provider value={{ reminders }}> {children} </QuickSettingsRemindersContext.Provider> ); };
7,172
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/drawer/useToggleDrawerApp.tsx
import { Dispatch, SetStateAction } from 'react'; import { useConfig, useOnline } from '@proton/components/hooks'; import useApiStatus from '@proton/components/hooks/useApiStatus'; import { getAppHref } from '@proton/shared/lib/apps/helper'; import { getLocalIDFromPathname } from '@proton/shared/lib/authentication/pathnameHelper'; import { addParentAppToUrl, getIsIframedDrawerApp, postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_APPS, DRAWER_EVENTS, IframeSrcMap, OpenDrawerArgs } from '@proton/shared/lib/drawer/interfaces'; interface Props { appInView: DRAWER_APPS | undefined; setAppInView: Dispatch<SetStateAction<DRAWER_APPS | undefined>>; iframeSrcMap: IframeSrcMap; setIframeSrcMap: Dispatch<SetStateAction<IframeSrcMap>>; } const useToggleDrawerApp = ({ appInView, setAppInView, iframeSrcMap, setIframeSrcMap }: Props) => { const { offline } = useApiStatus(); const onlineStatus = useOnline(); const { APP_NAME: currentApp } = useConfig(); const isAppReachable = !offline && onlineStatus; return (args: OpenDrawerArgs) => () => { const { app, path = '/' } = args; const isAppOpened = app === appInView; setAppInView(isAppOpened ? undefined : app); // If we show again the child app that was cached, we post a message to it in case it needs to take some actions upon becoming visible again (like updating its state) if (!isAppOpened) { postMessageToIframe( { type: DRAWER_EVENTS.SHOW, }, app ); } if (getIsIframedDrawerApp(app) && !iframeSrcMap[app] && isAppReachable) { const localID = getLocalIDFromPathname(window.location.pathname); const appHref = getAppHref(path, app, localID); setIframeSrcMap((map) => ({ ...map, [app]: addParentAppToUrl(appHref, currentApp), })); } }; }; export default useToggleDrawerApp;
7,173
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/cachedPromise.ts
import { Cache } from '@proton/shared/lib/helpers/cache'; type CacheValue<V, D> = | { dependency: D; promise: Promise<V>; } | { dependency: D; result: V; }; /** * Cache a promise by a key, and re-run it when the dependency changes. */ export const cachedPromise = <K, V, D>( cache: Cache<K, CacheValue<V, D>>, key: K, miss: () => Promise<V>, dependency: D ) => { const cachedValue = cache.get(key); if (cachedValue) { const { dependency: oldDependency } = cachedValue; if (dependency === oldDependency) { return 'promise' in cachedValue ? cachedValue.promise : Promise.resolve(cachedValue.result); } } const promise = miss(); cache.set(key, { dependency, promise, }); promise.then((result) => { const cachedValue = cache.get(key); if (!cachedValue) { throw new Error(`Cached value for ${key} was overwritten unexpectedly`); } if ('promise' in cachedValue && promise !== cachedValue.promise) { return result; } cache.set(key, { dependency, result, }); return result; }); return promise; };
7,174
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/createModelHook.ts
import { useCallback } from 'react'; import { Api } from '@proton/shared/lib/interfaces'; import useApi from '../useApi'; import useCache from '../useCache'; import useCachedModelResult from '../useCachedModelResult'; /** * Creates an async fn model hook. */ const createUseModelHook = <T>({ key, get }: { key: string; get: (api: Api) => void }): (() => [T, boolean, Error]) => { return () => { const api = useApi(); const cache = useCache(); return useCachedModelResult( cache, key, useCallback(() => get(api), [api]) ); }; }; export default createUseModelHook;
7,175
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/search.tsx
import { normalize } from '@proton/shared/lib/helpers/string'; /** * Returns a formatted JSX with all matches wrapped with <b></b> */ export const getMatch = ( input: string | undefined, match: string, getHighlightedText = (str: string) => <mark className="is-light">{str}</mark> ) => { if (!input) { return input; } const parts = normalize(input, true).split(match); if (parts.length < 2) { return; } const { result } = parts.reduce( (acc, part, partIndex) => { const matchPart = ( <> {acc.result} {input.substring(acc.currentIdx, acc.currentIdx + part.length)} {partIndex !== parts.length - 1 && getHighlightedText(match)} </> ); return { result: matchPart, currentIdx: acc.currentIdx + part.length + match.length }; }, { result: <></>, currentIdx: 0 } ); return result; };
7,176
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/index.ts
export * from './useOrganization'; export * from './usePlans'; export * from './useSubscription'; export * from './useUser'; export * from './useVpnServersCount';
7,177
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/useOrganization.ts
import { getOrganization } from '@proton/shared/lib/api/organization'; import { addApiMock } from '@proton/testing'; export const organizationDefaultResponse = { Code: 1000, Organization: { Name: '', DisplayName: '', PlanName: 'bundle2022', PlanFlags: 7, TwoFactorRequired: 0, TwoFactorGracePeriod: null, Theme: null, Email: null, Note: 0, MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, Features: 1, Flags: 0, CreateTime: 1676033386, LoyaltyCounter: 0, LoyaltyIncrementTime: 1707569386, BonusDomains: 0, BonusAddresses: 0, BonusSpace: 0, BonusMembers: 0, BonusVPN: 0, UsedDomains: 0, UsedAddresses: 0, UsedCalendars: 0, UsedSpace: 464014, AssignedSpace: 536870912000, UsedMembers: 1, UsedVPN: 10, HasKeys: 0, ToMigrate: 0, BrokenSKL: 0, }, }; export function mockOrganizationApi(organization = organizationDefaultResponse) { addApiMock(getOrganization().url, () => organization); }
7,178
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/usePlans.ts
import { KEY as PlansKey } from '@proton/components/hooks/usePlans'; import { queryPlans } from '@proton/shared/lib/api/payments'; import { addApiMock, addToCache } from '@proton/testing'; export const plansDefaultResponse = { Code: 1000, Plans: [ { ID: 'oVdQDF56OUBX2NOQ1BhY8ZWw96hw6B8r5TttqqwvJmcgTaHU30FRPn9jX3Q2l2V60Li-T8deZHwgA2VpI0ISiQ==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'drive2022', Title: 'Drive Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 214748364800, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 2, Features: 0, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 499, }, { ID: 'Wb4NAqmiuqoA7kCHE28y92bBFfN8jaYQCLxHRAB96yGj-bh9SxguXC48_WSU-fRUjdAr-lx95c6rFLplgXyXYA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'mail2022', Title: 'Mail Plus', MaxDomains: 1, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 499, '12': 4788, '24': 8376, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 499, }, { ID: 'rIJcBetavQi7h5qqN9nxrRnlojgl6HF6bAVG989deNJVVVx1nn2Ic3eyCVV2Adq11ddseZuWba9H5tmvLC727Q==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'mailpro2022', Title: 'Mail Essentials', MaxDomains: 3, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 1, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 799, }, { ID: 'V8YH-f59VKMEWv-eXJXf0NTtxxFUh7CcVwzdqnHNnnU38bQvhYEe7Dv8NiuyNTavhcxRmaVY1k73EyXZO0QZ_w==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'vpn2022', Title: 'VPN Plus', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 10, MaxTier: 2, Services: 4, Features: 0, State: 1, Pricing: { '1': 999, '12': 7188, '15': 14985, '24': 11976, '30': 29970, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '15': 1715345404, '24': 1739191804, '30': 1754830204, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 999, }, { ID: 'vl-JevUsz3GJc18CC1VOs-qDKqoIWlLiUePdrzFc72-BtxBPHBDZM7ayn8CNQ59Sk4XjDbwwBVpdYrPIFtOvIw==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'bundle2022', Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1199, }, { ID: 'qsp04zdW5J0BpEwN3obRrGUavhoXm_MksQozisI5JiFpGm0CaRTWMY44R3YBYXEP5bH7SrQQxn6jMndFsNqWtQ==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'drivepro2022', Title: 'Drive Essentials', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 1099511627776, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 2, Features: 1, State: 1, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1199, }, { ID: 'sS277jpbBUgah-s2u2i1dEQvMLPMpbXvAF_rcETf7UDk1ScetcBaCWENL6gBPpNec3va8oKHUWmFPt741LFlgA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'bundlepro2022', Title: 'Business', MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1299, }, { ID: 'T4e4LkfNW5sshJFZW0H_ylO5Ol_giW_BNyf-aLNgQTAMS91G7GWSWJIhd52hDkV_fvfGmL--05Q7N3PwS9cYdA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'enterprise2022', Title: 'Enterprise', MaxDomains: 10, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 1099511627776, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Pricing: { '1': 1599, '12': 16788, '24': 31176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1599, }, { ID: 'C4cbQr9wjCLGsxQLxGrkfyQfiawdf4T2BP2fc6K0CPnGnL9LWBM5IRlKWt5YkBOukOgHCJGeVyq3M0McQuXh1w==', ParentMetaPlanID: 'sS277jpbBUgah-s2u2i1dEQvMLPMpbXvAF_rcETf7UDk1ScetcBaCWENL6gBPpNec3va8oKHUWmFPt741LFlgA==', Type: 0, Name: '1domain-bundlepro2022', Title: '+1 Domain for Business', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { '1': 150, '12': 1680, '24': 3120, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 150, }, { ID: 'dM7tIbqARP2pnfphQaa9xDOEKHUo5Z5DCPj-dIM8g44xHRgDTg3aREOV2NzIiemcT-TZzCZH1HARpdzs_FGjLA==', ParentMetaPlanID: 'rIJcBetavQi7h5qqN9nxrRnlojgl6HF6bAVG989deNJVVVx1nn2Ic3eyCVV2Adq11ddseZuWba9H5tmvLC727Q==', Type: 0, Name: '1member-mailpro2022', Title: '+1 User', MaxDomains: 0, MaxAddresses: 10, MaxCalendars: 25, MaxSpace: 16106127360, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 1, Features: 0, State: 1, Pricing: { '1': 799, '12': 8388, '24': 15576, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 799, }, { ID: 'W9WsR1K0IWZ1RJtsy09D63IcHqhJOF_-XjFcSY6IXuMWLXYqecPZLX2nWXyCYIR6jsje6O_C3jgnSNiVrJUP1Q==', ParentMetaPlanID: 'sS277jpbBUgah-s2u2i1dEQvMLPMpbXvAF_rcETf7UDk1ScetcBaCWENL6gBPpNec3va8oKHUWmFPt741LFlgA==', Type: 0, Name: '1member-bundlepro2022', Title: '+1 User for Business', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { '1': 1299, '12': 13188, '24': 23976, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1299, }, { ID: 'm06m9l7AM8HPQDX9imVQ0TvrGKVaDWuSt5gI0lGRLgF0WJX5a6ZzOQRVzK9MK48XW3_I1mTXWnOx10048TSYCA==', ParentMetaPlanID: 'T4e4LkfNW5sshJFZW0H_ylO5Ol_giW_BNyf-aLNgQTAMS91G7GWSWJIhd52hDkV_fvfGmL--05Q7N3PwS9cYdA==', Type: 0, Name: '1domain-enterprise2022', Title: '+1 Domain for Enterprise', MaxDomains: 1, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 0, MaxMembers: 0, MaxVPN: 0, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { '1': 1599, '12': 16788, '24': 31176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1599, }, { ID: '5yWhEhzqCbAOSUNk6HFGKaLZ1kd4nkmS-nWqmDmndARZ62T7gWRHlxr3tukFafRfPr-weOSSgXobTuKKvfrXiQ==', ParentMetaPlanID: 'T4e4LkfNW5sshJFZW0H_ylO5Ol_giW_BNyf-aLNgQTAMS91G7GWSWJIhd52hDkV_fvfGmL--05Q7N3PwS9cYdA==', Type: 0, Name: '1member-enterprise2022', Title: '+1 User for Enterprise', MaxDomains: 0, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 1099511627776, MaxMembers: 1, MaxVPN: 10, MaxTier: 0, Services: 7, Features: 0, State: 1, Pricing: { '1': 1599, '12': 16788, '24': 31176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1599, }, { ID: '-KAeU_8b61bQm7RvjDok9zAtyrIG4mZOKI9eQSWfgpASpTa9ESL9yLnjB9eC2_8fyrNCbkJFlxzrLGZPTlvwtg==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'family2022', Title: 'Proton Family', MaxDomains: 5, MaxAddresses: 75, MaxCalendars: 100, MaxSpace: 2748779069440, MaxMembers: 5, MaxVPN: 50, MaxTier: 2, Services: 7, Features: 1, State: 0, Pricing: { '1': 2499, '12': 23988, '24': 35976, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 2499, }, { ID: 'h3CD-DT7rLoAw1vmpcajvIPAl-wwDfXR2MHtWID3wuQURDBKTiGUAwd6E2WBbS44QQKeXImW-axm6X0hAfcVCA==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'visionary2022', Title: 'Visionary', MaxDomains: 10, MaxAddresses: 100, MaxCalendars: 120, MaxSpace: 3298534883328, MaxMembers: 6, MaxVPN: 60, MaxTier: 2, Services: 7, Features: 1, State: 0, Pricing: { '1': 2999, '12': 28788, '24': 47976, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 2999, }, { ID: 'sZyLnO5gQs05PPVIGZ0Q3bGWXKTtdZtveZgt1NYtt3Ed9i4TQ2myimEHVCyKNOKa1b1utdvyuKkaoFQbSCyA4A==', ParentMetaPlanID: 'qsp04zdW5J0BpEwN3obRrGUavhoXm_MksQozisI5JiFpGm0CaRTWMY44R3YBYXEP5bH7SrQQxn6jMndFsNqWtQ==', Type: 0, Name: '1member-drivepro2022', Title: '+1 User', MaxDomains: 0, MaxAddresses: 0, MaxCalendars: 0, MaxSpace: 214748364800, MaxMembers: 1, MaxVPN: 0, MaxTier: 0, Services: 2, Features: 0, State: 0, Pricing: { '1': 1199, '12': 11988, '24': 19176, }, PeriodEnd: { '1': 1678452604, '12': 1707569404, '24': 1739191804, }, Currency: 'CHF', Quantity: 1, Cycle: 1, Amount: 1199, }, ], }; export function mockPlansApi(plans = plansDefaultResponse) { addApiMock(queryPlans({}).url, () => plans); } export function mockPlansCache(plans = plansDefaultResponse.Plans) { addToCache(PlansKey, plans); }
7,179
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/useSubscription.ts
import { getSubscription } from '@proton/shared/lib/api/payments'; import { SubscriptionModel } from '@proton/shared/lib/models'; import formatSubscription from '@proton/shared/lib/subscription/format'; import { addApiMock, addToCache } from '@proton/testing'; export const subscriptionDefaultResponse = { Code: 1000, Subscription: { ID: 'tKBxSXXdM4nTaNiGVfC_jnCpLsyR42iHAYK2WUoOuUX3hwedVDnseP4C_etGetdTjWhXVvwi4jgrhA5YVhn8_A==', InvoiceID: 'OA_Au351hvFThNyVvBk0GvbsBLK6N5sAJ5FHTDXGBvucyugf3ToBqirajcUrnMW7Kuen23V2mb-I-rpf9DsQRg==', Cycle: 12, PeriodStart: 1676033382, PeriodEnd: 1707569382, CreateTime: 1676033386, CouponCode: null, Currency: 'CHF', Amount: 11988, Discount: 0, RenewDiscount: 0, RenewAmount: 11988, Plans: [ { ID: 'vl-JevUsz3GJc18CC1VOs-qDKqoIWlLiUePdrzFc72-BtxBPHBDZM7ayn8CNQ59Sk4XjDbwwBVpdYrPIFtOvIw==', ParentMetaPlanID: 'hUcV0_EeNwUmXA6EoyNrtO-ZTD8H8F6LvNaSjMaPxB5ecFkA7y-5kc3q38cGumJENGHjtSoUndkYFUx0_xlJeg==', Type: 1, Name: 'bundle2022', Title: 'Proton Unlimited', MaxDomains: 3, MaxAddresses: 15, MaxCalendars: 25, MaxSpace: 536870912000, MaxMembers: 1, MaxVPN: 10, MaxTier: 2, Services: 7, Features: 1, State: 1, Cycle: 12, Currency: 'CHF', Amount: 11988, Quantity: 1, }, ], Renew: 1, External: 0, }, UpcomingSubscription: null, }; export function mockSubscriptionApi(subscription: typeof subscriptionDefaultResponse = subscriptionDefaultResponse) { addApiMock(getSubscription().url, () => subscription); } export const defaultSubscriptionCache = formatSubscription( subscriptionDefaultResponse.Subscription, subscriptionDefaultResponse.UpcomingSubscription ); export function mockSubscriptionCache(subscription: typeof defaultSubscriptionCache = defaultSubscriptionCache) { addToCache(SubscriptionModel.key, subscription); }
7,180
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/useUser.ts
import { getUser } from '@proton/shared/lib/api/user'; import { UserModel } from '@proton/shared/lib/models'; import { formatUser } from '@proton/shared/lib/models/userModel'; import { addApiMock, addToCache } from '@proton/testing'; export const userDefaultResponse = { Code: 1000, User: { ID: 'UtjmZQ61KXXx9IaKWEuWF1fMVraFABonV3pY5s9KiYcICgLf75vxuemuLrTVBPX0jSKAtSNO39HEJh4_gmAWmg==', Name: 'proton154', Currency: 'CHF', Credit: 0, Type: 1, CreateTime: 1675856278, MaxSpace: 536870912000, MaxUpload: 26214400, UsedSpace: 464014, Subscribed: 7, Services: 7, MnemonicStatus: 1, Role: 2, Private: 1, Delinquent: 0, Keys: [], ToMigrate: 0, Email: 'proton154@proton.black', DisplayName: 'proton154', }, }; export function mockUserApi() { addApiMock(getUser().url, () => userDefaultResponse); } export function mockUserCache(user = formatUser(userDefaultResponse.User)) { addToCache(UserModel.key, user); }
7,181
0
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers
petrpan-code/ProtonMail/WebClients/packages/components/hooks/helpers/test/useVpnServersCount.ts
import { queryVPNCountriesCount, queryVPNLogicalServerInfoCount, queryVPNServersCount, } from '@proton/shared/lib/api/vpn'; import { addApiMock } from '@proton/testing'; export const defaultServersCount = { Code: 1000, Servers: 437, Countries: 51, Capacity: 511.28999999999996, }; export const defaultCountriesCount = { Code: 1000, Counts: [ { MaxTier: 0, Count: 5, }, { MaxTier: 1, Count: 31, }, { MaxTier: 2, Count: 51, }, ], }; export const defaultLogicalVpnCount = { Code: 1000, Counts: [13, 173, 248], }; export function mockUserVPNServersCountApi() { addApiMock(queryVPNServersCount().url, () => defaultServersCount); addApiMock(queryVPNCountriesCount().url, () => defaultCountriesCount); addApiMock(queryVPNLogicalServerInfoCount().url, () => defaultLogicalVpnCount); }
7,182
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/credit-card-type.ts
import creditCardType from 'credit-card-type'; import { isNumber } from '@proton/shared/lib/helpers/validators'; const banks = require.context('@proton/styles/assets/img/credit-card-icons', true, /.svg$/); type BanksMap = { [bank: string]: () => string | undefined; }; const banksMap = banks.keys().reduce<BanksMap>((acc, key) => { acc[key] = () => banks(key); return acc; }, {}); export const getBankSvg = (type = '') => { const key = `./cc-${type}.svg`; if (!banksMap[key]) { return; } return banksMap[key](); }; export const isValidNumber = (v: string) => !v || isNumber(v); const withGaps = (value = '', gaps: number[] = []) => { return [...value].reduce((acc, digit, index) => { if (gaps.includes(index)) { return `${acc} ${digit}`; } return `${acc}${digit}`; }, ''); }; export const formatCreditCardNumber = (value: string) => { const [firstCreditCardType] = creditCardType(value); const { type = '', niceType = '', gaps = [], code } = firstCreditCardType || {}; const bankIcon = getBankSvg(type); const valueWithGaps = gaps.length ? withGaps(value, gaps) : value; return { valueWithGaps, bankIcon, niceType, codeName: code?.name ?? 'CVV', }; };
7,183
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/ensureTokenChargeable.ts
import { c } from 'ttag'; import { EnsureTokenChargeableInputs, EnsureTokenChargeableTranslations, ensureTokenChargeable as innerEnsureTokenChargeable, } from '../core'; export const defaultTranslations: EnsureTokenChargeableTranslations = { processAbortedError: c('Error').t`Process aborted`, paymentProcessCanceledError: c('Error').t`Payment process canceled`, paymentProcessFailedError: c('Error').t`Payment process failed`, paymentProcessConsumedError: c('Error').t`Payment process consumed`, paymentProcessNotSupportedError: c('Error').t`Payment process not supported`, unknownPaymentTokenStatusError: c('Error').t`Unknown payment token status`, tabClosedError: c('Error').t`Tab closed`, }; /** * Partially preconfigured ensureTokenChargeable function. */ export const getEnsureTokenChargeable = (translations: EnsureTokenChargeableTranslations = defaultTranslations) => (inputs: EnsureTokenChargeableInputs, delay?: number) => innerEnsureTokenChargeable(inputs, translations, delay); /** * Default implementation of the ensureTokenChargeable function. */ export const ensureTokenChargeable = getEnsureTokenChargeable();
7,184
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/index.ts
export * from './ensureTokenChargeable'; export * from './useMethods'; export * from './usePaymentFacade';
7,185
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/useMethods.ts
import { c } from 'ttag'; import { IconName } from '../../components/icon'; import { useApi, useAuthentication } from '../../hooks'; import { AvailablePaymentMethod, PAYMENT_METHOD_TYPES, PaymentMethodFlows, SavedPaymentMethod } from '../core'; import { MethodsHook, Props, useMethods as _useMethods } from '../react-extensions/useMethods'; export interface ViewPaymentMethod extends AvailablePaymentMethod { readonly icon: IconName | undefined; readonly text: string; } interface ClientMethodsHook extends MethodsHook { usedMethods: ViewPaymentMethod[]; newMethods: ViewPaymentMethod[]; allMethods: ViewPaymentMethod[]; lastUsedMethod: ViewPaymentMethod | undefined; } const getIcon = (paymentMethod: SavedPaymentMethod): IconName | undefined => { if (paymentMethod.Type === PAYMENT_METHOD_TYPES.PAYPAL) { return 'brand-paypal'; } if (paymentMethod.Type === PAYMENT_METHOD_TYPES.CARD) { switch (paymentMethod.Details.Brand.toLowerCase()) { case 'american express': return 'brand-amex'; case 'visa': return 'brand-visa'; case 'mastercard': return 'brand-mastercard'; case 'Discover': return 'brand-discover'; default: return 'credit-card'; } } }; const getMethod = (paymentMethod: SavedPaymentMethod): string => { switch (paymentMethod.Type) { case PAYMENT_METHOD_TYPES.CARD: const brand = paymentMethod.Details.Brand; const last4 = paymentMethod.Details.Last4; // translator: example would be: "Mastercard" ending in "7777" return c('new_plans: info').t`${brand} ending in ${last4}`; case PAYMENT_METHOD_TYPES.PAYPAL: return `PayPal - ${paymentMethod.Details.PayerID}`; default: return ''; } }; /** * Transform the payment method object from the react-extensions package to a view model that can be used in the UI. */ export function convertMethod( method: AvailablePaymentMethod, getSavedMethodById: MethodsHook['getSavedMethodByID'], flow: PaymentMethodFlows ): ViewPaymentMethod { if (method.paymentMethodId) { const savedMethod = getSavedMethodById(method.paymentMethodId) as SavedPaymentMethod; return { icon: getIcon(savedMethod), text: [getMethod(savedMethod), method.isExpired && `(${c('Info').t`Expired`})`].filter(Boolean).join(' '), ...method, }; } const isSignup = flow === 'signup' || flow === 'signup-pass' || flow === 'signup-vpn'; if (method.type === PAYMENT_METHOD_TYPES.PAYPAL || method.type === PAYMENT_METHOD_TYPES.PAYPAL_CREDIT) { return { icon: 'brand-paypal' as const, text: c('Payment method option').t`PayPal`, ...method, }; } else if (method.type === PAYMENT_METHOD_TYPES.BITCOIN) { return { icon: 'brand-bitcoin' as const, text: c('Payment method option').t`Bitcoin`, ...method, }; } else if (method.type === PAYMENT_METHOD_TYPES.CASH) { return { icon: 'money-bills' as const, text: c('Label').t`Cash`, ...method, }; } return { icon: 'credit-card' as const, text: isSignup ? c('Payment method option').t`Credit/debit card` : c('Payment method option').t`New credit/debit card`, ...method, }; } /** * Enhance the methods hook with client specific data like icons and text. * @param methodsHook - output of the useMethods hook from the react-extensions package * @param flow – current payment flow. Might modify the text of the payment methods * @returns */ export const wrapMethods = (methodsHook: MethodsHook, flow: PaymentMethodFlows): ClientMethodsHook => { const { getSavedMethodByID, usedMethods, newMethods, allMethods, lastUsedMethod } = methodsHook; return { ...methodsHook, usedMethods: usedMethods.map((method) => convertMethod(method, getSavedMethodByID, flow)), newMethods: newMethods.map((method) => convertMethod(method, getSavedMethodByID, flow)), allMethods: allMethods.map((method) => convertMethod(method, getSavedMethodByID, flow)), lastUsedMethod: lastUsedMethod && convertMethod(lastUsedMethod, getSavedMethodByID, flow), }; }; /** * A preconfigured version of the useMethods hook from the react-extensions package. * Returns view models of methods that can be used in the UI. */ export const useMethods = (props: Props): ClientMethodsHook => { const api = useApi(); const { UID } = useAuthentication(); const isAuthenticated = !!UID; const internalResult = _useMethods(props, { api, isAuthenticated }); return wrapMethods(internalResult, props.flow); };
7,186
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/usePaymentFacade.ts
import { useEffect } from 'react'; import { Api, Currency } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { useApi, useAuthentication, useModals } from '../../hooks'; import { ChargeablePaymentParameters, PAYMENT_METHOD_TYPES, PaymentMethodFlows, PaymentMethodStatus, PaymentMethodType, SavedPaymentMethod, } from '../core'; import { OnMethodChangedHandler, Operations, OperationsData, usePaymentFacade as useInnerPaymentFacade, } from '../react-extensions'; import { wrapMethods } from './useMethods'; import { getDefaultVerifyPayment, getDefaultVerifyPaypal } from './validators/validators'; type PaymentFacadeProps = { amount: number; currency: Currency; coupon?: string; /** * The flow parameter can modify the list of available payment methods and modify their behavior in certain cases. */ flow: PaymentMethodFlows; /** * The main callback that will be called when the payment is ready to be charged * after the payment token is fetched and verified with 3DS or other confirmation from the user. * @param operations - provides a common set of actions that can be performed with the verified payment token. * For example, the verified (that is, chargeable) payment token can be used to create a subscription or buy * credits. * @param data - provides the raw payment token, the payment source (or processor type) and operation context * like Plan or Cycle for subscription. */ onChargeable: ( operations: Operations, data: { chargeablePaymentParameters: ChargeablePaymentParameters; source: PaymentMethodType; context: OperationsData; } ) => Promise<unknown>; /** * The callback that will be called when the payment method is changed by the user. */ onMethodChanged?: OnMethodChangedHandler; paymentMethods?: SavedPaymentMethod[]; paymentMethodStatus?: PaymentMethodStatus; /** * Optional override for the API object. Can be helpful for auth/unauth flows. */ api?: Api; }; /** * Entry point for the payment logic for the monorepo clients. It's a wrapper around the * react-specific facade. The main purpose of this wrapper is to provide the default * implementation for the client-specific logic. It includes the implementation of the * token verification that depends on the view, as it requires user action. It also includes * pre-fetching of the payment tokens for PayPal and PayPal Credit. In addition, the payment * methods objects are enriched with the icons and texts. */ export const usePaymentFacade = ({ amount, currency, onChargeable, coupon, flow, onMethodChanged, paymentMethods, paymentMethodStatus, api: apiOverride, }: PaymentFacadeProps) => { const defaultApi = useApi(); const api = apiOverride ?? defaultApi; const { createModal } = useModals(); const { UID } = useAuthentication(); const isAuthenticated = !!UID; const hook = useInnerPaymentFacade( { amount, currency, onChargeable, coupon, flow, onMethodChanged, paymentMethods, paymentMethodStatus, }, { api, isAuthenticated, verifyPaymentPaypal: getDefaultVerifyPaypal(createModal, api), verifyPayment: getDefaultVerifyPayment(createModal, api), } ); const methods = wrapMethods(hook.methods, flow); const userCanTrigger = { [PAYMENT_METHOD_TYPES.BITCOIN]: false, [PAYMENT_METHOD_TYPES.CARD]: true, [PAYMENT_METHOD_TYPES.CASH]: false, [PAYMENT_METHOD_TYPES.PAYPAL]: true, [PAYMENT_METHOD_TYPES.PAYPAL_CREDIT]: true, [PAYMENT_METHOD_TYPES.TOKEN]: false, }; const userCanTriggerSelected = methods.selectedMethod?.type ? userCanTrigger[methods.selectedMethod.type] : false; /** * The longer I looked at this construction in its previous reincarnation, the more I was puzzled about it. * Interestingly enough, it crystalized again during the refactoring of payments, so it might be the only * way to make it work. * This construction makes possible rendering PayPal and PayPal Credit buttons at the same time. * - We must pre-fetch the payment token, otherwise we won't be able to open the payment verification tab * in Safari (as of 16.5, both Desktop and Mobile). The tab can be opened only as a result of * synchronous handler of the click. * - We can't prefetch the tokens inside the Paypal and Paypal Credit buttons, because Captcha must go * one after another. * - We can't put this overall logic into the lower levels (react-extensions or core), because it depends * on the view and app-specific assumptions. */ useEffect(() => { async function run() { if (hook.methods.isNewPaypal) { hook.paypal.reset(); hook.paypalCredit.reset(); try { await hook.paypal.fetchPaymentToken(); } catch {} // even if token fetching fails (for example because of network or Human Verification), // we still want to try to fetch the token for paypal-credit try { await hook.paypalCredit.fetchPaymentToken(); } catch {} } } run().catch(noop); }, [hook.methods.isNewPaypal, amount, currency]); const helpers = { selectedMethodValue: methods.selectedMethod?.value, selectedMethodType: methods.selectedMethod?.type, }; return { ...hook, ...helpers, methods, api, userCanTrigger, userCanTriggerSelected, }; };
7,187
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/validators/PaymentVerificationModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import { wait } from '@proton/shared/lib/helpers/promise'; import { applyHOCs, withNotifications } from '@proton/testing/index'; import PaymentVerificationModal, { PromiseWithController, Props } from './PaymentVerificationModal'; jest.mock('@proton/components/components/portal/Portal'); let props: Props; let promiseWithController: PromiseWithController; let promiseResolve: () => void; let promiseReject: (error: any) => void; beforeEach(() => { jest.clearAllMocks(); promiseWithController = { promise: new Promise((resolve, reject) => { promiseResolve = resolve; promiseReject = reject; }), abort: { abort: jest.fn(), } as any, }; props = { onSubmit: jest.fn(), onClose: jest.fn(), token: 'token123', onProcess: jest.fn().mockReturnValue(promiseWithController), }; }); const ContextPaymentVerificationModal = applyHOCs(withNotifications())(PaymentVerificationModal); it('should render', () => { const { container } = render(<ContextPaymentVerificationModal {...props} />); expect(container).not.toBeEmptyDOMElement(); }); it('should render redirect step by default', () => { render(<ContextPaymentVerificationModal {...props} />); expect(screen.getByTestId('redirect-message')).toBeInTheDocument(); expect(screen.getByText('Verify')).toBeInTheDocument(); }); it('should set redirecting step once user clicks on verify', () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); expect(screen.getByTestId('redirecting-message')).toBeInTheDocument(); }); it('should set redirected after processingDelay passes', async () => { const processingDelay = 100; render(<ContextPaymentVerificationModal {...props} processingDelay={processingDelay} />); screen.getByText('Verify').click(); await wait(processingDelay); expect(screen.getByTestId('redirected-message')).toBeInTheDocument(); }); it('should set fail step if promise rejects', async () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); promiseReject(new Error()); await screen.findByTestId('fail-message'); }); it('should call onSubmit and the onClose callback if promise resolves', async () => { render(<ContextPaymentVerificationModal {...props} />); screen.getByText('Verify').click(); promiseResolve(); await waitFor(() => expect(props.onSubmit).toHaveBeenCalledTimes(1)); expect(props.onClose).toHaveBeenCalledTimes(1); }); it('should abort the promise and call onClose if user cancels', async () => { const processingDelay = 100; render(<ContextPaymentVerificationModal {...props} processingDelay={processingDelay} />); screen.getByText('Verify').click(); await wait(processingDelay); screen.getByText('Cancel').click(); await waitFor(() => expect(props.onClose).toHaveBeenCalledTimes(1)); expect(promiseWithController.abort.abort).toHaveBeenCalledTimes(1); });
7,188
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/validators/PaymentVerificationModal.tsx
import { useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { FormModal, Loader, PrimaryButton } from '@proton/components/components'; import PaymentVerificationImage from '@proton/components/containers/payments/PaymentVerificationImage'; import { useNotifications } from '@proton/components/hooks'; import errorSvg from '@proton/styles/assets/img/errors/error-generic.svg'; import { CardPayment, PAYMENT_METHOD_TYPES, TokenPaymentMethod, toTokenPaymentMethod } from '../../core'; const STEPS = { REDIRECT: 'redirect', REDIRECTING: 'redirecting', REDIRECTED: 'redirected', FAIL: 'fail', }; const DEFAULT_PROCESSING_DELAY = 5000; export interface PromiseWithController { promise: Promise<void>; abort: AbortController; } export interface Props { onSubmit: (paymentMethod: TokenPaymentMethod) => void; onClose: () => void; token: string; payment?: CardPayment | {}; isAddCard?: boolean; type?: PAYMENT_METHOD_TYPES.PAYPAL | PAYMENT_METHOD_TYPES.PAYPAL_CREDIT | PAYMENT_METHOD_TYPES.CARD; onProcess: () => PromiseWithController; initialProcess?: PromiseWithController; processingDelay?: number; } const PaymentVerificationModal = ({ token, onSubmit, payment = {}, isAddCard, type = PAYMENT_METHOD_TYPES.CARD, onProcess, initialProcess, processingDelay = DEFAULT_PROCESSING_DELAY, ...rest }: Props) => { const isPayPal = [PAYMENT_METHOD_TYPES.PAYPAL, PAYMENT_METHOD_TYPES.PAYPAL_CREDIT].includes(type); let failTitle; if (isPayPal) { failTitle = c('Title').t`PayPal verification failed`; } else if (isAddCard) { failTitle = c('Title').t`Verification failed`; } else { failTitle = c('Title').t`Payment failed`; } const TITLES = { [STEPS.REDIRECT]: isAddCard ? c('Title').t`Card verification` : c('Title').t`Payment verification`, [STEPS.REDIRECTING]: c('Title').t`Processing...`, [STEPS.REDIRECTED]: isAddCard ? c('Title').t`Verifying your card...` : c('Title').t`Verifying your payment...`, [STEPS.FAIL]: failTitle, }; const [step, setStep] = useState(() => STEPS.REDIRECT); const [error, setError] = useState<{ tryAgain?: boolean }>({}); const { createNotification } = useNotifications(); const abortRef = useRef<AbortController>(); const timeoutRef = useRef<number>(); const handleCancel = () => { abortRef.current?.abort(); rest.onClose(); }; const handleSubmit = async ({ abort, promise }: PromiseWithController) => { try { setStep(STEPS.REDIRECTING); timeoutRef.current = window.setTimeout(() => { setStep(STEPS.REDIRECTED); }, processingDelay); abortRef.current = abort; await promise; onSubmit(toTokenPaymentMethod(token)); rest.onClose(); } catch (error: any) { window.clearTimeout(timeoutRef.current); setStep(STEPS.FAIL); setError(error); // if not coming from API error if (error && error.message && !error.config) { createNotification({ text: error.message, type: 'error' }); } } }; useEffect(() => { if (initialProcess) { handleSubmit(initialProcess); } }, []); useEffect(() => { return () => window.clearTimeout(timeoutRef.current); }, []); return ( <FormModal title={TITLES[step]} onSubmit={() => handleSubmit(onProcess())} small noTitleEllipsis hasClose={false} footer={ step === STEPS.REDIRECT ? ( <> <Button type="reset">{c('Action').t`Cancel`}</Button> <PrimaryButton type="submit">{c('Action').t`Verify`}</PrimaryButton> </> ) : null } {...rest} > {{ [STEPS.REDIRECT]: () => ( <> <p className="text-center"> {isAddCard ? c('Info').t`We need to authenticate your payment method with your bank.` : c('Info').t`We need to authenticate your payment with your bank.`} </p> <p className="text-center"> <PaymentVerificationImage payment={payment} type={type} /> </p> <div className="mb-4" data-testid="redirect-message"> {isAddCard ? c('Info') .t`Verification will open a new tab, please disable any popup blockers. You will not be charged. Any amount used to verify the card will be refunded immediately.` : c('Info') .t`The verification process will open a new browser tab. Please disable any active pop-up blockers.`} </div> </> ), [STEPS.REDIRECTING]: () => ( <> <p className="text-center"> {isPayPal ? c('Info').t`You will soon be redirected to PayPal to verify your payment.` : c('Info').t`You may be redirected to your bank’s website.`} </p> <Loader /> <div className="mb-4" data-testid="redirecting-message">{c('Info') .t`Don’t see anything? Remember to turn off pop-up blockers.`}</div> </> ), [STEPS.REDIRECTED]: () => ( <> <p className="text-center"> {isAddCard && !isPayPal ? c('Info').t`Please authenticate your card in the verification tab.` : c('Info').t`Please authenticate your payment in the verification tab.`} </p> <Loader /> <p className="text-center"> <Button onClick={handleCancel}>{c('Action').t`Cancel`}</Button> </p> <div className="mb-4" data-testid="redirected-message">{c('Info') .t`Verification may take a few minutes.`}</div> </> ), [STEPS.FAIL]: () => ( <div className="text-center" data-testid="fail-message"> <p>{!isAddCard && c('Info').t`We couldn’t process your payment.`}</p> <img src={errorSvg} alt={c('Title').t`Error`} /> <p> {isPayPal ? c('Info') .t`Please try again, use a different payment method, or contact PayPal for assistance.` : c('Info').t`Please try again using a different payment method, or contact your bank.`} </p> {error?.tryAgain ? ( <p> <Button type="submit">{c('Action').t`Try again`}</Button> </p> ) : null} <p> <PrimaryButton onClick={handleCancel}> {isAddCard ? c('Action').t`Use a different card` : c('Action').t`Use a different payment method`} </PrimaryButton> </p> </div> ), }[step]()} </FormModal> ); }; export default PaymentVerificationModal;
7,189
0
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions
petrpan-code/ProtonMail/WebClients/packages/components/payments/client-extensions/validators/validators.tsx
import { Api } from '@proton/shared/lib/interfaces'; import { PAYMENT_METHOD_TYPES, PaymentVerificator, TokenPaymentMethod } from '../../core'; import { ensureTokenChargeable } from '../ensureTokenChargeable'; import PaymentVerificationModal from './PaymentVerificationModal'; /** * Default implementation of the payment verificator for credit cards. * Once the function is called, it renders a modal that warns user about the upcoming 3DS verification. * When user confirms it, opens the verification page. Usually it's page of the bank, or PayPal's page, * or in case of Braintree it's a custom page that we render on our backend. * The implemntation depends on createModal function (useModal hook as of now) and on the API. * * @returns a function that returns a promise that resolves to a token payment method. * It can reject if user cancels the verification. Beyond that, verification can fail because of API error or because * user actually failed verification. This cases are handled inside {@link ensureTokenChargeable} and * {@link PaymentVerificationModal}. Such errors don't require Sentry error at the time being, as they are * communicated to the user might be gracefully handled by the view by offering user a retry. */ export const getDefaultVerifyPayment = (createModal: (modal: JSX.Element) => void, api: Api): PaymentVerificator => async function verify({ addCardMode, Payment, Token, ApprovalURL, ReturnHost, }: Parameters<PaymentVerificator>[0]): Promise<TokenPaymentMethod> { return new Promise<TokenPaymentMethod>((resolve, reject) => { createModal( <PaymentVerificationModal isAddCard={addCardMode} payment={Payment} token={Token} onSubmit={resolve} onClose={reject} onProcess={() => { const abort = new AbortController(); return { promise: ensureTokenChargeable({ Token, api, ReturnHost, ApprovalURL, signal: abort.signal, }), abort, }; }} /> ); }); }; /** * This function is very similar to {@link getDefaultVerifyPayment}, but it's used for PayPal. * There are differences in the configuration, but the overall idea and behavior is the same. * @returns */ export const getDefaultVerifyPaypal = (createModal: (modal: JSX.Element) => void, api: Api): PaymentVerificator => { return async function verify({ Token, ApprovalURL, ReturnHost }) { const tokenPaymentMethod = await new Promise<TokenPaymentMethod>((resolve, reject) => { const onProcess = () => { const abort = new AbortController(); return { promise: ensureTokenChargeable({ Token, api, ReturnHost, ApprovalURL, signal: abort.signal, }), abort, }; }; createModal( <PaymentVerificationModal token={Token} onSubmit={resolve} onClose={reject} type={PAYMENT_METHOD_TYPES.PAYPAL} onProcess={onProcess} initialProcess={onProcess()} /> ); }); return tokenPaymentMethod; }; };
7,190
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/cardDetails.test.ts
import { CardModel, toDetails } from './cardDetails'; describe('cardDetails', () => { it('should format card details correctly', () => { let card: CardModel = { number: '4111 1111 1111 1111', month: '10', year: '2020', cvc: '123', zip: '123 45', country: 'US', }; expect(toDetails(card)).toEqual({ Number: '4111111111111111', ExpMonth: '10', ExpYear: '2020', CVC: '123', ZIP: '123 45', Country: 'US', }); card = { number: '4111 1111 1111 1111', month: '10', year: '32', cvc: '123', zip: '123 45', country: 'US', }; expect(toDetails(card)).toEqual({ Number: '4111111111111111', ExpMonth: '10', ExpYear: '2032', CVC: '123', ZIP: '123 45', Country: 'US', }); }); });
7,191
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/cardDetails.ts
import valid from 'card-validator'; import creditCardType from 'credit-card-type'; import { c } from 'ttag'; import { getFirstTop } from '@proton/components/helpers/countries'; import { CreateCardDetailsBackend, isSavedCardDetails } from './interface'; const formatYear = (year: any) => { const pre = String(year).length === 2 ? '20' : ''; return `${pre}${year}`; }; export interface CardModel { number: string; month: string; year: string; cvc: string; zip: string; country: string; } export const toDetails = ({ number, month: ExpMonth, year, cvc: CVC, zip: ZIP, country: Country, }: CardModel): CreateCardDetailsBackend => { return { Number: String(number).replace(/\s+/g, ''), ExpMonth, ExpYear: formatYear(year), CVC, // Don't clean ZIP, space is allowed ZIP, Country, }; }; export const getDefaultCard = (): CardModel => { const { value: country } = getFirstTop(); return { number: '', month: '', year: '', cvc: '', zip: '', country, }; }; export const isCardNumber = (value: string | undefined) => valid.number(value).isValid; export const isCVV = (value: string | undefined, maxLength: number) => valid.cvv(value, maxLength).isValid; export const isPostalCode = (value: string | undefined) => valid.postalCode(value).isValid; export const isExpirationDate = (month: string, year: string) => valid.expirationDate({ month, year }).isValid; export type KeyOfCardModel = keyof CardModel; const check = (card: CardModel, key: KeyOfCardModel): string | undefined => { const value = card[key]; switch (key) { case 'month': case 'year': if (!isExpirationDate(card.month, card.year)) { return c('Error').t`Invalid expiration date`; } break; case 'number': if (!isCardNumber(value)) { return c('Error').t`Invalid card number`; } break; case 'cvc': { const number = card?.number || ''; const firstCreditCardType = creditCardType(number)?.[0]; const { name, size } = firstCreditCardType?.code || { name: 'CVV', size: 3 }; if (!isCVV(value, size)) { return c('Error').t`Invalid ${name} code`; } break; } case 'zip': if (!isPostalCode(value)) { return c('Error').t`Invalid postal code`; } break; default: break; } }; export const getErrors = (card: CardModel): Partial<CardModel> => { return ['number', 'month', 'year', 'cvc', 'zip', 'country'].reduce((acc, key) => { const error = check(card, key as KeyOfCardModel); if (error) { acc[key] = error; } return acc; }, Object.create(null)); }; export const isValid = (card: CardModel) => !Object.keys(getErrors(card)).length; /** * Check if card is expired at the end of current month */ export function isExpired(cardDetails: CreateCardDetailsBackend | unknown): boolean { if (!isSavedCardDetails(cardDetails)) { return false; } const { ExpMonth, ExpYear } = cardDetails; const currentTime = new Date(); const currentMonth = currentTime.getMonth() + 1; const currentYear = currentTime.getFullYear(); return currentMonth > +ExpMonth && currentYear >= +ExpYear; }
7,192
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/constants.ts
export enum PAYMENT_TOKEN_STATUS { STATUS_PENDING = 0, STATUS_CHARGEABLE = 1, STATUS_FAILED = 2, STATUS_CONSUMED = 3, STATUS_NOT_SUPPORTED = 4, } export enum PAYMENT_METHOD_TYPES { CARD = 'card', PAYPAL = 'paypal', PAYPAL_CREDIT = 'paypal-credit', BITCOIN = 'bitcoin', CASH = 'cash', TOKEN = 'token', }
7,193
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/createPaymentToken.ts
import { CreateTokenData, createToken } from '@proton/shared/lib/api/payments'; import { Api } from '@proton/shared/lib/interfaces'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from './constants'; import { AmountAndCurrency, CardPayment, ChargeablePaymentToken, ExistingPayment, ExistingPaymentMethod, NonChargeablePaymentToken, PaymentTokenResult, PaypalPayment, PlainPaymentMethodType, TokenPaymentMethod, WrappedCardPayment, } from './interface'; import { toTokenPaymentMethod } from './utils'; /** * Prepares the parameters and makes the API call to create the payment token. * * @param params * @param api * @param amountAndCurrency */ const fetchPaymentToken = async ( params: WrappedCardPayment | ExistingPayment, api: Api, amountAndCurrency?: AmountAndCurrency ): Promise<PaymentTokenResult> => { const data: CreateTokenData = { ...amountAndCurrency, ...params }; return api<PaymentTokenResult>({ ...createToken(data), notificationExpiration: 10000, }); }; export const formatToken = ( { Token, Status, ApprovalURL, ReturnHost }: PaymentTokenResult, type: PlainPaymentMethodType, amountAndCurrency?: AmountAndCurrency ): ChargeablePaymentToken | NonChargeablePaymentToken => { const chargeable = Status === PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE; const tokenPaymentMethod = toTokenPaymentMethod(Token); const base = { type, chargeable, ...amountAndCurrency, ...tokenPaymentMethod, }; if (chargeable) { return base as ChargeablePaymentToken; } else { return { ...base, status: Status, approvalURL: ApprovalURL, returnHost: ReturnHost, } as NonChargeablePaymentToken; } }; export const createPaymentTokenForCard = async ( params: WrappedCardPayment, api: Api, amountAndCurrency?: AmountAndCurrency ): Promise<ChargeablePaymentToken | NonChargeablePaymentToken> => { const paymentTokenResult = await fetchPaymentToken(params, api, amountAndCurrency); return formatToken(paymentTokenResult, PAYMENT_METHOD_TYPES.CARD, amountAndCurrency); }; export const createPaymentTokenForExistingPayment = async ( PaymentMethodID: ExistingPaymentMethod, type: PAYMENT_METHOD_TYPES.CARD | PAYMENT_METHOD_TYPES.PAYPAL, api: Api, amountAndCurrency: AmountAndCurrency ): Promise<ChargeablePaymentToken | NonChargeablePaymentToken> => { const paymentTokenResult = await fetchPaymentToken( { PaymentMethodID, }, api, amountAndCurrency ); return formatToken(paymentTokenResult, type, amountAndCurrency); }; export type PaymentVerificator = (params: { addCardMode?: boolean; Payment?: CardPayment | PaypalPayment; Token: string; ApprovalURL?: string; ReturnHost?: string; }) => Promise<TokenPaymentMethod>;
7,194
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/crypto-types.ts
export type CryptocurrencyType = 'bitcoin'; export interface CryptoPayment { Type: 'cryptocurrency'; Details: { Coin: CryptocurrencyType; }; } export interface WrappedCryptoPayment { Payment: CryptoPayment; }
7,195
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/ensureTokenChargeable.test.ts
import { PAYMENT_TOKEN_STATUS } from './constants'; import { EnsureTokenChargeableTranslations, ensureTokenChargeable } from './ensureTokenChargeable'; let tab: { closed: boolean; close: () => any }; const translations: EnsureTokenChargeableTranslations = { processAbortedError: 'Process aborted', paymentProcessCanceledError: 'Payment process canceled', paymentProcessFailedError: 'Payment process failed', paymentProcessConsumedError: 'Payment process consumed', paymentProcessNotSupportedError: 'Payment process not supported', unknownPaymentTokenStatusError: 'Unknown payment token status', tabClosedError: 'Tab closed', }; describe('process', () => { let ApprovalURL = 'https://example.proton.me'; let ReturnHost = 'https://return.proton.me'; let Token = 'some-payment-token-222'; let api: jest.Mock; let signal: AbortSignal; beforeEach(() => { jest.clearAllMocks(); tab = { closed: false, close: jest.fn() }; jest.spyOn(window, 'open').mockReturnValue(tab as any); jest.spyOn(window, 'removeEventListener'); jest.spyOn(window, 'addEventListener'); api = jest.fn(); signal = { aborted: false, reason: null, onabort: jest.fn(), throwIfAborted: jest.fn(), addEventListener: jest.fn(), removeEventListener: jest.fn(), dispatchEvent: jest.fn(), }; }); it('should open the ApprovalURL', () => { tab.closed = true; // prevents the test from hanging because of an unhandled promise ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations).catch(() => {}); expect(window.open).toHaveBeenCalledWith(ApprovalURL); }); it('should add abort listener to the signal', async () => { const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); expect(signal.addEventListener).toHaveBeenCalledTimes(1); const signalAddEventListenerMock = signal.addEventListener as jest.Mock; expect(signalAddEventListenerMock.mock.lastCall[0]).toEqual('abort'); expect(typeof signalAddEventListenerMock.mock.lastCall[1]).toBe('function'); expect(window.addEventListener).toHaveBeenCalledTimes(1); const windowAddEventListenerMock = window.addEventListener as jest.Mock; expect(windowAddEventListenerMock.mock.lastCall[0]).toEqual('message'); expect(typeof windowAddEventListenerMock.mock.lastCall[1]).toEqual('function'); const onMessage = windowAddEventListenerMock.mock.lastCall[1]; const abort = signalAddEventListenerMock.mock.lastCall[1]; abort(); expect(window.removeEventListener).toHaveBeenCalledWith('message', onMessage, false); expect(signal.removeEventListener).toHaveBeenCalledWith('abort', abort); expect(tab.close).toHaveBeenCalled(); await expect(promise).rejects.toEqual(new Error('Process aborted')); }); it('should resolve if Status is STATUS_CHARGEABLE', async () => { tab.closed = true; api.mockResolvedValue({ Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }); const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); await expect(promise).resolves.toEqual(undefined); }); it.each([ PAYMENT_TOKEN_STATUS.STATUS_PENDING, PAYMENT_TOKEN_STATUS.STATUS_FAILED, PAYMENT_TOKEN_STATUS.STATUS_CONSUMED, PAYMENT_TOKEN_STATUS.STATUS_NOT_SUPPORTED, ])('should reject if Status is %s', async (Status) => { tab.closed = true; api.mockResolvedValue({ Status, }); const promise = ensureTokenChargeable({ api, ApprovalURL, ReturnHost, signal, Token }, translations); await expect(promise).rejects.toEqual({ tryAgain: true }); }); it('should re-try to confirm until the tab is closed', async () => { api.mockResolvedValue({ Status: PAYMENT_TOKEN_STATUS.STATUS_CHARGEABLE, }); const delayListening = 10; const promise = ensureTokenChargeable( { api, ApprovalURL, ReturnHost, signal, Token }, translations, delayListening ); jest.runAllTimers(); tab.closed = true; await expect(promise).resolves.toEqual(undefined); }); });
7,196
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/ensureTokenChargeable.ts
import { getTokenStatus } from '@proton/shared/lib/api/payments'; import { wait } from '@proton/shared/lib/helpers/promise'; import { getHostname } from '@proton/shared/lib/helpers/url'; import { Api } from '@proton/shared/lib/interfaces'; import { PAYMENT_TOKEN_STATUS } from './constants'; import { PaymentTokenResult } from './interface'; const { STATUS_PENDING, STATUS_CHARGEABLE, STATUS_FAILED, STATUS_CONSUMED, STATUS_NOT_SUPPORTED } = PAYMENT_TOKEN_STATUS; const DELAY_PULLING = 5000; const DELAY_LISTENING = 1000; export interface EnsureTokenChargeableTranslations { processAbortedError: string; paymentProcessCanceledError: string; paymentProcessFailedError: string; paymentProcessConsumedError: string; paymentProcessNotSupportedError: string; unknownPaymentTokenStatusError: string; tabClosedError: string; } /** * Recursive function to check token status */ const pull = async ({ timer = 0, Token, api, signal, translations, }: { timer?: number; Token: string; api: Api; signal: AbortSignal; translations: EnsureTokenChargeableTranslations; }): Promise<any> => { if (signal.aborted) { throw new Error(translations.processAbortedError); } if (timer > DELAY_PULLING * 30) { throw new Error(translations.paymentProcessCanceledError); } const { Status } = await api({ ...getTokenStatus(Token), signal }); if (Status === STATUS_FAILED) { throw new Error(translations.paymentProcessFailedError); } if (Status === STATUS_CONSUMED) { throw new Error(translations.paymentProcessConsumedError); } if (Status === STATUS_NOT_SUPPORTED) { throw new Error(translations.paymentProcessNotSupportedError); } if (Status === STATUS_CHARGEABLE) { return; } if (Status === STATUS_PENDING) { await wait(DELAY_PULLING); return pull({ Token, api, timer: timer + DELAY_PULLING, signal, translations }); } throw new Error(translations.unknownPaymentTokenStatusError); }; export type EnsureTokenChargeableInputs = Pick<PaymentTokenResult, 'ApprovalURL' | 'ReturnHost' | 'Token'> & { api: Api; signal: AbortSignal; }; /** * Accepts the payment token as the input and processes it to make it chargeable. * Currently initializes a new tab where user can confirm the payment (3DS or Paypal confirmation). * After the verification tab is closed, the function checks the status of the token and resolves if it's chargeable. * An additional purpose of this function is to abstract away the verification mechanism and thus stress out that * alternative implementations are possible. */ export const ensureTokenChargeable = ( { Token, api, ApprovalURL, ReturnHost, signal }: EnsureTokenChargeableInputs, translations: EnsureTokenChargeableTranslations, delayListening = DELAY_LISTENING ) => { const tab = window.open(ApprovalURL); return new Promise<void>((resolve, reject) => { let listen = false; const reset = () => { listen = false; // eslint-disable-next-line @typescript-eslint/no-use-before-define window.removeEventListener('message', onMessage, false); // eslint-disable-next-line @typescript-eslint/no-use-before-define signal.removeEventListener('abort', abort); }; const listenTab = async (): Promise<any> => { if (!listen) { return; } if (tab && tab.closed) { try { reset(); const { Status } = await api({ ...getTokenStatus(Token), signal }); if (Status === STATUS_CHARGEABLE) { return resolve(); } throw new Error(translations.tabClosedError); } catch (error: any) { return reject({ ...error, tryAgain: true }); } } await wait(delayListening); return listenTab(); }; const onMessage = (event: MessageEvent) => { if (getHostname(event.origin) !== ReturnHost) { return; } reset(); tab?.close?.(); const { cancel } = event.data; if (cancel === '1') { return reject(); } pull({ Token, api, signal, translations }).then(resolve).catch(reject); }; const abort = () => { reset(); tab?.close?.(); reject(new Error(translations.processAbortedError)); }; signal.addEventListener('abort', abort); window.addEventListener('message', onMessage, false); listen = true; listenTab(); }); };
7,197
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/index.ts
export * from './cardDetails'; export * from './constants'; export * from './createPaymentToken'; export * from './crypto-types'; export * from './ensureTokenChargeable'; export * from './interface'; export * from './methods'; export * from './payment-processors/cardPayment'; export * from './payment-processors/paymentProcessor'; export * from './payment-processors/paypalPayment'; export * from './payment-processors/savedPayment'; export * from './utils';
7,198
0
petrpan-code/ProtonMail/WebClients/packages/components/payments
petrpan-code/ProtonMail/WebClients/packages/components/payments/core/interface.ts
import { Currency } from '@proton/shared/lib/interfaces'; import { PAYMENT_METHOD_TYPES, PAYMENT_TOKEN_STATUS } from './constants'; export interface CreateCardDetailsBackend { Number: string; ExpMonth: string; ExpYear: string; CVC: string; ZIP: string; Country: string; } export interface CardPayment { Type: PAYMENT_METHOD_TYPES.CARD; Details: CreateCardDetailsBackend; } export function isCardPayment(payment: any): payment is CardPayment { return payment?.Type === PAYMENT_METHOD_TYPES.CARD && !!payment?.Details; } export interface TokenPayment { Type: PAYMENT_METHOD_TYPES.TOKEN; Details: { Token: string; }; } export function isTokenPayment(payment: any): payment is TokenPayment { return payment?.Type === PAYMENT_METHOD_TYPES.TOKEN || !!(payment as any)?.Details?.Token; } export interface PaypalPayment { Type: PAYMENT_METHOD_TYPES.PAYPAL | PAYMENT_METHOD_TYPES.PAYPAL_CREDIT; } export interface WrappedPaypalPayment { Payment: PaypalPayment; } export function isPaypalPayment(payment: any): payment is PaypalPayment { return ( payment && (payment.Type === PAYMENT_METHOD_TYPES.PAYPAL || payment.Type === PAYMENT_METHOD_TYPES.PAYPAL_CREDIT) ); } export interface ExistingPayment { PaymentMethodID: string; } export interface WrappedCardPayment { Payment: CardPayment; } export interface TokenPaymentMethod { Payment: TokenPayment; } export function isTokenPaymentMethod(data: any): data is TokenPaymentMethod { return !!data && isTokenPayment(data.Payment); } export interface AmountAndCurrency { Amount: number; Currency: Currency; } export interface PaymentTokenResult { Token: string; Status: PAYMENT_TOKEN_STATUS; ApprovalURL?: string; ReturnHost?: string; } export type PlainPaymentMethodType = `${PAYMENT_METHOD_TYPES}`; export type ChargeablePaymentParameters = Partial<TokenPaymentMethod> & AmountAndCurrency & { type: PAYMENT_METHOD_TYPES.PAYPAL | PAYMENT_METHOD_TYPES.PAYPAL_CREDIT | PAYMENT_METHOD_TYPES.CARD; chargeable: true; }; export type ChargeablePaymentToken = TokenPaymentMethod & AmountAndCurrency & { type: PAYMENT_METHOD_TYPES.PAYPAL | PAYMENT_METHOD_TYPES.PAYPAL_CREDIT | PAYMENT_METHOD_TYPES.CARD; chargeable: true; }; export type VerifiedPaymentToken = TokenPaymentMethod & { type: PAYMENT_METHOD_TYPES.CARD; }; export type NonChargeablePaymentToken = Omit<ChargeablePaymentToken, 'chargeable'> & { chargeable: false; status: PAYMENT_TOKEN_STATUS; returnHost: string; approvalURL: string; }; export interface PaymentMethodStatus { Card: boolean; Paypal: boolean; Apple: boolean; Cash: boolean; Bitcoin: boolean; } export interface PayPalDetails { BillingAgreementID: string; PayerID: string; Payer: string; } export function isPaypalDetails(obj: any): obj is PayPalDetails { if (!obj) { return false; } const props: (keyof PayPalDetails)[] = ['BillingAgreementID', 'PayerID']; return props.every((prop) => typeof obj[prop] === 'string'); } export interface SavedCardDetails { /** * Even though you can't add the name to the card, it's still returned from the API for old users who already * have the card name. */ Name?: string | null; ExpMonth: string; ExpYear: string; ZIP: string; Country: string; Last4: string; Brand: string; } export function isSavedCardDetails(obj: any): obj is SavedCardDetails { if (!obj) { return false; } // Name is optional property, so we don't need to check it here const props: (keyof SavedCardDetails)[] = ['ExpMonth', 'ExpYear', 'ZIP', 'Country', 'Last4', 'Brand']; return props.every((prop) => typeof obj[prop] === 'string'); } export enum Autopay { DISABLE = 0, ENABLE = 1, } export type PaymentMethodCardDetails = { Order: number; ID: string; Type: PAYMENT_METHOD_TYPES.CARD; Details: SavedCardDetails; Autopay: Autopay; }; export type PaymentMethodPaypal = { Order: number; ID: string; Type: PAYMENT_METHOD_TYPES.PAYPAL; Details: PayPalDetails; }; export type SavedPaymentMethod = PaymentMethodPaypal | PaymentMethodCardDetails; export interface LatestSubscription { LastSubscriptionEnd: number; } export function methodMatches( method: PaymentMethodType | undefined, methods: PlainPaymentMethodType[] ): method is PlainPaymentMethodType { if (!method) { return false; } return (methods as string[]).includes(method); } export type ExistingPaymentMethod = string; export function isExistingPaymentMethod(paymentMethod?: PaymentMethodType): paymentMethod is ExistingPaymentMethod { return ( paymentMethod !== undefined && typeof paymentMethod === 'string' && !methodMatches(paymentMethod, Object.values(PAYMENT_METHOD_TYPES)) ); } export type PaymentMethodType = PlainPaymentMethodType | ExistingPaymentMethod; export interface AvailablePaymentMethod { readonly type: PlainPaymentMethodType; readonly paymentMethodId?: string; // defined only for existing payment methods readonly isExpired?: boolean; // defined only for existing credit cards readonly value: PaymentMethodType; readonly isSaved: boolean; } export type PaymentMethodFlows = | 'invoice' | 'signup' | 'signup-pass' | 'signup-vpn' | 'human-verification' | 'credit' | 'donation' | 'subscription';
7,199