npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@form-guardian/dom

v1.0.5

Published

Universal DOM-based form autosave library. Works with any form library (React, Vue, Angular, Svelte) or vanilla HTML forms. Provides attachFormAutosave function with analytics events, batching, and automatic draft restoration.

Readme

@form-guardian/dom

Universal DOM-based form autosave library. Works with any form library (React, Vue, Angular, Svelte) or vanilla HTML forms. Provides attachFormAutosave function with analytics events, batching, and automatic draft restoration.

Overview

@form-guardian/dom is the universal package for form autosave. It works by attaching event listeners to DOM elements, making it compatible with any JavaScript framework or vanilla HTML. It automatically saves form values as users type and can restore them when the form is loaded again.

Installation

npm install @form-guardian/dom

Features

  • Universal Compatibility - Works with React, Vue, Angular, Svelte, or vanilla HTML
  • Automatic Saving - Saves form values as users type (debounced)
  • Automatic Restoration - Optionally restores drafts on form load
  • Analytics Events - Callbacks for onBeforeSave, onAfterSave, onBeforeRestore, onAfterRestore, onDraftExpired
  • Batching - Save changes in batches to reduce storage operations
  • Field Filtering - Blacklist/whitelist specific fields
  • Type Safety - Full TypeScript support with generic types

Quick Start

Vanilla JavaScript

import { attachFormAutosave } from '@form-guardian/dom';

const form = document.querySelector('#my-form');

const autosave = attachFormAutosave({
  formId: 'contact-form',
  root: form,
  autoRestore: true,
  debounceMs: 500,
  onAfterSave: (values) => {
    console.log('Draft saved:', values);
  }
});

// Clear draft on successful submit
form.addEventListener('submit', async () => {
  await autosave.clear();
});

React

import { useEffect, useRef } from 'react';
import { attachFormAutosave } from '@form-guardian/dom';

function MyForm() {
  const formRef = useRef<HTMLFormElement>(null);

  useEffect(() => {
    if (!formRef.current) return;

    const autosave = attachFormAutosave({
      formId: 'my-form',
      root: formRef.current,
      autoRestore: true,
      onAfterSave: (values) => {
        console.log('Saved:', values);
      }
    });

    return () => {
      autosave.destroy();
    };
  }, []);

  return <form ref={formRef}>...</form>;
}

API

attachFormAutosave<T>(options)

Attach autosave functionality to a form element.

Options

  • formId (required) - Unique identifier for the form
  • root (required) - Form or container element
  • autoRestore (optional) - Automatically restore draft on mount (default: false)
  • debounceMs (optional) - Debounce delay in milliseconds (default: 500)
  • ttl (optional) - Time to live for drafts
  • blacklist (optional) - Array of CSS selectors for fields to exclude
  • whitelist (optional) - Array of CSS selectors for fields to explicitly include
  • batchSaveInterval (optional) - Save changes in batches (milliseconds)
  • onBeforeSave (optional) - Callback before saving
  • onAfterSave (optional) - Callback after saving
  • onBeforeRestore (optional) - Callback before restoring
  • onAfterRestore (optional) - Callback after restoring
  • onDraftExpired (optional) - Callback when draft expires

Returns

A FormAutosaveHandle object with methods:

  • restore() - Manually restore the draft
  • clear() - Clear the draft
  • destroy() - Remove event listeners and cleanup
  • getCurrentValues() - Get current form values
  • hasDraft() - Check if draft exists
  • getDraftMeta() - Get draft metadata

Examples

With Analytics

const autosave = attachFormAutosave({
  formId: 'checkout-form',
  root: form,
  onBeforeSave: async (values) => {
    // Track save attempt
    analytics.track('draft_save_started', { formId: 'checkout-form' });
  },
  onAfterSave: async (values) => {
    // Track successful save
    analytics.track('draft_saved', { formId: 'checkout-form', fieldCount: Object.keys(values).length });
  },
  onDraftExpired: async (draftId) => {
    // Track expiration
    analytics.track('draft_expired', { draftId });
  }
});

With Batching

const autosave = attachFormAutosave({
  formId: 'large-form',
  root: form,
  batchSaveInterval: 5000, // Save every 5 seconds
  onAfterSave: (values) => {
    console.log('Batch saved:', values);
  }
});

Field Filtering

const autosave = attachFormAutosave({
  formId: 'secure-form',
  root: form,
  // Exclude password fields and sensitive data
  blacklist: [
    '[data-no-save]',
    'input[name="password"]',
    'input[name="ssn"]'
  ],
  // But allow specific safe fields
  whitelist: [
    'input[data-safe]',
    'textarea[data-safe]'
  ]
});

TypeScript with Custom Types

interface ContactFormData {
  name: string;
  email: string;
  phone: string;
  message: string;
}

const autosave = attachFormAutosave<ContactFormData>({
  formId: 'contact-form',
  root: form,
  onAfterSave: (values) => {
    // values is typed as ContactFormData
    console.log(values.name); // TypeScript knows this exists
  }
});

Field Selection

By default, the library tracks:

  • <input> elements (except type="submit", type="button", type="reset", type="password")
  • <textarea> elements
  • Elements with contenteditable="true"

Fields are identified by:

  1. name attribute (preferred)
  2. id attribute
  3. data-fg-key attribute

When to Use

Use @form-guardian/dom if you:

  • Want universal compatibility with any framework
  • Need fine-grained control over autosave behavior
  • Are building a custom form solution
  • Want to use analytics events and batching

For React applications, consider using @form-guardian/react for a more React-idiomatic API with hooks.