CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vueuse--shared

Collection of essential shared Vue Composition Utilities providing foundational building blocks for reactive Vue applications

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Core utility functions including filters, type checking, promise helpers, and general-purpose functions that support VueUse shared functionality.

Capabilities

Filter Utilities

Event filtering functions for debouncing, throttling, and pausing function execution.

/**
 * Create debounce filter for function execution
 * @param ms - Debounce delay in milliseconds  
 * @param options - Debounce options
 * @returns Event filter function
 */
function debounceFilter(
  ms: MaybeRefOrGetter<number>, 
  options?: DebounceFilterOptions
): EventFilter;

/**
 * Create throttle filter for function execution
 * @param ms - Throttle delay in milliseconds
 * @param trailing - Execute on trailing edge
 * @param leading - Execute on leading edge  
 * @param rejectOnCancel - Reject promise when cancelled
 * @returns Event filter function
 */
function throttleFilter(
  ms: MaybeRefOrGetter<number>, 
  trailing?: boolean, 
  leading?: boolean, 
  rejectOnCancel?: boolean
): EventFilter;

/**
 * Create pausable filter that can be paused and resumed
 * @param extendFilter - Optional additional filter to extend
 * @returns Pausable event filter
 */
function pausableFilter(extendFilter?: EventFilter): Pausable & { eventFilter: EventFilter };

/**
 * Bypass filter - passes through all events
 */
const bypassFilter: EventFilter;

/**
 * Create filter wrapper for functions
 * @param filter - Event filter to apply
 * @param fn - Function to wrap
 * @returns Wrapped function with filter applied
 */
function createFilterWrapper<T extends AnyFn>(filter: EventFilter, fn: T): T;

interface DebounceFilterOptions {
  maxWait?: MaybeRefOrGetter<number>;
  rejectOnCancel?: boolean;
}

type EventFilter<Args extends any[] = any[], This = any, Invoke extends AnyFn = AnyFn> = (
  invoke: Invoke,
  options: FunctionWrapperOptions<Args, This>
) => ReturnType<Invoke> | Promisify<ReturnType<Invoke>>;

Usage Example:

import { debounceFilter, throttleFilter, useDebounceFn } from "@vueuse/shared";

// Create custom debounced function
const debouncedFn = useDebounceFn(
  () => console.log('Executed!'),
  300
);

// Using filters directly
const filter = debounceFilter(500, { maxWait: 1000 });
const throttled = throttleFilter(200, true, true);

Type Checking Utilities

Environment detection and type checking functions.

/**
 * Check if running in client environment (browser)
 */
const isClient: boolean;

/**
 * Check if running in Web Worker environment
 */
const isWorker: boolean;

/**
 * Check if value is defined (not undefined)
 * @param val - Value to check
 * @returns Type predicate for defined value
 */
function isDef<T = any>(val?: T): val is T;

/**
 * Check if value is not null or undefined
 * @param val - Value to check  
 * @returns Type predicate for non-nullish value
 */
function notNullish<T = any>(val?: T | null | undefined): val is T;

/**
 * Assert condition with console warning
 * @param condition - Condition to assert
 * @param infos - Additional info to log
 */
function assert(condition: boolean, ...infos: any[]): void;

/**
 * Check if value is plain object
 * @param val - Value to check
 * @returns Type predicate for object
 */
function isObject(val: any): val is object;

/**
 * Check if running on iOS device
 */
const isIOS: boolean;

/**
 * Check if object has own property
 * @param val - Object to check
 * @param key - Property key
 * @returns Type predicate for property existence  
 */
function hasOwn<T extends object, K extends keyof T>(val: T, key: K): key is K;

Usage Example:

import { isClient, isDef, notNullish, isObject } from "@vueuse/shared";

// Environment checks
if (isClient) {
  console.log('Running in browser');
}

// Type guards
const value: unknown = getData();
if (isDef(value) && notNullish(value)) {
  // value is defined and not null/undefined
  console.log(value);
}

if (isObject(value)) {
  // value is a plain object
  Object.keys(value).forEach(key => {
    if (hasOwn(value, key)) {
      console.log(value[key]);
    }
  });
}

General Purpose Utilities

Utility functions for common operations.

/**
 * Current timestamp in milliseconds
 * @returns Current Date.now() value
 */
function now(): number;

/**
 * Current timestamp (alias for now)
 * @returns Current timestamp
 */
function timestamp(): number;

/**
 * Clamp number between min and max values
 * @param n - Number to clamp
 * @param min - Minimum value
 * @param max - Maximum value
 * @returns Clamped value
 */
function clamp(n: number, min: number, max: number): number;

/**
 * No-operation function
 */
function noop(): void;

/**
 * Generate random integer between min and max (inclusive)
 * @param min - Minimum value
 * @param max - Maximum value  
 * @returns Random integer
 */
function rand(min: number, max: number): number;

/**
 * Identity function - returns input unchanged
 * @param arg - Input value
 * @returns Same value
 */
function identity<T>(arg: T): T;

/**
 * Convert value to array
 * @param array - Value or array
 * @returns Array containing the value(s)
 */
function toArray<T>(array: T | T[]): T[];

Usage Example:

import { now, clamp, rand, identity, toArray } from "@vueuse/shared";

// Timestamps
const currentTime = now();
const timestamp = timestamp();

// Math utilities  
const clamped = clamp(150, 0, 100); // 100
const randomNum = rand(1, 10); // Random number 1-10

// Utilities
const unchanged = identity('hello'); // 'hello'
const array = toArray('single'); // ['single']
const stillArray = toArray(['a', 'b']); // ['a', 'b']

Promise Utilities

Utilities for working with promises and async operations.

/**
 * Create promise that resolves after specified time
 * @param ms - Milliseconds to wait
 * @param throwOnTimeout - Whether to reject instead of resolve
 * @param reason - Rejection reason when throwOnTimeout is true
 * @returns Promise that resolves/rejects after delay
 */
function promiseTimeout(
  ms: number,
  throwOnTimeout?: boolean,
  reason?: string
): Promise<void>;

/**
 * Create singleton promise function
 * @param fn - Async function to wrap
 * @returns Singleton promise function with reset capability
 */
function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;

interface SingletonPromiseReturn<T> {
  (): Promise<T>;
  reset: () => Promise<void>;
}

/**
 * Invoke function with arguments
 * @param fn - Function to invoke
 * @param args - Arguments to pass
 * @returns Function result
 */
function invoke<T>(fn: () => T): T;
function invoke<T extends any[], R>(fn: (...args: T) => R, ...args: T): R;

Usage Example:

import { promiseTimeout, createSingletonPromise } from "@vueuse/shared";

// Promise timeout
await promiseTimeout(1000); // Wait 1 second
await promiseTimeout(5000, true, 'Request timeout'); // Timeout with error

// Singleton promise
const fetchData = createSingletonPromise(async () => {
  const response = await fetch('/api/data');
  return response.json();
});

// Multiple calls share same promise instance
const data1 = await fetchData(); // Makes API call
const data2 = await fetchData(); // Uses same promise
const data3 = await fetchData(); // Uses same promise

// Reset for new calls
await fetchData.reset();
const newData = await fetchData(); // Makes new API call

Object Utilities

Utilities for object manipulation and property access.

/**
 * Check if object contains property
 * @param obj - Object to check
 * @param key - Property key to look for
 * @returns Whether property exists
 */
function containsProp(obj: object, key: string): boolean;

/**
 * Pick properties from object
 * @param obj - Source object
 * @param keys - Keys to pick
 * @returns New object with picked properties
 */
function objectPick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;

/**
 * Omit properties from object  
 * @param obj - Source object
 * @param keys - Keys to omit
 * @returns New object with omitted properties
 */
function objectOmit<T, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;

/**
 * Get object entries as key-value pairs
 * @param obj - Object to get entries from
 * @returns Array of [key, value] tuples
 */
function objectEntries<T>(obj: T): Array<[keyof T, T[keyof T]]>;

Usage Example:

import { objectPick, objectOmit, objectEntries } from "@vueuse/shared";

const user = {
  id: 1,
  name: 'John',
  email: 'john@example.com',
  password: 'secret'
};

// Pick specific properties
const publicUser = objectPick(user, ['id', 'name', 'email']);
// { id: 1, name: 'John', email: 'john@example.com' }

// Omit sensitive properties
const safeUser = objectOmit(user, ['password']);
// { id: 1, name: 'John', email: 'john@example.com' }

// Get entries
const entries = objectEntries(user);
// [['id', 1], ['name', 'John'], ['email', 'john@example.com'], ['password', 'secret']]

Core Types

type Fn = () => void;
type AnyFn = (...args: any[]) => any;
type FunctionArgs<Args extends any[] = any[], Return = void> = (...args: Args) => Return;
type Arrayable<T> = T[] | T;
type ElementOf<T> = T extends (infer E)[] ? E : never;
type ArgumentsType<T> = T extends (...args: infer U) => any ? U : never;
type Awaitable<T> = Promise<T> | T;
type Promisify<T> = Promise<Awaited<T>>;
type TimerHandle = ReturnType<typeof setTimeout> | undefined;

Install with Tessl CLI

npx tessl i tessl/npm-vueuse--shared

docs

array-utilities.md

common-utilities.md

computed-utilities.md

index.md

reactivity.md

ref-utilities.md

state-management.md

time-async.md

utilities.md

watch-utilities.md

tile.json