Appearance
Autosave en auto bestandsnaam
Hier is een korte technische samenvatting die je als blauwdruk in andere projecten kunt gebruiken.
Autosave (debounced localStorage)
- Houd app-state bij in één object
- Gebruik
saveToLocal() - Gebruik
scheduleAutosave()
Framework-agnostische snippet
js
// --- Autosave (debounced localStorage) ---
const STORAGE_KEY = "app_state_v1";
let autosaveTimer;
function saveToLocal(state) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
function loadFromLocal(fallbackState) {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return fallbackState;
try {
return JSON.parse(raw);
} catch {
return fallbackState;
}
}
function scheduleAutosave(state, delayMs = 400) {
clearTimeout(autosaveTimer);
autosaveTimer = setTimeout(() => {
saveToLocal(state);
}, delayMs);
}
// --- Auto bestandsnaam voor JSON export ---
function slugify(input) {
return input
.trim()
.toLowerCase()
.replace(/\s+/g, "_")
.replace(/[^a-z0-9_-]/g, "");
}
function buildFilename({ label = "overzicht", date = new Date() } = {}) {
const dd = String(date.getDate()).padStart(2, "0");
const mm = String(date.getMonth() + 1).padStart(2, "0");
const yyyy = date.getFullYear();
const safeLabel = slugify(label) || "overzicht";
return `fin_${safeLabel}_${dd}-${mm}-${yyyy}.json`;
}
function exportJson(state, filename) {
const payload = JSON.stringify(state, null, 2);
const blob = new Blob([payload], {
type: "application/json",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
// --- Voorbeeld gebruik ---
const state = {
name: "Acme BV",
items: [],
};
scheduleAutosave(state);
const filename = buildFilename({
label: state.name,
});
exportJson(state, filename);