1 import { type FC, type PropsWithChildren, createContext, useCallback, useContext } from 'react';
3 import type { UnlockDTO } from '@proton/pass/lib/auth/lock/types';
4 import type { MaybeNull } from '@proton/pass/types';
6 type UnlockContextValue = { unlock: (dto: UnlockDTO) => Promise<void> };
8 const UnlockContext = createContext<MaybeNull<UnlockContextValue>>(null);
10 /** Ideally we could move this to `PassCoreProvider` but as
11 * the `unlock` implementation can depend on other context
12 * objects, we resort to a custom context provider */
13 export const UnlockProvider: FC<PropsWithChildren<UnlockContextValue>> = ({ unlock, children }) => (
14 <UnlockContext.Provider value={{ unlock }}>{children}</UnlockContext.Provider>
17 export const useUnlock = (onError?: (error: Error) => void) => {
18 const ctx = useContext(UnlockContext);
19 if (!ctx) throw new Error('Unlock context not initialized');
22 async (dto: UnlockDTO) => {
24 await ctx.unlock(dto);
26 if (err instanceof Error) onError?.(err);