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 · src/main/java/io/surveyjs/examples/ResumeProgressController.java · sjs:resume-progress.server
View on GitHub
// Return the current user's saved answers and UI state, or null when there is no draft
@GetMapping("/api/progress/{formId}")
public ResponseEntity<String> loadProgress(@PathVariable String formId, @AuthenticationPrincipal User user) {
if (user == null) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sign in to load progress");
}
String draft = jdbc.sql("SELECT json FROM progress WHERE key = ?").param(user.id() + ":" + formId)
.query(String.class).optional().orElse("null");
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(draft); // as stored, or the JSON text null
}
// Store progress under a key containing both the user ID and form ID
@PutMapping("/api/progress/{formId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void saveProgress(@PathVariable String formId, @RequestBody JsonNode body, @AuthenticationPrincipal User user) {
if (user == null) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sign in to save progress");
}
// A JsonNode, not a DTO: { data, uiState } is stored as it arrived, {} stays {}
storedJson.put("progress", user.id() + ":" + formId, body);
}
Server · src/main/java/io/surveyjs/examples/ResumeProgressController.java · sjs:resume-progress.delete
View on GitHub
// Remove only the current user's draft
@DeleteMapping("/api/progress/{formId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void clearProgress(@PathVariable String formId, @AuthenticationPrincipal User user) {
if (user == null) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sign in to clear progress");
}
jdbc.sql("DELETE FROM progress WHERE key = ?").param(user.id() + ":" + formId).update();
}