Subtlyv0.1.1
Reference

Complete API reference

Subtly is a small, framework-independent toolkit for thoughtful web interactions. It gives interfaces better timing, clearer feedback and accessible behavior while leaving rendering, state and styling in your hands.

Install

npm install subtly
import { createInteractions, hoverIntent, debounce } from 'subtly';
import 'subtly/styles.css'; // optional structural styles

const interactions = createInteractions();
interactions.start();
// On teardown: interactions.stop();

The floating positioning helper is an optional subpath. Install its peer dependency only if you use it:

npm install @floating-ui/dom
import { floating } from 'subtly/floating';

Subtly ships native ES modules and has no required framework, theme or global listeners. Utilities are opt-in. In a native browser without a bundler, copy src/, use relative module URLs and link the optional stylesheet.

The GitHub Packages mirror uses the registry-required scoped name @afonsoocamacho/subtly; the standard npm package remains the unscoped subtly name. See the distribution guide for GitHub registry setup.

See the HTML-first API, interactive documentation, and publishing guide.

API reference and recipes

Module / export Use it for Lifecycle / options
menu-aim / menuAim Nested menus and mega menus delay=300, tolerance=8; remember pointer on active trigger, request on competing trigger movement, cancel on panel entry or exit, destroy on unmount
hover-intent / hoverIntent Hover cards, navigation delay=150, closeDelay=120, distance=6; returns cleanup
tooltip-group / tooltipGroup Adjacent toolbar tips delay=500, cooldown=300; enter(key,show,hide,{immediate}), leave(key), destroy
floating / floating Flip/shift/size floating panels placement, gap=8, padding=8, onPlacement; returns cleanup
focus / captureFocus Restore focus after dialogs returns restore callback
focus / rovingFocus Composite widget keyboard navigation selector, orientation, wrap; refresh after DOM changes, destroy
scroll-lock / lockScroll Nested overlays returns idempotent release callback
prefetch / intentPrefetch Safe navigation links selector, delay=120, max=12; returns cleanup
optimistic / optimistic Low-risk reversible updates read, write, request, onError; run(next), busy
draft-recovery / draftRecovery Long nonsensitive forms key, fields allowlist, ttl, delay, version; load/save/flush/clear/destroy
motion / motionPreference Reduced motion onChange; duration(ms), reduced, destroy
motion / interruptibleMotion Reversible visual transitions to(target,{duration,easing}), destroy
input-modality / inputModality Last input method onChange; current, destroy
async / debounce Search, draft updates fn, delay; cancel, flush
async / latestRequest Race-free search task(signal,...args); run, cancel, destroy
async / singleFlight Prevent duplicate in-flight submissions task; run, busy; rejects on failure
async / loadingIndicator Avoid spinner flashes render, delay, minVisible; start/stop/destroy
forms / fieldValidation Validate after blur, then on correction field, validate, render; check/reset/destroy
forms / normalize Forgiving input whitespace, email, phone; not full validation
forms / focusInvalid Focus visible invalid field form, optional selector
forms / unsavedChanges Navigation warning set(boolean), dirty, destroy
navigation / typeahead Keyboard prefix search root, items(), label, timeout; returns cleanup
navigation / outsidePress Dismiss on outside pointer press inside() array, dismiss; returns cleanup
navigation / navigationMemory Restore lists, filters, scroll max; save/read/restore/clear
feedback / undoAction Local reversible action apply/revert/commit/duration; start/undo/finish/destroy
feedback / liveAnnouncer Screen reader status priority, parent; announce/destroy; include CSS
pointer / dragIntent Drag threshold and capture threshold, onStart/onMove/onEnd; returns cleanup
performance / staleCache Cached GET data ttl, max; read/clear
performance / nearViewport Lazy secondary content element, initialize, rootMargin; returns cleanup

Safe triangle: wiring contract

Create one menuAim() for each menu level. On pointermove over the active trigger call remember(event). On pointermove over a different trigger call request(event, activePanel, () => activate(id), side, id) with a stable item ID. side is the actual placement (right, left, bottom, top), including after collision flipping. Cancel when entering the panel or leaving the whole menu; use a separate close delay or hover bridge for gaps. Keyboard and click activate immediately, after cancelling pending timers. No roles, visibility or focus are assigned by this utility. Do not rely on hover for touch devices.

Search: debouncing plus cancellation

const search = latestRequest(async (signal, q) => {
    const response = await fetch('/api/search?q=' + encodeURIComponent(q), {signal});
    if (!response.ok) throw new Error('Search failed');
    return response.json();
});
const run = debounce(async q => {
    const result = await search.run(q);
    if (result.status === 'success') renderResults(result.value);
    if (result.status === 'error') renderError(result.error);
}, 250);
// Cancel immediately when input changes so old results cannot flash during debounce.
function onInput(event) { search.cancel(); run(event.target.value); }
// On unmount: run.cancel(); search.destroy();

Forms: validate without punishing early

const field = document.querySelector('#email');
const error = document.querySelector('#email-error');
const validation = fieldValidation(field, {
    validate: (value, input) => !value.trim() ? 'Enter your email.' :
        input.validity.typeMismatch ? 'Enter a valid email address.' : '',
    render(message, input) {
        error.textContent = message;
        input.setAttribute('aria-invalid', String(Boolean(message)));
    }
});
// Add aria-describedby="email-error" to field and ix-error-slot to error.
// On submit check all fields; focusInvalid(form) on failure.
// Retain field values after failed server requests. Destroy on unmount.

Drafts and unsaved changes

const drafts = draftRecovery('project:user-id:editor', {fields:['title','description'],version:1});
const initial = drafts.load(); // restore only after offering user a choice
// On edit: drafts.save({title,description});
// On successful server save or logout: drafts.clear();
// On unmount: drafts.destroy(); // flushes pending draft

Only store explicitly approved non-sensitive fields, including nested content. Session storage is accessible to scripts on the same origin; never store credentials, access tokens, personal records or payment information. Scope keys by project, user and form. Clear on logout. Storage errors are silently tolerated. For durable or cross-device drafts use authenticated server storage instead.

Optimistic state and undo

const favorite = optimistic({
    read: () => state.saved,
    write: saved => { state.saved = saved; render(); },
    request: async saved => { /* replace with actual API call; throw on failure */ },
    onError: () => showError('Could not save your preference.')
});
// await favorite.run(!state.saved);

For undoAction, apply changes locally and commit only after the undo window. Call finish explicitly if the operation must complete before navigation. destroy cancels pending local previews, not committed writes. Surface failures. Never claim payment, admission, booking, inventory or permission changes succeeded until the server confirms. Use server-side idempotency and authorization.

Framework integration

Additional UX patterns that need no JavaScript utility

Use :focus-visible for focus rings; inert for inactive regions (do not duplicate native dialog behaviour); native <dialog> or a tested accessible modal; aria-expanded and aria-controls on disclosure buttons; native form labels and autocomplete; inputmode for appropriate keyboards; explicit image dimensions or aspect-ratio; scroll-margin-top for anchored content; overscroll-behavior:contain on scrollable panels; scrollbar-gutter:stable for layout stability; responsive 44px targets where practical; visible labels and meaningful errors; preserve text selection and caret; use CSS transitions for simple reversible motion; View Transitions as progressive enhancement, not required navigation; prioritize essential content before lazy secondary widgets. Conditional disclosure must remove hidden fields from required validation and must not silently submit irrelevant data.

Testing checklist

Run npm test and npm run check (the latter requires a Unix-like shell). Open examples/index.html through a local static server from the kit directory, for example python3 -m http.server 8000. Test keyboard-only, mouse, touch and pen; zoom to 200%; RTL; reduced motion; slow network and offline errors; nested overlays; viewport edges; screen reader announcements; unmount/reopen; back navigation and logout. Ensure no controls are obstructed by invisible bridges. Test real iOS Safari scroll locking and virtual keyboard. Avoid layering these utilities over an existing component that already implements the same feature.

The included automated tests cover selected state, timing and geometry logic, not full browser behaviour or framework integration. The examples are illustrative, not complete accessible menu/dialog implementations. No general-purpose focus trap is provided: use native dialog or a mature accessibility library. Defaults are starting points, not universal UX rules.

Documentation website

Visit the public Next.js documentation website for guides and interactive examples. WEBSITE.md describes the older static GitHub Pages copy retained in this repository.

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close