Loading saved progress...
JSON definition · shared/definitions/resume-progress.jsonView on GitHub
{
"title": "Workspace onboarding",
"completeText": "Finish onboarding",
"showProgressBar": true,
"textUpdateMode": "onTyping",
"pages": [
{
"name": "about-you",
"title": "About you",
"elements": [
{
"type": "text",
"name": "full_name",
"title": "Full name"
},
{
"type": "text",
"name": "job_title",
"title": "Job title"
}
]
},
{
"name": "company-details",
"title": "Your company",
"elements": [
{
"type": "text",
"name": "company",
"title": "Company name"
},
{
"type": "dropdown",
"name": "team_size",
"title": "Team size",
"choices": [
"1-10",
"11-50",
"51-200",
"200+"
]
},
{
"type": "text",
"name": "website",
"title": "Website",
"inputType": "url"
}
]
},
{
"name": "onboarding-goals",
"title": "Goals",
"elements": [
{
"type": "checkbox",
"name": "goals",
"title": "What do you want to do first?",
"choices": [
"Collect feedback",
"Run registrations",
"Build quizzes",
"Replace paper forms"
]
},
{
"type": "comment",
"name": "notes",
"title": "Anything else?"
}
]
}
]
}Client · src/app/examples/resume-progress/client.tsx · sjs:resume-progress.restoreView on GitHub
// Restore the draft before rendering so saved answers cannot overwrite new input
async function restoreProgress() {
setStatus("Loading saved progress...");
try {
const response = await fetch(progressUrl, { headers: { Accept: "application/json" } });
if (!response.ok) throw new Error("Load failed");
const saved: Draft = await response.json();
if (saved !== null && (!saved.data || typeof saved.data !== "object" || Array.isArray(saved.data) ||
!saved.uiState || typeof saved.uiState !== "object" || Array.isArray(saved.uiState))) throw new Error("Invalid progress");
survey.data = saved?.data ?? {};
const uiState = restorePageNames(saved?.uiState);
if (uiState) survey.uiState = uiState;
await showSurvey(uiState);
lastSnapshot = JSON.stringify(snapshot());
recording = true;
setStatus(saved ? "Your saved progress has been restored" : "No saved progress");
} catch {
setStatus("Couldn't load saved progress. Retry to continue.", restoreProgress);
}
}Client · src/app/examples/resume-progress/client.tsx · sjs:resume-progress.saveView on GitHub
// Finish each save before sending a newer snapshot
async function persistProgress() {
if (recording) setStatus("Saving progress...");
while (pendingProgress !== null) {
const body = pendingProgress;
pendingProgress = null;
try {
const response = await fetch(progressUrl, {
method: "PUT", headers: jsonHeaders, body, keepalive: true
});
if (!response.ok) throw new Error("Save failed");
} catch (error) {
pendingProgress ??= body;
throw error;
}
}
if (recording) setStatus(`Progress saved at ${new Date().toLocaleTimeString()}`);
}Client · src/app/examples/resume-progress/client.tsx · sjs:resume-progress.clientView on GitHub
// debounce is lodash's (lodash-es/debounce, imported at the top of this file)
const saveProgress = debounce(() => flushProgress().catch(showSaveError), 800);
function flushProgress() {
saveProgress.cancel();
if (pendingProgress === null) return saving ?? Promise.resolve();
return saving ??= persistProgress().finally(() => { saving = null; });
}
function queueProgress() {
if (!recording || locked) return;
const body = JSON.stringify(snapshot());
if (body === lastSnapshot) return;
lastSnapshot = pendingProgress = body;
setStatus("Changes will be saved automatically");
saveProgress();
}
survey.onValueChanged.add(queueProgress);
survey.onUIStateChanged.add(queueProgress); // Include page and focus changes
const flushWhenHidden = () => {
if (document.visibilityState === "hidden" && recording && !locked) {
flushProgress().catch(showSaveError);
}
};
document.addEventListener("visibilitychange", flushWhenHidden);Server · src/server/routes/resume-progress.ts · sjs:resume-progress.serverView on GitHub
// Return the current user's saved answers and UI state
export function loadProgress(req: Request, { formId }: { formId: string }) {
const user = currentUser(req);
if (!user) throw httpError(401, "Sign in to load progress");
const row = db(req).prepare("SELECT json FROM progress WHERE key = ?").get(`${user.id}:${formId}`) as { json: string } | undefined;
// the document as stored, or null when there is none
return new Response(row?.json ?? "null", { headers: { "Content-Type": "application/json" } });
}
// Store progress under a key containing both the user ID and form ID
export async function saveProgress(req: Request, { formId }: { formId: string }) {
const user = currentUser(req);
if (!user) throw httpError(401, "Sign in to save progress");
const progress = await readJson(req); // the parsed raw body: {} stays {}; store it with JSON.stringify, never a copy
if (progress === undefined) throw httpError(400, "Expected { data, uiState }"); // not a JSON body
db(req).prepare("INSERT INTO progress (key, json) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET json = excluded.json")
.run(`${user.id}:${formId}`, JSON.stringify(progress));
return new Response(null, { status: 204 });
}Server · src/server/routes/resume-progress.ts · sjs:resume-progress.deleteView on GitHub
// Remove only the current user's draft
export function clearProgress(req: Request, { formId }: { formId: string }) {
const user = currentUser(req);
if (!user) throw httpError(401, "Sign in to clear progress");
db(req).prepare("DELETE FROM progress WHERE key = ?").run(`${user.id}:${formId}`);
return new Response(null, { status: 204 });
}