Files
site-builder/craft/src/editor/LoadGate.tsx
T

57 lines
2.0 KiB
TypeScript

import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useEditorConfig } from '../state/EditorConfigContext';
import { useSaveGuard } from '../state/SaveGuardContext';
import { useWhpApi, UnreadableSiteError } from '../hooks/useWhpApi';
/**
* Owns the initial project load (WHP mode only) and blocks the whole editor
* until it succeeds. On failure nothing is editable and nothing can save, so
* a failed load can never be autosaved over the customer's real site.
*/
export const LoadGate: React.FC = () => {
const { isWHP } = useEditorConfig();
const { loadState, setLoadState } = useSaveGuard();
const { load } = useWhpApi();
const startedRef = useRef(false);
const [unreadable, setUnreadable] = useState(false);
const runLoad = useCallback(() => {
setUnreadable(false);
setLoadState('loading');
load()
.then(() => setLoadState('loaded'))
.catch((e) => {
console.error('Failed to load project from WHP API:', e);
setUnreadable(e instanceof UnreadableSiteError);
setLoadState('failed');
});
}, [load, setLoadState]);
useEffect(() => {
if (!isWHP || startedRef.current) return;
startedRef.current = true;
runLoad();
}, [isWHP, runLoad]);
if (!isWHP || loadState === 'loaded') return null;
return (
<div className="load-gate" role={loadState === 'failed' ? 'alert' : 'status'} data-testid="load-gate">
{loadState === 'loading' ? (
<p><i className="fa fa-spinner fa-spin" aria-hidden="true" /> Loading your site…</p>
) : (
<>
<p>
{unreadable
? "We couldn't read part of your saved site. Your saved work has not been changed. Contact support if this keeps happening."
: "We couldn't load your site. Your saved work has not been changed."}
</p>
<button type="button" className="topbar-btn primary" onClick={runLoad} data-testid="load-retry">
Retry
</button>
</>
)}
</div>
);
};