preact-missing-hooks
Version:
A lightweight, extendable collection of missing React-like hooks for Preact — plus fresh, powerful new ones designed specifically for modern Preact apps.
40 lines (39 loc) • 2.1 kB
TypeScript
/**
* useWasmCompute – run WebAssembly computation off the main thread via a Web Worker.
* Flow: Preact Component → useWasmCompute() → Web Worker → WASM Module → Return result.
* @module useWasmCompute
*/
export interface UseWasmComputeOptions {
/** URL of the .wasm module to load in the worker. */
wasmUrl: string;
/** Name of the exported function to call for compute (default: 'compute'). */
exportName?: string;
/** Optional custom worker script URL. If provided, worker must handle init (wasmUrl, exportName) and compute(input) messages. */
workerUrl?: string;
/** Optional import object for WebAssembly.instantiate (only used when using default inline worker; must be serializable). */
importObject?: WebAssembly.Imports;
}
export interface UseWasmComputeReturn<TInput = number, TResult = number> {
/** Invoke the WASM export with the given input. Resolves with the return value when ready. */
compute: (input: TInput) => Promise<TResult>;
/** Last result from a successful compute call. */
result: TResult | undefined;
/** True while WASM is loading or a compute is in progress. */
loading: boolean;
/** Error message if environment is unsupported, init failed, or compute failed. */
error: string | null;
/** True when the WASM module is loaded and compute can be called. */
ready: boolean;
}
/**
* Runs WebAssembly computation in a Web Worker. Validates environment (browser, Worker, WebAssembly)
* and returns a stable compute function plus result/loading/error/ready state.
*
* @param options - wasmUrl, optional exportName, optional workerUrl, optional importObject.
* @returns { compute, result, loading, error, ready }.
*
* @example
* const { compute, result, loading, error, ready } = useWasmCompute({ wasmUrl: '/add.wasm', exportName: 'add' });
* // When ready: compute(2).then(sum => ...); result will update with the last return value.
*/
export declare function useWasmCompute<TInput = number, TResult = number>(options: UseWasmComputeOptions): UseWasmComputeReturn<TInput, TResult>;