Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-publish-flush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@emdash-cms/admin": patch
---

Fixes Publish saving and awaiting the editor's latest changes before making content live. Validation errors, failed saves, and revision conflicts now stop publishing instead of promoting stale draft data.
127 changes: 92 additions & 35 deletions packages/admin/src/components/ContentEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,11 @@ export interface ContentEditorProps {
autosaveCompletionToken?: number;
/** Entry-scoped token advanced after the server rejected an autosave payload. */
autosaveRejectionToken?: number;
onPublish?: () => void;
onPublish?: (payload: {
data: Record<string, unknown>;
slug?: string;
bylines?: BylineCreditInput[];
}) => void | Promise<void>;
onUnpublish?: () => void;
/** Callback to discard draft changes (revert to published version) */
onDiscardDraft?: () => void;
Expand Down Expand Up @@ -340,6 +344,8 @@ export function ContentEditor({
);
const pendingAutosaveStateRef = React.useRef<string | null>(null);
const [rejectedAutosaveState, setRejectedAutosaveState] = React.useState<string | null>(null);
const [isPublishing, setIsPublishing] = React.useState(false);
const isPublishingRef = React.useRef(false);

// Synchronously reset form state when the underlying item changes (e.g. a
// translation switch where TanStack Router keeps ContentEditor mounted but
Expand Down Expand Up @@ -384,11 +390,14 @@ export function ContentEditor({
React.useEffect(() => {
if (item) {
const nextBylines = resolveEditorBylines(item).explicitCredits;
setFormData(item.data);
setSlug(item.slug || "");
setSlugTouched(!!item.slug);
if (!isPublishingRef.current) {
setFormData(item.data);
setSlug(item.slug || "");
setSlugTouched(!!item.slug);
setInternalBylines(nextBylines);
setBylinesTouched(false);
}
setStatus(item.status);
setInternalBylines(nextBylines);
setLastSavedData(
serializeEditorState({
data: item.data,
Expand All @@ -398,7 +407,6 @@ export function ContentEditor({
);
pendingAutosaveStateRef.current = null;
setRejectedAutosaveState(null);
setBylinesTouched(false);
}
}, [item?.updatedAt, itemDataString, itemBylinesString, item?.slug, item?.status]);

Expand Down Expand Up @@ -484,10 +492,28 @@ export function ContentEditor({
},
[fields],
);
const createSavePayload = React.useCallback(() => {
const payload: {
data: Record<string, unknown>;
slug?: string;
bylines?: BylineCreditInput[];
} = {
data: formDataRef.current,
slug: slugRef.current || undefined,
};
if (isNew || bylinesTouched) payload.bylines = activeBylines;
return payload;
}, [activeBylines, bylinesTouched, isNew]);
const cancelPendingAutosave = React.useCallback(() => {
if (autosaveTimeoutRef.current) {
clearTimeout(autosaveTimeoutRef.current);
autosaveTimeoutRef.current = null;
}
}, []);

React.useEffect(() => {
// Don't autosave for new items (no ID yet) or if autosave isn't configured
if (isNew || !onAutosave || !item?.id || hasUnsupportedPortableTextMarks) {
if (isNew || !onAutosave || !item?.id || hasUnsupportedPortableTextMarks || isPublishing) {
return;
}

Expand All @@ -508,15 +534,7 @@ export function ContentEditor({
// Schedule autosave
autosaveTimeoutRef.current = setTimeout(() => {
if (hasInvalidUrls(formDataRef.current)) return;
const payload: {
data: Record<string, unknown>;
slug?: string;
bylines?: BylineCreditInput[];
} = {
data: formDataRef.current,
slug: slugRef.current || undefined,
};
if (bylinesTouched) payload.bylines = activeBylines;
const payload = createSavePayload();
pendingAutosaveStateRef.current = serializeEditorState({
data: payload.data,
slug: payload.slug || "",
Expand All @@ -540,31 +558,70 @@ export function ContentEditor({
isAutosaving,
activeBylines,
bylinesTouched,
createSavePayload,
hasInvalidUrls,
hasUnsupportedPortableTextMarks,
isPublishing,
rejectedAutosaveState,
]);

// Cancel pending autosave on manual save
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (hasInvalidUrls(formData) || hasUnsupportedPortableTextMarks) return;
// Cancel pending autosave
if (autosaveTimeoutRef.current) {
clearTimeout(autosaveTimeoutRef.current);
autosaveTimeoutRef.current = null;
}
const payload: {
data: Record<string, unknown>;
slug?: string;
bylines?: BylineCreditInput[];
} = {
data: formData,
slug: slug || undefined,
};
if (isNew || bylinesTouched) payload.bylines = activeBylines;
onSave?.(payload);
if (
isContentSaveBlocked ||
isPublishingRef.current ||
hasInvalidUrls(formData) ||
hasUnsupportedPortableTextMarks
)
return;
cancelPendingAutosave();
onSave?.(createSavePayload());
};
const handlePublish = React.useCallback(() => {
if (
isPublishingRef.current ||
!onPublish ||
hasInvalidUrls(formDataRef.current) ||
hasUnsupportedPortableTextMarks
)
return;
cancelPendingAutosave();
const payload = createSavePayload();
const savedState = serializeEditorState({
data: payload.data,
slug: payload.slug || "",
bylines: activeBylines,
});
isPublishingRef.current = true;
setIsPublishing(true);
const result = onPublish(payload);
if (!result) {
isPublishingRef.current = false;
setIsPublishing(false);
return;
}
void result.then(
() => {
setLastSavedData(savedState);
isPublishingRef.current = false;
setIsPublishing(false);
return undefined;
},
() => {
isPublishingRef.current = false;
setIsPublishing(false);
return undefined;
},
);
}, [
activeBylines,
cancelPendingAutosave,
createSavePayload,
hasInvalidUrls,
hasUnsupportedPortableTextMarks,
onPublish,
]);

// Preview URL state
const [isLoadingPreview, setIsLoadingPreview] = React.useState(false);
Expand Down Expand Up @@ -751,7 +808,7 @@ export function ContentEditor({
isNew={isNew}
isLive={isLive}
hasPendingChanges={hasPendingChanges}
onPublish={onPublish}
onPublish={handlePublish}
onUnpublish={onUnpublish}
/>
<MobileSettingsButton />
Expand Down Expand Up @@ -810,7 +867,7 @@ export function ContentEditor({
collectionLabel={collectionLabel}
isLive={isLive}
hasPendingChanges={hasPendingChanges}
onPublish={onPublish}
onPublish={handlePublish}
onUnpublish={onUnpublish}
size="sm"
/>
Expand Down Expand Up @@ -896,7 +953,7 @@ export function ContentEditor({
supportsPreview={supportsPreview}
isLoadingPreview={isLoadingPreview}
onPreview={handlePreview}
onPublish={onPublish}
onPublish={handlePublish}
onUnpublish={onUnpublish}
announceSaveStatus={!isDistractionFree}
/>
Expand Down
11 changes: 8 additions & 3 deletions packages/admin/src/lib/api/content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,16 +487,21 @@ export async function getPreviewUrl(
export async function publishContent(
collection: string,
id: string,
options?: { locale?: string },
options?: { locale?: string; _rev?: string },
): Promise<ContentItem> {
const params = new URLSearchParams();
if (options?.locale) params.set("locale", options.locale);
const query = params.toString() ? `?${params}` : "";
const response = await apiFetch(`${API_BASE}/content/${collection}/${id}/publish${query}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ _rev: options?._rev }),
});
const data = await parseApiResponse<{ item: ContentItem }>(response, "Failed to publish content");
return data.item;
const data = await parseApiResponse<{ item: ContentItem; _rev?: string }>(
response,
"Failed to publish content",
);
return { ...data.item, _rev: data._rev };
}

/**
Expand Down
Loading
Loading