Loading saved progress...
JSON definition · shared/definitions/resume-progress.json
View 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 · shared/client/resume-progress.js · sjs:resume-progress.restore
View 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 = 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 · shared/client/resume-progress.js · sjs:resume-progress.save
View 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 · shared/client/resume-progress.js · sjs:resume-progress.client
View on GitHub
import debounce from "lodash/debounce";
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
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden" && recording && !locked) {
flushProgress().catch(showSaveError);
}
});
Server · routes/resume-progress.js · sjs:resume-progress.server
View on GitHub
// Return the current user's saved answers and UI state
app.get("/api/progress/:formId", (req, res) => {
if (!req.user) throw httpError(401, "Sign in to load progress");
const row = db(req).prepare("SELECT json FROM progress WHERE key = ?").get(`${req.user.id}:${req.params.formId}`);
res.type("json").send(row?.json ?? "null"); // the document as stored, or null when there is none
});
// Store progress under a key containing both the user ID and form ID
app.put("/api/progress/:formId", (req, res) => {
if (!req.user) throw httpError(401, "Sign in to save progress");
if (req.body === undefined) throw httpError(400, "Expected { data, uiState }"); // not a JSON body
// req.body is the parsed raw body: {} stays {}; store it with JSON.stringify, never a copy
db(req).prepare("INSERT INTO progress (key, json) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET json = excluded.json")
.run(`${req.user.id}:${req.params.formId}`, JSON.stringify(req.body));
res.sendStatus(204);
});
Server · routes/resume-progress.js · sjs:resume-progress.delete
View on GitHub
// Remove only the current user's draft
app.delete("/api/progress/:formId", (req, res) => {
if (!req.user) throw httpError(401, "Sign in to clear progress");
db(req).prepare("DELETE FROM progress WHERE key = ?").run(`${req.user.id}:${req.params.formId}`);
res.sendStatus(204);
});