Subtlyv0.1.1
Forms & drafts

draftRecovery()

Restore a form after an interruption. Long nonsensitive forms.

Available in v0.1.1draft-recovery.jsForms

Try it

Write a sample project title and note, save the draft, then clear the editor. Restore brings your text back from this tab’s session storage. Delete draft removes the stored copy.

Live example
Project note

No changes saved in this example yet.

<div id="your-component">
<div class="sample-form"><span class="sample-label">Project note</span><label>Title<input name="title" placeholder="A new idea" autocomplete="off"></label><label>Note<textarea name="note" rows="3" placeholder="Use sample, non-sensitive text only."></textarea></label></div><div class="demo-row"><button data-save>Save draft</button><button data-empty>Clear editor</button><button data-load>Restore draft</button><button data-clear>Delete draft</button></div><p class="demo-status" role="status">No changes saved in this example yet.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const draft = kit.draftRecovery('docs:project-note:v2', {
            fields: ['title', 'note'], version: 1
          });
          const title = el.querySelector('[name="title"]');
          const note = el.querySelector('[name="note"]');
          el.querySelector('[data-save]').addEventListener('click', () => {
            draft.save({ title: title.value, note: note.value });
            draft.flush();
            status(draft.load() ? 'Draft saved in this tab.' : 'Storage unavailable. Draft could not be saved.');
          }, { signal });
          el.querySelector('[data-empty]').addEventListener('click', () => {
            title.value = ''; note.value = '';
            status('Editor cleared. Your saved draft is still available.');
          }, { signal });
          el.querySelector('[data-load]').addEventListener('click', () => {
            const value = draft.load();
            if (value) { title.value = value.title; note.value = value.note; }
            status(value ? 'Saved draft restored.' : 'No saved draft. Save one first.');
          }, { signal });
          el.querySelector('[data-clear]').addEventListener('click', () => {
            draft.clear(); status('Stored draft deleted. Editor text is unchanged.');
          }, { signal });
          return () => draft.destroy();
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Create an instance with a user/form-specific key and an explicit fields allowlist. save(data) queues a sessionStorage write; load() returns allowed values or null when no valid draft exists. Defaults: 24-hour TTL, 300 ms delay and version 1.

Interface
key, fields allowlist, ttl, delay, version; load/save/flush/clear/destroy.
Lifecycle
flush() persists pending data immediately. clear() removes the draft. destroy() flushes pending data and removes the pagehide listener. Clear after a confirmed save and on logout; change version when the form shape changes.

Accessibility and safety

Implementation notes

Only store explicit non-sensitive fields. Clear on logout and confirmed save. Session storage is accessible to same-origin scripts.

Only store non-sensitive fields. Never persist passwords, payment details or access tokens. Session storage is available to same-origin scripts and may be blocked or unavailable.

What to check

Save allowed and unlisted fields, then restore and verify only the allowlisted fields return. Check expired drafts, version changes, blocked storage and a confirmed save.

View documented module source
/** Explicit allowlist of non-sensitive draft fields. Session storage is tab-scoped.
 * Never store passwords, access codes, tokens, attendee data or payment details.
 * Use a user/form-specific key; clear after successful save or logout. */
export function draftRecovery(key,{fields=[],ttl=86400000,delay=300,version=1}={}){
    const storageKey=`subtly:draft:${key}`,legacyStorageKey=`intently:draft:${key}`;let timer,pending;
    function flush(){clearTimeout(timer);if(!pending)return;try{sessionStorage.setItem(storageKey,JSON.stringify(pending));}catch{/* Storage may be unavailable. */}pending=null;}
    function clear(){clearTimeout(timer);pending=null;try{sessionStorage.removeItem(storageKey);sessionStorage.removeItem(legacyStorageKey);}catch{}}
    function load(){try{const current=sessionStorage.getItem(storageKey);const legacy=current===null?sessionStorage.getItem(legacyStorageKey):null;const d=JSON.parse(current??legacy);if(!d)return null;if(legacy!==null&&current===null){sessionStorage.setItem(storageKey,legacy);sessionStorage.removeItem(legacyStorageKey);}if(d.version!==version||Date.now()-d.savedAt>ttl){clear();return null;}return Object.fromEntries(fields.filter(k=>Object.hasOwn(d.data,k)).map(k=>[k,d.data[k]]));}catch{return null;}}
    window.addEventListener('pagehide',flush);
    return {load,save(data){pending={version,savedAt:Date.now(),data:Object.fromEntries(fields.filter(k=>Object.hasOwn(data,k)).map(k=>[k,data[k]]))};clearTimeout(timer);timer=setTimeout(flush,delay);},flush,clear,destroy(){flush();window.removeEventListener('pagehide',flush);}};
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close