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/examples/resume-progress.php · sjs:resume-progress.server
View on GitHub
// Return the current user's saved answers and UI state
Route::get('/api/progress/{formId}', function (string $formId) {
$key = (Auth::id() ?? abort(401, 'Sign in to load progress')).':'.$formId;
$json = DB::table('progress')->where('key', $key)->value('json');
return response($json ?? 'null')->header('Content-Type', 'application/json');
});
// Store progress under a key containing both the user ID and form ID
Route::put('/api/progress/{formId}', function (Request $request, string $formId) {
$key = (Auth::id() ?? abort(401, 'Sign in to save progress')).':'.$formId;
// Read the raw request body to prevent PHP arrays from turning {} into [] in stored JSON
$progress = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
StoredJson::put('progress', $key, $progress); // Preserve float values such as 1.0
return response()->noContent();
});
Server · routes/examples/resume-progress.php · sjs:resume-progress.delete
View on GitHub
// Remove only the current user's draft
Route::delete('/api/progress/{formId}', function (string $formId) {
$key = (Auth::id() ?? abort(401, 'Sign in to clear progress')).':'.$formId;
DB::table('progress')->where('key', $key)->delete();
return response()->noContent();
});