Save a note and keep its versions
Save a note in localStorage, keep its versions in IndexedDB, and report a refused write.
Apache-2.0Runs on this page
Package: @awacloud/fw
Persist a note in localStorage through the storage module, keep every
saved version in IndexedDB when the browser has it, and report a write the
browser refuses.
Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.
When to use it
Drafts, preferences and offline data: small values in storage.local,
larger or many records in IndexedDB. Every browser runs the full path;
where IndexedDB is unavailable, the page says so and saving still works,
without history.
Copy-paste steps
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - Bump the version in
IDB.open(name, version, upgrade)whenever you add a store; the upgrade callback runs once per bump.
What it shows
storage.localisnullwhen unavailable; otherwiseget/setwith JSON values under your own key.setthrows on a full quota or blocked storage: the page says "Not saved" instead of failing silently.indexedDB.isSupported(), thenopen(name, version, upgradeCallback)(the third argument is a callback, not an options object) and a store accessor withsetandgetAllreturning promises.- Versions stored under an array key
[time, sequence]: IndexedDB compares array keys element by element, so the list is oldest first and two saves in the same millisecond keep both. The saved versions are listed when the page opens, not only after a save. - To hand the note to the user as a file, see
downloadinrecipes/zip-and-download.
Code
main.js
// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { storage } from '@awacloud/fw/dom/fs/storage.js';
import { indexedDB } from '@awacloud/fw/dom/fs/indexedDB.js';
fw.runtime.registerAllDeep([storage, indexedDB]);
const STORAGE = fw.runtime.resolve('storage');
const IDB = fw.runtime.resolve('indexedDB');
export const KEY = 'examples:note';
const note = /** @type {HTMLTextAreaElement} */ (document.getElementById('note'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
const historyStatus = /** @type {HTMLElement} */ (document.getElementById('history-status'));
const historyList = /** @type {HTMLElement} */ (document.getElementById('history'));
/** The current note, from localStorage (`storage.local` is null when unavailable). */
export const load = () => (STORAGE.local ? STORAGE.local.get(KEY) ?? '' : '');
/**
* History lives in IndexedDB when the browser has it; otherwise the page
* says so and keeps working without history.
* @returns {Promise<import('@awacloud/fw/dom/fs/indexedDB.js').DB | null>}
*/
export async function openHistory() {
if (!IDB.isSupported()) {
historyStatus.textContent = 'IndexedDB is not available here: history disabled, saving still works.';
return null;
}
// The third argument is the upgrade callback, run once per version bump.
const db = await IDB.open('examples-notes', 1, (raw) => { raw.createObjectStore('versions'); });
historyStatus.textContent = 'History kept in IndexedDB.';
return db;
}
const history = await openHistory();
let sequence = 0;
/**
* Store one version under `[time, sequence]`: IndexedDB compares array keys
* element by element, so versions sort oldest first and two saves in the
* same millisecond keep both.
* @param {{ set: (key: IDBValidKey, value: string) => Promise<IDBValidKey> }} store
* @param {string} text
*/
export const saveVersion = (store, text) => store.set([Date.now(), ++sequence], text);
/** @param {{ getAll: () => Promise<string[]> }} store @returns {Promise<number>} how many versions */
export async function showHistory(store) {
const all = await store.getAll();
historyList.replaceChildren(...all.map((text) => {
const li = document.createElement('li');
li.textContent = text.slice(0, 40);
return li;
}));
return all.length;
}
if (history) await showHistory(history.store('versions'));
/**
* @param {string} text
* @param {{ set: (key: string, value: string) => void } | null} [local] the store, `storage.local` by default
* @returns {Promise<number>} how many versions the history holds, -1 when the note was not saved
*/
export async function save(text, local = STORAGE.local) {
try {
if (!local) throw new Error('localStorage is not available');
local.set(KEY, text); // throws on a full quota or blocked storage
} catch (err) {
status.textContent = `Not saved: ${/** @type {Error} */ (err).message}`;
return -1;
}
status.textContent = `Saved ${text.length} characters.`;
if (!history) return 0;
await saveVersion(history.store('versions'), text);
return showHistory(history.store('versions'));
}
note.value = load();
/** @type {HTMLElement} */ (document.getElementById('save')).addEventListener('click', () => save(note.value));index.html
<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>fw · Save a note and keep its versions</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Save a note and keep its versions</h1>
<label for="note">Note</label>
<textarea id="note" rows="4"></textarea>
<button id="save" type="button">Save</button>
<p id="status" aria-live="polite"></p>
<h2>History</h2>
<p id="history-status"></p>
<ol id="history" aria-label="Saved versions"></ol>
</main>
</body>
</html>