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 · Endpoints/ResumeProgress.cs · sjs:resume-progress.server
View on GitHub
// Return the current user's saved answers and UI state
app.MapGet("/api/progress/{formId}", async (string formId, ClaimsPrincipal user, SurveyDb db) =>
{
if (user.FindFirstValue(ClaimTypes.NameIdentifier) is not { } userId)
return Results.Json(new { error = "Sign in to load progress" }, statusCode: 401);
var key = $"{userId}:{formId}";
var json = await db.Progress.Where(p => p.Key == key).Select(p => p.Json).SingleOrDefaultAsync();
return Results.Text(json ?? "null", "application/json"); // the draft as stored, or null when there is none
});
// Store progress under a key containing both the user ID and form ID
app.MapPut("/api/progress/{formId}", async (string formId, HttpRequest request, ClaimsPrincipal user, SurveyDb db) =>
{
if (user.FindFirstValue(ClaimTypes.NameIdentifier) is not { } userId)
return Results.Json(new { error = "Sign in to save progress" }, statusCode: 401);
// Read the raw request body: binding to a class would drop unknown keys and re-format numbers in the stored JSON
var progress = await StoredJson.ReadBodyAsync(request);
await StoredJson.UpsertAsync(db, StoredTable.Progress, $"{userId}:{formId}", progress); // Preserve float values such as 1.0
return Results.NoContent();
});
Server · Endpoints/ResumeProgress.cs · sjs:resume-progress.delete
View on GitHub
// Remove only the current user's draft
app.MapDelete("/api/progress/{formId}", async (string formId, ClaimsPrincipal user, SurveyDb db) =>
{
if (user.FindFirstValue(ClaimTypes.NameIdentifier) is not { } userId)
return Results.Json(new { error = "Sign in to clear progress" }, statusCode: 401);
var key = $"{userId}:{formId}";
await db.Progress.Where(p => p.Key == key).ExecuteDeleteAsync();
return Results.NoContent();
});