From 86b82ed15443e6522b43a932700bd703225469d7 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Wed, 7 Oct 2026 10:09:26 -0700 Subject: [PATCH] fix(site-builder): publish racing an edit stays a draft; no autosave during publish Refs #30 Co-Authored-By: Claude Sonnet 5.5 --- craft/src/editor/SaveState.test.tsx | 77 ++++++++++++++++++++++++++++ craft/src/panels/topbar/TopBar.tsx | 18 +++++-- craft/src/state/SaveGuardContext.tsx | 7 ++- 3 files changed, 96 insertions(+), 6 deletions(-) diff --git a/craft/src/editor/SaveState.test.tsx b/craft/src/editor/SaveState.test.tsx index 927b4ec..2d62ee1 100644 --- a/craft/src/editor/SaveState.test.tsx +++ b/craft/src/editor/SaveState.test.tsx @@ -329,3 +329,80 @@ describe('server refusal still goes to the dedicated banner', () => { expect(pill()).toBe('unsaved'); }); }); + +describe('publish racing an edit', () => { + test('an edit during an in-flight publish leaves the site a draft, not Published', async () => { + let finishPublish!: (r: unknown) => void; + fetchMock.mockImplementation((url: string) => { + const u = String(url); + if (u.includes('action=load')) return Promise.resolve(jsonResp({ success: true, project: null, rev: null })); + if (u.includes('action=publish')) return new Promise((res) => { finishPublish = res; }); + return Promise.resolve(jsonResp({ success: true })); + }); + await mount(); + edit(); + await act(async () => { q('button[aria-label="Publish to live site"]')!.click(); }); + await flush(); + expect(calls('publish')).toHaveLength(1); + + edit(); // typed while the publish request is out + await act(async () => { finishPublish(jsonResp({ success: true })); }); + await flush(); + expect(pill()).toBe('unsaved'); + + await clickSave(); + expect(pill()).toBe('saved'); + expect(q('.publish-badge.draft')).not.toBeNull(); + }); + + test('autosave does not start while a publish is running', async () => { + let finishPublish!: (r: unknown) => void; + fetchMock.mockImplementation((url: string) => { + const u = String(url); + if (u.includes('action=load')) return Promise.resolve(jsonResp({ success: true, project: null, rev: null })); + if (u.includes('action=publish')) return new Promise((res) => { finishPublish = res; }); + return Promise.resolve(jsonResp({ success: true })); + }); + await mount(); + edit(); + await act(async () => { q('button[aria-label="Publish to live site"]')!.click(); }); + await flush(); + const savesBefore = calls('save').length; // the publish's own save + await act(async () => { vi.advanceTimersByTime(30_000); }); + await flush(); + expect(calls('save')).toHaveLength(savesBefore); + await act(async () => { finishPublish(jsonResp({ success: true })); }); + await flush(); + }); +}); + +describe('populated project load', () => { + test('pages, header/footer and design restored by load() leave the editor clean', async () => { + const state = JSON.stringify({ + ROOT: { type: { resolvedName: 'Container' }, isCanvas: true, props: {}, displayName: 'Container', custom: {}, hidden: false, nodes: [], linkedNodes: {} }, + }); + fetchMock.mockImplementation(async () => jsonResp({ + success: true, + rev: 'r1', + project: { + design: { headCode: '' }, + header_craft_state: state, + footer_craft_state: state, + pages_craft_state: [ + { id: 'home', name: 'Home', slug: 'index', craftState: state }, + { id: 'page_2', name: 'About', slug: 'about', craftState: state }, + ], + }, + })); + await mount(); + await flush(); + expect(guard.loadState).toBe('loaded'); + expect(pill()).toBe('saved'); + expect(guard.dirty).toBe(false); + expect(addSpy.mock.calls.filter(([t]: unknown[]) => t === 'beforeunload')).toHaveLength(0); + + // ...and a real edit afterwards still registers. + edit(); + expect(pill()).toBe('unsaved'); + }); +}); diff --git a/craft/src/panels/topbar/TopBar.tsx b/craft/src/panels/topbar/TopBar.tsx index e177f84..377e270 100644 --- a/craft/src/panels/topbar/TopBar.tsx +++ b/craft/src/panels/topbar/TopBar.tsx @@ -34,7 +34,7 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid canRedo: query.history.canRedo(), })); const { save, publish } = useWhpApi(); - const { loadState, emptyRefusal, setEmptyRefusal, dirty, isDirty } = useSaveGuard(); + const { loadState, emptyRefusal, setEmptyRefusal, dirty, isDirty, getVersion } = useSaveGuard(); const canSave = loadState === 'loaded'; const { headerPage, footerPage, pages, activePageId } = usePages(); const { design } = useSiteDesign(); @@ -54,6 +54,7 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid const isMobile = useIsMobile(); const { open: openSitesmith } = useSitesmithModal(); const savingRef = useRef(false); + const publishingRef = useRef(false); // An edit after a publish means the live site no longer matches the editor. useEffect(() => { @@ -104,7 +105,8 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid useEffect(() => { // Paused until the site has loaded, and while the empty-save banner is up. if (!isWHP || !canSave || emptyRefusal) return; - const interval = setInterval(() => { void runSave(); }, 30000); + // A running publish does its own save; a second one would race it. + const interval = setInterval(() => { if (!publishingRef.current) void runSave(); }, 30000); return () => clearInterval(interval); }, [isWHP, canSave, emptyRefusal, runSave]); @@ -112,6 +114,9 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid const handlePublish = useCallback(async () => { if (!canSave) return; + // Anything edited after this point is not in what we are about to publish. + const versionAtStart = getVersion(); + publishingRef.current = true; setPublishing(true); setPublishWarnings([]); try { @@ -119,10 +124,12 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid if (result?.error === 'empty_overwrite_refused') { setEmptyRefusal(result.message ?? null); } else if (result?.success) { - setPublished(true); + const unchanged = getVersion() === versionAtStart; + setPublished(unchanged); setSaveFailed(false); setErrorNotice(null); - setIsDraft(false); + // Edited mid-publish: the live site lacks that edit, so it is still a draft. + setIsDraft(!unchanged); // The site published; these are fixable problems, not failures. Held // independently of the status pill so a later edit doesn't take the // warning down with it. @@ -137,9 +144,10 @@ export const TopBar: React.FC = ({ device, onDeviceChange, showGuid console.error('Publish failed:', e); setErrorNotice(messageOf(e, 'Publish')); } finally { + publishingRef.current = false; setPublishing(false); } - }, [publish, canSave, setEmptyRefusal]); + }, [publish, canSave, getVersion, setEmptyRefusal]); const emptyBanner = emptyRefusal ? ( boolean; /** Record a change. Ignored until the site has loaded (load itself rewrites state). */ markDirty: () => void; + /** Monotonic change counter: compare two reads to learn whether anything changed in between. */ + getVersion: () => number; /** 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`. */ @@ -48,6 +50,7 @@ const defaultValue: SaveGuardContextValue = { armForceEmptyNextSave: () => {}, dirty: false, isDirty: () => false, + getVersion: () => 0, markDirty: () => {}, beginSave: () => ({ version: 0 }), endSave: () => {}, @@ -90,6 +93,7 @@ export const SaveGuardProvider: React.FC<{ children: ReactNode }> = ({ children setDirty(true); }, []); const isDirty = useCallback(() => dirtyRef.current, []); + const getVersion = useCallback(() => versionRef.current, []); const beginSave = useCallback((): SaveTicket => { setSavesInFlight((n) => n + 1); return { version: versionRef.current }; @@ -125,12 +129,13 @@ export const SaveGuardProvider: React.FC<{ children: ReactNode }> = ({ children armForceEmptyNextSave: () => { forceEmptyNextSave.current = true; }, dirty, isDirty, + getVersion, markDirty, beginSave, endSave, saving, suppressBeforeUnload, - }), [loadState, emptyRefusal, dirty, saving, isDirty, markDirty, beginSave, endSave, suppressBeforeUnload]); + }), [loadState, emptyRefusal, dirty, saving, isDirty, getVersion, markDirty, beginSave, endSave, suppressBeforeUnload]); return {children}; };