All files / src/apps/gbs-music-web/components/hooks useUnsavedChangesGuard.ts

0% Statements 0/28
0% Branches 0/4
0% Functions 0/6
0% Lines 0/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                                                                                       
import { useCallback, useState } from "react";
 
type GuardedAction = () => void | Promise<void>;
 
interface UseUnsavedChangesGuardOptions {
  modified: boolean;
  save: () => Promise<boolean>;
}
 
interface UseUnsavedChangesGuardResult {
  hasPendingAction: boolean;
  runWithUnsavedCheck: (action: GuardedAction) => Promise<void>;
  closeConfirm: () => void;
  saveAndContinue: () => Promise<void>;
  discardAndContinue: () => Promise<void>;
}
 
export const useUnsavedChangesGuard = ({
  modified,
  save,
}: UseUnsavedChangesGuardOptions): UseUnsavedChangesGuardResult => {
  const [pendingAction, setPendingAction] = useState<GuardedAction | null>(
    null,
  );
 
  const closeConfirm = useCallback(() => {
    setPendingAction(null);
  }, []);
 
  const runWithUnsavedCheck = useCallback(
    async (action: GuardedAction) => {
      Iif (!modified) {
        await action();
        return;
      }
 
      setPendingAction(() => action);
    },
    [modified],
  );
 
  const saveAndContinue = useCallback(async () => {
    Iif (!pendingAction) {
      return;
    }
 
    const action = pendingAction;
    const didSave = await save();
 
    Iif (!didSave) {
      return;
    }
 
    closeConfirm();
    await action();
  }, [closeConfirm, pendingAction, save]);
 
  const discardAndContinue = useCallback(async () => {
    Iif (!pendingAction) {
      return;
    }
 
    const action = pendingAction;
    closeConfirm();
    await action();
  }, [closeConfirm, pendingAction]);
 
  return {
    hasPendingAction: pendingAction !== null,
    runWithUnsavedCheck,
    closeConfirm,
    saveAndContinue,
    discardAndContinue,
  };
};