Subtlyv0.1.1
Forms & drafts

unsavedChanges()

Warn before leaving unsaved edits. Navigation warning.

Available in v0.1.1forms.jsForms

Try it

Edit the project note to enable the guard, then save to disable it. After editing, you can use the test link to try leaving. Your browser chooses whether to show a confirmation.

Live example
All changes saved
Test leaving this page

The navigation guard is off.

<div id="your-component">
<label>Project note<textarea rows="3" placeholder="Write a sample note…"></textarea></label><div class="editor-state"><span data-state>All changes saved</span><button data-save>Save note</button></div><a class="text-link" href="install.html">Test leaving this page</a><p class="demo-status" role="status">The navigation guard is off.</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 guard = kit.unsavedChanges();
          const note = el.querySelector('textarea');
          const state = el.querySelector('[data-state]');
          let saved = note.value;
          function update() {
            const dirty = note.value !== saved;
            guard.set(dirty);
            state.textContent = dirty ? 'Unsaved changes' : 'All changes saved';
            state.dataset.dirty = String(dirty);
            status(dirty ? 'Guard enabled. Try the test link or save first.' : 'The navigation guard is off.');
          }
          note.addEventListener('input', update, { signal });
          el.querySelector('[data-save]').addEventListener('click', () => {
            // In production, update the baseline only after a successful server save.
            saved = note.value; update(); status('Note saved locally for this demonstration.');
          }, { signal });
          return () => guard.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 a guard and call set(true) when edits become unsaved. It attaches beforeunload only while dirty. Read dirty for the current flag and call set(false) after the server confirms a save.

Interface
set(boolean), dirty, destroy.
Lifecycle
destroy() removes the navigation warning. A client-side route change needs a separate router or Livewire guard; beforeunload does not cover every application navigation.

Accessibility and safety

Implementation notes

Browser navigation only; SPA route guards require separate integration.

The browser controls warning text and may suppress the prompt, especially on mobile. Pair the guard with recovery or autosave for important work.

What to check

Edit a field and try reloading or leaving the page, then save and repeat. Test your SPA router separately and confirm a successful save removes the guard.

View documented module source
/** Validate after first blur/submission, then immediately while correcting.
 * validate(value, field) returns an error string or empty string.
 * render(message, field) owns error text, aria-invalid and aria-describedby.
 * Never replace server validation. Use explicit submit validation as well. */
export function fieldValidation(field, { validate, render }) {
    let touched = false;
    function check() { const message = validate(field.value, field) || ''; render(message, field); return !message; }
    function blur() { touched = true; check(); }
    function input(event) { if (touched && !event.isComposing) check(); }
    field.addEventListener('blur', blur);
    field.addEventListener('input', input);
    field.addEventListener('compositionend', input);
    return { check() { touched = true; return check(); }, reset() { touched = false; render('', field); }, destroy() {
        field.removeEventListener('blur', blur); field.removeEventListener('input', input); field.removeEventListener('compositionend', input);
    }};
}

/** Pure normalization helpers. Use on blur or server submission, not on
 * every keystroke (which can break caret position and IME input).
 * Email local parts are intentionally not lowercased. */
export const normalize = {
    whitespace: value => value.trim().replace(/\s+/gu, ' '),
    email(value) { const s = value.trim(), i = s.lastIndexOf('@'); return i < 0 ? s : s.slice(0,i+1) + s.slice(i+1).toLowerCase(); },
    phone(value) { return value.trim().replace(/[\s().-]/g, ''); }
};

/** Focus first invalid field after submission; avoids focusing hidden inputs.
 * For custom widgets, supply a selector matching their focusable trigger. */
export function focusInvalid(form, selector = '[aria-invalid="true"], :invalid') {
    const field = [...form.querySelectorAll(selector)].find(e => typeof e.focus === 'function' && e.getClientRects().length && !e.disabled && !e.closest('[inert]'));
    field?.focus();
    return field || null;
}

/** Warn on browser navigation only while a form has unsaved edits.
 * SPA/Livewire route guards need separate integration. Browsers control
 * the warning text and may suppress it, especially on mobile. */
export function unsavedChanges() {
    let dirty = false;
    function warn(e) { e.preventDefault(); e.returnValue = true; }
    function set(value) { if (dirty === Boolean(value)) return; dirty = Boolean(value); if (dirty) window.addEventListener('beforeunload', warn); else window.removeEventListener('beforeunload', warn); }
    return { set, get dirty() { return dirty; }, destroy() { set(false); } };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close