Merge polish/save-pipeline: load gate, honest save state, idle autosave, conflict handling (Refs #28 #30 #31 #33)
This commit is contained in:
commit
eb134a4743
25 files changed
+2166
-196
No files matched your search
@@ -2,6 +2,7 @@ import React, { useState } from 'react';
|
||||
import { useSiteDesign, DEFAULT_SITE_DESIGN } from '../../state/SiteDesignContext';
|
||||
import { usePages } from '../../state/PageContext';
|
||||
import { useEditorConfig } from '../../state/EditorConfigContext';
|
||||
import { useSaveGuard } from '../../state/SaveGuardContext';
|
||||
import { SerializedTreeNode } from '../../types/sitesmith';
|
||||
import { FONT_FAMILIES } from '../../constants/presets';
|
||||
import { AssetPicker } from '../../ui/AssetPicker';
|
||||
@@ -224,6 +225,7 @@ export const SiteDesignPanel: React.FC = () => {
|
||||
const { design, updateDesign, resetToDefaults } = useSiteDesign();
|
||||
const { replaceAllPages, setHeader, setFooter } = usePages();
|
||||
const { whpConfig } = useEditorConfig();
|
||||
const { armForceEmptyNextSave } = useSaveGuard();
|
||||
// Standalone mode (no WHP_CONFIG) has no site domain to confirm against --
|
||||
// an empty typed input would then trivially "match" an empty siteDomain,
|
||||
// arming the destructive confirm button with no guard at all. The entry
|
||||
@@ -240,6 +242,9 @@ export const SiteDesignPanel: React.FC = () => {
|
||||
// future refactor that drops it).
|
||||
if (!siteResetConfirmMatches(siteResetTyped, siteDomain)) return;
|
||||
|
||||
// The user explicitly confirmed wiping the site, so the next save must
|
||||
// be allowed to replace the saved site with an empty one.
|
||||
armForceEmptyNextSave();
|
||||
replaceAllPages([{ name: 'Home', tree: BLANK_PAGE_TREE }]);
|
||||
setHeader(BLANK_HEADER_TREE);
|
||||
setFooter(BLANK_FOOTER_TREE);
|
||||
|
||||
@@ -2,9 +2,9 @@ import React from 'react';
|
||||
import { useSitesmith } from '../../hooks/useSitesmith';
|
||||
import { useEditorConfig } from '../../state/EditorConfigContext';
|
||||
|
||||
interface Props { onClick: () => void; }
|
||||
interface Props { onClick: () => void; disabled?: boolean; }
|
||||
|
||||
export const SitesmithButton: React.FC<Props> = ({ onClick }) => {
|
||||
export const SitesmithButton: React.FC<Props> = ({ onClick, disabled }) => {
|
||||
const cfg = useEditorConfig();
|
||||
const siteId = cfg.whpConfig?.siteId ?? 0;
|
||||
const { summary } = useSitesmith(siteId);
|
||||
@@ -14,6 +14,7 @@ export const SitesmithButton: React.FC<Props> = ({ onClick }) => {
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className="topbar-btn sitesmith-btn"
|
||||
title={locked ? 'Sitesmith — paid addon (click to learn more)' : 'Sitesmith AI Builder'}
|
||||
style={{
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import React from 'react';
|
||||
|
||||
export interface ConflictModalProps {
|
||||
/** True while "Keep mine" is re-saving. */
|
||||
busy: boolean;
|
||||
/** Set when "Keep mine" failed, so the customer sees why the modal is still up. */
|
||||
error?: string | null;
|
||||
onReload: () => void;
|
||||
onKeepMine: () => void;
|
||||
}
|
||||
|
||||
/** Blocking choice shown when the server holds a newer copy of the site than
|
||||
* the one this editor opened (another tab or device saved). Autosave stays
|
||||
* paused while it's up; there is deliberately no dismiss. */
|
||||
export const ConflictModal: React.FC<ConflictModalProps> = ({ busy, error, onReload, onKeepMine }) => (
|
||||
<div className="conflict-backdrop" data-testid="conflict-modal">
|
||||
<div className="conflict-modal" role="alertdialog" aria-modal="true" aria-labelledby="conflict-modal-title">
|
||||
<h3 id="conflict-modal-title">Site changed elsewhere</h3>
|
||||
<p>This site was changed in another tab or device since you opened it.</p>
|
||||
<p>Reload latest discards your changes here and loads the newer copy. Keep mine overwrites the newer copy with what you have now.</p>
|
||||
{error && <p className="conflict-modal-error" role="alert" data-testid="conflict-error">{error}</p>}
|
||||
<div className="conflict-modal-actions">
|
||||
<button type="button" onClick={onReload} disabled={busy} data-testid="conflict-reload">Reload latest</button>
|
||||
<button type="button" onClick={onKeepMine} disabled={busy} data-testid="conflict-keep-mine">Keep mine</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
|
||||
export interface EmptySaveBannerProps {
|
||||
onSaveAnyway: () => void;
|
||||
onUndo: () => void;
|
||||
}
|
||||
|
||||
/** Persistent banner shown when the server refused a save that would replace
|
||||
* the saved site with an empty page. Autosave stays paused while it's up. */
|
||||
export const EmptySaveBanner: React.FC<EmptySaveBannerProps> = ({ onSaveAnyway, onUndo }) => (
|
||||
<div className="empty-save-banner" role="alert" data-testid="empty-save-banner">
|
||||
<i className="fa fa-exclamation-triangle" aria-hidden="true" />
|
||||
<span className="empty-save-banner-text">This would replace your saved site with an empty page.</span>
|
||||
<button type="button" onClick={onSaveAnyway} data-testid="empty-save-anyway">Save anyway</button>
|
||||
<button type="button" onClick={onUndo} data-testid="empty-save-undo">Undo</button>
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,23 @@
|
||||
import React from 'react';
|
||||
|
||||
export interface ErrorNoticeProps {
|
||||
/** The error to show (the server's `message` when it sent one); null hides the notice. */
|
||||
message: string | null;
|
||||
onDismiss: () => void;
|
||||
}
|
||||
|
||||
/** The editor's error toast. It never times out: a failed save is something
|
||||
* the customer must read, so it stays until dismissed. */
|
||||
export const ErrorNotice: React.FC<ErrorNoticeProps> = ({ message, onDismiss }) => {
|
||||
if (!message) return null;
|
||||
|
||||
return (
|
||||
<div className="error-notice" role="alert" data-testid="error-notice">
|
||||
<i className="fa fa-exclamation-triangle" aria-hidden="true" />
|
||||
<span className="error-notice-text">{message}</span>
|
||||
<button type="button" onClick={onDismiss} aria-label="Dismiss" data-testid="error-notice-dismiss">
|
||||
<i className="fa fa-times" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import React from 'react';
|
||||
|
||||
export type SaveStatus = 'unsaved' | 'saving' | 'saved' | 'published' | 'failed';
|
||||
|
||||
const LABELS: Record<SaveStatus, string> = {
|
||||
unsaved: 'Unsaved changes',
|
||||
saving: 'Saving…',
|
||||
saved: 'Saved',
|
||||
published: 'Published',
|
||||
failed: 'Save failed',
|
||||
};
|
||||
|
||||
const ICONS: Record<SaveStatus, string> = {
|
||||
unsaved: 'fa-circle',
|
||||
saving: 'fa-spinner fa-spin',
|
||||
saved: 'fa-check',
|
||||
published: 'fa-check-circle',
|
||||
failed: 'fa-exclamation-triangle',
|
||||
};
|
||||
|
||||
/** Persistent save state. It changes only when the state does; nothing resets it on a timer. */
|
||||
export const SaveStatusPill: React.FC<{ status: SaveStatus }> = ({ status }) => (
|
||||
<span className={`save-pill ${status}`} role="status" data-testid="save-status-pill" data-status={status}>
|
||||
<i className={`fa ${ICONS[status]}`} aria-hidden="true" /> {LABELS[status]}
|
||||
</span>
|
||||
);
|
||||
@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { usePages } from '../../state/PageContext';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { useSaveGuard } from '../../state/SaveGuardContext';
|
||||
import {
|
||||
allTemplates,
|
||||
TemplateDefinition,
|
||||
@@ -48,6 +49,7 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
const { actions, query } = useEditor();
|
||||
const { pages, addPage, switchPage, deletePage, editHeader, editFooter } = usePages();
|
||||
const { updateDesign } = useSiteDesign();
|
||||
const { armForceEmptyNextSave } = useSaveGuard();
|
||||
|
||||
const [activeTab, setActiveTab] = useState<FilterTab>('all');
|
||||
const [confirmTemplate, setConfirmTemplate] = useState<TemplateDefinition | null>(null);
|
||||
@@ -231,13 +233,19 @@ export const TemplateModal: React.FC<TemplateModalProps> = ({ open, onClose }) =
|
||||
if (keepId) {
|
||||
await applyHeaderFooter(tpl, keepId);
|
||||
}
|
||||
|
||||
// A blank template replaces the whole site with an empty one; the user
|
||||
// confirmed that, so the next save must not be refused as accidental.
|
||||
// Armed only after the apply succeeded -- a failed apply must not
|
||||
// leave a force_empty pending for an unrelated later save.
|
||||
if (tpl.pages.every((p) => !p.content.components?.length)) armForceEmptyNextSave();
|
||||
} catch (e) {
|
||||
console.error('Failed to load template:', e);
|
||||
} finally {
|
||||
if (mountedRef.current) setLoading(false);
|
||||
onClose();
|
||||
}
|
||||
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose]);
|
||||
}, [confirmTemplate, applyDesign, pages, addPage, switchPage, deletePage, updateDesign, addTemplateComponents, clearCanvas, applyHeaderFooter, wait, onClose, armForceEmptyNextSave]);
|
||||
|
||||
// Mobile-A2: portaled to `document.body` -- TopBar.tsx mounts this modal
|
||||
// as a child of `.topbar`, which (as a flex item with its own z-index)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import React from 'react';
|
||||
import { createRoot, Root } from 'react-dom/client';
|
||||
import { act } from 'react-dom/test-utils';
|
||||
|
||||
/**
|
||||
* Autosave must not depend on isDirty() alone: with a context that reports
|
||||
* dirty but a load that failed, the load gate has to hold on its own.
|
||||
* (A real provider can't produce that state, since markDirty is ignored
|
||||
* until loaded, so the guard is stubbed.)
|
||||
*/
|
||||
vi.mock('@craftjs/core', () => ({
|
||||
useEditor: (collector?: (state: unknown, query: unknown) => Record<string, unknown>) => {
|
||||
const query = { serialize: () => '{}', history: { canUndo: () => false, canRedo: () => false } };
|
||||
const actions = { history: { undo: vi.fn(), redo: vi.fn() }, deserialize: vi.fn() };
|
||||
return { actions, query, ...(collector ? collector({}, query) : {}) };
|
||||
},
|
||||
}));
|
||||
vi.mock('./TemplateModal', () => ({ TemplateModal: () => null }));
|
||||
vi.mock('./HeadCodeModal', () => ({ HeadCodeModal: () => null }));
|
||||
vi.mock('../sitesmith/SitesmithButton', () => ({ SitesmithButton: () => null }));
|
||||
|
||||
// save() is stubbed (the real one also refuses before load) so this test
|
||||
// exercises TopBar's own gate, not the API hook's.
|
||||
const saveMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('../../hooks/useWhpApi', () => ({
|
||||
useWhpApi: () => ({
|
||||
save: saveMock, publish: vi.fn(), load: vi.fn(), uploadAsset: vi.fn(), isWHP: true,
|
||||
}),
|
||||
}));
|
||||
|
||||
const guardState = vi.hoisted(() => ({ loadState: 'failed' as 'failed' | 'loaded' }));
|
||||
vi.mock('../../state/SaveGuardContext', () => ({
|
||||
useSaveGuard: () => ({
|
||||
loadState: guardState.loadState,
|
||||
setLoadState: () => {},
|
||||
emptyRefusal: null,
|
||||
setEmptyRefusal: () => {},
|
||||
forceEmptyNextSave: { current: false },
|
||||
armForceEmptyNextSave: () => {},
|
||||
dirty: true,
|
||||
isDirty: () => true,
|
||||
getVersion: () => 1,
|
||||
markDirty: () => {},
|
||||
beginSave: () => ({ version: 1 }),
|
||||
endSave: () => {},
|
||||
saving: false,
|
||||
suppressBeforeUnload: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
import { TopBar } from './TopBar';
|
||||
import { EditorConfigProvider } from '../../state/EditorConfigContext';
|
||||
import { WhpConfig } from '../../types';
|
||||
|
||||
const whpConfig: WhpConfig = {
|
||||
user: 'u', apiUrl: '/api', csrfToken: 't', siteId: 1,
|
||||
siteDomain: 'example.com', siteName: 'Example', backUrl: '/', isRoot: false,
|
||||
};
|
||||
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
const saves = () => saveMock.mock.calls;
|
||||
|
||||
function mount() {
|
||||
container = document.createElement('div');
|
||||
document.body.appendChild(container);
|
||||
act(() => {
|
||||
root = createRoot(container);
|
||||
root.render(
|
||||
<EditorConfigProvider config={whpConfig}>
|
||||
<TopBar device="desktop" onDeviceChange={() => {}} showGuides onToggleGuides={() => {}} />
|
||||
</EditorConfigProvider>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
saveMock.mockReset();
|
||||
saveMock.mockResolvedValue({ success: true });
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => {
|
||||
act(() => { root.unmount(); });
|
||||
container.remove();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('autosave gate', () => {
|
||||
test('a dirty editor whose load failed makes no save call', async () => {
|
||||
guardState.loadState = 'failed';
|
||||
mount();
|
||||
await act(async () => { vi.advanceTimersByTime(90_000); });
|
||||
expect(saves()).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('control: the same dirty editor, once loaded, does autosave', async () => {
|
||||
guardState.loadState = 'loaded';
|
||||
mount();
|
||||
await act(async () => { vi.advanceTimersByTime(30_000); });
|
||||
expect(saves()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -145,12 +145,12 @@ describe('TopBar publish-warnings wiring', () => {
|
||||
|
||||
await clickPublish();
|
||||
|
||||
expect(container.querySelector('.publish-badge.published')).not.toBeNull();
|
||||
expect(container.querySelector('.save-indicator.error')).toBeNull();
|
||||
expect(container.querySelector('[data-testid="save-status-pill"]')!.getAttribute('data-status')).toBe('published');
|
||||
expect(container.querySelector('[data-testid="error-notice"]')).toBeNull();
|
||||
expect(container.textContent).toContain('Submissions will not be delivered until an administrator enables it.');
|
||||
});
|
||||
|
||||
test('warnings survive the 3-second "Published" flash timer', async () => {
|
||||
test('warnings and the Published pill both outlast the old 3-second flash', async () => {
|
||||
vi.useFakeTimers();
|
||||
publishMock.mockResolvedValue({ success: true, warnings: ['Sticks around after the flash.'] });
|
||||
render();
|
||||
@@ -161,18 +161,16 @@ describe('TopBar publish-warnings wiring', () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Sanity: both the flash and the warning are up before the timer fires.
|
||||
expect(container.querySelector('.publish-badge.published')).not.toBeNull();
|
||||
const pillStatus = () => container.querySelector('[data-testid="save-status-pill"]')!.getAttribute('data-status');
|
||||
expect(pillStatus()).toBe('published');
|
||||
expect(container.textContent).toContain('Sticks around after the flash.');
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(3000);
|
||||
});
|
||||
|
||||
// The 3s timer resets publishStatus -> the "Published" flash is gone...
|
||||
expect(container.querySelector('.publish-badge.published')).toBeNull();
|
||||
// ...but publishWarnings lives in its own state and must NOT have been
|
||||
// cleared by that same timer.
|
||||
// Published persists until the next edit; no timer resets it.
|
||||
expect(pillStatus()).toBe('published');
|
||||
expect(container.textContent).toContain('Sticks around after the flash.');
|
||||
});
|
||||
|
||||
|
||||
+162
-115
@@ -1,7 +1,7 @@
|
||||
import React, { useCallback, useState, useEffect, useRef } from 'react';
|
||||
import { useEditor } from '@craftjs/core';
|
||||
import { useEditorConfig } from '../../state/EditorConfigContext';
|
||||
import { useWhpApi } from '../../hooks/useWhpApi';
|
||||
import { useWhpApi, SaveOptions } from '../../hooks/useWhpApi';
|
||||
import { usePages } from '../../state/PageContext';
|
||||
import { useSiteDesign } from '../../state/SiteDesignContext';
|
||||
import { useIsMobile } from '../../hooks/useIsMobile';
|
||||
@@ -12,6 +12,11 @@ import { HeadCodeModal } from './HeadCodeModal';
|
||||
import { ReportIssueModal } from './ReportIssueModal';
|
||||
import { TopBarOverflowMenu } from './TopBarOverflowMenu';
|
||||
import { PublishWarnings } from './PublishWarnings';
|
||||
import { EmptySaveBanner } from './EmptySaveBanner';
|
||||
import { ConflictModal } from './ConflictModal';
|
||||
import { ErrorNotice } from './ErrorNotice';
|
||||
import { SaveStatusPill, SaveStatus } from './SaveStatusPill';
|
||||
import { useSaveGuard } from '../../state/SaveGuardContext';
|
||||
import { SitesmithButton } from '../sitesmith/SitesmithButton';
|
||||
import { useSitesmithModal } from '../../state/SitesmithContext';
|
||||
|
||||
@@ -29,12 +34,20 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
canUndo: query.history.canUndo(),
|
||||
canRedo: query.history.canRedo(),
|
||||
}));
|
||||
const { save, publish, load } = useWhpApi();
|
||||
const { save, publish } = useWhpApi();
|
||||
const {
|
||||
loadState, emptyRefusal, setEmptyRefusal, dirty, isDirty, getVersion,
|
||||
conflict, setConflict, armForceOverwriteNextSave, disarmForceOverwriteNextSave, reloadLatest,
|
||||
} = useSaveGuard();
|
||||
const canSave = loadState === 'loaded';
|
||||
const { headerPage, footerPage, pages, activePageId } = usePages();
|
||||
const { design } = useSiteDesign();
|
||||
|
||||
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
|
||||
const [publishStatus, setPublishStatus] = useState<'idle' | 'publishing' | 'published' | 'error'>('idle');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveFailed, setSaveFailed] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [published, setPublished] = useState(false);
|
||||
const [errorNotice, setErrorNotice] = useState<string | null>(null);
|
||||
const [publishWarnings, setPublishWarnings] = useState<string[]>([]);
|
||||
const [isDraft, setIsDraft] = useState(false);
|
||||
// Mobile-A2: lifted from private useState into MobileChromeContext so
|
||||
@@ -44,98 +57,144 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const isMobile = useIsMobile();
|
||||
const { open: openSitesmith } = useSitesmithModal();
|
||||
const saveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const publishTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const hasLoadedRef = useRef(false);
|
||||
const savingRef = useRef(false);
|
||||
const publishingRef = useRef(false);
|
||||
// Read at tick time by autosaveDue, never a stale closure.
|
||||
const conflictRef = useRef<string | null>(null);
|
||||
conflictRef.current = conflict;
|
||||
|
||||
// Load saved state on mount
|
||||
// An edit after a publish means the live site no longer matches the editor.
|
||||
useEffect(() => {
|
||||
if (!isWHP || hasLoadedRef.current) return;
|
||||
hasLoadedRef.current = true;
|
||||
if (dirty) setPublished(false);
|
||||
}, [dirty]);
|
||||
|
||||
load().catch((e) => {
|
||||
console.warn('Failed to load project from WHP API:', e);
|
||||
});
|
||||
}, [isWHP, load]);
|
||||
const status: SaveStatus = saving || publishing ? 'saving'
|
||||
: saveFailed ? 'failed'
|
||||
: dirty ? 'unsaved'
|
||||
: published ? 'published'
|
||||
: 'saved';
|
||||
|
||||
// Auto-save every 30 seconds
|
||||
useEffect(() => {
|
||||
if (!isWHP) return;
|
||||
const messageOf = (e: unknown, what: string) =>
|
||||
`${what} failed: ${e instanceof Error && e.message ? e.message : 'could not reach the server'}`;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
save()
|
||||
.then((result) => {
|
||||
if (result?.success) {
|
||||
setSaveStatus('saved');
|
||||
setIsDraft(true);
|
||||
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
|
||||
saveTimeoutRef.current = setTimeout(() => setSaveStatus('idle'), 2000);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Silent fail for auto-save
|
||||
});
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [isWHP, save]);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
setSaveStatus('saving');
|
||||
/** Shared by the Save button and autosave. */
|
||||
const runSave = useCallback(async (opts?: SaveOptions) => {
|
||||
if (!canSave || savingRef.current) return;
|
||||
// Draft means "saved changes that aren't live yet": a save with nothing
|
||||
// new in it must not flip the badge.
|
||||
const hadChanges = isDirty();
|
||||
savingRef.current = true;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await save();
|
||||
if (result?.success) {
|
||||
setSaveStatus('saved');
|
||||
setIsDraft(true);
|
||||
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
|
||||
saveTimeoutRef.current = setTimeout(() => setSaveStatus('idle'), 2500);
|
||||
} else {
|
||||
setSaveStatus('error');
|
||||
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
|
||||
saveTimeoutRef.current = setTimeout(() => setSaveStatus('idle'), 3000);
|
||||
const result = await save(opts);
|
||||
if (result?.error === 'conflict') {
|
||||
// The conflict modal (opened by save()) owns this outcome, not the error toast.
|
||||
} else if (result?.error === 'empty_overwrite_refused') {
|
||||
setConflict(null);
|
||||
setEmptyRefusal(result.message ?? null);
|
||||
} else if (result?.success) {
|
||||
setConflict(null);
|
||||
setEmptyRefusal(null);
|
||||
setSaveFailed(false);
|
||||
setErrorNotice(null);
|
||||
if (hadChanges) setIsDraft(true);
|
||||
} else if (result) {
|
||||
setSaveFailed(true);
|
||||
setErrorNotice(result.message || 'Save failed.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Save failed:', e);
|
||||
setSaveStatus('error');
|
||||
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
|
||||
saveTimeoutRef.current = setTimeout(() => setSaveStatus('idle'), 3000);
|
||||
setSaveFailed(true);
|
||||
setErrorNotice(messageOf(e, 'Save'));
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
setSaving(false);
|
||||
}
|
||||
}, [save]);
|
||||
}, [save, canSave, isDirty, setEmptyRefusal, setConflict]);
|
||||
|
||||
// Auto-save every 30 seconds
|
||||
useEffect(() => {
|
||||
// Paused until the site has loaded, and while the empty-save banner is up.
|
||||
if (!isWHP || !canSave || emptyRefusal || conflict) return;
|
||||
// A running publish does its own save; a second one would race it.
|
||||
// Read through refs/isDirty() at tick time, never a stale closure.
|
||||
// Also paused while the conflict modal is up: it is the authority, the
|
||||
// effect guard above only avoids a pointless timer.
|
||||
const autosaveDue = () => isDirty() && !publishingRef.current && !conflictRef.current;
|
||||
const interval = setInterval(() => { if (autosaveDue()) void runSave(); }, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, [isWHP, canSave, emptyRefusal, conflict, runSave, isDirty]);
|
||||
|
||||
const handleSave = runSave;
|
||||
|
||||
const handlePublish = useCallback(async () => {
|
||||
setPublishStatus('publishing');
|
||||
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 {
|
||||
const result = await publish();
|
||||
if (result?.success) {
|
||||
setPublishStatus('published');
|
||||
setIsDraft(false);
|
||||
if (result?.error === 'conflict') {
|
||||
// Nothing was published: the conflict modal (opened by save()) takes over.
|
||||
setSaveFailed(true);
|
||||
} else if (result?.error === 'empty_overwrite_refused') {
|
||||
setEmptyRefusal(result.message ?? null);
|
||||
} else if (result?.success) {
|
||||
const unchanged = getVersion() === versionAtStart;
|
||||
setPublished(unchanged);
|
||||
setSaveFailed(false);
|
||||
setErrorNotice(null);
|
||||
// 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 publishStatus so the 3s "Published" flash doesn't
|
||||
// take the warning down with it.
|
||||
// independently of the status pill so a later edit doesn't take the
|
||||
// warning down with it.
|
||||
setPublishWarnings(Array.isArray(result.warnings) ? result.warnings : []);
|
||||
if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current);
|
||||
publishTimeoutRef.current = setTimeout(() => setPublishStatus('idle'), 3000);
|
||||
} else {
|
||||
setPublishStatus('error');
|
||||
if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current);
|
||||
publishTimeoutRef.current = setTimeout(() => setPublishStatus('idle'), 3000);
|
||||
} else if (result) {
|
||||
// The save before the publish failed: that is a save failure, and
|
||||
// nothing went live.
|
||||
if (result.failedStep === 'save') setSaveFailed(true);
|
||||
setErrorNotice(result.message || 'Publish failed.');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Publish failed:', e);
|
||||
setPublishStatus('error');
|
||||
if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current);
|
||||
publishTimeoutRef.current = setTimeout(() => setPublishStatus('idle'), 3000);
|
||||
setErrorNotice(messageOf(e, 'Publish'));
|
||||
} finally {
|
||||
publishingRef.current = false;
|
||||
setPublishing(false);
|
||||
}
|
||||
}, [publish]);
|
||||
}, [publish, canSave, getVersion, setEmptyRefusal]);
|
||||
|
||||
// Cleanup timeouts on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
|
||||
if (publishTimeoutRef.current) clearTimeout(publishTimeoutRef.current);
|
||||
};
|
||||
}, []);
|
||||
// "Keep mine": arm force_overwrite so it survives an empty-overwrite refusal
|
||||
// followed by "Save anyway", then re-save. runSave closes the modal on success.
|
||||
const handleKeepMine = useCallback(async () => {
|
||||
setErrorNotice(null);
|
||||
armForceOverwriteNextSave();
|
||||
await runSave();
|
||||
}, [armForceOverwriteNextSave, runSave]);
|
||||
|
||||
const conflictModal = conflict ? (
|
||||
<ConflictModal
|
||||
busy={saving}
|
||||
error={errorNotice}
|
||||
onReload={reloadLatest}
|
||||
onKeepMine={() => { void handleKeepMine(); }}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
const emptyBanner = emptyRefusal ? (
|
||||
<EmptySaveBanner
|
||||
onSaveAnyway={() => { void handleSave({ forceEmpty: true }); }}
|
||||
onUndo={() => {
|
||||
actions.history.undo();
|
||||
setEmptyRefusal(null);
|
||||
// Backing out ends the Keep mine decision; a later autosave must be conflict-checked again.
|
||||
disarmForceOverwriteNextSave();
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
// Extracted so both the desktop inline Preview button and the mobile
|
||||
// overflow-menu "Preview" item can trigger the exact same flow.
|
||||
@@ -230,6 +289,9 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
return (
|
||||
<nav className="topbar topbar-mobile">
|
||||
<PublishWarnings warnings={publishWarnings} onDismiss={() => setPublishWarnings([])} />
|
||||
{emptyBanner}
|
||||
{conflictModal}
|
||||
<ErrorNotice message={errorNotice} onDismiss={() => setErrorNotice(null)} />
|
||||
<div className="topbar-left">
|
||||
{isWHP && (
|
||||
<a
|
||||
@@ -244,10 +306,11 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
</div>
|
||||
|
||||
<div className="topbar-right">
|
||||
{isWHP && <SaveStatusPill status={status} />}
|
||||
<button
|
||||
className="topbar-btn icon-only"
|
||||
onClick={() => actions.history.undo()}
|
||||
disabled={!canUndo}
|
||||
disabled={!canUndo || !canSave}
|
||||
aria-label="Undo"
|
||||
data-tooltip="Undo"
|
||||
>
|
||||
@@ -256,7 +319,7 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
<button
|
||||
className="topbar-btn icon-only"
|
||||
onClick={() => actions.history.redo()}
|
||||
disabled={!canRedo}
|
||||
disabled={!canRedo || !canSave}
|
||||
aria-label="Redo"
|
||||
data-tooltip="Redo"
|
||||
>
|
||||
@@ -265,22 +328,22 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
<span className="topbar-divider" />
|
||||
<button
|
||||
className="topbar-btn icon-only primary"
|
||||
onClick={handleSave}
|
||||
disabled={saveStatus === 'saving'}
|
||||
onClick={() => { void handleSave(); }}
|
||||
disabled={saving || !canSave}
|
||||
aria-label="Save Draft"
|
||||
data-tooltip="Save"
|
||||
>
|
||||
<i className={`fa ${saveStatus === 'saving' ? 'fa-spinner fa-spin' : 'fa-save'}`} />
|
||||
<i className={`fa ${saving ? 'fa-spinner fa-spin' : 'fa-save'}`} />
|
||||
</button>
|
||||
{isWHP && (
|
||||
<button
|
||||
className="topbar-btn icon-only publish"
|
||||
onClick={handlePublish}
|
||||
disabled={publishStatus === 'publishing' || saveStatus === 'saving'}
|
||||
disabled={publishing || saving || !canSave}
|
||||
aria-label="Publish to live site"
|
||||
data-tooltip="Publish"
|
||||
>
|
||||
<i className={`fa ${publishStatus === 'publishing' ? 'fa-spinner fa-spin' : 'fa-globe'}`} />
|
||||
<i className={`fa ${publishing ? 'fa-spinner fa-spin' : 'fa-globe'}`} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
@@ -307,7 +370,8 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
onOpenHeadCode={() => setHeadCodeModalOpen(true)}
|
||||
onOpenReportIssue={() => setReportOpen(true)}
|
||||
onPreview={handlePreview}
|
||||
sitesmithNode={<SitesmithButton onClick={() => openSitesmith()} />}
|
||||
sitesmithNode={<SitesmithButton onClick={() => openSitesmith()} disabled={!canSave} />}
|
||||
editingDisabled={!canSave}
|
||||
/>
|
||||
|
||||
<TemplateModal open={templateModalOpen} onClose={() => setTemplateModalOpen(false)} />
|
||||
@@ -320,6 +384,9 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
return (
|
||||
<nav className="topbar">
|
||||
<PublishWarnings warnings={publishWarnings} onDismiss={() => setPublishWarnings([])} />
|
||||
{emptyBanner}
|
||||
{conflictModal}
|
||||
<ErrorNotice message={errorNotice} onDismiss={() => setErrorNotice(null)} />
|
||||
<div className="topbar-left">
|
||||
{isWHP && (
|
||||
<a href={whpConfig!.backUrl} className="topbar-btn back-btn" aria-label="Back to Panel">
|
||||
@@ -360,19 +427,20 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
</div>
|
||||
|
||||
<div className="topbar-right">
|
||||
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo} title="Undo" aria-label="Undo">
|
||||
<button className="topbar-btn" onClick={() => actions.history.undo()} disabled={!canUndo || !canSave} title="Undo" aria-label="Undo">
|
||||
<i className="fa fa-undo" />
|
||||
</button>
|
||||
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo} title="Redo" aria-label="Redo">
|
||||
<button className="topbar-btn" onClick={() => actions.history.redo()} disabled={!canRedo || !canSave} title="Redo" aria-label="Redo">
|
||||
<i className="fa fa-repeat" />
|
||||
</button>
|
||||
<span className="topbar-divider" />
|
||||
<button className="topbar-btn" title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||
<button className="topbar-btn" disabled={!canSave} title="Templates" aria-label="Templates" onClick={() => setTemplateModalOpen(true)}>
|
||||
<i className="fa fa-th-large" /> Templates
|
||||
</button>
|
||||
<button
|
||||
className="topbar-btn icon-only"
|
||||
aria-label="Custom Head Code"
|
||||
disabled={!canSave}
|
||||
data-tooltip="Code"
|
||||
onClick={() => setHeadCodeModalOpen(true)}
|
||||
>
|
||||
@@ -391,45 +459,24 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
<i className="fa fa-bug" />
|
||||
</button>
|
||||
|
||||
{/* Draft/Published status badge */}
|
||||
{isWHP && isDraft && publishStatus !== 'published' && (
|
||||
{/* Draft badge: saved changes that aren't live yet */}
|
||||
{isWHP && isDraft && !published && (
|
||||
<span className="publish-badge draft">
|
||||
<i className="fa fa-pencil" /> Draft
|
||||
</span>
|
||||
)}
|
||||
{publishStatus === 'published' && (
|
||||
<span className="publish-badge published">
|
||||
<i className="fa fa-check-circle" /> Published
|
||||
</span>
|
||||
)}
|
||||
{isWHP && <SaveStatusPill status={status} />}
|
||||
|
||||
{/* Save status indicator */}
|
||||
{saveStatus === 'saved' && (
|
||||
<span className="save-indicator saved">
|
||||
<i className="fa fa-check" /> Saved!
|
||||
</span>
|
||||
)}
|
||||
{saveStatus === 'error' && (
|
||||
<span className="save-indicator error">
|
||||
<i className="fa fa-exclamation-triangle" /> Save Error
|
||||
</span>
|
||||
)}
|
||||
{publishStatus === 'error' && (
|
||||
<span className="save-indicator error">
|
||||
<i className="fa fa-exclamation-triangle" /> Publish Error
|
||||
</span>
|
||||
)}
|
||||
|
||||
<SitesmithButton onClick={() => openSitesmith()} />
|
||||
<SitesmithButton onClick={() => openSitesmith()} disabled={!canSave} />
|
||||
|
||||
<button
|
||||
className="topbar-btn primary"
|
||||
onClick={handleSave}
|
||||
disabled={saveStatus === 'saving'}
|
||||
onClick={() => { void handleSave(); }}
|
||||
disabled={saving || !canSave}
|
||||
title="Save Draft"
|
||||
aria-label="Save Draft"
|
||||
>
|
||||
{saveStatus === 'saving' ? (
|
||||
{saving ? (
|
||||
<><i className="fa fa-spinner fa-spin" /> Saving...</>
|
||||
) : (
|
||||
<><i className="fa fa-save" /> Save</>
|
||||
@@ -440,11 +487,11 @@ export const TopBar: React.FC<TopBarProps> = ({ device, onDeviceChange, showGuid
|
||||
<button
|
||||
className="topbar-btn publish"
|
||||
onClick={handlePublish}
|
||||
disabled={publishStatus === 'publishing' || saveStatus === 'saving'}
|
||||
disabled={publishing || saving || !canSave}
|
||||
title="Publish to live site"
|
||||
aria-label="Publish to live site"
|
||||
>
|
||||
{publishStatus === 'publishing' ? (
|
||||
{publishing ? (
|
||||
<><i className="fa fa-spinner fa-spin" /> Publishing...</>
|
||||
) : (
|
||||
<><i className="fa fa-globe" /> Publish</>
|
||||
|
||||
@@ -16,6 +16,8 @@ export interface TopBarOverflowMenuProps {
|
||||
* re-implemented here so the mobile menu reuses the exact same
|
||||
* lock/cap-aware button the desktop topbar shows. */
|
||||
sitesmithNode: React.ReactNode;
|
||||
/** Canvas-changing items (Templates, Head Code) are disabled until the site has loaded. */
|
||||
editingDisabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -37,6 +39,7 @@ export const TopBarOverflowMenu: React.FC<TopBarOverflowMenuProps> = ({
|
||||
onOpenReportIssue,
|
||||
onPreview,
|
||||
sitesmithNode,
|
||||
editingDisabled,
|
||||
}) => {
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -84,13 +87,13 @@ export const TopBarOverflowMenu: React.FC<TopBarOverflowMenuProps> = ({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenTemplates)}>
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" disabled={editingDisabled} onClick={runAndClose(onOpenTemplates)}>
|
||||
<i className="fa fa-th-large" aria-hidden="true" /> Templates
|
||||
</button>
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onPreview)}>
|
||||
<i className="fa fa-eye" aria-hidden="true" /> Preview
|
||||
</button>
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenHeadCode)}>
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" disabled={editingDisabled} onClick={runAndClose(onOpenHeadCode)}>
|
||||
<i className="fa fa-code" aria-hidden="true" /> Head Code
|
||||
</button>
|
||||
<button type="button" className="topbar-overflow-item" role="menuitem" onClick={runAndClose(onOpenReportIssue)}>
|
||||
|
||||
Reference in new issue
Block a user