Files
site-builder/craft/src/state/SaveGuardContext.tsx
T

136 lines
5.1 KiB
TypeScript
Raw Normal View History

import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, ReactNode } from 'react';
import { useEditorConfig } from './EditorConfigContext';
export type LoadState = 'loading' | 'loaded' | 'failed';
interface SaveGuardContextValue {
/** Nothing may be saved until this is 'loaded' -- a failed load leaves the
* canvas blank, and saving that would overwrite the customer's site. */
loadState: LoadState;
setLoadState: (s: LoadState) => void;
/** Server refused a save that would replace a non-empty site with an empty
* one (409 empty_overwrite_refused). Holds the message while the banner is up. */
emptyRefusal: string | null;
setEmptyRefusal: (message: string | null) => void;
/** One-shot: the next save sends force_empty (consumed by the next successful save). */
forceEmptyNextSave: React.MutableRefObject<boolean>;
armForceEmptyNextSave: () => void;
/** True when the editor holds changes (canvas, pages, design, header/footer)
* made after the last successful save or load. Cleared only by a save. */
dirty: boolean;
/** Synchronous read of `dirty`, for handlers that must not see a stale render. */
isDirty: () => boolean;
/** Record a change. Ignored until the site has loaded (load itself rewrites state). */
markDirty: () => void;
/** Call right before serializing for a save; pass the ticket to `endSave`. */
beginSave: () => SaveTicket;
/** Finish a save. Clears dirty only if it succeeded AND nothing changed since `beginSave`. */
endSave: (ticket: SaveTicket, succeeded: boolean) => void;
/** True while at least one save request is in flight. */
saving: boolean;
/** Skip the unsaved-changes prompt for the next unload (e.g. a deliberate "Reload latest"). */
suppressBeforeUnload: () => void;
}
/** Identifies the editor state a save was built from. */
export interface SaveTicket {
version: number;
}
// Default (no provider: standalone mode and isolated unit tests) is
// permissive -- the gate only applies inside <SaveGuardProvider> in WHP mode.
const defaultValue: SaveGuardContextValue = {
loadState: 'loaded',
setLoadState: () => {},
emptyRefusal: null,
setEmptyRefusal: () => {},
forceEmptyNextSave: { current: false },
armForceEmptyNextSave: () => {},
dirty: false,
isDirty: () => false,
markDirty: () => {},
beginSave: () => ({ version: 0 }),
endSave: () => {},
saving: false,
suppressBeforeUnload: () => {},
};
const SaveGuardContext = createContext<SaveGuardContextValue>(defaultValue);
export const useSaveGuard = () => useContext(SaveGuardContext);
export const SaveGuardProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const { isWHP } = useEditorConfig();
const [loadState, setLoadState] = useState<LoadState>(isWHP ? 'loading' : 'loaded');
const [emptyRefusal, setEmptyRefusal] = useState<string | null>(null);
const forceEmptyNextSave = useRef(false);
// Dirty tracking. `versionRef` counts changes so a save that raced with an
// edit cannot mark that edit clean.
const [dirty, setDirty] = useState(false);
const [savesInFlight, setSavesInFlight] = useState(0);
const dirtyRef = useRef(false);
const versionRef = useRef(0);
const loadedRef = useRef(loadState === 'loaded');
const suppressRef = useRef(false);
// A (re)load replaces the whole editor state: it is the new clean baseline.
useEffect(() => {
loadedRef.current = loadState === 'loaded';
if (loadState === 'loaded') {
dirtyRef.current = false;
setDirty(false);
}
}, [loadState]);
const markDirty = useCallback(() => {
if (!loadedRef.current) return;
versionRef.current += 1;
dirtyRef.current = true;
setDirty(true);
}, []);
const isDirty = useCallback(() => dirtyRef.current, []);
const beginSave = useCallback((): SaveTicket => {
setSavesInFlight((n) => n + 1);
return { version: versionRef.current };
}, []);
const endSave = useCallback((ticket: SaveTicket, succeeded: boolean) => {
setSavesInFlight((n) => Math.max(0, n - 1));
if (succeeded && ticket.version === versionRef.current) {
dirtyRef.current = false;
setDirty(false);
}
}, []);
const suppressBeforeUnload = useCallback(() => { suppressRef.current = true; }, []);
const saving = savesInFlight > 0;
const needsPrompt = isWHP && (dirty || saving);
useEffect(() => {
if (!needsPrompt) return;
const onBeforeUnload = (e: BeforeUnloadEvent) => {
if (suppressRef.current) return;
e.preventDefault();
e.returnValue = '';
};
window.addEventListener('beforeunload', onBeforeUnload);
return () => window.removeEventListener('beforeunload', onBeforeUnload);
}, [needsPrompt]);
const value = useMemo<SaveGuardContextValue>(() => ({
loadState,
setLoadState,
emptyRefusal,
setEmptyRefusal,
forceEmptyNextSave,
armForceEmptyNextSave: () => { forceEmptyNextSave.current = true; },
dirty,
isDirty,
markDirty,
beginSave,
endSave,
saving,
suppressBeforeUnload,
}), [loadState, emptyRefusal, dirty, saving, isDirty, markDirty, beginSave, endSave, suppressBeforeUnload]);
return <SaveGuardContext.Provider value={value}>{children}</SaveGuardContext.Provider>;
};