DocsReference
Get started

Search Subtly documentation

Search by a task, helper name or framework.

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

Terminal
npm install subtly
JavaScript
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:

Terminal
npm install @floating-ui/dom
JavaScript
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 / exportUse it forLifecycle / options
menu-aim / menuAimNested menus and mega menusdelay=300, tolerance=8; remember pointer on active trigger, request on competing trigger movement, cancel on panel entry or exit, destroy on unmount
hover-intent / hoverIntentHover cards, navigationdelay=150, closeDelay=120, distance=6; returns cleanup
tooltip-group / tooltipGroupAdjacent toolbar tipsdelay=500, cooldown=300; enter(key,show,hide,{immediate}), leave(key), destroy
floating / floatingFlip/shift/size floating panelsplacement, gap=8, padding=8, onPlacement; returns cleanup
focus / captureFocusRestore focus after dialogsreturns restore callback
focus / rovingFocusComposite widget keyboard navigationselector, orientation, wrap; refresh after DOM changes, destroy
scroll-lock / lockScrollNested overlaysreturns idempotent release callback
prefetch / intentPrefetchSafe navigation linksselector, delay=120, max=12; returns cleanup
optimistic / optimisticLow-risk reversible updatesread, write, request, onError; run(next), busy
draft-recovery / draftRecoveryLong nonsensitive formskey, fields allowlist, ttl, delay, version; load/save/flush/clear/destroy
motion / motionPreferenceReduced motiononChange; duration(ms), reduced, destroy
motion / interruptibleMotionReversible visual transitionsto(target,{duration,easing}), destroy
input-modality / inputModalityLast input methodonChange; current, destroy
async / debounceSearch, draft updatesfn, delay; cancel, flush
async / latestRequestRace-free searchtask(signal,...args); run, cancel, destroy
async / singleFlightPrevent duplicate in-flight submissionstask; run, busy; rejects on failure
async / loadingIndicatorAvoid spinner flashesrender, delay, minVisible; start/stop/destroy
forms / fieldValidationValidate after blur, then on correctionfield, validate, render; check/reset/destroy
forms / normalizeForgiving inputwhitespace, email, phone; not full validation
forms / focusInvalidFocus visible invalid fieldform, optional selector
forms / unsavedChangesNavigation warningset(boolean), dirty, destroy
navigation / typeaheadKeyboard prefix searchroot, items(), label, timeout; returns cleanup
navigation / outsidePressDismiss on outside pointer pressinside() array, dismiss; returns cleanup
navigation / navigationMemoryRestore lists, filters, scrollmax; save/read/restore/clear
feedback / undoActionLocal reversible actionapply/revert/commit/duration; start/undo/finish/destroy
feedback / liveAnnouncerScreen reader statuspriority, parent; announce/destroy; include CSS
pointer / dragIntentDrag threshold and capturethreshold, onStart/onMove/onEnd; returns cleanup
performance / staleCacheCached GET datattl, max; read/clear
performance / nearViewportLazy secondary contentelement, 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

JavaScript
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

JavaScript
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

JavaScript
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

JavaScript
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

  • Alpine: create utilities in init() and release them in destroy(). Use $nextTick for a newly rendered floating panel. Livewire morphing may replace nodes; reinitialize only changed widgets. Avoid duplicate listeners.
  • React: initialize in useEffect, return cleanup, use refs for latest callbacks/state. Do not create DOM utilities during rendering. Prefer existing accessible primitives where available.
  • Vue: initialize in onMounted, release in onBeforeUnmount, use nextTick for conditional elements.
  • Vanilla: initialize on DOMContentLoaded or use a module script; keep cleanup references for dynamically removed widgets.

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

See the website editing and publishing instructions for the separate Next.js website. Its editable sources are MDX pages and JavaScript examples, with GitHub Actions verifying changes and Vercel building the public website. The original library repository's WEBSITE.md and generated docs/ describe its legacy static deployment.