@robonen/vue

A collection of 213+ tree-shakeable, SSR-safe composables for Vue 3 — reactive primitives for state, sensors, the DOM, browser APIs, animation, forms and more.

Every Vue app ends up re-implementing the same building blocks: a toggle, a debounced ref, an event listener that cleans itself up, a media query, local-storage state. @robonen/vue ships those building blocks as small, composable functions with a consistent API. Each one is independently tree-shakeable, written in TypeScript with full inference, and safe to call during server-side rendering — guards for window, document and navigator are built in, so the same code runs on the server and hydrates cleanly on the client.

Tree-shakeable by design

Import only what you use. Each composable lives on its own and pulls in nothing it doesn't need — your bundle stays exactly as small as your usage.

SSR-safe out of the box

Browser-only access is guarded behind lifecycle hooks and configurable window/document targets, so Nuxt and SSR setups just work.

Fully typed

Written in TypeScript with precise return types and generics. MaybeRefOrGetter arguments mean you can pass plain values, refs or getters interchangeably.

Broad coverage

From state and reactivity to sensors, elements, storage, math and form handling — one cohesive toolkit spanning the whole surface of a Vue app.

Install

sh
pnpm add @robonen/vue

Quick start

Import the composables you need and use them inside <script setup>. Here's a counter clamped to a range, with auto-cleaning keyboard shortcuts:

ts
import { useCounter, useEventListener, useToggle } from '@robonen/vue';

// Clamped, reactive counter
const { count, increment, decrement, reset } = useCounter(0, { min: 0, max: 10 });

// A boolean toggle with custom truthy/falsy values
const { value: theme, toggle } = useToggle('light', {
  truthyValue: 'dark',
  falsyValue: 'light',
});

// Listener is removed automatically on unmount
useEventListener('keydown', (e) => {
  if (e.key === 'ArrowUp') increment();
  if (e.key === 'ArrowDown') decrement();
});

The same useCounter running live:

Where to next

The full API reference is listed right below. A few good starting points:

  • useCounter — a clamped, reactive counter with increment / decrement / set / reset.
  • useToggle — a boolean toggle with customizable truthy / falsy values.
  • useEventListener — declarative event listeners that clean up on unmount.
  • useStorage — reactive state synced to localStorage / sessionStorage.
  • useMagicKeys — reactive keyboard state for building shortcuts.

animation · 16

fn
formatDatedemo

Format a `Date` against a token string. Exposed for one-shot, non-reactive formatting; {@link useDateFormat} wraps this in a `computed`.

fn
formatTimeAgodemo

Pure (non-reactive) relative-time formatter. Useful on its own and reused by `useTimeAgo` on every tick.

fn
normalizeDatedemo

Coerce a {@link DateLike} into a `Date`. `null`/`undefined` become the current time; a non-UTC string is parsed leniently so partial dates such as `'2024-3'` are accepted.

V
TransitionPresetsdemo

Common cubic bezier easing presets (same curves as CSS / VueUse).

fn
useAnimatedemo

Reactive [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) wrapper for a single element. Exposes imperative controls (`play`, `pause`, `reverse`, `finish`, `cancel`) alongside reactive state (`playState`, `currentTime`, `playbackRate`, ...). The reactive state is synced via `requestAnimationFrame` only while the animation is running, so an idle animation costs nothing. SSR-safe: nothing touches the DOM until the element resolves.

fn
useCountdowndemo

Reactive countdown timer exposing the remaining seconds plus `start`/`stop`/`pause`/`resume`/`reset` controls and `onTick`/`onComplete` callbacks. Built on `useIntervalFn`, so it is SSR-safe and cleans up on scope dispose.

fn
useDateFormatdemo

Reactively format a `Date`, timestamp, or date string against a token string (`YYYY MM DD HH mm ss SSS dddd A` etc.). Recomputes when the date, format, or locale changes.

fn
useIntervaldemo

Reactive counter that increments on every interval tick.

fn
useIntervalFndemo

Call a function on every interval. Supports reactive interval duration, pause/resume, and automatic cleanup on scope dispose.

fn
useNowdemo

Reactive current `Date`, updated via `requestAnimationFrame` or a fixed interval.

fn
useRafFndemo

Call a function on every `requestAnimationFrame` with delta time tracking. Automatically cleans up when the component scope is disposed.

fn
useTimeAgodemo

Reactive relative time string (e.g. `'3 minutes ago'`) that ticks on a fixed interval. Fully customizable messages (i18n), units, rounding, and an automatic fallback to a full date once `max` is exceeded.

fn
useTimeoutdemo

Reactive boolean that flips to `true` after a given delay. Built on `useTimeoutFn`; optionally exposes `start`/`stop` controls. SSR-safe.

fn
useTimeoutFndemo

Call a function after a given delay, with manual `start`/`stop` control and a reactive `isPending` flag. SSR-safe and cleans up on scope dispose.

fn
useTimestampdemo

Reactive current timestamp, updated via `requestAnimationFrame` or a fixed interval.

fn
useTransitiondemo

Reactively transition between numeric values (or numeric arrays) over a duration with configurable easing. Wraps a single, paused `requestAnimationFrame` loop that only runs while a transition is in flight, so it is cheaper than re-creating an RAF loop per change. SSR-safe: without a `window` the output tracks the source synchronously.

array · 13

browser · 41

V
breakpointsAntDesigndemo

Ant Design default breakpoints.

V
breakpointsBootstrapV5demo

Bootstrap v5 default breakpoints.

V
breakpointsTailwinddemo

Tailwind CSS default breakpoints.

V
breakpointsVuetifyV3demo

Vuetify v3 default breakpoints.

fn
broadcastedRefdemo

Creates a custom ref that syncs its value across browser tabs via the BroadcastChannel API

fn
useBreakpointsdemo

Reactive viewport breakpoints derived from a breakpoints map. SSR-safe (resolves width queries from `ssrWidth` before `matchMedia` exists), reactive to breakpoint values, and built on a single `useMediaQuery` per comparison. Comes with presets: `breakpointsTailwind`, `breakpointsBootstrapV5`, `breakpointsAntDesign`, `breakpointsVuetifyV3`.

fn
useClipboarddemo

Reactive async Clipboard API.

fn
useClipboardItemsdemo

Reactive async Clipboard API with rich `ClipboardItem` support (read/write images, HTML, and arbitrary MIME types — not just text). SSR-safe; uses passive `copy`/`cut` listeners and guards stale async writes.

fn
useCloseWatcherdemo

Wrap the native `CloseWatcher` API to handle close requests (the `Esc` key or the Android back gesture). Falls back to listening for `Escape` keydown when `CloseWatcher` is unavailable. SSR-safe.

fn
useColorModedemo

Reactive color mode (`light` / `dark` / `auto`) with system detection, storage persistence, and automatic application of a class or attribute to a target element.

fn
useCssVardemo

Read and write a CSS custom property on an element as a reactive ref. Defaults to `document.documentElement`. Set `observe` to react to external changes via a `MutationObserver`.

fn
useDarkdemo

Reactive dark mode boolean with system detection and storage persistence, built on `useColorMode`. Writing `false` while the system already prefers light (or `true` while it prefers dark) falls back to `'auto'`, so the mode keeps tracking the OS preference.

fn
useDocumentPiPdemo

Reactive wrapper around the [Document Picture-in-Picture API](https://developer.mozilla.org/en-US/docs/Web/API/DocumentPictureInPicture) for rendering arbitrary DOM in an always-on-top window.

fn
useEventListenerdemo

Registers an event listener using the `addEventListener` on mounted and removes it automatically on unmounted Overload 1: Omitted window target

fn
useEyeDropperdemo

Reactive wrapper around the [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper) for picking colors from the screen.

fn
useFavicondemo

Reactive favicon.

fn
useFileDialogdemo

Open a native file dialog programmatically and reactively track the selected files.

fn
useFileSystemAccessdemo

Create, read, and write local files via the File System Access API.

fn
useFullscreendemo

Reactive Fullscreen API for an element (or the document element). Handles vendor-prefixed fallbacks for request/exit/state detection and syncs `isFullscreen` from `fullscreenchange` events. SSR-safe.

fn
useImagedemo

Reactively load an image in the browser; await the result to render it or show a fallback.

fn
useLocalFontsdemo

Reactive wrapper around the [Local Font Access API](https://developer.mozilla.org/en-US/docs/Web/API/Local_Font_Access_API) for enumerating the user's locally installed fonts.

fn
useMediaQuerydemo

Reactive `window.matchMedia`. SSR-safe, reactive to the query, and with optional SSR width resolution for `min-width` / `max-width` queries.

fn
useObjectUrldemo

Create and auto-revoke an object URL for a `Blob`, `File`, or `MediaSource`. The previous URL is revoked whenever the source changes, and the active URL is revoked on scope dispose.

fn
useOtpCredentialsdemo

Reactive, SSR-safe wrapper around the [WebOTP API](https://developer.mozilla.org/en-US/docs/Web/API/WebOTP_API) (`navigator.credentials.get({ otp })`) for auto-reading one-time passwords delivered by SMS. Exposes the received `code`, in-flight/error state, `receive()`/`abort()` controls, and `onReceive`/`onError` hooks. Pairs with an `<input autocomplete="one-time-code">`.

fn
usePermissiondemo

Reactive Permissions API state.

fn
usePreferredColorSchemedemo

Reactive `prefers-color-scheme` media query.

fn
usePreferredContrastdemo

Reactive `prefers-contrast` media query, resolving to the user's preferred contrast level. SSR-safe with an optional SSR fallback value.

fn
usePreferredDarkdemo

Reactive `prefers-color-scheme: dark` media query.

fn
usePreferredLanguagesdemo

Reactive `navigator.languages`. Tracks the user's preferred languages and updates automatically whenever the browser emits a `languagechange` event. Falls back to `['en']` during SSR or when no `window` is available, so the returned value is always a non-empty array.

fn
usePreferredReducedMotiondemo

Reactive `prefers-reduced-motion` media query, resolving to `'reduce'` when the user requests reduced motion and `'no-preference'` otherwise. SSR-safe via {@link useMediaQuery}.

fn
usePreferredReducedTransparencydemo

Reactive `prefers-reduced-transparency` media query, resolving to `'reduce'` or `'no-preference'`. SSR-safe (defaults to `'no-preference'`).

fn
useScriptTagdemo

Dynamically inject and manage a `<script>` tag. The returned `load`/`unload` controls append the element to the document `<head>` (reusing an existing tag with the same `src`) and resolve once the script has loaded. Loading is de-duplicated, listeners are passive, and everything is SSR-safe.

fn
useSharedemo

Reactive Web Share API wrapper to invoke the native share sheet.

fn
useStyleTagdemo

Inject a reactive `<style>` tag into the document `<head>`. The CSS is a writable ref — assigning to it updates the live stylesheet. Multiple instances sharing an `id` reuse a single element via reference counting, and everything is SSR-safe.

fn
useTabLeaderdemo

Elects a single leader tab using the Web Locks API. Only one tab at a time holds the lock for a given key. When the leader tab closes or the scope is disposed, another tab automatically becomes the leader.

fn
useTextareaAutosizedemo

Auto-resizes a `<textarea>` to fit its content. Reacts to user input, programmatic content changes, and element resize. Reuses `useEventListener` for a passive, auto-cleaned `input` listener and `useResizeObserver` to re-measure when the textarea's width changes (so reflowed text is re-fitted). SSR safe.

fn
useTitledemo

Reactive `document.title`. Pass a getter to derive the title from other reactive state (returns a read-only ref), or a plain value/ref for two-way binding.

fn
useUrlSearchParamsdemo

Reactive `URLSearchParams` exposed as a plain reactive object. Reads from and (optionally) writes back to the URL using the `history`, `hash`, or `hash-params` location source. Listens for `popstate`/`hashchange` with passive listeners and pauses its own writer while syncing to avoid feedback loops. SSR-safe: returns the seeded reactive object when no `window` is available.

fn
useVibratedemo

Reactive wrapper around the `navigator.vibrate` Vibration API.

fn
useWakeLockdemo

Reactive wrapper over the Screen Wake Lock API to keep the screen awake. Re-acquires a deferred lock automatically when the document returns to visible.

fn
useWebNotificationdemo

Reactive, SSR-safe wrapper around the Web Notification API with permission handling and `onClick`/`onShow`/`onError`/`onClose` event hooks.

component · 6

fn
createReusableTemplatedemo

Define a template once and reuse it multiple times within the same component. Returns a `[DefineTemplate, ReuseTemplate]` pair (also destructurable as `{ define, reuse }`). The template captured by `DefineTemplate`'s default slot is rendered wherever `ReuseTemplate` appears, receiving its props/attrs as slot bindings. Supports a generic for typed bindings, typed slots, custom `props`, and `inheritAttrs`. Render-only and fully SSR-safe — it never touches `window`/`document`. The pair is created lazily and shares a single `shallowRef` for the captured render function, so there are no watchers and no per-render allocations beyond the vnode itself.

fn
unrefElementdemo

Unwraps a Vue element reference to get the underlying instance or DOM element.

fn
useCurrentElementdemo

Reactive root DOM element of the current component instance. Resolves to `vm.$el` (or the unwrapped `rootComponent` ref when provided) and is re-read on `onMounted` and `onUpdated` via a controlled computed — so it stays correct across re-renders without an always-on watcher. Generic over the element type; the type is inferred from the component's `$el` when available. SSR-safe: returns `undefined` until the component is mounted on the client.

fn
useForwardExposedemo

Forwards a child component's exposed API and DOM element (`$el`) through the parent component. Useful for wrapper / headless components that need to transparently proxy the inner component's ref to the consumer. Merges the parent's own props and any prior `expose()` bindings onto `instance.exposed`, then updates them when `forwardRef` is called with a child element or component instance.

fn
useTemplateRefsListdemo

Collects a dynamic list of template refs for use with `v-for`. Automatically clears the list before each component update and repopulates it with fresh element references. Handles both plain DOM elements and Vue component instances (unwraps `$el`). Uses a non-reactive buffer internally to collect refs during the render cycle, then flushes to a `shallowRef` in `onMounted`/`onUpdated` to avoid triggering recursive update loops.

fn
useVirtualListdemo

Virtualize a large list with dynamically measured item sizes. Rows render at their natural size: layout starts from `estimateSize` and is corrected by a shared ResizeObserver, which fires after layout but before paint, so corrections are not visible as flicker. Offsets come from a Fenwick tree (O(log n) hot paths). When an item above the viewport changes size — or the list is prepended to — the scroll position is compensated so content does not jump; the compensation write is deferred until after the DOM patch (still pre-paint) so it is never clamped by a stale wrapper height. Supports vertical and horizontal (LTR) layouts, `gap`/paddings, an external `scrollElement`, `followOutput` chat pinning, `scrollTo` with nearest-edge `'auto'` alignment, and SSR via `initialContainerSize`. Non-goals (by design): window as scroller (element scrollers only), RTL horizontal mode, reactive options (only the source and `scrollElement` are reactive), pixel-perfect `behavior: 'smooth'` landings.

debug · 2

elements · 17

fn
onElementRemovaldemo

Fire a callback when the target element — or any ancestor containing it — is removed from the DOM. Backed by a single `childList`/`subtree` `MutationObserver` on the element's owning document, so it also catches removal of a parent further up the tree.

fn
useActiveElementdemo

Reactive `document.activeElement`, traversing open shadow roots.

fn
useDocumentReadyStatedemo

Reactive `document.readyState` (`loading` | `interactive` | `complete`), updated on `readystatechange`.

fn
useDocumentVisibilitydemo

Reactive `document.visibilityState`.

fn
useDraggabledemo

Make an element draggable by pointer, tracking its position with optional axis locking, a drag handle, container constraints, and lifecycle callbacks. SSR-safe and built on passive pointer listeners.

fn
useDropZonedemo

Create a drag-and-drop file drop zone on a target element or document.

fn
useElementBoundingdemo

Reactive bounding box of an element (`getBoundingClientRect`), kept in sync via `ResizeObserver`, `MutationObserver`, and window scroll/resize. Supports deferring reads to the next animation frame to avoid layout thrash.

fn
useElementSizedemo

Reactive size of an element, backed by `ResizeObserver`. Measures synchronously on mount, handles SVG elements via `getBoundingClientRect`, and sums multiple box fragments (e.g. multi-column layouts).

fn
useElementVisibilitydemo

Track whether an element is visible within the viewport (or a custom scroll root), backed by `IntersectionObserver`.

fn
useFocusGuarddemo

Adds a pair of focus guards at the boundaries of the DOM tree to ensure consistent focus behavior

fn
useIntersectionObserverdemo

Detect when an element enters or leaves the viewport via `IntersectionObserver`. Accepts a single target, an array of targets, or a ref/getter resolving to either, plus reactive `rootMargin` and `threshold`.

fn
useMutationObserverdemo

Watch for changes to the DOM tree via `MutationObserver`. Accepts a single target, an array of targets, or a getter returning either.

fn
useParentElementdemo

Reactive `parentElement` of a given element (or the current component instance's root element when no target is supplied). Resolves the target through `unrefElement`, so it accepts plain elements, template refs, component instances, getters and computed refs. A single `immediate` watcher tracks the resolved target and re-reads its parent only when the element itself changes — no extra lifecycle hooks or always-on observers. SSR-safe: stays `undefined` until the target is resolved on the client.

fn
useResizeObserverdemo

Reports changes to the dimensions of an element via `ResizeObserver`. Accepts a single target or an array of (reactive) targets. The observer is recreated only when the resolved elements change, and can be paused/resumed.

fn
useWindowFocusdemo

Reactively track whether the window is focused via `focus`/`blur` events.

fn
useWindowScrolldemo

Reactive window scroll position with arrived/direction tracking. Writing to `x`/`y` scrolls the window.

fn
useWindowSizedemo

Reactive window size. Tracks the inner viewport, the outer window, or the visual viewport (pinch-zoom aware), and reacts to resize and orientation changes.

forms · 33

fn
applyOverwriteMode

Under a collapsed caret, `replace` extends the selection to cover the next `newCharacters.length` characters (so they are overwritten); `shift` leaves it collapsed (pure insert). An existing range is returned untouched.

fn
areElementStatesEqual

Deep value + selection equality, used as the no-op-change guard.

fn
calibrateValueByMask

Entry point: conform `state.value` to `mask`. Fast-returns when the value is already a valid prefix, otherwise dispatches to the array or RegExp guesser.

fn
collectFixedCharacters

Collect the contiguous run of fixed (literal) characters starting at `startIndex`, stopping at the first matcher slot or the end of the mask. These are auto-inserted before the next typed character (and a literal the user happens to type is harmlessly dropped at the following matcher slot).

V
DEFAULT_MASK_TOKENS

Default {@link maskFromTemplate} tokens: `#` → digit, `A` → letter, `*` → letter or digit. Every other template character is a fixed literal.

fn
guessValidValueByPattern

Conform a value to an array mask slot-by-slot: auto-insert fixed characters, accept matcher slots one character at a time, drop characters that don't fit, and track the caret in masked-output coordinates.

fn
guessValidValueByRegExp

Conform a value to a single-RegExp mask: keep the greedy prefix for which the value still matches, dropping the first character that breaks the pattern.

fn
isFixedCharacter

Whether a mask slot is a fixed (literal) character rather than a matcher.

fn
isMaskComplete

Whether `value` fully satisfies the mask (array: every slot filled).

V
MASK_NOOP

Thrown by {@link MaskModel} mutations that produce no change, so callers can swallow the gesture (e.g. typing a fixed character that is already present) without polluting input/undo history.

fn
maskCardOptions

A dynamic payment-card mask that groups digits by the detected brand. The mask is a function of state: it reads the digits, resolves the brand via {@link findCardBrand} (by IIN/BIN prefix), and applies that brand's grouping template (e.g. `#### ###### #####` for Amex) — falling back to a generic 16-digit grouping until a brand is recognized. The unmasked value is the digit string.

fn
maskDateOptions

Mask options for a date. Auto-inserts separators and clamps fully-typed day/month segments (day ≤ 31, month ≤ 12). No calendar/timezone validation — pair with a schema for that.

fn
maskFromTemplate

Compile a human-readable template into a mask array. Token characters become matcher slots; everything else becomes a fixed literal. With the default tokens the compiled array is cached and shared (frozen) per template string; pass a custom `tokens` map to opt out.

C
MaskModel

The stateful masking model. Holds the masked `value`/`selection` and performs insertions/deletions in **unmasked space** (fixed characters stripped) before re-calibrating to the masked form — the device that makes backspacing across fixed characters and `overwriteMode` correct.

fn
maskNumberOptions

Mask options for a formatted number: optional thousands grouping, decimal precision, sign, prefix/postfix, and a live upper-bound clamp. The unmasked value is the canonical, separator-free number string.

fn
maskPhoneCountryOptions

A dynamic phone mask that switches format based on the typed country dialing code. The mask is a function of state: it reads the leading digits, resolves the country via {@link findPhoneCountry} (dialing code → area code → priority), and applies that country's template — falling back to a generic international template until a code is recognized. Defaults to the full {@link PHONE_COUNTRIES} set. The unmasked value is the digit string.

fn
maskPhoneOptions

Mask options for a phone number, built from a single template string. For a mask that adapts to the typed country code, see {@link maskPhoneCountryOptions}.

fn
maskTransform

Pure, DOM-free masking: conform a string (or {@link ElementState}) through the full preprocessor → mask → postprocessor pipeline. Ideal for SSR, server-side validation, and tests. Returns a `string` for string input and an {@link ElementState} for state input.

fn
normalizeMaskOptions

Normalize the friendly authoring union to full {@link MaskOptions}: a template string is compiled via {@link maskFromTemplate}, a bare mask is wrapped, and full options pass through.

fn
removeFixedMaskCharacters

Strip fixed mask characters from a (masked) state, returning the raw value and the selection remapped into that unmasked space. RegExp masks have no fixed characters, so the state is returned unchanged.

fn
resolveMask

Resolve a (possibly dynamic) mask to a concrete {@link MaskExpression}.

fn
resolveMaskOptions

Apply {@link MaskOptions} defaults.

fn
resolveOverwriteMode

Resolve a (possibly function) {@link OverwriteMode} to a concrete value.

fn
runPostprocessors

Run the postprocessor chain against `initialState`.

fn
runPreprocessors

Run the preprocessor chain, threading `{ elementState, data }`.

fn
unmask

The masked → raw bridge: strip a mask's fixed characters from a masked string, without needing a DOM element. RegExp masks have no fixed characters, so the value is returned unchanged.

fn
useFielddemo

Bind a single field by path. When rendered under a {@link useForm}(or given an explicit `form`), it reads/writes that form's state; otherwise it runs standalone with its own value, errors, and validation. Returns a writable `value`, reactive errors/meta, blur/change handlers, and `attrs` to spread.

fn
useFieldArraydemo

Manage a dynamic array field within a {@link useForm}. Exposes a reactive `fields` list with **stable keys** (preserved across reorders, so `v-for :key` keeps DOM/state intact) plus immutable `push`/`prepend`/`insert`/ `remove`/`move`/`swap`/`replace`/`update` operations that also re-key the matching errors and touched state.

fn
useFormdemo

Headless, performant form state management. Holds reactive `values`, flat path-keyed `errors`/touched maps, derived `meta`, and a full set of mutation/validation/submit/reset helpers. Validation accepts a [Standard Schema](https://github.com/standard-schema/standard-schema) (zod/valibot/arktype), a custom resolver, or per-field function validators.

fn
useFormContextdemo

Retrieve the {@link useForm} instance provided by an ancestor, for building field components that live anywhere in the form's subtree. Returns `null` when no form has been provided (so callers can support standalone use).

fn
useMaskedFielddemo

A masked form field: fuses {@link useField} with {@link useMaskedInput} so a formatted value is shown while the form stores the raw value (validation, dirty/touched, schema, and submit all read raw). Returns a single `bind` object to spread onto the input — it merges the field's `name`/`onBlur`/`aria-invalid` with the mask bindings (ref + handlers). Purely additive — it composes the existing form composables without modifying them.

fn
useMaskedInputdemo

Headless input masking. Returns a `bind` object to spread onto an `<input>`/`<textarea>` (`<input v-bind="bind">`) — it carries the template ref and the event handlers, so there is no separate ref wiring. Conforms the value on every keystroke (insert/delete/paste/IME) with a correct caret, and exposes the `masked`/`unmasked` views plus a `complete` signal.

fn
validateValueWithMask

Whether `value` is a valid (possibly partial) prefix of the mask. Used as the conform fast-path and to derive a `complete` signal at full length.

general · 43

fn
assignStyle

Merges a style patch onto an element's inline `style` and returns a cleanup function that restores the element's entire previous `cssText`. Unlike {@link setStyle}, the snapshot is the full `cssText`, so the cleanup is an all-or-nothing revert — handy for scoped effects.

fn
createGuardAttrs
fn
decodeCookieValue

Decodes a cookie value: unwraps an RFC 6265 DQUOTE-wrapped value (the quotes are transport dressing, not payload), then decodes percent-escapes. Malformed escapes (e.g. third-party cookies that never used percent-encoding) are returned as-is instead of throwing.

fn
dispatchAnimationEvent

Dispatches a non-bubbling custom event on an element for animation lifecycle tracking

fn
encodeCookieName

Percent-encodes the characters a cookie name cannot contain (cookie names are RFC 2616 tokens). Typical names — letters, digits, `-`, `_`, `.` — pass through unchanged. `(` and `)` are escaped as `%28`/`%29`.

fn
encodeCookieValue

Percent-encodes only the characters a cookie value cannot contain per RFC 6265 (controls, whitespace, `"` `,` `;` `\` and `%` itself), leaving everything else readable. Compatible with js-cookie's default write converter.

fn
findCardBrand

Detect a payment-card brand from a number's digits by its IIN/BIN pattern. Returns the brand whose pattern matches the most leading digits (so it narrows down as the user types), or `undefined` if none match. Pure.

fn
findFirstVisible

Returns the first visible element from a list. Checks visibility up the DOM to `container` (exclusive).

fn
findLastVisible

Returns the last visible element from a list. Checks visibility up the DOM to `container` (exclusive).

fn
findPhoneCountry

Resolve a digit string to its country among a {@link PhoneCountry}list. Matches the **longest dialing code** (codes are prefix-free, so this is unambiguous), then — for countries sharing a code (NANP `+1`, `+7` RU/KZ) — the most specific **area code**, then the lowest **priority** (the primary country) when no area code matches. The default dataset is indexed for O(1) lookup; a custom list falls back to a linear scan.

fn
focus

Focuses an element without scrolling. Optionally calls select on input elements.

fn
focusFirst

Attempts to focus the first element from a list of candidates. Stops when focus actually moves.

fn
focusGuard

Adds a pair of focus guards at the boundaries of the DOM tree to ensure consistent focus behavior

fn
getActiveElement

Returns the active element of the document (or shadow root)

fn
getAnimationName

Returns the current CSS animation name(s) of an element

fn
getCookieValue

Looks up a single cookie in a `document.cookie`-style string without building a full map — same first-occurrence and verbatim-raw-value semantics as {@link parseCookieString}, but allocation-free for misses and cheap for hot paths (reactive reads, polling).

fn
getCountryFlagByCode

Convert an ISO 3166-1 alpha-2 country code (e.g. `'RU'`, `'us'`) into its flag emoji by mapping each letter to a Unicode regional indicator symbol. Case-insensitive; returns an empty string for anything that isn't two ASCII letters. Pure and environment-agnostic.

fn
getTabbableCandidates

Collects all tabbable candidates via TreeWalker (faster than querySelectorAll). This is an approximate check — does not account for computed styles. Visibility is checked separately in `findFirstVisible`.

fn
getTabbableEdges

Returns the first and last tabbable elements inside a container

fn
getTranslate

Reads the current translation of an element along one axis from its computed `transform`, parsing both `matrix(...)` (2D) and `matrix3d(...)` (3D) forms. Returns `null` when the element has no matrix transform.

fn
hideOthers

Marks every sibling of `target` (within `parentNode`, defaulting to `document.body`) as `aria-hidden="true"` so assistive technologies skip them. `aria-live` regions and `<script>` elements are preserved. Returns an undo function that restores the previous state; calls stack (ref-counted) across multiple layers. Port of the `aria-hidden` npm package, kept dependency-free.

fn
isAnimatable

Checks whether an element has a running CSS animation or transition

fn
isEventTarget

Type guard for a value that is itself an {@link EventTarget}(e.g. `window`, `document`, or an element) — i.e. it can be attached to directly rather than unwrapped from a ref/getter first.

fn
isHidden

Checks if an element is hidden via `visibility: hidden` or `display: none` up the DOM tree

fn
isInView

Reports whether an element is fully within the visual viewport, accounting for on-screen keyboards via `window.visualViewport`. A 40px slack is allowed at the bottom to tolerate Safari's viewport quirks. Returns `false` when `visualViewport` is unavailable.

fn
isIOS

Whether the current device runs iOS/iPadOS (iPhone or iPad).

fn
isIPad

Whether the current device is an iPad. iPadOS 13+ masquerades as a Mac, so this also treats a touch-capable Mac (`maxTouchPoints > 1`) as an iPad.

fn
isIPhone

Whether the current platform is an iPhone (per `navigator.platform`).

fn
isMac

Whether the current platform is macOS (per `navigator.platform`). Note iPadOS reports as a Mac — combine with {@link isIPad} to disambiguate.

fn
isMobileFirefox

Whether the current browser is Firefox on a mobile device (Android Firefox or iOS Firefox / `FxiOS`).

fn
isSafari

Whether the current browser is Safari (desktop or iOS), excluding Chrome and Android browsers that also include "Safari" in their UA string.

fn
isSelectableInput

Checks if an element is an input element with a select method

fn
isValidCardNumber

Whether `value` is a complete, valid payment-card number: it passes the Luhn checksum (`luhn` from `@robonen/encoding`) AND its digit length matches the detected {@link findCardBrand} brand (or the 12–19 digit ISO/IEC 7812 range when the brand is unknown). For the bare checksum, use `luhn` directly.

fn
onAnimationSettle

Attaches animation/transition end listeners to an element with fill-mode flash prevention. Returns a cleanup function.

fn
parseCookieString

Parses a `document.cookie`-style string (`'a=1; b=2'`) into a `Map` of decoded names to values. Keeps the **first** occurrence per name — browsers order cookies most-specific-path first, so the first one is the one a server would use. The raw value is passed to `decode` verbatim (including any wrapping quotes) so it matches what the Cookie Store API would report; the default decoder unwraps quotes and percent-escapes.

fn
pxValue

Parse a CSS length token (`"1024px"`, `"48em"`, `"30rem"`, `"50%"`) into a pixel number. `em`/`rem` use the conventional 16px root size. Returns `NaN` for non-numeric input.

fn
readInputState

Reads the value and current selection of an `<input>`/`<textarea>` into a plain {@link InputState}. A `null` selection (some input types report it) falls back to a collapsed caret at the end of the value.

fn
resetStyle

Restores the inline styles an element had before the most recent cached {@link setStyle}. With `prop` it restores a single property; otherwise it restores every property that was remembered. A no-op if nothing was cached.

fn
serializeCookie

Builds a `document.cookie` assignment string from an **already-encoded** name and value (see {@link encodeCookieName} / {@link encodeCookieValue}) plus {@link CookieAttributes}. `Path` and `SameSite` are always emitted explicitly. Fails loudly on combinations browsers silently drop: `SameSite=None` or `Partitioned` without `Secure`, and `name=value` over 4096 UTF-8 bytes.

fn
setStyle

Applies a batch of inline styles to an element, remembering the values it overwrote so {@link resetStyle} can restore them later. `--custom` properties are written through `setProperty`. Pass `ignoreCache` to apply the styles without recording the originals (e.g. for transient, per-frame writes during a drag that you intend to clear wholesale).

fn
shouldSuspendUnmount

Determines whether unmounting should be delayed due to a running animation/transition change

fn
testUserAgentPlatform

Tests `navigator.platform` against a regular expression, guarding for non-browser environments. Returns `undefined` when there is no `navigator` (e.g. during SSR) so callers can distinguish "no" from "unknown".

fn
writeInputState

Writes value and selection back to an `<input>`/`<textarea>`. The value is only assigned when it actually changed (avoids spurious cursor jumps), and the caret is moved **only while the element is focused** so programmatic updates never steal or reposition focus. `setSelectionRange` is guarded because some input types (`number`, `email`, `date`) forbid it.

lifecycle · 4

math · 21

V
anddemo

Alias for {@link logicAnd}.

fn
createGenericProjectiondemo

Create a reusable projection between two arbitrary (non-numeric) domains using a custom projector. The returned factory turns a reactive input into a `ComputedRef` of the projected value, so the same projection can be applied to many inputs without re-resolving the domains each time.

fn
createProjectiondemo

Create a reusable numeric projection from one numeric domain to another. Without a custom projector it performs a linear (lerp-based) remap that extrapolates past the bounds; pass `{ clamp: true }` to clamp the input to the `from` domain via the stdlib `remap`. The returned factory can be reused for many inputs.

fn
logicAnddemo

Reactive logical `AND` across boolean refs or getters. The result is `true` only when every input resolves to a truthy value.

fn
logicNotdemo

Reactive logical `NOT` of a boolean ref or getter. The result is `true` whenever the input resolves to a falsy value.

fn
logicOrdemo

Reactively compute the logical `OR` across a list of boolean sources (each a ref, getter, or raw value). Returns a `ComputedRef<boolean>` that is `true` when at least one source is truthy. Short-circuits on the first truthy source, so later refs are only read when needed. With no arguments the result is `false` (the identity for `OR`). Fully SSR-safe — touches no globals.

V
notdemo

Alias for {@link logicNot}.

V
ordemo

Alias for {@link logicOr}. Reactively computes the logical `OR` across boolean refs, getters, or raw values.

fn
useAbsdemo

Reactive `Math.abs` of a number ref or getter

fn
useAveragedemo

Reactively compute the average (arithmetic mean) of the provided numbers. Accepts either a variadic list of numbers (each a ref, getter, or raw value) or a single reactive array whose items may themselves be refs/getters. Returns `NaN` when there are no values, mirroring `0 / 0`.

fn
useCeildemo

Reactive `Math.ceil`. Rounds a number up to the next largest integer.

fn
useClampdemo

Clamps a value between a minimum and maximum value

fn
useFloordemo

Reactive `Math.floor`. Returns the largest integer less than or equal to the given value

fn
useMathdemo

Reactive wrapper over any callable `Math.<key>` method. Each argument may be a plain value, a ref or a getter; the result recomputes lazily whenever a reactive input changes.

fn
useMaxdemo

Reactively compute the maximum of the provided numbers. Accepts either a variadic list of numbers (each a ref, getter, or raw value) or a single reactive array whose items may themselves be refs/getters.

fn
useMindemo

Reactive `Math.min`. Accepts a variadic list of numbers (each a ref, getter, or plain value) or a single reactive array whose items may themselves be refs/getters.

fn
usePrecisiondemo

Reactively set the decimal precision of a number.

fn
useProjectiondemo

Reactive numeric projection from one numeric domain to another. A thin one-shot wrapper over {@link createProjection}: it projects a single reactive `input` and returns a `ComputedRef` of the result. The default (lerp-based) projector extrapolates past the domain bounds; pass `{ clamp: true }` to clamp the input to the `from` domain. SSR-safe — it performs only pure arithmetic and touches no browser globals.

fn
useRounddemo

Reactive `Math.round` with optional decimal-place precision

fn
useSumdemo

Reactively compute the sum of the provided numbers. Accepts either a variadic list of numbers (each a ref, getter, or raw value) or a single reactive array whose items may themselves be refs/getters.

fn
useTruncdemo

Reactive `Math.trunc`. Returns the integer part of a number by removing any fractional digits.

media · 10

fn
useBluetoothdemo

Reactive Web Bluetooth API. Prompts for a device and tracks its GATT server connection.

fn
useDisplayMediademo

Reactive `mediaDevices.getDisplayMedia` (screen share) streaming.

fn
useMediaControlsdemo

Reactive controls and state for an `<audio>`/`<video>` element: play/pause, seeking, duration, buffered ranges, volume, mute, rate, text tracks, and Picture-in-Picture. Source and track injection are handled for you, and all DOM listeners attach passively with automatic cleanup. SSR-safe.

fn
useMemorydemo

Reactive `performance.memory` heap statistics, polled on an interval. SSR-safe and a no-op where the API is unavailable.

fn
usePerformanceObserverdemo

Observe performance metrics via `PerformanceObserver`. The observer is (re)created only when activation changes, and can be paused, resumed, or permanently stopped. SSR-safe: nothing runs until mounted in a supporting environment.

fn
useSpeechRecognitiondemo

Reactive wrapper around the Web Speech API `SpeechRecognition` for transcribing speech to text.

fn
useSpeechSynthesisdemo

Reactive wrapper around the Web Speech `SpeechSynthesis` API for text-to-speech.

fn
useUserMediademo

Reactive `navigator.mediaDevices.getUserMedia` streaming. Acquires a `MediaStream` for camera/microphone capture, keeps it in sync with reactive constraints, and auto-restarts on constraint changes while enabled. SSR-safe and race-safe — overlapping acquisitions never leave an orphaned stream open.

fn
useWebWorkerdemo

Simple Web Worker communication with reactive incoming data and automatic teardown

fn
useWebWorkerFndemo

Run an expensive function in a transient Web Worker off the main thread

reactivity · 27

V
asyncComputeddemo

Alias for {@link computedAsync}.

fn
cloneFnDefaultdemo

Default clone implementation. Prefers the structured clone algorithm and falls back to a JSON round-trip when `structuredClone` is unavailable (older runtimes / SSR) or the value is not structured-cloneable.

fn
computedAsyncdemo

Computed value driven by an async (promise-returning) evaluation callback. The value updates reactively when its dependencies change, exposing an optional `evaluating` ref for pending state, an `onError` handler, lazy evaluation, and a default value used until the first resolution settles. Out-of-order resolutions are discarded so only the latest run wins, and an `onCancel` hook lets callbacks abort stale work.

fn
computedEagerdemo

Eager (non-lazy) computed value backed by a `watchEffect`-driven `shallowRef`. Unlike `computed`, the getter runs immediately and on every dependency change rather than lazily on read, so the cached value is always up to date. Best for cheap derived values that are read in many places.

fn
computedWithControldemo

A computed ref whose recomputation is driven only by an explicitly declared dependency `source`, plus a manual `.trigger()`. Built on `customRef` with a single `flush: 'sync'` watcher and a lazy `dirty` flag, so the getter is cached and only re-runs when the source changes or you trigger it — never on unrelated reactive reads. Also exposes `.peek()` (untracked read) and `.stop()` (detach the source watcher).

V
controlledComputeddemo

Alias of {@link computedWithControl}.

V
controlledRefdemo

Alias of {@link refWithControl}.

V
eagerComputeddemo

Alias for {@link computedEager}.

fn
extendRefdemo

Attach extra (optionally reactive) attributes to a ref while keeping it a usable ref.

fn
reactiveComputeddemo

Computed that resolves to a reactive object whose individual fields stay reactive — read a single property and only that property is tracked, instead of the whole getter re-running on every access. The getter is wrapped in a single cached `computed`, so the object is recomputed only when one of its reactive dependencies changes. The returned value is a `reactive` proxy over that computed: destructuring with `toRefs`, spreading and writing back individual fields all work as on a normal `reactive` object.

fn
reactiveOmitdemo
fn
reactivePickdemo

Reactively pick a subset of keys (or keys matched by a predicate) from a reactive object. The result is a live `reactive` proxy: reads forward to the source's current value (so it tracks reassignment of nested refs) and writes pass straight back to the source. Unlike a `computed` of an object literal, no new object is allocated per recompute — the proxy is built once and lookups are resolved lazily on access.

fn
refAutoResetdemo

Create a ref that resets to its default value after a delay since the last write. Each set restarts the timer; reading is reactive.

fn
refDebounceddemo

A readonly ref whose value mirrors a source but only after updates stop arriving for `ms`. Wraps the source change in our debounce primitive (built on `debounceFilter`), so rapid bursts collapse into a single delayed write. Supports a `maxWait` ceiling so the value still progresses under sustained input, and tears its timer down with the owning scope.

fn
refDefaultdemo

Wrap a writable `ref` so that reads fall back to a default value whenever the source holds `null` or `undefined`, while writes pass straight through to the source. The default may itself be reactive (a ref, getter, or plain value), so the fallback can track other state. Implemented as a single writable `computed` — no watchers, no extra refs, nothing to tear down — which keeps it allocation-light and SSR-safe (it never touches the DOM).

fn
refThrottleddemo

A ref whose value updates are throttled. The returned ref mirrors the source but propagates changes at most once per `delay` window, making it useful for rate-limiting reactive updates driven by high-frequency events such as `scroll` or `resize`.

fn
refWithControldemo

A ref with fine-grained control over its reactivity: read/write without tracking or triggering, plus `onBeforeChange` (vetoable) and `onChanged` hooks. Built on `customRef`, so there are no extra watchers.

fn
syncRefdemo

Keeps two refs in sync (two-way by default, or one-way via `direction`), with optional value transforms.

fn
toReactivedemo

Convert a ref of object to a reactive proxy. Property reads and writes pass straight through to the ref's current value, so the proxy stays in sync even if the ref is reassigned to a whole new object. Writing a plain value onto a key that currently holds a ref unwraps into that ref's `.value`. Passing a plain object simply returns `reactive(object)`.

fn
useCacheddemo

Caches the value of an external ref and updates it only when the value changes

fn
useCloneddemo

Reactive deep clone of a source with a mutable cloned ref, modification tracking, and manual mode.

fn
useDebounceFndemo

Debounce execution of a function — a thin reactive wrapper around `@robonen/stdlib`'s `debounce`. Postpones invocation until `ms` have elapsed since the last call and resolves with the wrapped function's result. Supports a reactive delay, a `maxWait` ceiling, `rejectOnCancel`, and exposes `cancel`, `flush`, and `isPending`. Pending timers are cleared on scope dispose.

fn
usePreviousdemo

Track the previous value of a ref, getter, or reactive source.

fn
useSyncRefsdemo

Syncs the value of a source ref with multiple target refs

fn
useThrottleFndemo

Throttle execution of a function — a thin reactive wrapper around `@robonen/stdlib`'s `throttle`. Invokes `fn` at most once per `delay` window and resolves with the wrapped function's result. Especially useful for rate-limiting handlers on high-frequency events like `scroll` and `resize`. Accepts either positional arguments or a single options object, and exposes `cancel`/`flush` controls on the returned function.

fn
useToNumberdemo

Reactively convert a string or number ref to a number.

fn
useToStringdemo

Reactively stringify a value, equivalent to `computed(() => String(toValue(value)))`.

sensors · 44

V
DefaultMagicKeysAliasMapdemo

Default lowercase alias map: maps common shorthand key names to their canonical `KeyboardEvent.key` (lowercased) equivalents.

fn
isFocusedElementEditabledemo

Decides whether the currently focused element already swallows text input (an `<input>`, `<textarea>`, or any `contenteditable` host). When it does we leave the keystroke alone so we never steal focus from a real text field.

fn
isTypedCharValiddemo

Returns `true` when the event represents a single printable character typed without a command/control/alt modifier. Uses `KeyboardEvent.key` (a single Unicode grapheme for printable keys) instead of the deprecated `keyCode`, so it transparently covers digits, latin letters and any other printable glyph.

fn
mapGamepadToXbox360Controllerdemo

Maps a raw {@link Gamepad} into a named Xbox 360 controller layout (buttons, bumpers, triggers, sticks, dpad). Returns `null` while no gamepad is present.

fn
onKeyDowndemo

Listen for `keydown` strokes. Shorthand for `onKeyStroke` with `eventName: 'keydown'`.

fn
onKeyPresseddemo

Listen for `keypress` strokes. Shorthand for `onKeyStroke` with `eventName: 'keypress'`.

fn
onKeyStrokedemo

Listen for keyboard strokes. Accepts a key, list of keys, or a predicate and fires the handler for matching events. Auto-cleans up on scope dispose. Overload 1: Explicit key filter

fn
onKeyUpdemo

Listen for `keyup` strokes. Shorthand for `onKeyStroke` with `eventName: 'keyup'`.

fn
onLongPressdemo

Directive-like helper that invokes a handler after a sustained long press on a target element. Movement beyond `distanceThreshold` cancels the press, and an optional `onMouseUp` callback reports the press duration, distance, and long-press status. Listeners are passive by default and registered via `useEventListener` for automatic cleanup.

fn
onStartTypingdemo

Fires the callback when the user starts typing on a non-editable element, ideal for auto-focusing a search box.

fn
useBatterydemo

Reactive Battery Status API. Tracks the device charging state, charge level, and the estimated charging/discharging times, keeping them in sync with the underlying `BatteryManager` events.

fn
useBodyScrollLockdemo

Reference-counted body scroll lock. Safe to invoke from multiple concurrent modals — the lock releases only after all holders release. Preserves the original overflow/padding/touch-action values and compensates for scrollbar removal to prevent layout shift.

fn
useClickOutsidedemo

Invokes `handler` when a pointer event occurs outside `target`. SSR-safe: no-op on the server. Handles portaled/ignored subtrees and guards against synthetic "outside" clicks on removed nodes.

fn
useDeviceMotiondemo

Reactive `DeviceMotionEvent` exposing acceleration (with and without gravity), rotation rate, and the hardware sampling interval. SSR-safe, uses a single passive listener, and supports the iOS 13+ permission flow.

fn
useDeviceOrientationdemo

Reactive [`DeviceOrientationEvent`](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent). Provides physical orientation of the device relative to Earth's coordinate frame.

fn
useDevicePixelRatiodemo

Reactively track `window.devicePixelRatio`, updated via a `matchMedia(resolution)` listener (fires on zoom and on monitor changes).

fn
useDevicesListdemo

Reactive `enumerateDevices` listing available media input/output devices.

fn
useElementByPointdemo

Reactive element(s) at a given viewport point, sampled every animation frame via `document.elementFromPoint` (or `elementsFromPoint` when `multiple` is set).

fn
useElementHoverdemo

Reactive hover state of an element, driven by `mouseenter` / `mouseleave`. Supports independent enter/leave delays to debounce flicker.

fn
useEscapeKeydemo

Register a callback for the topmost Escape keydown. Uses an internal stack so that nested layers (e.g. nested Dialogs) dismiss in the correct order — only the most recently-registered listener fires for a given keydown.

fn
useFocusdemo

Reactive focus state of an element. The returned `focused` ref tracks focus/blur events and can be written to in order to focus or blur the target.

fn
useFocusWithindemo

Reactive tracking of whether an element or any of its descendants are focused, backed by the `focusin`/`focusout` events.

fn
useFpsdemo

Reactive FPS counter based on `requestAnimationFrame`. Reports a smoothed FPS value averaged over a configurable number of frames, and tracks min/max values.

fn
useGamepaddemo

Reactive wrapper around the Gamepad API. Tracks connected gamepads, emits connection/disconnection events, and polls live button/axis state on every animation frame. The polling loop stays paused while no gamepad is connected and resumes automatically on the first connection, so there is zero idle work. SSR-safe.

fn
useGeolocationdemo

Reactive Geolocation API. Watches the device position, exposing reactive coordinates, error, and readiness state, plus pause/resume controls and a one-shot `getCurrentPosition`.

fn
useIdledemo

Track whether the user has been inactive for a given duration.

fn
useInfiniteScrolldemo

Trigger a loader as a scroll container nears one of its edges. Backed by {@link useScroll} for RTL-aware arrived-edge detection: the `distance` is folded into that direction's offset, so `onLoadMore` fires the moment the edge comes within `distance` pixels. Re-checks automatically after each load (so an under-filled container keeps loading) and degrades safely under SSR and when `IntersectionObserver` is unavailable.

fn
useKeyModifierdemo

Reactive state of a keyboard modifier (CapsLock, NumLock, Shift, Control, Alt, Meta, ...) tracked via `KeyboardEvent.getModifierState`.

fn
useMagicKeysdemo

Reactive keys pressed state, with magical combination keys support via a Proxy. Access combinations directly as properties, e.g. `keys['ctrl+a']` or `keys.ctrl_a`.

fn
useMousedemo

Reactive mouse (and optionally touch) position with optional custom target, scroll tracking, custom extractors, and event filtering.

fn
useMouseInElementdemo

Reactive mouse position relative to an element. Exposes the cursor position, the cursor position relative to the element's top-left corner, the element's position and size, and whether the cursor is outside the element. Element geometry is observed via `useElementBounding` (`ResizeObserver` + `MutationObserver` + window scroll/resize), so the relative coordinates stay correct as the element moves or resizes — without re-measuring the element on every pointer move.

fn
useMousePresseddemo

Reactive mouse/touch/drag pressed state on a target, with the input source type and optional press/release callbacks.

fn
useNetworkdemo

Reactive Network Information API state plus online/offline status.

fn
useOnlinedemo

Reactive online/offline status based on `navigator.onLine`. For connection details (effectiveType, downlink, saveData, transition timestamps, ...) use {@link useNetwork} instead.

fn
usePageLeavedemo

Reactive flag indicating whether the mouse has left the page.

fn
useParallaxdemo

Reactive parallax effect. Prefers the device orientation sensors and transparently falls back to mouse position when orientation is unavailable. Composes {@link useDeviceOrientation} and {@link useMouse}; pass a `target` to make the mouse fallback relative to an element's centre instead of the whole viewport. SSR-safe.

fn
usePointerdemo

Reactive pointer state (position, pressure, tilt, size, and pointer type) sourced from pointer events on a target, plus whether the pointer is currently inside it.

fn
usePointerLockdemo

Reactive [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). Locks the mouse cursor to an element and tracks the locked element reactively.

fn
usePointerSwipedemo

Detect swipe gestures via PointerEvents on a target element. Works for mouse, touch and pen with a single unified event model, tracking start/end coordinates, the active state and the resolved direction.

fn
useScreenOrientationdemo

Reactive Screen Orientation API. Tracks the current orientation `type` and `angle`, and exposes helpers to lock/unlock the orientation. SSR-safe.

fn
useScrolldemo

Reactive scroll position and state for an element or the window, with arrived-edge detection (RTL-aware), scroll directions, an `isScrolling` flag, optional throttling, and a `measure()` method for manual re-sync.

fn
useScrollLockdemo

Lock scrolling of an element by toggling `overflow: hidden`, preserving the element's prior inline overflow and handling iOS `touchmove`. Returns a writable boolean ref — set it to lock/unlock, read it for state.

fn
useSwipedemo

Detect swipe gestures via touch events on a target element. Tracks start/end coordinates, the active state and the resolved direction.

fn
useTextSelectiondemo

Reactively track the user's text selection via `Window.getSelection`.

state · 22

V
activeAppPlugindemo

Vue plugin that registers the app as the active one and clears the registration when the app unmounts (unless another app took over in the meantime).

fn
createSharedComposabledemo

Promotes a composable to a shared one: every call reuses the same instance backed by a single effect scope. The scope is created lazily on the first consumer and is ref-counted, so it is disposed only when the last consumer's scope unmounts. State is recreated on the next call after a full dispose.

fn
getActiveAppdemo

Returns the closest Vue app instance: the current component's app when called during setup (or anywhere `getCurrentInstance` works), otherwise the app registered via `setActiveApp` / `activeAppPlugin`.

fn
injectWithAppdemo

Drop-in replacement for `inject` that also works outside of component setup. Inside an injection context it behaves exactly like `inject` (component-level provides win); outside it resolves app-level provides through the active app. When no app is available it falls back to the provided default value, or throws if there is none.

fn
runWithAppdemo

Runs a function inside `app.runWithContext`, so `inject` (and everything built on it) resolves app-level provides even outside of component setup — in router guards, store actions, event handlers or timers. The app defaults to `getActiveApp()`; pass one explicitly to target a specific app (recommended for SSR, where apps are created per request).

fn
setActiveAppdemo

Registers the Vue app instance used by `getActiveApp`, `runWithApp` and `injectWithApp` outside of component context. Pass `undefined` to clear the registration. The registration is module-global (one slot per JS realm). On the client this is exactly what you want; on the server create one app per request and prefer passing the app explicitly to `runWithApp` instead of relying on the global slot, otherwise concurrent requests may observe each other's app.

fn
useAppSharedStatedemo

Provides a shared state object for use across Vue instances

fn
useAsyncStatedemo

A composable that provides a state for async operations without setup blocking

fn
useContextFactorydemo

A composable that provides a factory for creating context with unique key

fn
useCounterdemo

A composable that provides a counter with increment, decrement, set, get, and reset functions

fn
useCycleListdemo

Cycle through a list of items, with `next`/`prev`/`shift`/`go` controls. Supports a reactive list — the index is kept valid when the list changes.

fn
useDebouncedRefHistorydemo

Track the change history of a ref, debouncing commits so that rapid bursts of changes collapse into a single history record. A shorthand for {@link useRefHistory} pre-wired with a debounce {@link EventFilter}.

fn
useIddemo

SSR-safe unique identifier. Thin wrapper around Vue 3.5's built-in `useId()` that accepts an optional prefix and allows callers to pass a pre-existing id (useful for primitives that accept a user-supplied `id` prop).

fn
useInjectionStoredemo

Create a global state that can be injected into components

fn
useLastChangeddemo

Records the last time a value changed

fn
useManualRefHistorydemo

Manually-committed undo/redo history for a ref. Records snapshots only when `commit()` is called, with optional cloning, serialization, and a bounded capacity.

fn
useOffsetPaginationdemo

A composable function that provides pagination functionality for offset based pagination

fn
useRefHistorydemo

Track the change history of a ref with undo/redo, pause/resume, batching, and manual commits.

fn
useStateMachinedemo

Reactive wrapper around the stdlib `StateMachine`: a type-safe finite state machine whose current state is exposed as a shallow ref, so templates and computeds can branch on `state`/`matches`/`can`. States, events, guards, and entry/exit hooks follow the stdlib `createMachine` config verbatim — this composable only adds reactivity.

fn
useStepperdemo

A composable for building wizards/steppers over a list or record of steps

fn
useThrottledRefHistorydemo

Shorthand for {@link useRefHistory} with a throttled event filter, so rapid source changes are committed at most once per interval (trailing edge by default).

fn
useToggledemo

A composable that provides a boolean toggle with customizable truthy/falsy values

storage · 9

fn
createCookieStoreAdapterdemo

{@link CookieStorageLike} adapter over the [Cookie Store API](https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API): async reads/writes plus a `change`-event subscription that observes other tabs, server `Set-Cookie` responses, and expiry. The API can only write `Secure` cookies, so `secure: false` is rejected — use {@link createDocumentCookieAdapter} for that.

fn
createDocumentCookieAdapterdemo

{@link CookieStorageLike} adapter over `document.cookie`: synchronous reads/writes that work in every browser and can express non-`Secure` cookies. Changes are observed through the Cookie Store API `change` event when the browser has one (covering other tabs, server responses, and expiry even though writes stay on `document.cookie`); otherwise every write pings a BroadcastChannel by cookie name and receivers re-read their own `document.cookie` (same-tab and cross-tab, ordering-proof since no value travels), with a same-tab CustomEvent as the last resort. Without the Cookie Store API, changes made outside the adapter (server `Set-Cookie`, other libraries) are not observed.

fn
guessSerializerdemo
fn
shallowMergedemo
fn
useCookiedemo

Reactive cookie binding — creates a ref synced with a cookie through a pluggable {@link CookieStorageLike} backend. By default that is the [Cookie Store API](https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API) when the browser supports it (async, with `change`-event sync across tabs and server `Set-Cookie` responses) and `document.cookie` otherwise (synchronous, BroadcastChannel same-tab/cross-tab sync); pass a custom `store` to run on top of a framework's cookie context (e.g. Nuxt) including during SSR. Setting the state to `null` deletes the cookie. Cookie attributes (`path`, `domain`, `maxAge`/`expires`, `secure`, `sameSite`, `partitioned`) apply to every write; `secure` defaults to the page's secure-context status, and an explicit `secure: false` selects the `document.cookie` adapter since the Cookie Store API can only write `Secure` cookies.

fn
useLocalStoragedemo

Reactive localStorage binding — creates a ref synced with `window.localStorage`

fn
useSessionStoragedemo

Reactive sessionStorage binding — creates a ref synced with `window.sessionStorage`

fn
useStoragedemo

Reactive Storage binding — creates a ref synced with a storage backend

fn
useStorageAsyncdemo

Reactive Storage binding with async support — creates a ref synced with an async storage backend

types · 14

T
MaybeComputedRefArgs

Argument form accepted by the reactive math helpers (`useMax`, `useMin`, `useSum`, `useAverage`): either a spread of (possibly reactive) values, or a single (possibly reactive) array of them.

T
RemovableRef

A ref that can be set to `null` to remove the associated storage entry. Setting the value to `null` or `undefined` will call `removeItem` on the storage backend.

I
ResumableActions

The actions for a resumable process.

I
ResumableOptions

Often times, we want to pause and resume a process. This is a common pattern in reactive programming. This interface defines the options and actions for a resumable process.

I
StandardSchemaFailureResult

A failed validation result.

T
StandardSchemaInferInput

Infer the input type of a Standard Schema.

T
StandardSchemaInferOutput

Infer the output type of a Standard Schema.

I
StandardSchemaIssue

A single validation issue.

I
StandardSchemaPathSegment

A single segment of an issue path.

I
StandardSchemaProps

The properties carried on a schema's `~standard` key.

T
StandardSchemaResult

The result of validating a value: either a success carrying the typed output or a failure carrying a list of issues.

I
StandardSchemaSuccessResult

A successful validation result.

I
StandardSchemaTypes

The inferred input/output types of a schema.

I
StandardSchemaV1

Vendored, dependency-free types for the [Standard Schema](https://github.com/standard-schema/standard-schema) spec (v1). Any validation library implementing the `~standard` contract — zod, valibot, arktype, … — is structurally assignable to {@link StandardSchemaV1}, so the forms layer can accept them without taking on a dependency. The namespace pattern from the official spec is flattened into named exports to stay within the repo's lint rules.

utilities · 8

fn
createEventHookdemo

Lightweight, non-reactive event hook factory exposing `{ on, off, trigger, clear }`. `on` returns a callable off handle (also carrying an `.off` method) and auto-removes the listener on scope dispose. `trigger` awaits async listeners and resolves with all their results. SSR-safe (touches no browser globals) and tree-shakeable.

fn
getdemo

Shorthand accessor that unwraps a ref/getter to its value, optionally reading a single property off the resolved value. Accepts plain values, refs and getter functions (via `toValue`), so it works anywhere `unref`/`toValue` would. Purely synchronous and side-effect free, so it is fully SSR-safe.

fn
isDefineddemo

Type-guard that checks whether a ref's (or plain value's) current value is neither `null` nor `undefined`, narrowing the source to its `NonNullable` form. Unwraps refs with a single `unref` — no extra reactivity or watchers are created, so it is a cheap synchronous check that is fully SSR-safe. For a reactive guard that tracks changes, use {@link useIsDefined}.

fn
setdemo

Shorthand setter that mirrors {@link get}. Either assigns `value` to a ref (`ref.value = value`) or assigns `value` to a single property of an object (`target[key] = value`). The arity is resolved at the type level via overloads, so both forms stay fully type-safe. Purely synchronous and side-effect free, so it is fully SSR-safe.

fn
useEventBusdemo

A typed, SSR-safe event bus. Calls sharing an identifier share listeners, giving cross-component (and cross-module) communication without prop drilling or provide/inject. Backed by stdlib `PubSub` for stable snapshot-based emit semantics, and auto-removes the current scope's listeners on dispose so components never leak subscriptions.

fn
useIsDefineddemo

Reactive counterpart to {@link isDefined}. Returns a `ComputedRef<boolean>` that re-evaluates whenever the source ref, getter, or plain value resolves to a non-nullish value. Use this when the definedness itself needs to drive reactivity (templates, watchers, derived state); reach for the synchronous {@link isDefined} when you only need a one-off type guard.

fn
useMemoizedemo

Cache the result of a (possibly async) function by its arguments, exposing a reactive cache and explicit `load`/`delete`/`clear`/`generateKey` controls. When no custom `cache` is supplied the default `Map` path delegates to `@robonen/stdlib`'s `memoize` for the get-or-compute core and is wrapped in `shallowReactive` so cache reads inside effects stay live. A custom cache backend (e.g. an LRU) can be plugged in via `options.cache`. SSR-safe: no browser globals are touched.

fn
useSupporteddemo

SSR-friendly way to check if a feature is supported

utils · 7

watch · 8