diff --git a/backend/e2e/sponsor-doc-utm-save.spec.js b/backend/e2e/sponsor-doc-utm-save.spec.js new file mode 100644 index 00000000..a7f59ad6 --- /dev/null +++ b/backend/e2e/sponsor-doc-utm-save.spec.js @@ -0,0 +1,97 @@ +// Regression (t2909u): clicking the "Add UTM" suggestion on a sponsor doc changed +// ctaUrl in the page only; nothing reached the server until a manual Save, so +// the value was lost. The page now autosaves every edit, including +// helper-filled values and image uploads, and a failed save is loud. +const { test, expect } = require("@playwright/test"); +const { createDocsCacheRoot } = require("./helpers/docs-content-root"); +const { startOwnedTestServer, stopOwnedTestServer } = require("./helpers/isolated-capability-server"); + +// 1x1 PNG +const VALID_PNG = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+X2ZkAAAAASUVORK5CYII=", + "base64", +); + +let server; +test.use({ screenshot: "off", trace: "off", video: "off" }); + +test.beforeAll(async () => { + server = await startOwnedTestServer({ environment: { DTC_CACHE_ROOT: createDocsCacheRoot("sponsor-doc-autosave") } }); +}); +test.afterAll(async () => { await stopOwnedTestServer(server); }); + +async function openSponsorDoc(page, request, title) { + const tplRes = await request.post(`${server.baseURL}/__e2e__/template-fixtures`, { + data: { name: `Autosave ${title}`, type: "newsletter", sourcePath: `workflow-templates/autosave-${title}.yaml`, taskDefinitions: [] }, + }); + expect(tplRes.status()).toBe(201); + const { template } = await tplRes.json(); + const cardRes = await request.post(`${server.baseURL}/api/cards`, { + data: { templateId: template.id, title: `Autosave ${title}`, anchorDate: "2026-12-14" }, + }); + expect(cardRes.status()).toBe(201); + const { card } = await cardRes.json(); + const docRes = await request.post(`${server.baseURL}/api/sponsor-docs`, { + data: { cardId: card.id, template: "newsletter-main", sponsorName: "Acme Corp", autoSendEmail: false }, + }); + expect(docRes.status()).toBe(201); + const { doc } = await docRes.json(); + // Save a plain ctaUrl first, exactly like the reported doc. + const putRes = await request.put(`${server.baseURL}/api/sponsor-docs/${doc.id}`, { + data: { content: { ...(doc.content || {}), ctaUrl: "https://maven.com/example/product-shipping" } }, + }); + expect(putRes.status()).toBe(200); + await page.setExtraHTTPHeaders({ "x-sponsor-doc-anonymous": "true" }); + await page.goto(`${server.baseURL}/sponsor-docs/${doc.id}?code=${encodeURIComponent(doc.accessCode)}`); + await expect(page.locator('[data-sponsor-view="editor"]')).toBeVisible(); + return doc; +} + +const status = (page) => page.locator("[data-sponsor-save-status]"); + +test("clicking the UTM suggestion autosaves ctaUrl; reload shows it", async ({ page, request }) => { + test.setTimeout(60_000); + await openSponsorDoc(page, request, "utm"); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved"); + const putDone = page.waitForResponse((res) => res.request().method() === "PUT" && /\/api\/sponsor-docs\//.test(res.url())); + await page.locator('[data-sponsor-action="apply-utm-suggestion"][data-sponsor-utm-field="ctaUrl"]').click(); + expect((await putDone).status()).toBe(200); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved"); + await expect(status(page)).toContainText("All changes saved"); + await page.reload(); + await expect(page.locator("#sponsor-field-ctaUrl")).toHaveValue(/^https:\/\/maven\.com\/example\/product-shipping\?.*utm_source=/); +}); + +test("typing and an image upload autosave without a Save click", async ({ page, request }) => { + test.setTimeout(60_000); + await openSponsorDoc(page, request, "typing"); + await page.locator("#sponsor-field-title").fill("Autosaved headline"); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 }); + await page.locator('[data-sponsor-visual-upload="graphicsUrl"]').setInputFiles({ name: "banner.png", mimeType: "image/png", buffer: VALID_PNG }); + await expect(page.locator('img[data-sponsor-visual-image="graphicsUrl"]')).toBeVisible(); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 }); + await page.reload(); + await expect(page.locator("#sponsor-field-title")).toHaveValue("Autosaved headline"); + await expect(page.locator("#sponsor-field-graphicsUrl")).toHaveValue(/\/api\/public-images\/[0-9a-f-]+\.png$/); +}); + +test("a failed autosave shows a loud NOT SAVED error, reports it, and Retry saves", async ({ page, request }) => { + test.setTimeout(60_000); + await openSponsorDoc(page, request, "failure"); + const reports = []; + page.on("request", (req) => { if (req.url().endsWith("/api/client-errors")) reports.push(req.postDataJSON()); }); + const failPut = (route) => (route.request().method() === "PUT" + ? route.fulfill({ status: 500, json: { error: "boom" } }) + : route.continue()); + await page.route("**/api/sponsor-docs/*", failPut); + await page.locator("#sponsor-field-title").fill("Will fail first"); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "error", { timeout: 10_000 }); + await expect(status(page)).toHaveAttribute("role", "alert"); + await expect(status(page)).toContainText("NOT SAVED"); + await expect.poll(() => reports.length).toBeGreaterThan(0); + await page.unroute("**/api/sponsor-docs/*", failPut); + await page.locator('[data-sponsor-action="retry-save"]').click(); + await expect(status(page)).toHaveAttribute("data-sponsor-save-state", "saved", { timeout: 10_000 }); + await page.reload(); + await expect(page.locator("#sponsor-field-title")).toHaveValue("Will fail first"); +}); diff --git a/backend/src/docs/frontend-assets.json b/backend/src/docs/frontend-assets.json index 47a844cd..ef24eafa 100644 --- a/backend/src/docs/frontend-assets.json +++ b/backend/src/docs/frontend-assets.json @@ -165,7 +165,9 @@ "src/surfaces/operations/contract-sign.js", "src/surfaces/operations/index.js", "src/surfaces/operations/newsletter-preview.js", + "src/surfaces/operations/sponsor-doc-autosave.js", "src/surfaces/operations/sponsor-doc-bullets.js", + "src/surfaces/operations/sponsor-doc-files.js", "src/surfaces/operations/sponsor-doc-visual.js", "src/surfaces/operations/sponsor-doc-email-card.js", "src/surfaces/operations/sponsor-doc-event-time.js", diff --git a/backend/src/routes/sponsorDocs.ts b/backend/src/routes/sponsorDocs.ts index ab60cfc1..345f3d2b 100644 --- a/backend/src/routes/sponsorDocs.ts +++ b/backend/src/routes/sponsorDocs.ts @@ -347,6 +347,8 @@ export function isAnonymousSponsorDocAsset(method: string, path: string): boolea || path === '/src/surfaces/operations/sponsor-doc-radio.js' || path === '/src/surfaces/operations/sponsor-doc-bullets.js' || path === '/src/surfaces/operations/sponsor-doc-visual.js' + || path === '/src/surfaces/operations/sponsor-doc-autosave.js' + || path === '/src/surfaces/operations/sponsor-doc-files.js' || path === '/src/surfaces/operations/sponsor-doc-email-card.js' || path === '/src/surfaces/operations/sponsor-doc-event-time.js' || path === '/src/surfaces/operations/sponsor-doc-guest-schedule.js' diff --git a/backend/tests/sponsor-docs.test.ts b/backend/tests/sponsor-docs.test.ts index c36ba677..7b05cc5a 100644 --- a/backend/tests/sponsor-docs.test.ts +++ b/backend/tests/sponsor-docs.test.ts @@ -1068,6 +1068,8 @@ describe('Sponsor Content Docs API (/api/sponsor-docs)', () => { it('keeps podcast run sheet, episode brief, research, and hostContext isolated from guests while serving them to staff', async () => { assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-podcast.js'), true); + assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-autosave.js'), true); + assert.equal(isAnonymousSponsorDocAsset('GET', '/src/surfaces/operations/sponsor-doc-files.js'), true); const card = await createCard(client, { ...templateLink(), diff --git a/frontend/src/surfaces/operations/sponsor-doc-autosave.js b/frontend/src/surfaces/operations/sponsor-doc-autosave.js new file mode 100644 index 00000000..d9b4918b --- /dev/null +++ b/frontend/src/surfaces/operations/sponsor-doc-autosave.js @@ -0,0 +1,218 @@ +import { reportClientFailure } from "../../core/guarded-fetch.js"; + +/** Debounce between the last edit and the automatic save. */ +export const SPONSOR_DOC_AUTOSAVE_DELAY_MS = 1200; + +// The guest time choice is confirmed with its own "Save time choice" button +// (it records a booking intent), so autosave keeps its saved value. +const EXPLICIT_SAVE_KEYS = ["slotChoice"]; + +export function notSavedMessage(err) { + return `NOT SAVED: ${err?.message || "Failed to save changes."} Your edits are still in this form.`; +} + +/** + * 5xx, timeouts and network errors are already reported by the request layer; + * report the rest (4xx) too so no failed save goes unnoticed. + */ +export function reportSaveFailure(err) { + if (typeof err?.status === "number" && err.status < 500) { + reportClientFailure({ surface: "sponsor-doc", check: "PUT /api/sponsor-docs", status: err.status, message: String(err.message || "") }); + } +} + +/** + * Autosave for the sponsor doc page: every edit (typing, helper buttons, + * uploads, selects) is saved after a short debounce, without re-rendering the + * form, and the visible status line shows saving / saved / NOT SAVED. + * `baseline` is the content last persisted. + */ +export function createSponsorDocAutosave({ + el, + actionBtn, + root, + request, + announce, + ctx, + delayMs = SPONSOR_DOC_AUTOSAVE_DELAY_MS, +}) { + let baseline = null; + let timer = null; + let inFlight = null; + let state = "saved"; + let error = ""; + + function savedContent() { + const content = ctx.savableContent(); + for (const key of EXPLICIT_SAVE_KEYS) { + if (!baseline || !(key in baseline)) delete content[key]; + else content[key] = baseline[key]; + } + return content; + } + + function markClean(content = ctx.savableContent()) { + baseline = { ...content }; + } + + function forgetBaseline() { + baseline = null; + } + + function isDirty() { + if (!ctx.doc() || !baseline) return false; + const draft = savedContent(); + const keys = new Set([...Object.keys(baseline), ...Object.keys(draft)]); + for (const key of keys) { + if (String(baseline[key] ?? "") !== String(draft[key] ?? "")) return true; + } + return false; + } + + function setSaved() { + state = "saved"; + error = ""; + } + + function setError(message) { + state = "error"; + error = message; + } + + function fillStatus(node) { + const tone = { saved: "success", pending: "warning", saving: "info", error: "danger" }[state] || "info"; + node.className = `dk-callout dk-callout--${tone} sponsor-doc-save-status`; + node.dataset.sponsorSaveStatus = ""; + node.dataset.sponsorSaveState = state; + node.setAttribute("role", state === "error" ? "alert" : "status"); + const body = el("div", "dk-callout__body"); + if (state === "error") { + body.append(el("span", "", `${error} `)); + body.append(actionBtn("dk-button dk-button--secondary dk-button--sm", "Retry save", "retry-save", () => run())); + } else if (state === "saving") { + body.textContent = "Saving…"; + } else if (state === "pending") { + body.textContent = "Unsaved changes · saving automatically…"; + } else { + const label = ctx.savedLabel(); + body.textContent = label ? `All changes saved · ${label}` : "Changes save automatically."; + } + node.replaceChildren(body); + } + + function statusNode() { + const node = el("div"); + fillStatus(node); + return node; + } + + function refresh() { + for (const node of root?.querySelectorAll?.("[data-sponsor-save-status]") || []) fillStatus(node); + } + + function clearTimer() { + if (timer) clearTimeout(timer); + timer = null; + } + + function schedule(delay = delayMs) { + if (!ctx.editing()) return; + if (!isDirty()) { + if (state === "pending") state = "saved"; + refresh(); + return; + } + if (state !== "error" && state !== "saving") state = "pending"; + clearTimer(); + timer = setTimeout(() => { + timer = null; + run(); + }, delay); + refresh(); + } + + async function run() { + clearTimer(); + if (inFlight) { + await inFlight; + return run(); + } + if (!ctx.editing()) return undefined; + if (ctx.busy()) { + // A manual save / submit is running; it sends the same content. + schedule(); + return undefined; + } + if (!isDirty()) { + if (state !== "error") state = "saved"; + refresh(); + return undefined; + } + const content = savedContent(); + const docId = ctx.docId(); + state = "saving"; + refresh(); + inFlight = (async () => { + try { + const code = ctx.accessCode(); + const payload = await request(`/api/sponsor-docs/${encodeURIComponent(docId)}`, { + method: "PUT", + headers: code ? { "x-sponsor-doc-code": code } : {}, + body: JSON.stringify({ content }), + }); + if (ctx.docId() !== docId || !ctx.doc()) return; + ctx.setDoc(payload.doc); + markClean(content); + setSaved(); + announce("All changes saved."); + } catch (err) { + setError(notSavedMessage(err)); + if (err?.fields && typeof err.fields === "object") { + ctx.setFieldErrors(err.fields); + for (const key of Object.keys(err.fields)) { + root?.querySelector?.(`[data-sponsor-field="${key}"]`)?.setAttribute?.("aria-invalid", "true"); + } + } + reportSaveFailure(err); + announce(error); + } finally { + inFlight = null; + } + })(); + await inFlight; + // Edits made while the request was in flight get their own save. + if (state === "saved" && isDirty()) schedule(); + else refresh(); + return undefined; + } + + /** Before a manual save: drop the pending timer and let a running save finish. */ + async function settle() { + clearTimer(); + if (inFlight) await inFlight; + } + + /** Save now if a save is pending (tab hidden / page unloading). */ + function flush() { + if (timer) run(); + } + + /** Save on every edit event; warn before leaving with unsaved work; flush on tab hide. */ + function attach(documentRef) { + root.addEventListener("input", () => schedule()); + root.addEventListener("change", () => schedule()); + globalThis.addEventListener?.("beforeunload", (event) => { + if (!ctx.editing() || !(isDirty() || inFlight || ctx.busy())) return; + flush(); + event.preventDefault(); + event.returnValue = ""; + }); + documentRef.addEventListener?.("visibilitychange", () => { + if (documentRef.visibilityState === "hidden") flush(); + }); + } + + return { + attach, clearTimer, fillStatus, flush, forgetBaseline, markClean, run, schedule, setError, setSaved, settle, statusNode, + }; +} diff --git a/frontend/src/surfaces/operations/sponsor-doc-email-card.js b/frontend/src/surfaces/operations/sponsor-doc-email-card.js index b72c8db4..ea42245c 100644 --- a/frontend/src/surfaces/operations/sponsor-doc-email-card.js +++ b/frontend/src/surfaces/operations/sponsor-doc-email-card.js @@ -335,6 +335,7 @@ export function attachSoftUtmSuggestion({ updateCount, updateLivePreview, announce, + onApplied, }) { const shouldSuggest = Boolean(fieldDef.suggestNewsletterUtm) || fieldDef.key === "ctaUrl" @@ -369,6 +370,9 @@ export function attachSoftUtmSuggestion({ syncUtmSuggestion(); updateLivePreview(); announce?.(`Added ${DEFAULT_NEWSLETTER_UTM_SOURCE} UTM parameters to ${fieldDef.label}.`); + // Helper-filled values are real edits: tell the page (dirty indicator, autosave). + control.dispatchEvent(new Event("input", { bubbles: true })); + onApplied?.(fieldDef.key, nextUrl); }, ); applyBtn.dataset.sponsorUtmField = fieldDef.key; diff --git a/frontend/src/surfaces/operations/sponsor-doc-files.js b/frontend/src/surfaces/operations/sponsor-doc-files.js new file mode 100644 index 00000000..b88b557e --- /dev/null +++ b/frontend/src/surfaces/operations/sponsor-doc-files.js @@ -0,0 +1,29 @@ +/** Read an uploaded image file as a data: URL (browser File or test double). */ +function bytesToDataUrl(bytes, mimeType = "image/png") { + let binary = ""; + for (let i = 0; i < bytes.length; i += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + } + const base64 = typeof globalThis.btoa === "function" + ? globalThis.btoa(binary) + : globalThis.Buffer ? globalThis.Buffer.from(bytes).toString("base64") : ""; + return `data:${mimeType || "image/png"};base64,${base64}`; +} + +export async function readVisualFileAsDataUrl(file) { + if (!file) return ""; + if (typeof file.dataUrl === "string" && file.dataUrl) return file.dataUrl; + if (typeof file.arrayBuffer === "function") { + const buffer = await file.arrayBuffer(); + return bytesToDataUrl(new Uint8Array(buffer), file.type || "image/png"); + } + if (typeof globalThis.FileReader === "function") { + return new Promise((resolve, reject) => { + const reader = new globalThis.FileReader(); + reader.onload = () => resolve(String(reader.result || "")); + reader.onerror = () => reject(new Error("Could not read image file")); + reader.readAsDataURL(file); + }); + } + return ""; +} diff --git a/frontend/src/surfaces/operations/sponsor-doc-visual.js b/frontend/src/surfaces/operations/sponsor-doc-visual.js index c82b03ce..d48fb002 100644 --- a/frontend/src/surfaces/operations/sponsor-doc-visual.js +++ b/frontend/src/surfaces/operations/sponsor-doc-visual.js @@ -191,7 +191,7 @@ export function mountSponsorDocVisualControls({ if (imageOnly) { uploadLabel.textContent = v ? "Replace image" : "Upload image"; statusSpan.textContent = name - ? `Uploaded ${name}. Save to keep it.` + ? `Uploaded ${name}.` : v ? "" : "Drag and drop works too."; clearBtn.hidden = !v; return; diff --git a/frontend/src/surfaces/operations/sponsor-docs.js b/frontend/src/surfaces/operations/sponsor-docs.js index 9c4e79e3..597dc565 100644 --- a/frontend/src/surfaces/operations/sponsor-docs.js +++ b/frontend/src/surfaces/operations/sponsor-docs.js @@ -25,6 +25,7 @@ import { import { formatEditedTimestamp } from "../../core/dates.js"; import { formatUserCode } from "../../dakit/device-code.js"; import { renderSponsorDocGate } from "./sponsor-doc-gate.js"; +import { SPONSOR_DOC_AUTOSAVE_DELAY_MS, createSponsorDocAutosave, notSavedMessage, reportSaveFailure } from "./sponsor-doc-autosave.js"; import { appendSponsorDocRadioField } from "./sponsor-doc-radio.js"; import { appendSponsorDocSelectField } from "./sponsor-doc-select.js"; import { isImageOnlyVisualField, mountSponsorDocVisualControls } from "./sponsor-doc-visual.js"; @@ -69,34 +70,7 @@ export { export const SPONSOR_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ23456789"; export const SPONSOR_CODE_LENGTH = 16; -function bytesToDataUrl(bytes, mimeType = "image/png") { - let binary = ""; - for (let i = 0; i < bytes.length; i += 0x8000) { - binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); - } - const base64 = typeof globalThis.btoa === "function" - ? globalThis.btoa(binary) - : globalThis.Buffer ? globalThis.Buffer.from(bytes).toString("base64") : ""; - return `data:${mimeType || "image/png"};base64,${base64}`; -} - -export async function readVisualFileAsDataUrl(file) { - if (!file) return ""; - if (typeof file.dataUrl === "string" && file.dataUrl) return file.dataUrl; - if (typeof file.arrayBuffer === "function") { - const buffer = await file.arrayBuffer(); - return bytesToDataUrl(new Uint8Array(buffer), file.type || "image/png"); - } - if (typeof globalThis.FileReader === "function") { - return new Promise((resolve, reject) => { - const reader = new globalThis.FileReader(); - reader.onload = () => resolve(String(reader.result || "")); - reader.onerror = () => reject(new Error("Could not read image file")); - reader.readAsDataURL(file); - }); - } - return ""; -} +export { readVisualFileAsDataUrl } from "./sponsor-doc-files.js"; function isNewsletterTemplate(templateKey, tDef) { return String(templateKey || tDef?.key || "").startsWith("newsletter-"); @@ -144,6 +118,7 @@ export function createSponsorDocPage({ historyRef, storageRef = globalThis.sessionStorage, clipboardRef = globalThis.navigator?.clipboard, + autosaveDelayMs = SPONSOR_DOC_AUTOSAVE_DELAY_MS, }) { const root = documentRef.querySelector("#sponsor-doc-root"); const identity = documentRef.querySelector("#sponsor-doc-identity"); @@ -300,7 +275,10 @@ export function createSponsorDocPage({ if (accessCode) saveStoredCode(docId, accessCode); gateError = ""; phase = "editor"; + autosave.setSaved(); + autosave.forgetBaseline(); render(); + autosave.markClean(); } catch (err) { if (err.status === 404) { phase = "notfound"; @@ -325,7 +303,25 @@ export function createSponsorDocPage({ } } + function savableContent() { + const derivedKeys = new Set((doc?.templateDefinition?.sections || []).flatMap(section => + (section.fields || []).filter(field => field.derived).map(field => field.key))); + return Object.fromEntries(Object.entries(draftContent).filter(([key]) => !derivedKeys.has(key))); + } + + const autosave = createSponsorDocAutosave({ + el, actionBtn, root, request, announce, delayMs: autosaveDelayMs, + ctx: { + doc: () => doc, setDoc: (next) => { doc = next; }, docId: () => docId, accessCode: () => accessCode, + editing: () => phase === "editor" && Boolean(doc), busy: () => busy, savableContent, + savedLabel: () => (doc?.lastEditedAt ? formatEditorLabel(doc) : ""), + setFieldErrors: (fields) => { fieldErrors = { ...fields }; }, + }, + }); + async function saveChanges(nextStatus, timeChoiceIntent) { + if (busy || !doc) return; + await autosave.settle(); if (busy || !doc) return; if (nextStatus === "submitted") { const validationErrors = validateSponsorDocDraft(doc.templateDefinition, draftContent); @@ -344,9 +340,7 @@ export function createSponsorDocPage({ render(); try { const headers = accessCode ? { "x-sponsor-doc-code": accessCode } : {}; - const derivedKeys = new Set((doc.templateDefinition?.sections || []).flatMap(section => - (section.fields || []).filter(field => field.derived).map(field => field.key))); - const body = { content: Object.fromEntries(Object.entries(draftContent).filter(([key]) => !derivedKeys.has(key))) }; + const body = { content: savableContent() }; if (nextStatus) body.status = nextStatus; if (timeChoiceIntent) body.timeChoiceIntent = timeChoiceIntent; const payload = await request(`/api/sponsor-docs/${encodeURIComponent(docId)}`, { @@ -358,6 +352,8 @@ export function createSponsorDocPage({ draftContent = { ...(doc.content || {}) }; if (timeChoiceIntent) recordingSlotExpanded = false; busy = false; + autosave.setSaved(); + autosave.forgetBaseline(); if (nextStatus === "submitted") { feedbackMsg = "Submitted and marked ready for DataTalks.Club review."; feedbackTone = "success"; @@ -370,13 +366,16 @@ export function createSponsorDocPage({ } announce(feedbackMsg); render(); + autosave.markClean(); } catch (err) { busy = false; if (err.fields && typeof err.fields === "object") { fieldErrors = { ...err.fields }; } - feedbackMsg = err.message || "Failed to save changes."; + feedbackMsg = `${notSavedMessage(err)} Try again.`; feedbackTone = "danger"; + autosave.setError(notSavedMessage(err)); + reportSaveFailure(err); announce(feedbackMsg); render(); } @@ -575,6 +574,8 @@ export function createSponsorDocPage({ const updateLivePreview = () => { for (const fn of previewSyncListeners) fn(); renderNewsletterLivePreview({ el, previewCard, doc, tDef, draftContent, hasField, uploadedVisualName, safePreviewHref }); + // Helpers (uploads, bullets, radios, selects) report edits through here. + autosave.schedule(); }; const onSourceFieldEdit = () => { syncAutoSocialPosts(); updateLivePreview(); }; @@ -760,6 +761,8 @@ export function createSponsorDocPage({ const syncUtmSuggestion = attachSoftUtmSuggestion({ el, actionBtn, fieldWrap, fieldDef, control, draftContent, publicationDate: doc.publicationDate, updateCount, updateLivePreview: onSourceFieldEdit, announce, + // A helper-filled value is a real edit: save it right away. + onApplied: () => autosave.schedule(0), }); control.addEventListener("input", () => { @@ -821,6 +824,7 @@ export function createSponsorDocPage({ } form.addEventListener("submit", (event) => { event.preventDefault(); saveChanges(undefined); }); + form.append(autosave.statusNode()); form.append(renderSponsorDocFormActions({ el, actionBtn, @@ -924,10 +928,15 @@ export function createSponsorDocPage({ return; } - if (phase === "editor" && doc) renderEditor(); + if (phase === "editor" && doc) { + renderEditor(); + // Edits applied through a re-render (e.g. timezone) are saved too. + autosave.schedule(); + } } async function start() { + autosave.attach(documentRef); const url = new URL(locationRef.href); const extracted = extractDocId(url.pathname); docId = extracted.id; @@ -954,6 +963,7 @@ export function createSponsorDocPage({ } function destroy() { + autosave.clearTimer(); unbindCode?.(); unbindCode = null; } diff --git a/frontend/test/sponsor-docs.test.mjs b/frontend/test/sponsor-docs.test.mjs index 0dd522bd..ce438aa1 100644 --- a/frontend/test/sponsor-docs.test.mjs +++ b/frontend/test/sponsor-docs.test.mjs @@ -115,6 +115,7 @@ function harness(options = {}) { historyRef: { replaceState: (...args) => history.push(args) }, storageRef, clipboardRef: { writeText: async (text) => copied.push(text) }, + ...(options.autosaveDelayMs !== undefined ? { autosaveDelayMs: options.autosaveDelayMs } : {}), request: async (url, opts = {}) => { calls.push([url, opts]); if (options.request) return options.request(url, opts); @@ -1069,3 +1070,85 @@ test("sponsor share-link view never renders the internal staff panel", async () } h.controller.destroy(); }); + +const settle = () => new Promise((resolve) => setTimeout(resolve, 5)).then(() => nextTicks(4)); + +test("UTM suggest button autosaves the helper-filled ctaUrl without a Save click", async () => { + const h = harness({ autosaveDelayMs: 0 }); + await h.controller.start(); + const status = () => h.root.querySelector("[data-sponsor-save-status]"); + assert.equal(status().dataset.sponsorSaveState, "saved", "a freshly loaded doc is not dirty and is not re-saved"); + assert.equal(h.calls.filter(([, o]) => o.method === "PUT").length, 0); + const applyBtn = h.root.querySelector('[data-sponsor-action="apply-utm-suggestion"]'); + assert.ok(applyBtn, "UTM suggestion button is offered for a ctaUrl without UTM"); + await applyBtn.click(); + await settle(); + const puts = h.calls.filter(([, o]) => o.method === "PUT"); + assert.equal(puts.length, 1, "helper-filled value is persisted automatically"); + const body = JSON.parse(puts[0][1].body); + assert.match(body.content.ctaUrl, /utm_source=/); + assert.equal(body.status, undefined, "autosave never changes the doc status"); + assert.equal(status().dataset.sponsorSaveState, "saved"); + assert.match(status().textContent, /All changes saved/); + h.controller.destroy(); +}); + +test("typing autosaves after the debounce; a failed autosave is loud and Retry saves", async () => { + let failPuts = true; + const puts = []; + const h = harness({ + autosaveDelayMs: 0, + request: async (url, opts = {}) => { + if (opts.method === "PUT") { + puts.push(JSON.parse(opts.body)); + if (failPuts) throw Object.assign(new Error("Could not save: it took too long to respond."), { status: "timeout" }); + return { doc: { ...sampleDoc(), content: { ...sampleDoc().content, ...puts.at(-1).content } } }; + } + return { doc: sampleDoc() }; + }, + }); + await h.controller.start(); + const status = () => h.root.querySelector("[data-sponsor-save-status]"); + const input = h.root.querySelector("#sponsor-field-headline"); + input.value = "Edited"; + await input.dispatch("input"); + await settle(); + assert.equal(puts.length, 1, "edit is saved without a Save click"); + assert.equal(puts[0].content.headline, "Edited"); + assert.equal(status().dataset.sponsorSaveState, "error"); + assert.equal(status().getAttribute("role"), "alert"); + assert.match(status().textContent, /NOT SAVED: Could not save: it took too long to respond/); + failPuts = false; + await h.root.querySelector('[data-sponsor-action="retry-save"]').click(); + await settle(); + assert.equal(puts.length, 2); + assert.equal(status().dataset.sponsorSaveState, "saved"); + h.controller.destroy(); +}); + +test("a 4xx autosave failure is reported to the server, not only shown", async () => { + const reports = []; + const prevFetch = globalThis.fetch; + globalThis.fetch = async (url, opts) => { reports.push([url, JSON.parse(opts.body)]); return { ok: true }; }; + try { + const h = harness({ + autosaveDelayMs: 0, + request: async (url, opts = {}) => { + if (opts.method === "PUT") throw Object.assign(new Error("Document is locked"), { status: 409 }); + return { doc: sampleDoc() }; + }, + }); + await h.controller.start(); + const input = h.root.querySelector("#sponsor-field-headline"); + input.value = "Edited"; + await input.dispatch("input"); + await settle(); + assert.match(h.root.querySelector("[data-sponsor-save-status]").textContent, /NOT SAVED: Document is locked/); + assert.equal(reports.length, 1); + assert.equal(reports[0][0], "/api/client-errors"); + assert.equal(reports[0][1].status, 409); + h.controller.destroy(); + } finally { + globalThis.fetch = prevFetch; + } +});