@ndriadev/react-tools
Version:
A React library of hooks, components, utils and types ready to use
2,910 lines • 197 kB
TypeScript
import { AriaAttributes } from 'react';
import { Component } from 'react';
import { ComponentPropsWithRef } from 'react';
import { ComponentType } from 'react';
import { DependencyList } from 'react';
import { DetailedReactHTMLElement } from 'react';
import { Dispatch } from 'react';
import { DispatchWithoutAction } from 'react';
import { DOMAttributes } from 'react';
import { EffectCallback } from 'react';
import { ErrorInfo } from 'react';
import { HTMLAttributes as HTMLAttributes_2 } from 'react';
import { JSX as JSX_2 } from 'react/jsx-runtime';
import { JSXElementConstructor } from 'react';
import { Key } from 'react';
import { KeyboardEvent as KeyboardEvent_2 } from 'react';
import { LazyExoticComponent } from 'react';
import { MediaHTMLAttributes } from 'react';
import { MemoExoticComponent } from 'react';
import { MutableRefObject } from 'react';
import { PropsWithChildren } from 'react';
import { ReactElement } from 'react';
import { ReactNode } from 'react';
import { Reducer } from 'react';
import { ReducerAction } from 'react';
import { ReducerState } from 'react';
import { Ref } from 'react';
import { RefCallback } from 'react';
import { RefObject } from 'react';
import { SetStateAction } from 'react';
import { SyntheticEvent } from 'react';
import { useDeferredValue as useDeferredValue_2 } from 'react';
import { useId as useId_2 } from 'react';
import { useSyncExternalStore as useSyncExternalStore_2 } from 'react';
/**
* **`alphanumericCompare`**: Function which, given two strings, the type of comparison to be verified, and optional options, performs the comparison between the two strings and returns a boolean indicating whether the indicated comparison is respected or not. [See demo](https://react-tools.ndria.dev/#/utils/alphanumericCompare)
* @param {Object} param - object
* @param {string} param.string1 - first string to compare.
* @param {string} param.string2 - second string to compare.
* @param {"<" | ">" | "=" | ">=" | "<="} [param.compareType] - type of compare to verify.
* @param {Intl.LocalesArgument} [param.locales] - A string with a BCP 47 language tag or an Intl.Locale instance, or an array of such locale identifiers. The runtime's default locale is used when undefined is passed or when none of the specified locale identifiers is supported.
* @param {Intl.CollatorOptions} [param.opts] - An object adjusting the output format. Corresponds to the options parameter of the Intl.Collator() constructor.
* @returns {boolean|number} result - boolean or number that indicates whether the indicated comparison is respected or not.
*/
export declare function alphanumericCompare({ string1, string2, compareType, locales, opts }: {
string1: string;
string2: string;
compareType?: undefined;
locales?: Intl.LocalesArgument;
opts?: Intl.CollatorOptions;
}): number;
export declare function alphanumericCompare({ string1, string2, compareType, locales, opts }: {
string1: string;
string2: string;
compareType?: "<" | ">" | "=" | ">=" | "<=";
locales?: Intl.LocalesArgument;
opts?: Intl.CollatorOptions;
}): boolean;
/**
* Utility type that constructs an array of __`T`__ with one element at least.
*/
export declare type ArrayMinLength1<T> = {
0: T;
} & Array<T>;
export declare interface BatteryStatus {
isSupported: boolean;
level: number;
charging: boolean;
chargingTime: number;
dischargingTime: number;
}
export declare interface Bluetooth extends EventTarget {
/**Returns a Promise to a _BluetoothDevice_ object with the specified options.*/
requestDevice: (opts?: BluetoothDevicesOptions) => Promise<BluetoothDevice | TypeError | DOMException>;
}
/**Provides properties of a particular BluetoothRemoteGATTCharacteristic.*/
export declare interface BluetoothCharacteristicProperties {
/**Returns a boolean that is true if signed writing to the characteristic value is permitted.*/
readonly authenticatedSignedWrites: boolean;
/**Returns a boolean that is true if the broadcast of the characteristic value is permitted using the Server Characteristic Configuration Descriptor.*/
readonly broadcast: boolean;
/**Returns a boolean that is true if indications of the characteristic value with acknowledgement is permitted.*/
readonly indicate: boolean;
/**Returns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted.*/
readonly notify: boolean;
/**Returns a boolean that is true if the reading of the characteristic value is permitted.*/
readonly read: boolean;
/**Returns a boolean that is true if reliable writes to the characteristic is permitted.*/
readonly reliableWrite: boolean;
/**Returns a boolean that is true if reliable writes to the characteristic descriptor is permitted.*/
readonly writableAuxiliaries: boolean;
/**Returns a boolean that is true if the writing to the characteristic with response is permitted.*/
readonly write: boolean;
/**Returns a boolean that is true if the writing to the characteristic without response is permitted.*/
readonly writeWithoutResponse: boolean;
}
export declare type BluetoothCharacteristicUUID = number | string;
export declare type BluetoothDescriptorUUID = number | string;
/**Represents a Bluetooth device inside a particular script execution environment.*/
export declare interface BluetoothDevice {
/**A string that uniquely identifies a device.*/
readonly id: string;
/**A string that provides a human-readable name for the device.*/
readonly name: string;
/**A reference to the device's BluetoothRemoteGATTServer.*/
readonly gatt: BluetoothRemoteGATTServer;
}
export declare interface BluetoothDevicesOptions {
/**An array of BluetoothScanFilters. This filter consists of an array of _BluetoothServiceUUIDs_, a _name_ parameter, and a _namePrefix_ parameter.*/
filters?: BluetoothScanFilters[];
/**An array of _BluetoothServiceUUID_s.*/
optionalServices?: BluetoothServiceUUID[];
/**A boolean value indicating that the requesting script can accept all Bluetooth devices. The default is __false__.*/
acceptAllDevices?: boolean;
}
/**Represents a GATT Characteristic, which is a basic data element that provides further information about a peripheral's service.*/
export declare interface BluetoothRemoteGATTCharacteristic extends EventTarget {
/**Returns the _BluetoothRemoteGATTService_ this characteristic belongs to.*/
readonly service: BluetoothRemoteGATTService;
/**Returns a string containing the UUID of the characteristic, for example '00002a37-0000-1000-8000-00805f9b34fb' for the Heart Rate Measurement characteristic.*/
readonly uuid: BluetoothCharacteristicUUID;
/**Returns the properties of this characteristic.*/
readonly properties: BluetoothCharacteristicProperties;
/**The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication.*/
readonly value: ArrayBuffer;
/**Event handler for the characteristicvaluechanged event.*/
oncharacteristicvaluechanged: (evt: EventTarget) => void;
/**Returns a Promise that resolves to the first BluetoothRemoteGATTDescriptor for a given descriptor UUID.*/
getDescriptor: (uuid: BluetoothDescriptorUUID) => Promise<BluetoothRemoteGATTDescriptor>;
/**Returns a Promise that resolves to an Array of all BluetoothRemoteGATTDescriptor objects for a given descriptor UUID.*/
getDescriptors: (uuid: BluetoothDescriptorUUID) => Promise<BluetoothRemoteGATTDescriptor[]>;
/**Returns a Promise that resolves to an DataView holding a duplicate of the value property if it is available and supported. Otherwise it throws an error.*/
readValue: () => Promise<DataView>;
/**
* Sets the value property to the bytes contained in a given ArrayBuffer, calls WriteCharacteristicValue(this=this, value=value, response="optional"), and returns the resulting Promise.
* @deprecated
*/
writeValue: (value: ArrayBuffer) => Promise<void>;
/**Sets the value property to the bytes contained in a given ArrayBuffer, calls WriteCharacteristicValue(this=this, value=value, response="required"), and returns the resulting Promise.*/
writeValueWithResponse: (value: ArrayBuffer) => Promise<void>;
/**Sets the value property to the bytes contained in a given ArrayBuffer, calls WriteCharacteristicValue(this=this, value=value, response="never"), and returns the resulting Promise.*/
writeValueWithoutResponse: (value: ArrayBuffer) => Promise<void>;
/**Returns a Promise that resolves when navigator.bluetooth is added to the active notification context.*/
startNotifications: () => Promise<BluetoothRemoteGATTCharacteristic>;
/**Returns a Promise that resolves when navigator.bluetooth is removed from the active notification context.*/
stopNotifications: () => Promise<void>;
}
/**Represents a GATT Descriptor, which provides further information about a characteristic's value.*/
export declare interface BluetoothRemoteGATTDescriptor {
/**Returns the BluetoothRemoteGATTCharacteristic this descriptor belongs to.*/
characteristic: BluetoothRemoteGATTCharacteristic;
/**Returns the UUID of the characteristic descriptor, for example '00002902-0000-1000-8000-00805f9b34fb' for theClient Characteristic Configuration descriptor.*/
uuid: BluetoothDescriptorUUID;
/**Returns the currently cached descriptor value.This value gets updated when the value of the descriptor is read.*/
value: ArrayBuffer;
/**Returns a Promise that resolves to an ArrayBuffer holding a duplicate of the value property if it is available and supported.Otherwise it throws an error.*/
readValue: () => Promise<ArrayBuffer>;
/**Sets the value property to the bytes contained in an ArrayBuffer and returns a Promise.*/
writeValue: (value: ArrayBuffer) => Promise<void>;
}
/**Represents a GATT Server on a remote device.*/
export declare interface BluetoothRemoteGATTServer {
/**A boolean value that returns true while this script execution environment is connected to this.device. It can be false while the user agent is physically connected.*/
readonly connected: boolean;
/**A reference to the BluetoothDevice running the server.*/
readonly device: BluetoothDevice;
/**Causes the script execution environment to connect to _this.device_.*/
connect: () => Promise<BluetoothRemoteGATTServer>;
/**Causes the script execution environment to disconnect from _this.device_.*/
disconnect: () => void;
/**Returns a promise to the primary _BluetoothRemoteGATTService_ offered by the Bluetooth device for a specified _BluetoothServiceUUID_.*/
getPrimaryService: (uuid: BluetoothServiceUUID) => Promise<BluetoothRemoteGATTService>;
/**Returns a promise to a list of primary _BluetoothRemoteGATTService_ objects offered by the Bluetooth device for a specified _BluetoothServiceUUID_.*/
getPrimaryServices: (uuid: BluetoothServiceUUID) => Promise<BluetoothRemoteGATTService[]>;
}
/**Represents a service provided by a GATT server, including a device, a list of referenced services, and a list of the characteristics of this service.*/
export declare interface BluetoothRemoteGATTService {
/**Returns information about a Bluetooth device through an instance of _BluetoothDevice_.*/
readonly device: BluetoothDevice;
/**Returns a boolean value indicating whether this is a primary or secondary service.*/
readonly isPrimary: boolean;
/**Returns a string representing the UUID of this service.*/
readonly uuid: BluetoothServiceUUID;
/**Returns a Promise to an instance of BluetoothRemoteGATTCharacteristic for a given universally unique identifier (UUID).*/
getCharacteristic: (uuid: BluetoothCharacteristicUUID) => Promise<BluetoothRemoteGATTCharacteristic>;
/**Returns a Promise to an Array of BluetoothRemoteGATTCharacteristic instances for an optional universally unique identifier (UUID).*/
getCharacteristics: (uuid: BluetoothCharacteristicUUID) => Promise<BluetoothRemoteGATTCharacteristic[]>;
}
export declare type BluetoothScanFilters = {
name: string;
namePrefix: string;
services: BluetoothServiceUUID[];
} | {
name: string;
namePrefix?: never;
services?: never;
} | {
name: string;
namePrefix: string;
services?: never;
} | {
name: string;
namePrefix?: never;
services: BluetoothServiceUUID[];
} | {
name?: never;
namePrefix: string;
services: BluetoothServiceUUID[];
} | {
name?: never;
namePrefix?: never;
services: BluetoothServiceUUID[];
} | {
name?: never;
namePrefix: string;
services?: never;
};
export declare type BluetoothServiceUUID = number | string;
/**The CaptureController interface provides methods that can be used to further manipulate a capture session separate from its initiation via MediaDevices.getDisplayMedia().*/
export declare interface CaptureController {
/**controls whether the captured tab or window will be focused when an associated MediaDevices.getDisplayMedia() Promise fulfills, or whether the focus will remain with the tab containing the capturing app.*/
setFocusBehavior: (
/**An enumerated value that describes whether the user agent should transfer focus to the captured display surface, or keep the capturing app focused. Possible values are focus-captured-surface (transfer focus) and no-focus-change (keep focus on the capturing app).*/
focusBehavior: "focus-captured-surface" | "no-focus-change") => void;
}
/**
* **`changeStringCase`**: Function that given a string, a case type, and an optional delimiter, returns the string in the specified case or empty string. [See demo](https://react-tools.ndria.dev/#/utils/changeStringCase)
* @param {Object} param - object
* @param {string|undefined} [param.string] - string to the which change case.
* @param {"pascalCase" | "snakeCase" | "kebabCase" | "camelCase"} param.caseType - selected case to change string.
* @param {"upperCase" | "lowerCase" | string} [param.delemiter] - optional delemiter for case that support it.
* @returns {string} result - string with changed case or empty string.
*/
export declare function changeStringCase({ string, caseType, delimiter }: {
string?: string;
caseType: "pascalCase" | "snakeCase" | "kebabCase" | "camelCase";
delimiter?: "upperCase" | "lowerCase" | string;
}): string;
/**
* **`clickElementOnKeydownEvent`**: Function which, given a triggering code, executes _click_ on element when a keyDown event with triggering code is executed. [See demo](https://react-tools.ndria.dev/#/utils/clickElementOnKeydownEvent)
* @param {codeTriggering: KeyboardEventCode} codeTriggering
* @returns {(e: KeyboardEvent) => void}
*/
export declare function clickElementOnKeydownEvent(codeTriggering: KeyboardEventCode): ((e: KeyboardEvent) => void);
/**
* **`CompareFn<T>`**: receive 2 parameters of type T, respectively *old* and *new* version. It compares them
* and returns `true` if they are different, otherwise `false`.
*/
export declare interface CompareFn<T = unknown> {
(oldDeps: DependencyListTyped<T>, newDeps: DependencyListTyped<T>): boolean;
}
export declare interface ConnectionState {
isSupported: boolean;
isOnline: boolean;
since?: number;
downlink?: number;
downlinkMax?: number;
effectiveType?: "slow-2g" | "2g" | "3g" | "4g";
rtt?: number;
saveData?: boolean;
type?: "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown";
}
/**
* **`createPubSubStore`**: A state management hook implemented on Publish-Subscribe pattern. It allows components to subscribe to state changes and receive updates whenever the state is modified, providing a scalable and decoupled state management solution.__N.B.: to work properly, objects like Set, Map, Date or more generally objects without _Symbol.iterator_ must be treated as immutable__. [See demo](https://react-tools.ndria.dev/#/hooks/state/createPubSubStore)
* @param {T extends object} obj - Object that rapresent the initialState of the store.
* @param {E extends Record<string, (store: T, ...args: any) => void>} [mutatorsFn] - Object that contains specified void function to mutate the store value, not the store itself, that receives the store as first parameter and other optional parameters.
* @param {"localStorage" | "sessionStorge"|undefined} [persist=undefined] - value that indicates where persist the store, on the local or session Storage. If it isn't provided then store will not persist.
* @returns {{getStore:()=>T, mutateStore:(cb:(globStore:T)=>void), usePubSubStore:<C>(subscribe?: (store: T) => C)=>[T|C, (store: T|C|((currStore: T) => T)|((currStore: C) => C)) => void, () => T]}} result
* An object with:
* - __getStore__: __IMMUTABLE__ function that returns the store object.
* - __mutateStore__: __IMMUTABLE__ function that modifies the store value, not the store itself, by a void callback function that receives an only parameter, the store. Changes will be published to every subscriber.
* - __mutators__: object with __IMMUTABLE__ functions built on _mutatorsFn_ param, if it is present: they work like __mutateStore__ function and they can be executed passing them optional parameters if specified in _mutatorsFn param_. Changes will be published to every subscriber.
* - __usePubSubStore__: It's the hook to be used inside components to access the store. It receives an optional callback _subscribe_ to specify to which part of store you want to subscribe.If callback missed, the whole store will be subscribed. It returns an array of four elements:
* - _first element_: the __state__. It represents what has been subscribed.
* - _second element_: the __setState__. An _immutable_ function to update the state. It can be executed given it a new version of the subscribed value or with a callback that receives the subscribed value and returns a new version of it.
* - _third element_: the __getState__. An _immutable_ function that returns the current subscribed value.
* - _fourth element_: the __mutators__. Like above.
*/
export declare const createPubSubStore: <T extends object, E extends Record<string, (store: T, ...args: any) => void>>(obj: T, mutatorsFn?: E, persist?: "localStorage" | "sessionStorge") => {
getStore: () => T;
mutateStore: (cb: (globStore: T) => void) => void;
mutators: Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>;
usePubSubStore: {
(subscribe?: undefined): [T, (store: T | ((currStore: T) => T)) => void, () => T, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>];
<C>(subscribe?: ((store: T) => C) | undefined): [C, (store: C | ((currStore: C) => C)) => void, () => C, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>];
<C_1>(subscribe?: ((store: T) => C_1) | undefined): [T | C_1, (store: T | C_1 | ((currStore: T) => T) | ((currStore: C_1) => C_1)) => void, () => T, Record<keyof E, (...args: ExtractTail<Parameters<E[keyof E]>>) => void>];
};
};
declare const defaultConfig: UseResponsiveBreakpoints<"xs" | "sm" | "md" | "lg" | "xl">;
/**
* **`defaultSerializer`**: Function to serialize any type of value. [See demo](https://react-tools.ndria.dev/#/utils/defaultSerializer)
* @param {T} target
* @returns {string}
*/
export declare function defaultSerializer<T>(target: T): string;
/**
* Utility type that works like __DependencyList__ react type but it can be specified dependencies list element types.
*/
export declare type DependencyListTyped<T = unknown> = ReadonlyArray<T>;
/**
* **`detectBrowser`**: It detects used browser or return __"No detection"__. [See demo](https://react-tools.ndria.dev/#/utils/detectBrowser)
* @returns {"chrome"|"firefox"|"safari"|"opera"|"edge"|"No detection"} result
*/
export declare function detectBrowser(): "chrome" | "firefox" | "safari" | "opera" | "edge" | "No detection";
export declare interface DeviceMotionProps {
isSupported: boolean;
acceleration: DeviceMotionEventAcceleration | null;
accelerationIncludingGravity: DeviceMotionEventAcceleration | null;
rotationRate: DeviceMotionEventRotationRate | null;
interval: number | null;
}
export declare interface DeviceOrientationProps {
isSupported: boolean;
absolute: boolean | null;
alpha: number | null;
beta: number | null;
gamma: number | null;
}
export declare interface DocumentPictureInPictureEvent extends Event {
window: Window;
}
export declare interface DocumentPIPOptions {
window?: {
width: number;
height: number;
};
inheritCSS?: boolean;
}
/**
* **`ErrorBoundary`**: Wrapper component that lets you display some fallback UI when your application throws an error during rendering. [See demo](https://react-tools.ndria.dev/#/components/ErrorBoundary)
* @param {Object} props
* @param {(error:Error, info:ErrorInfo)=>void} [props.onCatch] - function that will be executed on component did catch.
* @param {ReactNode|((error: Error, info: ErrorInfo, retry: ()=>void)=>ReactNode)|((props: { error: Error, info: ErrorInfo, retry: ()=>void })=>JSX.Element)} [props.fallback] - it is rendered when an error occurred. It can be an element, or a Component or a function. If it is a component or a function, it receive the _error_ the _info_ and the _retry_ function as props. _retry_ function try to rerender.
* @param {ReactNode} props.children - element to render.
* @returns {JSX.Element} result - element or fallback.
*/
export declare class ErrorBoundary extends Component<PropsWithChildren<{
onCatch?: (error: Error, info: ErrorInfo) => void;
fallback?: ReactNode | ((error: Error, info: ErrorInfo, retry: () => void) => ReactNode) | ((props: {
error: Error;
info: ErrorInfo;
retry: () => void;
}) => JSX_2.Element);
}>, {
hasError: boolean;
error?: Error;
info?: ErrorInfo;
}> {
state: {
hasError: boolean;
error?: Error;
info?: ErrorInfo;
};
static getDerivedStateFromError(_: Error): {
hasError: boolean;
error?: Error;
info?: ErrorInfo;
};
componentDidCatch(error: Error, info: ErrorInfo): void;
retry(): void;
render(): string | number | boolean | Iterable<ReactNode> | JSX_2.Element | null | undefined;
}
/**
* Utility type that constructs an object from __`T`__ and whose property values are _`boolean`_.
*/
export declare type ErrorModel<T extends object> = {
[k in keyof T]: T[k] extends object ? ErrorModel<T[k]> : boolean;
};
/**
* Utility type that given an array extracts a new array with all elements from array expect last.
*/
export declare type ExtractHead<T extends unknown[]> = T extends [...infer Tail, unknown] ? Tail : never;
/**
* Utility type that given an array extracts a new array with all elements from array expect first and last.
*/
export declare type ExtractMiddle<T extends unknown[]> = T extends [unknown, ...infer Tail, unknown] ? Tail : never;
/**
* Utility type that given an array extracts a new array with all elements from array expect first.
*/
export declare type ExtractTail<T extends unknown[]> = T extends [unknown, ...infer Tail] ? Tail : never;
/**
* **`For`**: Component to optimize the rendering of a list of elements without need to specify a key value for all elements, and other options. [See demo](https://react-tools.ndria.dev/#/components/For)
* @param {Object} props - component properties object.
* @param {Array<T>} props.of - array of elements.
* @param {(T|S) extends object ? keyof (T|S) | ((item: T|S) => Key) : Key | ((item: T|S) => Key)} [props.elementKey] - if the elements are objects, this prop can be a key of the elements in __of__ prop, or a function with one parameter which type is the type of the elements in __of__ prop and returns a __React.Key__ type, otherwise this prop can be the function described before or a __React.Key__. If it isn't specified, element index in __of__ props will be used as key.
* @param {(item: T|S, index: number, key: Key) => ReactNode} props.children - it's a function that takes the current item as first argument and optionally a second argument that is the index of current item and a third element that is the key specified in the _elementKey_ prop. Item is the current element of __of__ prop or, if __map__ prop is present, is the current element produces from __map__ prop.
* @param {ReactNode} [props.fallback] - optional element to render when _of_ prop is an empty array.
* @param {Parameters<Array<T>["filter"]>[0]} [props.filter] - callback executed to filter _of_ elements.
* @param {undefined|((...args: Parameters<Parameters<Array<T>["map"]>[0]>) => S)} [props.map] - callback executed to map _of_ elements.
* @param {true|Parameters<Array<T>["sort"]>[0]} [props.sort] - callback executed to sort _of_ elements or __`true`__ to use native sort.
* @returns {null|JSX.Element|Array<JSX.Element>} result - elements list, rendered from _of_ prop or _fallback_ if exist, otherwise null.
*/
export declare function For<T>({ of, elementKey, fallback, filter, sort, map, children }: {
of: Array<T>;
elementKey?: T extends object ? keyof T | ((item: T) => Key) : Key | ((item: T) => Key);
children: (item: T, index: number, key: Key) => ReactNode;
fallback?: ReactNode;
filter?: Parameters<Array<T>["filter"]>[0];
sort?: true | Parameters<Array<T>["sort"]>[0];
map?: undefined;
}): null | JSX.Element | Array<JSX.Element>;
export declare function For<T, S extends T>({ of, elementKey, fallback, filter, sort, map, children }: {
of: Array<T>;
elementKey?: S extends object ? keyof S | ((item: S) => Key) : Key | ((item: S) => Key);
children: (item: S, index: number, key: Key) => ReactNode;
fallback?: ReactNode;
filter?: Parameters<Array<T>["filter"]>[0];
sort?: true | Parameters<Array<T>["sort"]>[0];
map?: (...args: Parameters<Parameters<Array<T>["map"]>[0]>) => S;
}): null | JSX.Element | Array<JSX.Element>;
export declare namespace For {
var displayName: string;
}
/**
* **`ForMemoized`**: Memoized version of _For_ component. [See demo](https://react-tools.ndria.dev/#/components/ForMemoized)
* @param {Object} props - component properties object.
* @param {Array<T>} props.of - array of elements.
* @param {(T|S) extends object ? keyof (T|S) | ((item: T|S) => Key) : Key | ((item: T|S) => Key)} [props.elementKey] - if the elements are objects, this prop can be a key of the elements in __of__ prop, or a function with one parameter which type is the type of the elements in __of__ prop and returns a __React.Key__ type, otherwise this prop can be the function described before or a __React.Key__. If it isn't specified, element index in __of__ props will be used as key.
* @param {(item: T|S, index: number, key: Key) => ReactNode} props.children - it's a function that takes the current item as first argument and optionally a second argument that is the index of current item and a third element that is the key specified in the _elementKey_ prop. Item is the current element of __of__ prop or, if __map__ prop is present, is the current element produces from __map__ prop.
* @param {ReactNode} [props.fallback] - optional element to render when _of_ prop is an empty array.
* @param {Parameters<Array<T>["filter"]>[0]} [props.filter] - callback executed to filter _of_ elements.
* @param {undefined|((...args: Parameters<Parameters<Array<T>["map"]>[0]>) => S)} [props.map] - callback executed to map _of_ elements.
* @param {true|Parameters<Array<T>["sort"]>[0]} [props.sort] - callback executed to sort _of_ elements or __`true`__ to use native sort.
* @returns {null|JSX.Element|Array<JSX.Element>} result - elements list, rendered from _of_ prop or _fallback_ if exist, otherwise null.
*/
export declare const ForMemoized: typeof For;
export declare type GeoLocationObject = ({
isSupported: true;
position?: GeolocationPosition;
}) | ({
isSupported: false;
position?: never;
});
/**
* **`getBase64`**: Function to obtain a Base64 from value specified if supported, otherwise throw an Error. [See demo](https://react-tools.ndria.dev/#/utils/getBase64)
* @param {string | Blob | ArrayBuffer | HTMLCanvasElement | HTMLImageElement | T | T[]} target
* @param {ToDataURLOptions | UseBase64ObjectOptions<T>} [options]
* @returns {string}
*/
export declare function getBase64(target: string, options?: undefined): Promise<string>;
export declare function getBase64(target: Blob, options?: undefined): Promise<string>;
export declare function getBase64(target: ArrayBuffer, options?: undefined): Promise<string>;
export declare function getBase64(target: HTMLCanvasElement, options?: ToDataURLOptions): Promise<string>;
export declare function getBase64(target: HTMLImageElement, options?: ToDataURLOptions): Promise<string>;
export declare function getBase64<T extends object>(target: T, options?: UseBase64ObjectOptions<T>): Promise<string>;
export declare function getBase64<T extends Map<string, unknown>>(target: T, options?: UseBase64ObjectOptions<T>): Promise<string>;
export declare function getBase64<T extends Set<unknown>>(target: T, options?: UseBase64ObjectOptions<T>): Promise<string>;
export declare function getBase64<T>(target: T[], options?: UseBase64ObjectOptions<T[]>): Promise<string>;
/**
* **`getKeyObjectFromValue`**: Function that given an object and a value, returns the corrispondent key of this value or undefined. [See demo](https://react-tools.ndria.dev/#/utils/getKeyObjectFromValue)
* @param {Record<string,unknown>} object - object from which get key by a value.
* @param {unknown} value - value of the object
* @returns {keyof Record<string,unknown>|undefined} key - object key for the given value.
*/
export declare function getKeyObjectFromValue<T extends Record<string, unknown>, E extends string | number | symbol = keyof T>(object: T, value?: unknown): E | undefined;
/**
* **`getObjectFromDottedString`**: Function that, given a path, a value and an optional object, returns an object with as many properties as there are in the path, assigning the value passed to the last one specified. [See demo](https://react-tools.ndria.dev/#/utils/getObjectFromDottedString)
* @param {string} path - string value separated by dot, indicating that path where assign the passed value.
* @param {unknown} value - value to assign to the property specified in path.
* @param {Record<string,unknown>} [object] - optional object that will be used as start object.
* @returns {Record<string, unknown>} result - object create by path and value indicated.
*/
export declare function getObjectFromDottedString<T, E extends Record<string, unknown>>(path: string, value: T, object?: E): E;
/**
* **`hotKeyHandler`**: utility function for _onKeyDown_ and _onKeyUp_ events handler that supports keys combination. [See demo](https://react-tools.ndria.dev/#/utils/hotKeyHandler)
* @param {`${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`} hotKeys - hotKey string: _ctrlCommand_ indicates to listen __Ctrl__ (on Windows) or __Command__ (on Mac) keys.
* @param {(evt: KeyboardEvent|React.KeyboardEvent<HTMLElement>) => void | Promise<void>} listener - listener to be executed on specified event
* @returns {(evt: KeyboardEvent|React.KeyboardEvent<HTMLElement>) => void}
*/
export declare const hotKeyHandler: (hotKeys: `${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`, listener: (evt: KeyboardEvent | KeyboardEvent_2<HTMLElement>) => void | Promise<void>) => (evt: KeyboardEvent | KeyboardEvent_2<HTMLElement>) => void;
export declare interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
popover?: "auto" | "manual";
}
export declare interface HTMLMediaControls {
play: () => Promise<void> | void;
pause: () => void;
mute: () => void;
unmute: () => void;
playbackRate: (playbackRate: number) => void;
volume: (volume: number) => void;
seek: (time: number) => void;
}
export declare interface HTMLMediaState {
buffered: {
start: number;
end: number;
}[] | null;
duration: number;
paused: boolean;
muted: boolean;
time: number;
volume: number;
playbackRate: number;
playing: boolean;
}
/**
* **`isAsync`**: It detects if a function is asynchronous. [See demo](https://react-tools.ndria.dev/#/utils/isAsync)
* @param {(...args: unknown[])=> unknown | Promise<unknown>} fn
* @returns {boolean} result
*/
export declare const isAsync: <T extends unknown[], E = unknown>(fn: E | Promise<E> | ((...args: T) => E | Promise<E>)) => boolean;
/**
* **`isClient`**: It detects if code is running on client. [See demo](https://react-tools.ndria.dev/#/utils/isClient)
* @returns {boolean} result
*/
export declare const isClient: () => boolean;
/**
* __`isDeepEqual`__: It returns true if the params are equal in depth. [See demo](https://react-tools.ndria.dev/#/utils/isDeepEqual)
* @param {unknown} objA
* @param {unknown} objB
* @param {WeakMap} [map=new WeakMap()]
* @returns {boolean} result
*/
export declare const isDeepEqual: (objA: unknown, objB: unknown, map?: WeakMap<WeakKey, any>) => boolean;
/**
* __`isMouseEvent`__: It returns true if the event param is of MouseEvent type. [See demo](https://react-tools.ndria.dev/#/utils/isMouseEvent)
* @param {SyntheticEvent} event
* @returns {boolean} result
*/
export declare const isMouseEvent: (event: SyntheticEvent) => boolean;
/**
* **`isShallowEqual`**: It returns true if the params are equal until first level depth. [See demo](https://react-tools.ndria.dev/#/utils/isShallowEqual)
* @param {unknown} objA
* @param {unknown} objB
* @returns {boolean} result
*/
export declare const isShallowEqual: (objA: unknown, objB: unknown) => boolean;
/**
* __`isTouchEvent`__: It returns true if the event param is of TouchEvent type. [See demo](https://react-tools.ndria.dev/#/utils/isTouchEvent)
* @param {SyntheticEvent} event
* @returns {boolean} result
*/
export declare const isTouchEvent: (event: SyntheticEvent | Event) => boolean;
/**
* Utility type for __`Keyboard Event Code`__
*/
export declare type KeyboardEventCode = "Escape" | "Digit1" | "Digit2" | "Digit3" | "Digit4" | "Digit5" | "Digit6" | "Digit7" | "Digit8" | "Digit9" | "Digit0" | "Minus" | "Equal" | "Backspace" | "Tab" | "KeyQ" | "KeyW" | "KeyE" | "KeyR" | "KeyT" | "KeyY" | "KeyU" | "KeyI" | "KeyO" | "KeyP" | "BracketLeft" | "BracketRight" | "Enter" | "ControlLeft" | "KeyA" | "KeyS" | "KeyD" | "KeyF" | "KeyG" | "KeyH" | "KeyJ" | "KeyK" | "KeyL" | "Semicolon" | "Quote" | "Backquote" | "ShiftLeft" | "Backslash" | "KeyZ" | "KeyX" | "KeyC" | "KeyV" | "KeyB" | "KeyN" | "KeyM" | "Comma" | "Period" | "Slash" | "ShiftRight" | "NumpadMultiply" | "AltLeft" | "Space" | "CapsLock" | "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "F8" | "F9" | "F10" | "Pause" | "ScrollLock" | "Numpad7" | "Numpad8" | "Numpad9" | "NumpadSubtract" | "Numpad4" | "Numpad5" | "Numpad6" | "NumpadAdd" | "Numpad1" | "Numpad2" | "Numpad3" | "Numpad0" | "NumpadDecimal" | "IntlBackslash" | "F11" | "F12" | "NumpadEqual" | "F13" | "F14" | "F15" | "F16" | "F17" | "F18" | "F19" | "F20" | "F21" | "F22" | "F23" | "KanaMode" | "Lang2" | "Lang1" | "IntlRo" | "F24" | "Lang4" | "Lang3" | "Convert" | "NonConvert" | "IntlYen" | "NumpadComma" | "MediaTrackPrevious" | "MediaTrackNext" | "NumpadEnter" | "ControlRight" | "AudioVolumeMute" | "LaunchApp2" | "MediaPlayPause" | "MediaStop" | "VolumeDown" | "AudioVolumeDown" | "VolumeUp" | "AudioVolumeUp" | "BrowserHome" | "NumpadDivide" | "PrintScreen" | "AltRight" | "NumLock" | "Pause" | "Home" | "ArrowUp" | "PageUp" | "ArrowLeft" | "ArrowRight" | "End" | "ArrowDown" | "PageDown" | "Insert" | "Delete" | "MetaLeft" | "OSLeft" | "MetaRight" | "MetaRight" | "ContextMenu" | "Power" | "BrowserSearch" | "BrowserFavorites" | "BrowserRefresh" | "BrowserStop" | "BrowserForward" | "BrowserBack" | "LaunchApp1" | "LaunchMail" | "MediaSelect";
/**
* Utility type for Language BCP-47 tags.
*/
export declare type LanguageBCP47Tags = "ar-SA" | "bn-BD" | "bn-IN" | "cs-CZ" | "da-DK" | "de-AT" | "de-CH" | "de-DE" | "el-GR" | "en-AU" | "en-CA" | "en-GB" | "en-IE" | "en-IN" | "en-NZ" | "en-US" | "en-ZA" | "es-AR" | "es-CL" | "es-CO" | "es-ES" | "Central-No" | "es-MX" | "es-US" | "fi-FI" | "fr-BE" | "fr-CA" | "fr-CH" | "fr-FR" | "he-IL" | "hi-IN" | "hu-HU" | "id-ID" | "it-CH" | "it-IT" | "ja-JP" | "ko-KR" | "nl-BE" | "nl-NL" | "no-NO" | "pl-PL" | "pt-BR" | "pt-PT" | "ro-RO" | "ru-RU" | "sk-SK" | "sv-SE" | "ta-IN" | "ta-LK" | "th-TH" | "tr-TR" | "zh-CN" | "zh-HK" | "zh-TW";
/**
* **`lazy`**: Wrapper around _React.lazy_ that works also with component without default export and with possibility to execute a function before and after component loading. [See demo](https://react-tools.ndria.dev/#/utils/lazy)
* @param {() => Promise<{ [k:string]: T }>} load - function that returns a Promise or another thenable.
* @param {Object} [opts] - optional settings.
* @param {string} [opts.componentName] - name of the of the module to load lazy. If it is missing, and the _load_ execution result not have a default property, the first key in res is returned as result.
* @param {()=> void} [opts.beforeLoad] - function that will be executed before load component.
* @param {()=> void} [opts.afterLoad] - function that will be executed after load component.
* @returns {LazyExoticComponent<T>} result - a React component you can render in your tree.
*/
export declare const lazy: <T extends ComponentType<unknown>>(load: () => Promise<{
[k: string]: T;
}>, opts?: {
componentName?: string;
beforeLoad?: () => void;
afterLoad?: () => void;
}) => LazyExoticComponent<T>;
/**
* **`LazyComponent`**: Component Wrapper to lazy loading a Component. [See demo](https://react-tools.ndria.dev/#/components/LazyComponent)
* @param {Object} param - properties to load component.
* @param {() => Promise<{ [k:string]: T }>} param.factory - function that returns a Promise or another thenable.
* @param {string} [param.componentName] - name of the of the module to load lazy. If it is missing, and the _load_ execution result not have a default property, the first key in res is returned as result.
* @param {ReactNode} [object.fallback] - optional element to render when _when_ prop is false.
* @param {()=>void} [param.beforeLoad] - function that will be executed before loading component .
* @param {()=>void} [param.afterLoad] - function that will be executed after loading component .
* @returns {JSX.Element} element
*/
export declare const LazyComponent: <T extends {
default: ComponentType<unknown>;
} | {
[k: string]: ComponentType<unknown>;
}>({ factory, componentName, fallback, beforeLoad, afterLoad }: {
factory: () => Promise<T>;
componentName?: string;
fallback?: ReactNode;
beforeLoad?: () => void;
afterLoad?: () => void;
}) => JSX_2.Element;
/**
* **`mergeObjects`**: Function that, given two objects version, merges them into a single one. Via an optional parameter _forceUndefinedValue_ you can define how undefined values are treated. [See demo](https://react-tools.ndria.dev/#/utils/mergeObjects)
* @param {object} oldObj - previous object version.
* @param {RecursivePartial<object>} newObj - new object version.
* @param {boolean} [forceUndefinedValue=false] - boolean to indicate how treat undefined value.
* @returns {Record<string, any>} result - mergedObject
*/
export declare function mergeObjects<T extends object>(oldObj: T, newObj: RecursivePartial<T>, forceUndefinedValue?: boolean): T;
/**
* Utility type that constructs a type by picking all properties and nested proprerties from __`T`__ in form _`property.nestedProprerty`_.
*/
export declare type NestedKeyOf<T extends Record<string, unknown>> = {
[Key in keyof T & (string | number)]: T[Key] extends Record<string, unknown> ? `${Key}.${NestedKeyOf<T[Key]>}` : `${Key}`;
}[keyof T & (string | number)];
/**
* Utility type that constructs a type that is __`T`__ or __`E`__, if specified otherwise __`null`__.
*/
export declare type Optional<T = unknown, E = null> = T | E;
export declare type OrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary";
/**
* Utility type that constructs a record with all properties set to optional.
*/
export declare type PartialRecord<K extends keyof any, T> = Partial<Record<K, T>>;
declare type PermissionNamePolyfill = "midi" | "ambient-light-sensor" | "accessibility-events" | "clipboard-read" | "clipboard-write" | "payment-handler" | "idle-detection" | "periodic-background-sync" | "system-wake-lock" | "window-management" | "window-placement" | "local-fonts" | "top-level-storage-access" | "captured-surface-control" | "persistent-storage" | "storage-access" | "accelerometer" | "background-fetch" | "bluetooth" | "camera" | "display-capture" | "geolocation" | "gyroscope" | "magnetometer" | "microphone" | "nfc" | "notifications" | "push" | "screen-wake-lock" | "speaker-selection";
/**
* Utility type that works like __Partial__ but set nested properties to optional also.
*/
export declare type RecursivePartial<T extends object> = {
[K in keyof T]?: T[K] extends object ? RecursivePartial<T[K]> : Partial<T[K]>;
};
/**
* **`removePropertiesFromArrayObjects`**: Function that, given an array of objects and a property or an array of properties, return a new array without specified properties. [See demo](https://react-tools.ndria.dev/#/utils/removePropertiesFromArrayObjects)
* @param {T[]} array - array of object.
* @param {keyof T| (keyof T)[]} property - a property object or an array of properties inside objects of the given array.
* @returns {Omit<T,E>[]} array - a new array without targeted properites.
*/
export declare function removePropertiesFromArrayObjects<T, E extends string | number | symbol = keyof T>(array: T[], property: E | E[]): Omit<T, E>[];
export declare interface ScreenDetail extends Omit<Screen, "orientation"> {
/** A number representing the x-coordinate (left-hand edge) of the available screen area. */
readonly availLeft: number | undefined;
/** A number representing the y - coordinate(top edge) of the available screen area. */
readonly availTop: number | undefined;
/** A number representing the screen's device pixel ratio. */
readonly devicePixelRatio: number | undefined;
/** A boolean indicating whether the screen is internal to the device or external. */
readonly isInternal: boolean | undefined;
/** A boolean indicating whether the screen is set as the operating system (OS) primary screen or not. */
readonly isPrimary: boolean | undefined;
/** A string providing a descriptive label for the screen, for example "Built-in Retina Display". */
readonly label: string | undefined;
/** A number representing the x-coordinate (left-hand edge) of the total screen area. */
readonly left: number | undefined;
/** A number representing the y-coordinate (top edge) of the total screen area. */
readonly top: number | undefined;
/** The current orientation of the screen. */
readonly orientation: {
/** The document's current orientation type, one of portrait-primary, portrait-secondary, landscape-primary, or landscape-secondary. */
type: OrientationType;
/** The document's current orientation angle. */
angle: number;
};
}
export declare interface ScreenDetails {
readonly currentScreen: ScreenDetail;
readonly screens: ScreenDetail[] | undefined;
}
/**
* Utility type that works like __Partial__ but allows to specify which properties set to optional.
*/
export declare type SelectivePartial<T extends object, E extends keyof T> = Omit<T, E> & Partial<Pick<T, E>>;
/**
* **`Show`**: Generic component used to conditional render part of the view: it renders _children_ when the _when_ prop is truthy, otherwise the _fallback_ prop, if it is present, or null. [See demo](https://react-tools.ndria.dev/#/components/Show)
* @param {PropsWithChildren<{when: T|boolean|undefined|null, fallback?: ReactNode}>} object
* @param {T|boolean|undefined|null} object.when - boolean indicating if to show _children_ or _fallback_/_null_.
* @param {ReactNode} [object.fallback] - optional element to render when _when_ prop is false.
* @param {PropsWithChildren<any>["children"]} [object.children] - optional element to render when _when_ prop is true.
* @returns {JSX.Element|null} element - the element rendered or null.
*/
export declare function Show<T>({ when, fallback, children }: PropsWithChildren<{
when: T | boolean | undefined | null;
fallback?: ReactNode;
}>): JSX_2.Element | null;
/**
* **`ShowMemoized`**: Memoized version of _Show_ component. [See demo](https://react-tools.ndria.dev/#/components/ShowMemoized)
* @param {PropsWithChildren<{when: T|boolean|undefined|null, fallback?: ReactNode}>} object
* @param {T|boolean|undefined|null} object.when - boolean indicating if to show _children_ or _fallback_/_null_.
* @param {ReactNode} [object.fallback] - optional element to render when _when_ prop is false.
* @param {PropsWithChildren<any>["children"]} [object.children] - optional element to render when _when_ prop is true.
* @returns {JSX.Element|null} element - the element rendered or null.
*/
export declare const ShowMemoized: MemoExoticComponent<typeof Show>;
/**The SpeechGrammar interface of the Web Speech API represents a set of words or patterns of words that we want the recognition service to recognize.*/
export declare interface SpeechGrammar {
/**Sets and returns a string containing the grammar from within in the SpeechGrammar object instance.*/
src: string;
/**Sets and returns the weight of the SpeechGrammar object.*/
weight?: number;
}
/**The SpeechGrammarList interface of the Web Speech API represents a list of SpeechGrammar objects containing words or patterns of words that we want the recognition service to recognize.*/
export declare interface SpeechGrammarList {
/**Returns the number of SpeechGrammar objects contained in the SpeechGrammarList.*/
readonly length: number;
/**Standard getter — allows individual SpeechGrammar objects to be retrieved from the SpeechGrammarList using array syntax.*/
item: (index: number) => SpeechGrammar;
/**Takes a grammar present at a specific URI and adds it to the SpeechGrammarList as a new SpeechGrammar object.*/
addFromURI: (
/**A string representing the URI of the grammar to be added.*/
src: string,
/**A float representing the weight of the grammar relative to other grammars present in the SpeechGrammarList. The weight means the importance of this grammar, or the likelihood that it will be recognized by the speech recognition service. The value can be between 0.0 and 1.0; If not specified, the default used is 1.0.*/
weight?: number) => undefined;
/**Adds a grammar in a string to the SpeechGrammarList as a new SpeechGrammar object.*/
addFromString: (
/**A string representing the URI of the grammar to be added.*/
src: string,
/**A float representing the weight of the grammar relative to other grammars present in the SpeechGrammarList. The weight means the importance of this grammar, or the likelihood that it will be recognized by the speech recognition service. The value can be between 0.0 and 1.0; If not specified, the default used is 1.0.*/
weight?: number) => undefined;
[index: number]: SpeechGrammar;
}
/**The SpeechRecognition interface of the Web Speech API is the controller interface for the recognition service; this also handles the SpeechRecognitionEvent sent from the recognition service.*/
export declare interface SpeechRecognition extends EventTarget {
/**Returns and sets a collection of _SpeechGrammar_ objects that represent the grammars that will be understood by the current SpeechRecognition.*/
grammars: SpeechGrammarList;
/**Returns and sets the language of the current SpeechRecognition. If not specified, this defaults to the HTML lang attribute value, or the user agent's language setting if that isn't set either.*/
lang: LanguageBCP47Tags;
/**Controls whether continuous results are returned for each recognition, or only a single result. Defaults to single (false.)*/
continuous: boolean;
/**Controls whether interim results should be returned (true) or not (false.) Interim results are results that are not yet final (e.g. the SpeechRecognitionResult.isFinal property is false.)*/
interimResults: boolean;
/**Sets the maximum number of SpeechRecognitionAlternatives provided per result. The default value is 1.*/
maxAlternatives: number;
/**Fired when the user agent has started to capture audio.*/
onaudiostart: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when the user agent has finished capturing audio.*/
onaudioend: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when the speech recognition service has disconnected.*/
onend: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when a speech recognition error occurs.*/
onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null;
/**Fired when the speech recognition service returns a final result with no significant recognition. This may involve some degree of recognition, which doesn't meet or exceed the confidence threshold.*/
onnomatch: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null;
/**Fired when the speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.*/
onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null;
/**Fired when any sound — recognizable speech or not — has been detected.*/
onsoundstart: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when any sound — recognizable speech or not — has stopped being detected.*/
onsoundend: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when sound that is recognized by the speech recognition service as speech has been detected.*/
onspeechstart: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when speech recognized by the speech recognition service has stopped being detected.*/
onspeechend: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Fired when the speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.*/
onstart: ((this: SpeechRecognition, ev: Event) => void) | null;
/**Stops the speech recognition service from listening to incoming audio, and doesn't attempt to return a SpeechRecognitionResult.*/
abort(): void;
/**Starts the speech recognition service listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.*/
start(): void;
/**Stops the speech recognition service from listening to incoming audio, and attempts to return a SpeechRecognitionResult using the audio captured so far.*/
stop(): void;
addEventListener<K extends keyof SpeechRecognitionEventMap>(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => void, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof SpeechRecognitionEventMap>(type: K, listener: (this: SpeechRecognition, ev: SpeechRecognitionEventMap[K]) => void, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
export declare interface SpeechRecognitionConfig {
/**Returns and sets a collection of _SpeechGrammar_ objects that represent the grammars that will be understood by the current SpeechRecognition.*/
grammars?: SpeechGrammarList;
/**Returns and sets the language of the current SpeechRecognition. If not specified, this defaults to the HTML lang attribute value, or the user agent's language setting if that isn't set either.*/
lang?: LanguageBCP47Tags;
/**Controls whether continuous results are returned for each recognition, or only a single result. Defaults to single (false.)*/
continuous?: boolean;
/**Controls whether interim results should be returned (true) or not (false.) Interim results are results that are not yet final (e.g. the SpeechRecognitionResult.isFinal property is false.)*/
interimResults?: boolean;
/**Sets the maximum number of SpeechRecognitionAlternatives provided per result. The default value is 1.*/
maxAlternatives?: number;
}
export declare type SpeechRecognitionErrorCode = 'aborted' | 'audio-capture' | 'bad-grammar' | 'language-not-supported' | 'network' | 'no-speech' | 'not-allowed' | 'service-not-allowed';
export declare interface SpeechRecognitionErrorEvent extends Event {
readonly error: SpeechRecognitionErrorCode;
readonly message?: string;
}
export declare interface SpeechRecognitionEvent extends Event {
/**Returns the lowest index value result in the SpeechRecognitionResultList "array" that has actually changed.*/
readonly resultIndex: number;
/**Returns a SpeechRecognitionResultList object representing all the speech recognition results for the current session.*/
results: SpeechRecognitionResultList;
}
declare interface SpeechRecognitionEventMap {
'audioend': Event;
'audiostart': Event;
'end': Event;
'error': SpeechRecognitionErrorEvent;
'nomatch': SpeechRecognitionEvent;
'result': SpeechRecognitionEvent;
'soundend': Event;
'soundstart': Event;
'speechend': Event;
'speechstart': Event;
'start': Event;
}
/**The interface of state value returned from _useSpeechRecognition_ hook.*/
export declare interface SpeechRecognitionState {
/**Returns a boolean value indicating SpeechRecognition availability.*/
isSupported: boolean;
/**Returns a boolean value indicating if SpeechRecognition is listening or not.*/
isListening: boolean;
/**Returns an object with _results_ and _resultIndex_ properties of SpeechRecognition execution.*/
result: {
results: SpeechRecognitionEvent["results"] | null;
resultIndex: SpeechRecognitionEvent["resultIndex"] | null;
};
}
declare type SpeechSynthesisonCancel = ((this: SpeechSynthesisUtterance, ev: {
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisEvent/charIndex).*/
readonly charIndex: number;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisEvent/charLength).*/
readonly charLength: number;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisEvent/elapsedTime).*/
readonly elapsedTime: number;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisEvent/name).*/
readonly name: string;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisEvent/utterance).*/
readonly utterance: SpeechSynthesisUtterance;
}) => void) | null;
export declare type SpeechSynthesisSpeakParam = SpeechSynthesisUtterance["text"] | ({
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/text).*/
text: SpeechSynthesisUtterance["text"];
/**boolean that if true invokes __speak__ method of _SpeechSynthesis_ cancelling currenty speaking.*/
startImmediatly?: boolean;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/start_event).*/
onStart?: SpeechSynthesisUtterance["onstart"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/pause_event).*/
onPause?: SpeechSynthesisUtterance["onpause"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/resume_event).*/
onResume?: SpeechSynthesisUtterance["onresume"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/boundary_event).*/
onBoundary?: SpeechSynthesisUtterance["onboundary"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/mark_event).*/
onMark?: SpeechSynthesisUtterance["onmark"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/error_event).*/
onError?: SpeechSynthesisUtterance["onerror"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/end_event).*/
onEnd?: SpeechSynthesisUtterance["onend"];
onCancel?: SpeechSynthesisonCancel;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/lang).*/
lang?: LanguageBCP47Tags;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/pitch).*/
pitch?: SpeechSynthesisUtterance["pitch"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/rate).*/
rate?: SpeechSynthesisUtterance["rate"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/voice).*/
voice?: SpeechSynthesisUtterance["voice"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/volume).*/
volume?: SpeechSynthesisUtterance["volume"];
});
export declare interface StateValidator<T> {
(this: T, state: T, validation: T extends object ? {
[k in keyof T]: {
invalid: boolean;
message?: string;
};
} : {
invalid: boolean;
message?: string;
}): typeof validation;
(state: T, validation: T extends object ? {
[k in keyof T]: {
invalid: boolean;
message?: string;
};
} : {
invalid: boolean;
message?: string;
}): typeof validation;
}
export declare type SwipeDirection = "up" | "right" | "down" | "left" | "none";
/**
* **`SwitchCase`**: It works like switch-case construct. It useful for when there are more than 2 mutual exclusive conditions. [See demo](https://react-tools.ndria.dev/#/components/SwitchCase)
* @param {Object} object - Object with _Switch_ and _Case_ components.
* @returns {{Switch: (props:{children:ReactElement<CaseProps>|ReactElement<CaseProps>[], fallback?:ReactNode})=>JSX.Element|null, Case: (props:{children:ReactNode, when:booleaan|undefined|null})=>JSX.Element|null}}
*/
export declare const SwitchCase: {
Switch: ({ children, fallback }: {
children: ReactElement<PropsWithChildren<{
when: boolean | null | undefined;
}>, string | JSXElementConstructor<any>> | ReactElement<PropsWithChildren<{
when: boolean | null | undefined;
}>, string | JSXElementConstructor<any>>[];
fallback?: ReactNode;
}) => JSX_2.Element | null;
Case: ({ children, when }: PropsWithChildren<{
when: boolean | null | undefined;
}>) => JSX_2.Element | null;
};
/**
* **`SwitchCaseMemoized`**: Memoized version of _SwitchCase_ component. [See demo](https://react-tools.ndria.dev/#/components/SwitchCaseMemoized)
* @param {Object} object - Object with _Switch_ and _Case_ components.
* @returns {{Switch: (props:{children:ReactElement<CaseProps>|ReactElement<CaseProps>[], fallback?:ReactNode})=>JSX.Element|null, Case: (props:{children:ReactNode, when:booleaan|undefined|null})=>JSX.Element|null}}
*/
export declare const SwitchCaseMemoized: {
Switch: MemoExoticComponent<({ children, fallback }: {
children: ReactElement<PropsWithChildren<{
when: boolean | null | undefined;
}>, string | JSXElementConstructor<any>> | ReactElement<PropsWithChildren<{
when: boolean | null | undefined;
}>, string | JSXElementConstructor<any>>[];
fallback?: ReactNode;
}) => JSX_2.Element | null>;
Case: MemoExoticComponent<({ children, when }: PropsWithChildren<{
when: boolean | null | undefined;
}>) => JSX_2.Element | null>;
};
export declare type TDisplayMediaStreamOptions = DisplayMediaStreamOptions & {
controller?: CaptureController;
};
export declare interface TextSelection {
text: string;
direction: "forward" | "backward";
outsideRectangle: DOMRect;
innerRectangles: DOMRect[];
}
export declare interface ToDataURLOptions {
/**MIME type*/
type?: string | undefined;
/**A Number between 0 and 1 indicating the image quality to be used when creating images*/
quality?: number;
}
export declare type TPermissionName = PermissionName | PermissionNamePolyfill;
export declare type TPermissionState = PermissionState | "not supported" | "asking";
/**
* Utility type for __`Typed Arrays`__.
*/
export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
/**
* **`uniqueElementsArray`**: Function that given one or more array of object, returns a single array with unique elements by a specified property, an array of properties or _none_. [See demo](https://react-tools.ndria.dev/#/utils/uniqueElementsArray)
* @param {keyof T | (keyof T)[] | "none"} property - propertyo or array of properties of the arrays, or _none_. If elements of the arrays aren't objects, _none_ is required.
* @param {(T[])[]} args - arrays from which remove duplicated.
* @returns {T[]} result - array
*/
export declare function uniqueElementsArray<T extends string | number | boolean | ((...args: unknown[]) => unknown) | bigint>(property: "none", ...args: (T[])[]): T[];
export declare function uniqueElementsArray<T extends object>(property: keyof T | (keyof T)[] | "none", ...args: (T[])[]): T[];
/**
* **`useActiveElement`**: Hook that returns activeElement and listen its changes. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useActiveElement)
* @returns {Element | null} activeELement
*/
export declare const useActiveElement: () => Element | null;
/**
* **`useAnimation`**: Hook to use [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useAnimation)
* @param {UseAnimationProps} param - object
* @param {Keyframe[] | PropertyIndexedKeyframes | null} param.keyFrames - array of keyfram objects ot a keyframe object whose properties are arrays of values to iterate over.
* @param {boolean} [param.immediate=false] - boolean to start animation immediatly or not.
* @param {number | KeyframeAnimationOptions} [param.opts] - either an integer representing the animation's duration (in milliseconds), or an Object containing one or more timing properties.
* @param {(this: Animation, evt: AnimationPlaybackEvent) => void} [param.onFinish] - function that will be executed when animation has been finished.
* @param {(this: Animation, evt: Event) => void} [param.onRemove] - function that will be executed when animation has been removed.
* @param {(this: Animation, evt: AnimationPlaybackEvent) => void} [param.onCancel] - function that will be executed when animation has been canceled.
* @param {(err: unknown) => void} [param.onError] - function that will be executed when an error occurred.
* @returns {UseAnimationResult} result
* Object with these properties:
* - __isSupported__: boolean to indicate if Web Animations API is supported or not.
* - __ref__: RefCallback that need to be attached to element to animate.
* - __playAnimation__: function to play animation.
* - __pauseAnimation__: function to pause animation.
* - __finishAnimation__: function to finish animation.
* - __cancelAnimation__: function to cancel animation.
* - __persistAnimation__: function to persist animation.
* - __reverseAnimation__: function to reverse animation.
* - __commitStyles__: function that writes the computed values of the animation's current styles into its target element's style attribute.
* - __updatePlaybackRate__: function that sets the speed of an animation after first synchronizing its playback position.
*/
export declare const useAnimation: <T extends Element>({ keyFrames, immediate, opts, onCancel, onFinish, onRemove, onError }: UseAnimationProps) => UseAnimationResult<T>;
export declare interface UseAnimationProps {
keyFrames: Keyframe[] | PropertyIndexedKeyframes | null;
immediate?: boolean;
opts?: number | KeyframeAnimationOptions;
onFinish?: (this: Animation, evt: AnimationPlaybackEvent) => void;
onRemove?: (this: Animation, evt: Event) => void;
onCancel?: (this: Animation, evt: AnimationPlaybackEvent) => void;
onError?: (err: unknown) => void;
}
export declare interface UseAnimationResult<T extends Element> {
isSupported: boolean;
ref: RefCallback<T>;
playAnimation: () => void;
pauseAnimation: () => void;
finishAnimation: () => void;
cancelAnimation: () => void;
persistAnimation: () => void;
reverseAnimation: () => void;
commitStyles: () => void;
updatePlaybackRate: (playbackRate: number) => void;
}
/**
* __`useArray`__: Hook to use _Array data structure_ to handle component state with all Array methods. [See demo](https://react-tools.ndria.dev/#/hooks/state/useArray)
* @param {Array<T> | (() => Array<T>} [initialState] - An Array or function that returns it.
* @returns {Array<T>}
*/
export declare const useArray: <T>(initialState?: Array<T> | (() => Array<T>)) => T[];
/**
* **`useAudio`**: Hook to use an HTML audio element. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useAudio)
* @param {UseAudioProps} param - Media HTML Attributes of an html audio element.
* @returns {UseAudioResult} result
* Object with these properties:
* - __state__: object with current audio properties:
* - _buffered_: array of objects, with __start__ and __end__ properties, or null. It indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed.
- _duration_: a read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is NaN.
- _paused_: returns a boolean that indicates whether the media element is paused.
- _muted_: boolean that determines whether audio is muted. true if the audio is muted and false otherwise.
- _time_: value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline.
- _volume_: double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
- _playbackRate_: double that indicates the rate at which the media is being played back.
- _playing_: boolean indicating if audio is playing or not.
* - __controls__: object with current audio properties:
* - _play_: function to set audio.
* - _pause_: function to pause audio.
* - _mute_: function to mute audio.
* - _unmute_: function to unmute audio.
* - _playbackRate_: function to set audio playbackRate.
* - _volume_: function to set audio volume.
* - _seek_: function to seek to the given time with low precision.
* - MediaElement: HTMLAudioElement to render.
* - ref: ref to HTMLAudioElement.
*/
export declare const useAudio: (props: MediaHTMLAttributes<HTMLAudioElement>) => {
MediaElement: ReactElement<DetailedReactHTMLElement<HTMLAttributes_2<HTMLAudioElement>, HTMLAudioElement>, string | JSXElementConstructor<any>>;
state: HTMLMediaState;
controls: {
play: () => Promise<void> | undefined;
pause: () => void;
seek: (time: number) => void;
playbackRate: (playbackRate: number) => void;
volume: (volume: number) => void;
mute: () => void;
unmute: () => void;
};
ref: MutableRefObject<HTMLAudioElement | null>;
};
export declare type UseAudioProps = MediaHTMLAttributes<HTMLAudioElement>;
export declare interface UseAudioResult {
state: HTMLMediaState;
controls: HTMLMediaControls;
MediaElement: DetailedReactHTMLElement<HTMLAttributes_2<HTMLAudioElement>, HTMLAudioElement>;
ref: MutableRefObject<HTMLAudioElement | null>;
}
export declare interface UseBase64ObjectOptions<T> {
serializer: (v: T) => string;
}
/**
* **`useBattery`**: Hook for accessing and monitoring device battery status. Refer to [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useBattery)
* @param {Object} [opts] - optional object parameter to listen battery events change.
* @param {(evt: Event) => void} [opts.onChargingChange] - callback that will be executed when chargingchange event is fired.
* @param {(evt: Event) => void} [opts.onChargingTimeChange] - callback that will be executed when chargingtimechange event is fired.
* @param {(evt: Event) => void} [opts.onDischargingTimeChange] - callback that will be executed when dischargingtimechange event is fired.
* @param {(evt: Event) => void} [opts.onLevelChange] - callback that will be executed when levelchange event is fired.
* @returns {BatteryStatus} result
* Object with:
* - __isSupported__: boolean that indicates if Battery Status API is available.
* - __level__: number that indicates battery level: is a number between 0 and 1.
* - __charging__: boolean that indicates if battery is charging.
* - __chargingTime__: number that indicates time in seconds remaining to full charge, or infinity.
* - __dischargingTime__: number that indicates time in seconds remaining to empty charge, rounded in 15 minutes by API.
*/
export declare const useBattery: (opts?: {
onChargingChange?: (evt: Event) => void;
onChargingTimeChange?: (evt: Event) => void;
onDischargingTimeChange?: (evt: Event) => void;
onLevelChange?: (evt: Event) => void;
}) => BatteryStatus;
/**
* **`useBeforeUnload`**: Hook to handle beforeunload event. [See demo](https://react-tools.ndria.dev/#/hooks/events/useBeforeUnload)
* @param {Object} options
* @param {(evt: BeforeUnloadEvent) => void} options.listener - listener to be executed on beforeunload event fired.
* @param {RefObject<HTMLElement> | Window} [options.element=window] - element on which attaching eventListener.
* @param {boolean | AddEventListenerOptions} [options.listenerOpts] - options for listener
* @returns {()=>void} remove - function to manually remove listener.
*/
export declare const useBeforeUnload: ({ element, listener, opts }: {
element?: RefObject<HTMLElement> | Window | undefined;
listener: (evt: BeforeUnloadEvent) => void;
opts?: boolean | AddEventListenerOptions;
}) => () => void;
/**
* **`useBluetooth`**: Hook to use [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useBluetooth)
* @returns {[{isSupported: boolean, isConnected: boolean, device: BluetoothDevice|null, server: BluetoothRemoteGATTServer|null}, (opts?: BluetoothDevicesOptions)=>Promise<void>]} result
*/
export declare const useBluetooth: () => [{
isSupported: boolean;
isConnected: boolean;
device: BluetoothDevice | null;
server: BluetoothRemoteGATTServer | null;
}, (opts?: BluetoothDevicesOptions) => Promise<void>];
/**
* **`useBroadcastChannel`**: Hook to use [Broadcast Channel API](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useBroadcastChannel)
* @param {string} name - broadcast channel name.
* @param {(evt:MessageEvent)=>void} [onMessage] - function that will be execute when a message occurred.
* @param {(evt:MessageEvent)=>void} [onError] - function that will be execute when a error message occurred.
* @returns {[T|undefined, (data:T)=>void]} result
* Array of:
* - first element: __data__ received in broadcast channel.
* - second element: __send__ function to send data on broadcast channel.
*/
export declare const useBroadcastChannel: <T>(name: string, onMessage?: (evt: MessageEvent<T>) => void, onError?: (evt: MessageEvent) => void) => [T | undefined, (data: T) => void];
/**
* **`useCallbackCompare`**: custom useCallback that returns memoized callback that changes only when comparator function, received as third parameter, returns true. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useCallbackCompare)
* @param {T} cb - callback.
* @param {DependencyListTyped} deps - typed DependencyList.
* @param {CompareFn} [compareFn] - optional function that executes comparing between old and new `deps`: it returns true if they are different, otherwise false. If there isn't, hook works like normal useCallback.
* @returns {T} cb - memoized callback
*/
export declare const useCallbackCompare: <T extends Function, E = unknown>(cb: T, deps: DependencyListTyped<E>, compareFn?: CompareFn<E>) => T;
/**
* **`useCallbackDeepCompare`**: custom useCallback that returns memoized callback that changes only if deps are different in depth. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useCallbackDeepCompare)
* @param {T} cb - callback.
* @param {React.DependencyList} deps - DependencyList.
* @returns {T} cb - memoized callback
*/
export declare const useCallbackDeepCompare: <T extends Function>(cb: T, deps: DependencyList) => T;
/**
* **`useClickOutside`**: Hook to listen and execute an action when there is a click outside an element. [See demo](https://react-tools.ndria.dev/#/hooks/events/useClickOutside)
* @param {RefObject<HTMLElement> | HTMLElement} target - DOM element or ref
* @param {(evt:Event)=>void} handler - callback to be executed.
*/
export declare const useClickOutside: (target: RefObject<HTMLElement> | HTMLElement, handler: (evt: Event) => void) => void;
/**
* **`useClipboard`**: Hook to handle Clipboard. Refers to [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API). __N.B.__: The hook has the same compatibility issues as the Clipboard API for Firefox, i.e. it is currently impossible to read from the clipboard. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useClipboard)
* @param {Object} param
* @param {boolean} param.useValue - return a value with current clipboard value or not.
* @param {RefObject<HTMLElement>|HTMLElement} [param.target] - target on which delimiter handling.
* @param {"text"|"any"} [param.dataType] - data type handling. Based on it, Hook will return the functions for writing or reading text only or any type of data.
* @returns {[string, (text: string) => Promise<void>, () => Promise<string>] | [string|Blob|(string|Blob)[], (blob: Blob|Blob[]) => Promise<void>, () => Promise<string|Blob|(string|Blob)[]>] | [(text: string) => Promise<void>, () => Promise<string>] | [(blob: Blob|Blob[]) => Promise<void>, () => Promise<string|Blob|(string|Blob)[]>]} array - elements depends on _useValue_ and _dataType_ values: if _dataType_ equals __text__ there will are only function to writing and reading text data type, otherwise any data type. If _useValue_ is true the first element will be _clipboard current value_.
*/
export declare function useClipboard({ useValue, dataType, target }: {
useValue: true;
dataType: "text";
target?: RefObject<HTMLElement> | HTMLElement;
}): [string, (text: string) => Promise<void>, () => Promise<string>];
export declare function useClipboard({ useValue, dataType, target }: {
useValue: true;
dataType: "any";
target?: RefObject<HTMLElement> | HTMLElement;
}): [string | Blob | (string | Blob)[], (blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>];
export declare function useClipboard({ useValue, dataType, target }: {
useValue: false;
dataType: "text";
target?: RefObject<HTMLElement> | HTMLElement;
}): [(text: string) => Promise<void>, () => Promise<string>];
export declare function useClipboard({ useValue, dataType, target }: {
useValue: false;
dataType: "any";
target?: RefObject<HTMLElement> | HTMLElement;
}): [(blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>];
/**
* **`useColorScheme`**: Hook to handle ColorScheme. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useColorScheme)
* @param {Object} param
* @param {"dark"|"light"|"mediaQuery"} param.defaultValue - initial value if _getter_ function isn't present or isn't return a valid value. It can be _dark_ _light_ or _mediaQuery_ which means that must to be used media query prefers-color-scheme to detect initial value.
* @param {()=>"dark"|"light"|null|undefined} [param.getter] - an optional function used to initialize current value. For example, it can be useful for reading the value from an attribute of an html file or from localStorage.
* @param {("dark"|"light")=>void} [param.setter] - an optional function, which should work in conjunction with the _getter_ function, to run when the color scheme changes to save the value for future runs.
* @param {boolean} param.returnValue - if true returns only a function to manually change the color scheme value.
* @returns {["dark"|"light", (schema:"dark"|"light") => void] | (schema:"dark"|"light") => void} result - if _returnValue_ is true, _result_ is the function to update color scheme value, otherwise is an array where first element is current value and second element is the function to update value.
*/
export declare function useColorScheme({ defaultValue, getter, setter, returnValue }: {
defaultValue: "dark" | "light" | "mediaQuery";
getter?: () => "dark" | "light" | null | undefined;
setter?: (schema: "light" | "dark") => void;
returnValue: true;
}): ["light" | "dark", (schema: "light" | "dark") => void];
export declare function useColorScheme({ defaultValue, getter, setter, returnValue }: {
defaultValue: "dark" | "light" | "mediaQuery";
getter?: () => "dark" | "light" | null | undefined;
setter?: (schema: "light" | "dark") => void;
returnValue: false;
}): ((schema: "light" | "dark") => void);
/**
* **`useContextMenu`**: Hook to add contextmenu event listener. The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key. [See demo](https://react-tools.ndria.dev/#/hooks/events/useContextMenu)
* @param {Object} param - props
* @param {(evt: PointerEvent)=>void|Promise<void>} [param.listener] - listener function executed when event fires.
* @param {RefObject<HTMLElement> | Window} [options.element=window] - element on which attaching eventListener.
* @param {"normal"|"layout"} [param.effectType="normal"] - props
* @param {boolean | AddEventListenerOptions} [param.listenerOpts] - props
*/
export declare const useContextMenu: ({ element, listener, effectType, listenerOpts }: {
element: RefObject<HTMLElement> | Window;
listener: (evt: PointerEvent) => void | Promise<void>;
effectType?: "normal" | "layout";
listenerOpts?: boolean | AddEventListenerOptions | undefined;
}) => void;
/**
* **`useDebounce`**: Hook to delay a function execution with possibility to cancel execution and to invoke them immediately. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDebounce)
* @param {T extends (...args: unknown[]) => void} fn - The function to debounce.
* @param {Object} opts - options for debounce behaviors.
* @param {number} opts.delay - time in milliseconds to delay function execution.
* @param {boolean} [opts.focusedWindow] - if true, the function is executed after delay but only if the window is focused. __N.B._: works only in browser context.
* @returns {[(...args: unknown[]) => void, ()=>void, (...args: unknown[]) => void]} - array with debounced function, cancel function to abor debounced function and and immediate function to execute function immediately.
*/
export declare const useDebounce: <T extends unknown[]>(fn: (...args: T) => void, opts: {
delay: number;
focusedWindow?: boolean;
}) => [(...args: T) => void, () => void, (...args: T) => void];
export declare const useDeferredValue: typeof useDeferredValue_2;
/**
* **`useDerivedState`**: Hook useful when the internal state of a component depends on one or more props. It receives an _initial state_ and a _dependency array_ that works the same way as that of a _useEffect_, _useMemo_, and _useCallback_. Every time the dependencies change, the __derived state__ is resetted to _initial state_. A third optional parameter can be passed, to execute a _compute_ function after the dependencies are updated, without having a _useEffect_ within the component. [See demo](https://react-tools.ndria.dev/#/hooks/state/useDerivedState)
* @param {T|()=>T} initialState
* @param {DependencyList} deps - dependencies list from which depends derived state.
* @param {EffectCallback} [compute] - function that will be executed when dependencies list change after resetting derived state to __initialState__.
* @returns {[T, Dispatch<SetStateAction<T>>]} result - array with a stateful value and a function to update it.
*/
export declare const useDerivedState: <T>(initialState: T | (() => T), deps: DependencyList, compute?: EffectCallback) => [T, Dispatch<SetStateAction<T>>];
/**
* **`useDeviceMotion`**: Hook to handle [device motion](https://developer.mozilla.org/en-US/docs/Web/API/Window/devicemotion_event). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDeviceMotion)
* @returns {DeviceMotionProps} props - device motion properties.
*/
export declare const useDeviceMotion: () => DeviceMotionProps;
/**
* **`useDeviceOrientation`**: Hook to handle [device orientation](https://developer.mozilla.org/en-US/docs/Web/API/Window/deviceorientation_event). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDeviceOrientation)
* @returns {DeviceOrientationProps} props - device orientation properties.
*/
export declare const useDeviceOrientation: () => DeviceOrientationProps;
/**
* **`useDialogBox`**: Hook to use Dialog Box _prompt_, _alert_ or _confirm_. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDialogBox)
* @param {"prompt"|"alert"|"confirm"} type - set dialog box type.
* @returns {((message?: string, default?: string) => string|null) | ((message?: any) => void) | ((message?: string) => boolean)} open - function to activate dialog box.
*/
export declare function useDialogBox(type: "prompt"): ((message?: string, _default?: string) => string | null);
export declare function useDialogBox(type: "alert"): ((message?: any) => void);
export declare function useDialogBox(type: "confirm"): ((message?: string) => boolean);
/**
* **`useDisplayMedia`**: Hook to capture the contents of a display. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDisplayMedia)
* @returns {[MediaStream|undefined, (options: TDisplayMediaStreamOptions | undefined) => Promise<void>, ()=>void]} result
* Array containing:
* - first element: the captured stream.
* - second element: function that starts capture.
* - third element: function that stops capture.
*/
export declare const useDisplayMedia: () => [MediaStream | undefined, (options?: TDisplayMediaStreamOptions) => Promise<void>, () => void];
/**
* **`useDocumentPIP`**: Hook to use Document PIP [(Document-Picture-in-Picture API)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Picture-in-Picture_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useDocumentPIP)
* @param {UseDocumentPIPProps} param - object
* @param {DocumentPIPOptions} [param.options] - object
* @param {boolean} [param.options.inheritCSS] - boolean that indicates if PIP window will inherit CSS from main window.
* @param {Object} [param.options.window] - object
* @param {number} [param.options.width=450] - number that indicates PIP window width. Default value is 450.
* @param {number} [param.options.height=300] - number that indicates PIP window height. Default value is 300.
* @param {()=>void} [param.onOpen] - function that will be executed on PIP opening.
* @param {(evt: DocumentPictureInPictureEvent)=>void} [param.onOpened] - function that will be executed when PIP is opened.
* @param {(evt: PageTransitionEvent)=>void} [param.onClose] - function that will be executed on PIP closing.
* @param {(err: unknown)=>void} [param.onError] - function that will be executed when error is throwing.
* @returns {UseDocumentPIPResult} result
* Object with four properties:
* - __isSupported__: boolean that indicates if PIP is supported or not.
* - __openPIP__: function to open PIP.
* - __closePIP__: function to close PIP.
* - __PipWindow__: Component that wraps the element to render in Document Picture in Picture.
*/
export declare const useDocumentPIP: ({ options: { inheritCSS, window: wind }, onOpen, onOpened, onClose, onError }: UseDocumentPIPProps) => UseDocumentPIPResult;
export declare interface UseDocumentPIPProps {
options?: DocumentPIPOptions;
onOpen?: () => void;
onOpened?: (evt: DocumentPictureInPictureEvent) => void;
onClose?: (evt: PageTransitionEvent) => void;
onError?: (err: unknown) => void;
}
export declare interface UseDocumentPIPResult {
isSupported: boolean;
openPIP: (opts?: DocumentPIPOptions) => Promise<void>;
closePIP: () => void;
window?: Window;
PipWindow: (props: PropsWithChildren) => JSX.Element | null;
}
/**
* **`useDocumentVisibility`**: Hook to track document visibility. Refers to [Document VisibilityState](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState). [See demo](https://react-tools.ndria.dev/#/hooks/events/useDocumentVisibility)
* @returns {DocumentVisibilityState} documentVisibility
*/
export declare const useDocumentVisibility: () => DocumentVisibilityState;
/**
* **`useDoubleClick`**: hook to handle double click event. Double clicking in react as well as with vanilla js, it is possible to manage it but it is not possible to have both managers on the same element. Thanks to this hook it is possible to do this, and it works with all events that can be associated with a user click (for example _mousedown_ but also _touchstart_). [See demo](https://react-tools.ndria.dev/#/hooks/events/useDoubleClick)
* @param {((evt: SyntheticEvent<T, E>) => Promise<void>|void)|Object} handler
* @param {((evt: SyntheticEvent<T, E>) => Promise<void> | void)} handler.doubleClick - callback executed on double click.
* @param {((evt: SyntheticEvent<T, E>) => Promise<void> | void)} [handler.singleClick] - callback executed on single click.
* @param {number} [handler.tolerance=300] - delay to execute __singleClick__ callback.
* @returns {((evt: SyntheticEvent<T, E>) => Promise<void>|void)} callback
*/
export declare const useDoubleClick: <T extends Element = Element, E extends Event = Event>(handler: ((evt: SyntheticEvent<T, E>) => Promise<void> | void) | {
doubleClick: (evt: SyntheticEvent<T, E>) => Promise<void> | void;
singleClick?: (evt: SyntheticEvent<T, E>) => Promise<void> | void;
tolerance?: number;
}) => ((evt: SyntheticEvent<T, E>) => Promise<void> | void);
/**
* **`useEffectCompare`**: custom useEffect that reexecutes EffectCallback only when comparator function, received as third parameter, returns true. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useEffectCompare)
* @param {EffectCallback} cb - Imperative function that can return a cleanup function.
* @param {DependencyListTyped} deps - typed dependency list.
* @param {CompareFn} [compareFn] - optional function that executes comparing between old and new `deps`: it returns true if they are different, otherwise false. If there isn't, hook works like normal useEffect.
* @returns {void}
*/
export declare const useEffectCompare: <T = unknown>(cb: EffectCallback, deps: DependencyListTyped<T>, compareFn?: CompareFn<T>) => void;
/**
* **`useEffectDeepCompare`**: custom useEffect that reexecutes EffectCallback only when deps are different in depth. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useEffectDeepCompare)
* @param {EffectCallback} cb - Imperative function that can return a cleanup function.
* @param {DependencyList} deps - dependency list.
* @returns {void}
*/
export declare const useEffectDeepCompare: (cb: EffectCallback, deps: DependencyList) => void;
/**
* **`useEffectOnce`**: Hook to executes _effect_ and _clean up_ after component mount __only once__. It prevents _React 18 StrictMode_ behavior if present, otherwise it works like a normal _useEffect_ with empty dependencies array. __*N.B.*__ Not use in a component with normal _useEffect_, if it executes a _React.DispatchAction_, because this action is executes twice if there is _React.StrictMode_. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useEffectOnce)
* @param {EffectCallback} effect
*/
export declare const useEffectOnce: (effect: EffectCallback) => void;
/**
* __`useEventDispatcher`__: Hook to dispatch an Event or a CustomEvent. [See demo](https://react-tools.ndria.dev/#/hooks/events/useEventDispatcher)
* @param {RefObject<HTMLElement> | Window} [element=window] - target on which dispatch event
* @returns {(evt: Event | CustomEvent) => void} dispatch - function that dispatch the event on target
*/
export declare const useEventDispatcher: (element?: RefObject<HTMLElement> | Window) => (evt: Event | CustomEvent) => void;
/**
* __`useEventListener`__: Hook to simplify add and remove EventListener use. It's persist during rerendering and automatically remove eventlistener on unMount component lifecycle. [See demo](https://react-tools.ndria.dev/#/hooks/events/useEventListener)
* @param {Object} options
* @param {keyof WindowEventMap|(keyof WindowEventMap)[]} options.type - event or events type.
* @param {(evt: Event | CustomEvent) => void} options.listener - listener to be executed on specified event.
* @param {RefObject<Element> | Element | Window} [options.element=window] - element on which attaching eventListener.
* @param {boolean | AddEventListenerOptions} [options.listenerOpts] - options for listener.
* @param {"normal"|"layout"} [options.effectType="normal"] - option to set which hook is used to attach event listener.
* @returns {()=>void} remove - used to manually remove the eventListener, otherwise is removed when component is unmounted.
*/
export declare function useEventListener<T extends keyof DocumentEventMap, E extends Element>({ type, listener, element, listenerOpts, effectType }: {
type: T | (T[]);
listener: ((evt: DocumentEventMap[T]) => unknown | Promise<unknown>);
element?: RefObject<E> | E | Window;
listenerOpts?: boolean | AddEventListenerOptions;
effectType?: "normal" | "layout";
}): (() => void);
export declare function useEventListener<T extends keyof HTMLElementEventMap, E extends Element>({ type, listener, element, listenerOpts, effectType }: {
type: T | (T[]);
listener: ((evt: HTMLElementEventMap[T]) => unknown | Promise<unknown>);
element?: RefObject<E> | E | Window;
listenerOpts?: boolean | AddEventListenerOptions;
effectType?: "normal" | "layout";
}): (() => void);
export declare function useEventListener<T extends string, E extends Event | CustomEvent, S extends Element>({ type, listener, element, listenerOpts, effectType }: {
type: T | (T[]);
listener: ((evt: E) => unknown | Promise<unknown>);
element?: RefObject<S> | S | Window;
listenerOpts?: boolean | AddEventListenerOptions;
effectType?: "normal" | "layout";
}): (() => void);
/**
* **`useEvents`**: Communication system based on Events pattern implemented on a EventTarget subclass. AddListener and dispatch functions to communicate. The result of invoking the _addListener_ function in turn returns a function that can be used to _removeListener_ on event. Otherwise, the listener is automatically removed when the component that has instantiated it is unmounted. [See demo](https://react-tools.ndria.dev/#/hooks/events/useEvents)
* @returns {[(type: string, callback<T>:(evt: Event | CustomEvent<T>) => void, options?: boolean | AddEventListenerOptions) => ()=>void, <T>(evt: Event | CustomEvent<T>) => void]} result - contains the _addListener_ and _dispatch_ functions.
*/
export declare const useEvents: () => [(type: string, callback: <T>(evt: Event | CustomEvent<T>) => void, options?: boolean | AddEventListenerOptions) => () => void, <T_1>(evt: Event | CustomEvent<T_1>) => void];
/**
* **`useEventSource`**: Hook to handle an [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) connection to an HTTP server, which sends events in text/event-stream format. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useEventSource)
* @param {UseEventSourceProps} param - object
* @param {string|URL} [param.url] - string that represents the location of the remote resource serving the events/messages.
* @param {EventSourceInit} [param.opts] - options to configure the new connection. The possible entries are: __withCredentials__ -> boolean value, defaulting to false, indicating if CORS should be set to include credentials.
* @param {{name: string, handler?:(evt:MessagEvent)=>void}[]} [param.events] - array of objects with properties __name__ and __handler__ to listen specified events from source.
* @param {boolean} [param.immediateConnection] - boolean to start connection immediatly.
* @param {(evt: Event)=>void} [param.onOpen] - function that will be executed when connection is opened.
* @param {(evt: Event)=>void} [param.onError] - function that will be executed when an error occurred.
* @param {(evt: MessageEvent<T>)=>void} [param.onMessage] - function that will be executed when a message from without event arrived.
* @returns {UseEventSourceResult} result
* Object with these properties:
* - __status__: string rapresenting eventsource state connection: __READY__ __CONNECTING__ __OPENED__ or __CLOSED__.
* - __data__: last data value arrived from eventSource.
* - __open__: function that opens connection.
* - __close__: function that closes connection.
*/
export declare const useEventSource: <T>({ url, opts, events, immediateConnection, onOpen, onError, onMessage }: UseEventSourceProps) => UseEventSourceResult<T>;
export declare interface UseEventSourceProps {
url?: string | URL;
opts?: EventSourceInit;
events?: {
name: string;
handler?: (evt: MessageEvent) => void;
}[];
immediateConnection?: boolean;
onOpen?: (evt: Event) => void;
onError?: (evt: Event) => void;
onMessage?: <T>(evt: MessageEvent<T>) => void;
}
export declare interface UseEventSourceResult<T> {
status: "READY" | "CONNECTING" | "OPENED" | "CLOSED";
data: T | null;
open: (url?: string) => void;
close: () => void;
}
/**
* **`useEyeDropper`**: Hook to use [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useEyeDropper)
* @param {Object} opts - options.
* @param {()=>void} [opts.onStart] - function that will be executed on __open__ invocation.
* @param {(result: `#${string}`) => void} [opts.onFinish] - function that will be on __open__ retuns.
* @returns {{isSupported: boolean, open: (signal?: AbortSignal) => Promise<`#${string}`>|Promise<void>}} result - __isSupported__ to known if EyeDropper API is supported and __share__ function to use EyeDropper API.
*/
export declare const useEyeDropper: ({ onStart, onFinish }?: {
onStart?: () => void;
onFinish?: (result: `#${string}`) => void;
}) => {
isSupported: boolean;
open: (signal?: AbortSignal) => Promise<void> | Promise<`#${string}`>;
};
/**
* **`useFetch`**: Hook to use [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) with more control and the possibility to execute request with suspense support. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useFetch)
* @param {RequestInfo|URL} url - The resource that you wish to fetch. This can either be a string, a Request object or an URL object.
* @param {Object} [options] - An object containing any custom settings you want to apply to the fetch invokation.
* @param {RequestInit} [...options.rest] - properties to customize fetch settings.
* @param {(loading: boolean)=>void} [options.onLoading] - function that will be executed when loading state changes.
* @param {(error:unknown)=>void} [options.onError] - function that will be executed when error occurred.
* @param {boolean} [options.suspensable] - boolean that indicates if fetch request need to be suspends or not.
* @returns {[T|undefined, (conf?: RequestInit) => Promise<void>, boolean, unknown]}
* Array with:
* - __data__: data returned from fetch.
* - __call__: function to fetch request.
* - __loading__: value that handle loading state.
* - __error__: value that handle error state.
*/
export declare const useFetch: <T>(url: RequestInfo | URL, { suspensable, onError, onLoading, ...rest }?: RequestInit & {
suspensable?: boolean;
onLoading?: (loading: boolean) => void;
onError?: (err: unknown) => void;
}) => [T | undefined, (conf?: RequestInit) => Promise<void>, boolean, unknown];
/**
* **`useFPS`**: Hook to detect FPS (Frames per second). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useFPS)
* @param {UseFPSProps} [opts] - configuration options to detect FPS.
* @param {number} [opts.everySeconds=0.5] - it indicates how often to compute FPS. Default is 0.5 second.
* @param {number} [opts.windowSize=10] - it indicates how FPS result keep in memory and computing average. Default is 10.
* @returns {UseFPSResult} result
* Stateful object with these properties:
* - __fps__: array of computed FPS by _windowSize_.
* - __currentFps__: current FPS value.
* - __avg__: average of FPS values kept in memory.
* - __maxFps__: maximum FPS value computed.
*/
export declare const useFPS: ({ everySeconds, windowSize }?: UseFPSProps) => UseFPSResult;
export declare interface UseFPSProps {
everySeconds: number;
windowSize: number;
}
export declare interface UseFPSResult {
fps: number[];
avg: number;
maxFps: number;
currentFps: number;
}
/**
* **`useFullscreen`**: Hook to use [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useFullscreen)
* @param {()=>void|Promise<void>} [onEnter] - callback that will be executed before enter in fullscreen mode.
* @param {(evt: Event)=>void} [onChange] - callback that will be executed when target element fullscreen change.
* @param {()=>void|Promise<void>} [onExit] - callback that will be executed before exit from fullscreen mode.
* @returns {[boolean, RefCallback<T>, (opts?: FullscreenOptions) => Promise<void>, () => Promise<void>]} result - array with: _isFullscreen_: boolean to indicate if there is fullscreen or not; _refCallback_: ref callback to be attached at target element; _enter_: function to enter in fullscreen mode; _exit_: function to exit from fullscreen mode.
*/
export declare const useFullscreen: <T extends Element>(onEnter?: () => void | Promise<void>, onChange?: (evt: Event) => void, onExit?: () => void | Promise<void>) => [boolean, RefCallback<T>, (opts?: FullscreenOptions) => Promise<void>, () => Promise<void>];
/**
* **`useGeolocation`**: Hook to use user's geographic location. Refer to [GeoLocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useGeolocation)
* @param {Object} opts - options to use geolocation.
* @param {PositionOptions} [opts.locationOptions] - An optional object which provides options for retrieval of the position data.
* @param {boolean} [opts.mode] - it establishes how to obtain the geographic location:
* - __current__: it gets the location when invoked.
* - __observer__: it gets the current position every time it changes.
* - __manual__: to obtain the location it need to invoke functions returned from hook.
* @param {GeolocationPositionError} [opts.onError] - callback that will be executed if there will be errors.
* @returns {[GeoLocationObject|undefined, (successCallback: PositionCallback, errorCallback?: PositionErrorCallback|null|undefined, options?: PositionOptions|undefined) => number|void, ()=>void]} results
* Array with:
* - _first element_: is the location object with two properties: __isSupported__ and __position__.
* - _second element_: function to obtain manually current location.
* - _third element_: function to obtain location on every changes.
*/
export declare const useGeolocation: ({ mode, locationOptions, onError }: {
locationOptions?: PositionOptions;
mode: "observe" | "current" | "manual";
onError?: (error: GeolocationPositionError) => void;
}) => [GeoLocationObject, () => Promise<void>, () => Promise<() => void>];
/**
* __`useHotKeys`__: Hook to listen for the keyboard press, support key combinations, built on [hotKeyHandler](#/hotKeyHandler) utility function. [See demo](https://react-tools.ndria.dev/#/hooks/events/useHotKeys)
* @param {Object} options
* @param {`${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`} options.hotKey - hotKey string: _ctrlCommand_ indicates to listen __Ctrl__ (on Windows) or __Command__ (on Mac) keys.
* @param {"keydown"|"keyup"} [options.type="keydown"] - event type.
* @param {(evt: KeyboardEvent|React.KeyboardEvent<HTMLElement>) => void | Promise<void>} options.listener - listener to be executed on specified event.
* @param {RefObject<HTMLElement> | Window} [options.target=window] - element on which attaching eventListener.
* @param {boolean | AddEventListenerOptions} [options.listenerOpts] - options for listener.
* @returns {()=>void} remove - used to manually remove the eventListener, otherwise is removed when component is unmounted.
*/
export declare const useHotKeys: ({ hotKey, type, target, listener, listenerOpts }: {
hotKey: `${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}` | `${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${'alt' | 'ctrl' | 'meta' | 'shift' | 'ctrlCommand'}+${string}`;
type?: "keydown" | "keyup";
target?: RefObject<HTMLElement> | Window;
listener: (evt: KeyboardEvent | KeyboardEvent_2<HTMLElement>) => void | Promise<void>;
listenerOpts?: boolean | AddEventListenerOptions;
}) => (() => void);
/**
* **`useHover`**: Hook that determines whether the item is hovered or not and handles state hovers. [See demo](https://react-tools.ndria.dev/#/hooks/events/useHover)
* @param {RefObject<HTMLElement> | HTMLElement} target - DOM element or ref
* @param {{ onEnter?: (evt: Event) => void, onChange?: (isHover: boolean) => void, onLeave?: (evt: Event) => void, returnValue?: boolean }} [opts] - __onEnter__ function to be executed on starting hover, __onLeave__ function to be executed on hover finished, __onChange__ function to be executed when hover state changes, __return value__ boolean to return hover state value or not.
* @returns {boolean|void} result - if __returnValue__ option is true or not specified, hook return state hover value, otherwise returns nothing.
*/
export declare function useHover(target: RefObject<HTMLElement> | HTMLElement, opts?: {
onEnter?: (evt: Event) => void;
onChange?: (isHover: boolean) => void;
onLeave?: (evt: Event) => void;
returnValue?: true;
}): boolean;
export declare function useHover(target: RefObject<HTMLElement> | HTMLElement, opts?: {
onEnter?: (evt: Event) => void;
onChange?: (isHover: boolean) => void;
onLeave?: (evt: Event) => void;
returnValue?: false;
}): void;
export declare const useId: typeof useId_2;
/**
* **`useIdleCallback`**: Hook to invoke a callback when the browser is idle. Refer to [requestIdleCallback](https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback) in React. The __options__ parameter differs from _IdleRequestOptions_ type: it adds the possibility to pass another property __unsupportedBehavior__ to specify what do if requestIdleCallback is not supported. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useIdleCallback)
* @param {(deadline?: IdleDeadline | DOMHighResTimeStamp | void)=> void} cb -callback that should be called in the near future.
* @param {IdleRequestOptions & { unsupportedBehavior: "animationFrame"|"timeout"|"immediatly" }} [opts] - Contains optional configuration parameters.
* @returns {[()=>void, ()=>void]} result
* Array with three elements:
* - first element: __isSupported__; boolean value that indicates if _requestIdleCallback_ is supported or not.
* - second element: __invoke__: function to invoke execution.
* - third element: __cancel__: function to cancel execution.
*/
export declare const useIdleCallback: (cb: (deadline?: IdleDeadline | DOMHighResTimeStamp | void) => void, opts?: {
timeout: number;
unsupportedBehavior?: "animationFrame" | "timeout" | "immediatly";
}) => [boolean, () => void, () => void];
/**
* **`useInfiniteScroll`**: Hook to deal with large sets of data. It allow users to scroll through content endlessly without explicit pagination or loading new pages. [See demo](https://react-tools.ndria.dev/#/hooks/events/useInfiniteScroll)
* @param {Object} param
* @param {(data?: T | undefined) => Promise<T>} param.request - request to obtain data.
* @param {RefObject<E extends Element>} param.ref - a reference to container element.
* @param {(data?: T | undefined) => boolean} param.hasMoreData - function that will be executed every time _data_ changes to detect if there will be new data values.
* @param {number|undefined} [param.threshold=0] - a threshold value by which load next data during scroll.
* @param {()=>void} [param.onBefore] - function that will be executed before to execute __request__.
* @param {()=>void} [param.onSuccess] - function that will be executed if __request__ execution has success.
* @param {(err:unknown)=>void} [param.onError] - function that will be executed if an error occurred calling __request__.
* @returns {{data: T|undefined, loading: boolean, fullData: boolean, updateData: (data:T|((currentState?:T)=>T))=>void, loadData: ()=>Promise<void>}} result
* Object with these properties:
* - __data__: data returned from _request_ execution.
* - __loading__: boolean that will be true if a _request_ execution is in pending, otherwise it will be false.
* - __fullData__: boolean that indicates if all data are returned or not.
* - __updateData__: function to update data from outside.
* - __loadData__: function to manual load next data.
*/
export declare const useInfiniteScroll: <T, E extends Element>({ request, ref, hasMoreData, threshold, onBefore, onError, onSuccess }: {
request: (data?: T) => Promise<T>;
ref: RefObject<E>;
hasMoreData: (data?: T) => boolean;
threshold?: number;
onBefore?: () => void;
onSuccess?: () => void;
onError?: (err: unknown) => void;
}) => {
data: T | undefined;
loading: boolean;
fullData: boolean;
updateData: (data: T | ((currentState?: T) => T)) => void;
loadData: () => Promise<void>;
};
/**
* **`useIntersectionObserver`**: Hook to use Intersection Observer. Refer to [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API). [See demo](https://react-tools.ndria.dev/#/hooks/events/useIntersectionObserver)
* @param {IntersectionObserverCallback} cb - The function which is called when the percentage of the target element is visible crosses a threshold. The callback is called with two parameters: __entries__ and __observer__.
* @param {IntersectionObserverInit} [opts] - An options object allowing you to set options for the observation.
* @returns {[RefCallback<T>, ()=>void, ()=>void]} result - array with: callback for ref element attribute to observe, function to _disconnect_ observer, function to _reconnect_ observer.
*/
export declare const useIntersectionObserver: <T extends Element>(cb: IntersectionObserverCallback, opts?: IntersectionObserverInit) => [RefCallback<T>, () => void, () => void];
/**
* **`useInterval`**: Hook to handle setInterval timer function with the possibility to clear and promisify execution. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useInterval)
* @param {(...args: unknown[])=>void} callback - Function to call when the timer elapses.
* @param {number} delay - The number of milliseconds to wait before calling the `callback`.
* @returns {[(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>]} - array: first element is the function to call setInterval; second element is the function to clearInterval; thrid element promisify setInterval.
*/
export declare const useInterval: <TArgs extends unknown[]>(callback: (...args: TArgs) => void, delay: number) => [(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>];
/**
* **`useIsMounted`**: Hoos to know when a component is mounted or not. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useIsMounted)
* @returns {()=>boolean}
*/
export declare const useIsMounted: () => () => boolean;
/**
* **`useIsOnline`**: Hook to detect network connection status. [See demo](https://react-tools.ndria.dev/#/hooks/events/useIsOnline)
* @returns {boolean} isOnline
*/
export declare const useIsOnline: () => boolean;
/**
* **`useLayoutEffectCompare`**: custom useLayoutEffect that reexecutes EffectCallback only when comparator function, received as third parameter, returns true. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useLayoutEffectCompare)
* @param {EffectCallback} cb - Imperative function that can return a cleanup function.
* @param {DependencyListTyped} deps - typed dependency list.
* @param {CompareFn} [compareFn] - optional function that executes comparing between old and new `deps`: it returns true if they are different, otherwise false. If there isn't, hook works like normal useLayoutEffect.
* @returns {void}
*/
export declare const useLayoutEffectCompare: <T = unknown>(cb: EffectCallback, deps: DependencyListTyped<T>, compareFn?: CompareFn<T>) => void;
/**
* **`useLayoutEffectDeepCompare`**: custom useEffect that reexecutes EffectCallback only when deps are different in depth. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useLayoutEffectDeepCompare)
* @param {EffectCallback} cb - Imperative function that can return a cleanup function.
* @param {DependencyList} deps - dependency list.
* @returns {void}
*/
export declare const useLayoutEffectDeepCompare: (cb: EffectCallback, deps: DependencyList) => void;
/**
* **`useLayoutEffectOnce`**: Hook to executes _effect_ and _clean up_ after component mount __only once__. It prevents _React 18 StrictMode_ behavior if present, otherwise it works like a normal _useLayoutEffect_ with empty dependencies array. __*N.B.*__ Not use in a component with normal _useLayoutEffect_, if it executes a _React.DispatchAction_, because this action is executes twice if there is _React.StrictMode_. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useLayoutEffectOnce)
* @param {EffectCallback} effect
*/
export declare const useLayoutEffectOnce: (effect: EffectCallback) => void;
/**
* **`useLazyRef`**: Hook that works 'partially' like the _useState_ hook with lazy initialization: ensures that the __initializer__ function is executed only once. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useLazyRef)
* @param {()=>T} initializer
* @returns {React.MutableRefObject<T>}
*/
export declare const useLazyRef: <T>(initializer: () => T) => React.MutableRefObject<T>;
/**
* ___useLocalStorageState___: Custom _useState_ hook implementation using _LocalStorage_, with immutable _getter state_ function and to _remove_ key from localStorage. [See demo](https://react-tools.ndria.dev/#/hooks/state/useLocalStorageState)
* @param {Object} params
* @param {string} params.key - item key in local storage.
* @param {T | () => T} [params.initialState] - value or a function , optional.
* @param {{serializer: (item: T)=> string, deserializer: (item: string)=> T, mode?: "read" | "write" | "read/write"}} [params.opts={serializer: JSON.stringify, deserializer: jSON.parse, mode: "read/write"}] - object with serializer and deserializer function to handle values in localStorage and mode property to use hook only to read, write or both.
* @returns {[T, () => T, () => void] | [Dispatch<SetStateAction<T>>, () => T, () => void] | [T, Dispatch<SetStateAction<T>>, () => T, () => void]}
*/
export declare function useLocalStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: undefined;
};
}): [T, Dispatch<SetStateAction<T>>, () => T, () => void];
export declare function useLocalStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "read";
};
}): [T, () => T, () => void];
export declare function useLocalStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "write";
};
}): [Dispatch<SetStateAction<T>>, () => T, () => void];
export declare function useLocalStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "read/write";
};
}): [T, Dispatch<SetStateAction<T>>, () => T, () => void];
/**
* **`useLock`**: Hook to use [Web Locks API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useLock)
* @param {string} [name] - an identifier for the lock.
* @param {LockGrantedCallback | LockOptions} [options] - an object describing characteristics of the lock.
* @param {LockGrantedCallback} [callback] - method called when the lock is granted.
* @returns {[<T>(currName?: string, currCb?: LockGrantedCallback, currOpts?: LockOptions) => Promise<T>, () => Promise<LockManagerSnapshot>]} result
* Array with two element:
* - first element: __acquire__ function that requests a Lock object with parameters specified in hook invocation or passed to this function. The requested Lock is passed to the callback specified in hook or passed to this function. It returns a Promise that resolves (or rejects) with the result of the callback after the lock is released, or rejects if the request is aborted.
* - second element: __query__ function that returns a Promise that resolves with an object containing information about held and pending locks.
*/
export declare const useLock: <T>(name?: string, cb?: LockGrantedCallback, opts?: LockOptions) => [(currName?: string, currCb?: LockGrantedCallback, currOpts?: LockOptions) => Promise<T>, () => Promise<LockManagerSnapshot>];
/**
* **`useLogger`**: Hook to log componet details during Lifecycle events. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useLogger)
* @param {string} name - component name.
* @param {object} props - props object to track.
*/
export declare const useLogger: (name: string, props: object) => void;
/**
* **`useLongPress`**: Hook to execute a callback on a long press event. [See demo](https://react-tools.ndria.dev/#/hooks/events/useLongPress)
* @param {(evt:E)=>void} cb - callback to execute after a certain duration.
* @param {Object} opts
* @param {number} [opts.duration=1000] - long press event duration in milliseconds.
* @param {(evt:E)=>void} [opts.onStart] - callback that will be executed on initial press event.
* @param {(evt:E)=>void} [opts.onFinish] - callback that will be executed when long press callback has done.
* @param {(evt:E)=>void} [opts.normalPress] - callback executed on normal press event.
* @returns {RefCallback<T>} ref callback - to be attached on target element.
*/
export declare const useLongPress: <T extends Element = Element, E extends Event = Event>(cb: useLongPressCallback<E>, { duration, normalPress, onStart, onFinish }: useLongPressOptions<E>) => RefCallback<T>;
declare interface useLongPressCallback<E extends Event = Event> {
(evt: E): void | Promise<void>;
}
declare interface useLongPressOptions<E extends Event = Event> {
duration?: number;
normalPress?: (evt: E) => void;
onStart?: (evt: E) => void;
onFinish?: (evt: E) => void;
}
/**
* __`useMap`__: Hook to use _Map data structure_ to handle component state with all Map methods. [See demo](https://react-tools.ndria.dev/#/hooks/state/useMap)
* @param {Iterable<readonly [K, V]> | (() => Iterable<readonly [K, V]>)} [initialState] - An Array or other iterable object whose elements are key-value pairs, or function that returns it.
* @returns {Map<K,V>}
*/
export declare const useMap: <K, V>(initialState?: Iterable<readonly [K, V]> | (() => Iterable<readonly [K, V]>)) => Map<K, V>;
/**
* **`useMeasure`**: Hook to measure and track element's dimensions. [See demo](https://react-tools.ndria.dev/#/hooks/events/useMeasure)
* @returns {[React.RefCallback<T>, DOMRectReadOnly]} result - a refCallback for target element and a object with target element size.
*/
export declare const useMeasure: <T extends Element>() => [React.RefCallback<T>, DOMRectReadOnly];
/**
* **`useMediaDevices`**: Hook to use [MediaDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices) interface methods, that give access to any hardware source of media data. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useMediaDevices)
* @param {UseMediaDevicesProps} action - it is a string that identifies which method to return as a result. It can be _devicesList_, _supportedConstraintsList_, _DisplayCapture_, or _mediaInputCapture_.
* @returns {UseMediaDevicesResult} result - the function returned by __action__ parameter value.
* if __action__ is:
* - _devicesList_: so _result_ is __enumeratedDevices__ method of MediaDevices interface.
* - _supportedConstraintsList_: so _result_ is __getSupportedConstraints__ method of MediaDevices interface.
* - _DisplayCapture_: so _result_ is __getDisplayMedia__ method of MediaDevices interface.
* - _mediaInputCapture_: so _result_ is __getUserMedia__ method of MediaDevices interface.
*/
export declare function useMediaDevices(action: "devicesList"): (onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaDeviceInfo[]>;
export declare function useMediaDevices(action: "supportedConstraintsList"): (onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => MediaTrackSupportedConstraints;
export declare function useMediaDevices(action: "DisplayCapture"): (options?: DisplayMediaStreamOptions, onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaStream>;
export declare function useMediaDevices(action: "mediaInputCapture"): (constraints?: MediaStreamConstraints, onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaStream>;
export declare type UseMediaDevicesProps = "devicesList" | "supportedConstraintsList" | "DisplayCapture" | "mediaInputCapture";
export declare type UseMediaDevicesResult = ((onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaDeviceInfo[]>) | ((onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => MediaTrackSupportedConstraints) | ((options?: DisplayMediaStreamOptions, onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaStream>) | ((constraints?: MediaStreamConstraints, onDevicesChange?: ((evt: Event) => void | Promise<void>) | undefined) => Promise<MediaStream>);
/**
* **`useMediaQuery`**: Hook to handle CSS mediaQuery. It returns an object with __matches__ and __media__ properties and receives an optional _onChange_ function to handle _MediaQueryListEvent change_ event. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useMediaQuery)
* @param {string} mediaQuery - media query to test.
* @param {(evt: MediaQueryListEvent) => void} [onChange] - MediaQueryListEvent change handler.
* @returns {{matches: boolean, media: string}} result - object with __matches__, boolean value that returns true if the document currently matches the media query, __media__, string that represents media query.
*/
export declare const useMediaQuery: (mediaQuery: string, onChange?: (evt: MediaQueryListEvent) => void) => {
matches: boolean;
media: string;
};
/**
* **`useMemoCompare`**: custom useMemo that returns memoized value that changes only when comparator function, received as third parameter, returns true. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useMemoCompare)
* @param {() => T} factory - computes value.
* @param {DependencyListTyped} deps - typed DependencyList.
* @param {CompareFn} [compareFn] - optional function that executes comparing between old and new `deps`: it returns true if they are different, otherwise false. If there isn't, hook works like normal useMemo.
* @returns {T} result - memoized value
*/
export declare const useMemoCompare: <T = unknown, E = unknown>(cb: () => T, deps: DependencyListTyped<E>, compareFn?: CompareFn<E>) => T;
/**
* **`useMemoDeepCompare`**: custom useMemo that returns memoized value that changes only if deps are different in depth. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useMemoDeepCompare)
* @param {() => T} factory - computes value.
* @param {DependencyList} deps - DependencyList.
* @returns {T} result - memoized value
*/
export declare const useMemoDeepCompare: <T = unknown>(cb: () => T, deps: DependencyList) => T;
/**
* **`useMemoizedFn`**: Hook to store a function that will never change while keeping its dependencies always up to date. Can be used instead of _useCallback_, without esplicity dependencies array. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useMemoizedFn)
* @param {T} fn
* @returns {T} memoizedFn
*/
export declare const useMemoizedFn: <T extends (...args: any[]) => any>(fn: T) => T;
/**
* **`useMergedRef`**: Hook to merge multiple refs into one. [See demo](https://react-tools.ndria.dev/#/hooks/performance/useMergedRef)
* @param {Ref<T>[]} refs
* @returns {RefObject<T>} mergedRef
*/
export declare const useMergedRef: <T>(...refs: Ref<T>[]) => Ref<T>;
/**
* **`useMouse`**: Hook to track mouse position also in relationship with an element. It works with pointerEvents. [See demo](https://react-tools.ndria.dev/#/hooks/events/useMouse)
* @param {Object} opts
* @param {"client"|"page"|"screen"} [opts.type="client"] - position by client page or screen.
* @param {RefObject<HTMLElement> | HTMLElement} [opts.relativeElement] - if it is presents, position is relative to element.
* @returns {{x:number|null, y:number|null} | {x:number|null, y:number|null, relativeElementDim?: DOMRect}} object - postion by axis and if relativeElement is present, relativeElement dimensions also.
*/
export declare function useMouse(opts?: undefined): {
x: number;
y: number;
};
export declare function useMouse(opts?: {
type?: "client" | "page" | "screen";
relativeElement?: undefined;
}): {
x: number | null;
y: number | null;
};
export declare function useMouse(opts?: {
type?: "client" | "page" | "screen";
relativeElement?: RefObject<HTMLElement | null> | HTMLElement;
}): {
x: number | null;
y: number | null;
relativeElementDim?: DOMRect;
};
/**
* **`useMutationObserver`**: Hook to use Mutation Observer. Refer to [Mutation Observer API](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). [See demo](https://react-tools.ndria.dev/#/hooks/events/useMutationObserver)
* @param {MutationCallback} cb - The function which will be called on each DOM change that qualifies given the observed node or subtree and options. The callback takes as input two parameters: __mutationList__ and __observer__.
* @param {MutationObserverInit} [opts] - An options object allowing you to set options for the observation.
* @returns {[RefCallback<T>, ()=>void, ()=>void, () => MutationRecord[]|undefined]} result - array with: cb for ref component attribute to observe, function to _disconnect_ observer, function _takeRecords_ to take observer records not yet processed, function to _reconnect_ observer.
*/
export declare const useMutationObserver: <T extends Element>(cb: MutationCallback, opts?: MutationObserverInit) => [RefCallback<T>, () => void, () => void, () => MutationRecord[] | undefined];
/**
* **`useNetwork`**: Hook to detect network connection infos, refer to [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation). It takes optinally a parameter __selectedInfo__ to specify a subset of connection status property. [See demo](https://react-tools.ndria.dev/#/hooks/events/useNetwork)
* @template T
* @extends {}
* @param {ArrayMinLength1<T>} [selectedInfo] - array of connection property.
* @returns {ConnectionState|{[k in T] : ConnectionState[k]}} object - Network connection property or a subset if __selectedInfo__ is specified.
*/
export declare function useNetwork(selectedInfo?: undefined): ConnectionState;
export declare function useNetwork<T extends keyof ConnectionState>(selectedInfo?: ArrayMinLength1<T>): {
[k in T]: ConnectionState[k];
};
/**
* **`usePerformAction`**: Hook that executes a callback after a render. [See demo](https://react-tools.ndria.dev/#/hooks/events/usePerformAction)
* @param {(...args: unknown[])=>void} cb - callback to execute
* @returns {(...args: unknown[]) => void} performAction
*/
export declare const usePerformAction: <T extends (...args: unknown[]) => void>(cb: T) => (...args: Parameters<T>) => void;
/**
* **`usePermission`**: Hook to query the status of API permissions attributed to the current context. Refer to [PermissionAPI](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/usePermission)
* @param {TPermissionName} permission - name of the API whose permissions you want to query.
* @returns {UsePermissionResult} result
* Array of two elements:
* - first element: current state of the request permission: one of __'asking'__, __'granted'__, __'denied'__, __'prompt'__ or __'not supported'__.
* - second element: function to manual query fot permission status.
*/
export declare function usePermission(permission: TPermissionName): UsePermissionResult;
export declare type UsePermissionResult = [TPermissionState, () => Promise<TPermissionState>];
/**
* **`usePinchZoom`**: Hook to handle pinch zoom gestures. [See demo](https://react-tools.ndria.dev/#/hooks/events/usePinchZoom)
* @param {Object} options
* @param {(evt: PointerEvent, type: "zoomIn"|"zoomOut") => void | Promise<void>} options.listener - listener to be executed on pinch zoom event.
* @param {RefObject<HTMLElement> | Window} [options.target=window] - element on which attaching eventListener.
* @returns {()=>void} remove - remove listener manually.
*/
export declare const usePinchZoom: ({ target, listener }: {
target?: RefObject<HTMLElement> | Window;
listener: (evt: PointerEvent, type: "zoomIn" | "zoomOut") => void | Promise<void>;
}) => (() => void);
/**
* **`usePIP`**: Hook to use PIP [(Picture-in-Picture API)](https://developer.mozilla.org/en-US/docs/Web/API/Picture-in-Picture_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/usePIP)
* @param {UsePIPProps} param - object
* @param {RefObject<HTMLVideoElement>|HTMLVideoElement} param.target - element to PIP.
* @param {()=>void} [param.onOpen] - function that will be executed on PIP opening.
* @param {(pip: PictureInPictureWindow)=>void} [param.onOpened] - function that will be executed when PIP is opened.
* @param {(evt: PictureInPictureEvent)=>void} [param.onClose] - function that will be executed on PIP closing.
* @param {(err: unknown)=>void} [param.onError] - function that will be executed when error is throwing.
* @returns {UsePIPResult} result
* Object with three properties:
* - __isSupported__: boolean that indicates if PIP is supported or not.
* - __openPIP__: function to open PIP.
* - __closePIP__: function to close PIP.
*/
export declare const usePIP: ({ onOpen, onOpened, onClose, onError, target }: UsePIPProps) => UsePIPResult;
export declare interface UsePIPProps {
target: RefObject<HTMLVideoElement> | HTMLVideoElement;
onOpen?: (evt: Event) => void;
onOpened?: (pipWindow: PictureInPictureWindow) => void;
onClose?: (evt: PictureInPictureEvent) => void;
onError?: (err: unknown) => void;
}
export declare interface UsePIPResult {
isSupported: boolean;
openPIP: () => Promise<void>;
closePIP: () => Promise<void>;
}
/**
* **`usePointerLock`**: Hook to use [PointerLock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). [See demo](https://react-tools.ndria.dev/#/hooks/events/usePointerLock)
* @param {UsePointerLockProps} param - object
* @param {RefObject<T>|T} param.target - element that requires lock.
* @param {boolean} [param.unadjustedMovement] - Disables OS-level adjustment for mouse acceleration, and accesses raw mouse input instead. The default value is false; setting it to true will disable mouse acceleration.
* @param {(e: unknown)=>void} param.onError - function that will be executed when an error throwing during request.
* @param {(target: RefObject<T>|T) => void} [param.onLock] - function that will be executed when lock has been acquired.
* @param {() => void} [param.onUnlock] - function that will be executed when lock has been released.
* @returns {UsePointerLockResult} result
* Object with two properties:
* - __lock__: function to acquire lock.
* - __unlock__: function to release lock.
*/
export declare const usePointerLock: <T extends HTMLElement>({ target, unadjustedMovement, onLock, onUnlock, onError }: UsePointerLockProps<T>) => UsePointerLockResult;
export declare interface UsePointerLockProps<T extends HTMLElement> {
/**Element that asks for the pointer lock.*/
target: RefObject<T> | T;
/**Disables OS-level adjustment for mouse acceleration, and accesses raw mouse input instead. The default value is false; setting it to true will disable mouse acceleration.*/
unadjustedMovement?: boolean;
onError: (e: unknown) => void;
onLock?: (target: T) => void;
onUnlock?: (target: T) => void;
}
export declare interface UsePointerLockResult {
/**Function to acquire lock.*/
lock: () => Promise<void>;
/**Function to release lock.*/
unlock: () => void;
}
/**
* **`usePopover`**: Hook to use [Popover API](https://developer.mozilla.org/en-US/docs/Web/API/Popover_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/usePopover)
* @param {UsePopoverProps} param - object
* @param {"auto"|"manual"} param.mode - popover state: __auto__ indicates that popover can be "light dismissed" by selecting outside the popover area, by contrast __manual__ popover must always be explicity hidden.
* @param {(evt: ToggleEvent) => void} [param.onBeforeToggle] - function that will be executed before popover showed/hidden.
* @param {(evt: ToggleEvent) => void} [param.onToggle] - function that will be executed when popover has been showed/hidden.
* @returns {UsePopoverResult} result
* Object with these properties:
* - __isSupported__: boolean that indicates if Popover API is supported or not.
* - __isSupported__: boolean that indicates if popover is opened or not.
* - __showPopover__: function to show popover.
* - __hidePopover__: function to hide popover.
* - __togglePopover__: function to toggle popover.
* - __Popover__: Component that wraps the element to render in popover. It can be stylized with _className_ and _style_ props.
*/
export declare function usePopover({ mode, onBeforeToggle, onToggle }: UsePopoverProps): UsePopoverResult;
export declare interface UsePopoverProps {
mode: "auto" | "manual";
onBeforeToggle?: (evt: ToggleEvent) => void;
onToggle?: (evt: ToggleEvent) => void;
}
export declare interface UsePopoverResult {
isSupported: boolean;
isOpen: boolean;
showPopover: () => void;
hidePopover: () => void;
togglePopover: () => void;
Popover: ({ children, ...rest }: ComponentPropsWithRef<"div"> & HTMLAttributes<"div">) => false | JSX.Element;
}
/**
* **`usePrevious`**: It's track the previous value of a variable, with possibility to enable/disable tracking. [See demo](https://react-tools.ndria.dev/#/hooks/state/usePrevious)
* @param {T} variable - variable whose value is to be tracked.
* @returns {[T|undefined, (enable:boolean)=>void]} array
*/
export declare const usePrevious: <T = unknown>(variable: T) => [T | undefined, (enable: boolean) => void];
/**
* **`usePromiseSuspensible`**: Hook to resolve promise with Suspense support. The component that uses it, it need to be wrapped with Suspense component. This hook can be used in conditional blocks. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/usePromiseSuspensible)
* @param {()=>Promise<T>} promise - Function that returns a promise to suspense.
* @param {DependencyList} deps - DependencyList for promise to suspense.
* @param {{ clearCacheOnUnmount?: "unmount"|number, cleanOnError?: boolean }} [options] - optional options.
* @param {"unmount"|number} [options.cache=undefined] - value can be "unmount", to clean promise cached at component unmounting, or it can be the duration in __seconds__ of cached promise.
* @param {boolean} [options.cleanOnError=undefined] - if true, when there is an error, remove promise from cache with a delay of 20 millisecond (due to multiple renders of react strict mode).
* @param {boolean} [options.invalidateManually=undefined] - if true, returns resolved promise value and a function to invalidate and revaluate promise.
* @param {string} [options.identifier=undefined] - a string to identify _promise_. If it isn't present, a serialization of _promise_ will be used.
* @returns {Awaited<ReturnType<T>> | [Awaited<ReturnType<T>>, ()=>void]} result - resolve promise value.
*/
export declare function usePromiseSuspensible<T>(promise: () => Promise<T>, deps: DependencyList, options: {
cache?: "unmount" | number;
cleanOnError?: boolean;
identifier?: string;
invalidateManually?: undefined;
}): Awaited<ReturnType<typeof promise>>;
export declare function usePromiseSuspensible<T>(promise: () => Promise<T>, deps: DependencyList, options: {
cache?: "unmount" | number;
cleanOnError?: boolean;
identifier?: string;
invalidateManually?: false;
}): Awaited<ReturnType<typeof promise>>;
export declare function usePromiseSuspensible<T>(promise: () => Promise<T>, deps: DependencyList, options: {
cache?: "unmount" | number;
cleanOnError?: boolean;
identifier?: string;
invalidateManually?: true;
}): [Awaited<ReturnType<typeof promise>>, () => void];
/**
* __`useProxyState`__: Hook to handle component state that allows you to use an object for your state and mutating it in a way more idiomatic for JS. __*N.B.*__ not destructure state, otherwise break changes updated. [See demo](https://react-tools.ndria.dev/#/hooks/state/useProxyState)
* @param {T | () => T} initialState - value or function
* @param {boolean} [proxyInDepth=false] - if true, it creates proxy for nested object also.
* @returns {T} state
*/
export declare const useProxyState: <T extends Record<string, any>>(initialState: T | (() => T), proxyInDepth?: boolean) => T;
/**
* **`usePublishSubscribe`**: Communication system based on PubSub pattern. Instantiate a topic and use the publish and subscribe functions to communicate. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/usePublishSubscribe)
* @param {string} topic
* @returns {[(listener: (value?: T) => Promise<void> | void) => () => void, (value?: T) => Promise<void> ]} result - contains the _publish_ and _subscribe_ functions. The result of invoking the _subscribe_ function in turn returns a function that can be used to _unsubscribe_ the topic
*/
export declare const usePublishSubscribe: <T>(topic: string) => [(listener: (value?: T) => Promise<void> | void) => () => void, (value?: T) => Promise<void>];
/**
* **`useRaf`**: Hook to execute a callback function with _requestAnimationFrame_ to optimize performance. Refer to (requestAnimationFrame)[https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame]. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useRaf)
* @param {(timer:number, repeat:()=>void, ...args: T)=>void} cb - callback to execute prior to the next repaint. In addition to the classic timeStamp parameter, which indicates the end time of rendering of the previous frame, the second parameter is a function which, if invoked, re-executes the requestAnimationFrame with the callback itself, and finally various parameters can be added, passed with the invocation function returned by the hook.
* @returns {[(...args: T)=>void, ()=>void]} results - array with __start__ function to invoke _requestAnimationFrame_ and __cancel__ function to invoke _cancelAnimationFrame_.
*/
export declare const useRaf: <T extends unknown[]>(cb: (timer: number, repeat: () => void, ...args: T) => void) => [(...args: T) => void, () => void];
/**
* **`useReducedMotion`**: Hook to detect if user prefers to reduce motion. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useReducedMotion)
* @returns {boolean} result - it is true if user prefers reduced motion, otherwise it is false.
*/
export declare const useReducedMotion: () => boolean;
/**
* **`useReducerGetReset`**: Custom useReducer with get and reset state functions. [See demo](https://react-tools.ndria.dev/#/hooks/state/useReducerGetReset)
* @param {R extends Reducer<any, any>} reducer - The reducer function that specifies how the state gets updated.
* @param {ReducerState<R>} initialState - The value from which the initial state is calculated. How the initial state is calculated from it depends on the next _init_ argument.
* @param {(init: ReducerState<R>) => ReducerState<R>} [initializer] - Function that should return the _initial state_. If it’s not specified, the initial state is set to _initialState_, otherwise is set to the result of calling _initializer(initialState)_.
* @returns {[ReducerState<R>, Dispatch<ReducerAction<R>>, ()=>ReducerState<R>, ()=>void]} array
*/
export declare const useReducerGetReset: <R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>) => [ReducerState<R>, Dispatch<ReducerAction<R>>, () => ReducerState<R>, () => void];
/**
* **`useReducerHistory`**: Custom useReducer that tracks and allows to use previous values. [See demo](https://react-tools.ndria.dev/#/hooks/state/useReducerHistory)
* @param {R extends Reducer<any, any>} reducer - The reducer function that specifies how the state gets updated.
* @param {ReducerState<R>} initialState - The value from which the initial state is calculated. How the initial state is calculated from it depends on the next _init_ argument.
* @param {(init: ReducerState<R>) => ReducerState<R>} [initializer] - Function that should return the _initial state_. If it’s not specified, the initial state is set to _initialState_, otherwise is set to the result of calling _initializer(initialState)_.
* @param {number | "no-limit"} [capacity="no-limit"] - history capacity (default 'no-limit').
* @returns {[ReducerState<R>, Dispatch<ReducerAction<R>>, {history: readonly ReducerState<R>[], presentPointer: number, trackUpdate: (enable:boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: ReducerAction<R>) => void}]} array
*/
export declare const useReducerHistory: <R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>, capacity?: number | "no-limit") => [ReducerState<R>, Dispatch<ReducerAction<R>>, {
history: readonly ReducerState<R>[];
presentPointer: number;
trackUpdate: (enable: boolean) => void;
canUndo: boolean;
canRedo: boolean;
undo: () => void;
redo: () => void;
go: (index: number) => void;
clear: (value?: ReducerAction<R>) => void;
}];
/**
* **`useReducerHistoryGetter`**: Custom useReducer with getter state function and that tracks and allows to use previous values. [See demo](https://react-tools.ndria.dev/#/hooks/state/useReducerHistoryGetter)
* @param {R extends Reducer<any, any>} reducer - The reducer function that specifies how the state gets updated.
* @param {ReducerState<R>} initialState - The value from which the initial state is calculated. How the initial state is calculated from it depends on the next _init_ argument.
* @param {(init: ReducerState<R>) => ReducerState<R>} [initializer] - Function that should return the _initial state_. If it’s not specified, the initial state is set to _initialState_, otherwise is set to the result of calling _initializer(initialState)_.
* @param {number | "no-limit"} [capacity="no-limit"] - history capacity (default 'no-limit').
* @returns {[ReducerState<R>, Dispatch<ReducerAction<R>>, ()=>ReducerState<R>, {history: readonly ReducerState<R>[], presentPointer: number, trackUpdate: (enable:boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: ReducerAction<R>) => void}]} array
*/
export declare const useReducerHistoryGetter: <R extends Reducer<any, any>>(reducer: R, initialState: ReducerState<R>, initializer?: (init: ReducerState<R>) => ReducerState<R>, capacity?: number | "no-limit") => [ReducerState<R>, Dispatch<ReducerAction<R>>, () => ReducerState<R>, {
history: readonly ReducerState<R>[];
presentPointer: number;
trackUpdate: (enable: boolean) => void;
canUndo: boolean;
canRedo: boolean;
undo: () => void;
redo: () => void;
go: (index: number) => void;
clear: (value?: ReducerAction<R>) => void;
}];
/**
* **`useRemotePlayback`**: Hook to use [RemotePlayback API](https://developer.mozilla.org/en-US/docs/Web/API/RemotePlayback). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useRemotePlayback)
* @param {UseRemotePlaybackProps} param - object
* @param {(evt:Event) => void} [param.onConnecting] - function that will be executed when remote device has been connected.
* @param {(evt:Event) => void} [param.onConnect] - function that will be executed when remote device connecting.
* @param {(evt:Event) => void} [param.onDisconnect] - function that will be executed when remote device has been disconnected.
* @param {(err: unknown) => void} [param.onError] - function that will be executed on error watching or cancel watching devices availability.
* @returns {UseRemotePlaybackResult} result
* Object with these properties:
* - __ref__: ref to attach media element.
* - __isSupported__: boolean that indicates if RemotePlayback API is available or not.
* - __state__: remote device state: _connected_, _connecting_ or _disconnect_.
* - __prompt__: function that prompts the user to select an available remote playback device and give permission for the current media to be played using that device.
*/
export declare const useRemotePlayback: <T extends HTMLMediaElement>({ onConnecting, onConnect, onDisconnect, onError }?: UseRemotePlaybackProps) => UseRemotePlaybackResult<T>;
export declare interface UseRemotePlaybackProps {
onConnecting?: (evt: Event) => void;
onConnect?: (evt: Event) => void;
onDisconnect?: (evt: Event) => void;
onError?: (err: unknown) => void;
}
export declare interface UseRemotePlaybackResult<T extends HTMLMediaElement> {
ref: RefCallback<T>;
isSupported: boolean;
state: "unavailable" | "connected" | "connecting" | "disconnected";
prompt: () => Promise<void>;
}
/**
* **`useRerender`**: Hook to force a render. [See demo](https://react-tools.ndria.dev/#/hooks/lifecycle/useRerender)
* @param {boolean} [withValue] - optional boolean value: if it is true, an array with _value_ and _rerender_ function is returned.
* @returns {DispatchWithoutAction|[T,DispatchWithoutAction]} array with _value_ and _updateValue_ function or _rerender_ function.
*/
export declare function useRerender(withValue?: never): DispatchWithoutAction;
export declare function useRerender(withValue?: false): DispatchWithoutAction;
export declare function useRerender<T>(withValue?: true): [T, DispatchWithoutAction];
/**
* **`useResizeObserver`**: Hook to use Resize Observer. Refer to [Resize Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API). [See demo](https://react-tools.ndria.dev/#/hooks/events/useResizeObserver)
* @param {ResizeObserverCallback} cb - The function called whenever an observed resize occurs. The callback is called with two parameters: __entries__ and __observer__.
* @param {ResizeObserverOptions} [opts] - An options object allowing you to set options for the observation.
* @returns {[RefCallback<T>, ()=>void, ()=>void]} result - array with: cb for ref component attribute to observe, function to _disconnect_ observer, function to _reconnect_ observer.
*/
export declare const useResizeObserver: <T extends Element>(cb: ResizeObserverCallback, opts?: ResizeObserverOptions) => [RefCallback<T>, () => void, () => void];
/**
* **`useResponsive`**: Hook for getting responsive window size. [See demo](https://react-tools.ndria.dev/#/hooks/events/useResponsive). It receives an optional param __config__ to manually setting breakpoint keys. __config__ can have a keys subset and value can be a number or an object with _value_ and _condition_ properties. If _value_ is a number, the condition will be ">". By default Breakpoints are:
*
* - xs: { value: 576, condition: "<" }
* - sm: { value: 576, condition: ">=" }
* - md: { value: 768, condition: ">=" }
* - lg: { value: 992, condition: ">=" }
* - xl: { value: 1200, condition: ">=" }
* @param {UseResponsiveBreakpoints} [config] - custom breakpoint object.
* @returns {keyof UseResponsiveBreakpoints} breakpoint key - returns the __size key__ of the __config__, parameter if passed otherwise __default config__, corresponding to the size of the window.
*/
export declare function useResponsive(config?: undefined): {
[s in (keyof typeof defaultConfig)]: boolean;
};
export declare function useResponsive<T extends UseResponsiveKeys>(config?: UseResponsiveBreakpoints<T>): {
[s in UseResponsiveKeys<T>]: boolean;
};
export declare type UseResponsiveBreakpoints<T extends UseResponsiveKeys = UseResponsiveKeys> = {
[k in T]: number | {
value: number;
condition: "<" | "<=" | ">" | ">=";
};
};
export declare type UseResponsiveKeys<T extends UseResponsiveKeysType = UseResponsiveKeysType> = T extends UseResponsiveKeysType ? Extract<UseResponsiveKeysType, T> : never;
declare type UseResponsiveKeysType = "xxxs" | "xxs" | "xs" | "sm" | "md" | "lg" | "xl" | "xxl" | "xxxl";
/**
* **`useScreen`**: Hook to work with [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API) and [Window Management API](https://developer.mozilla.org/en-US/docs/Web/API/Window_Management_API). [See demo](https://react-tools.ndria.dev/#/hooks/events/useScreen)
* @param {boolean} [allScreen=false] - to interact with all screens or only with current screen.
* @returns {[ScreenDetails, (orientation: OrientationLockType)=>void, ()=> void]}
* It contains:
* - __details__: an object with two properties:
* - _currentScreen_: object of type _ScreenDetail_ with informations of current screen.
* - _screens_: a _ScreenDetail_ array of all available screens, if browser supports this functionality, otherwise _undefined_.
* - A _ScreenDetail_ object has these properties:
* - __availHeight__
* - __availWidth__
* - __height__
* - __width__
* - __colorDepth__
* - __pixelDepth__
* - __orientation__:
* - __angle__
* - __type__
* - __availLeft__: only available if browser supports them, otherwise is _undefined_
* - __availTop__: only available if browser supports them, otherwise is _undefined_
* - __left__: only available if browser supports them, otherwise is _undefined_
* - __top__: only available if browser supports them, otherwise is _undefined_
* - __devicePixelRatio__: only available if browser supports them, otherwise is _undefined_
* - __isInternal__: only available if browser supports them, otherwise is _undefined_
* - __isPrimary__: only available if browser supports them, otherwise is _undefined_
* - __label__: only available if browser supports them, otherwise is _undefined_
* - __lock__: function that locks the orientation of the containing document to the specified orientation. Typically orientation locking is only enabled on mobile devices, and when the browser context is full screen.
* - __unlock__: function that unlocks the orientation of the containing document from its default orientation.
*/
export declare const useScreen: (allScreen?: boolean) => [ScreenDetails, (orientation: OrientationLockType) => Promise<void>, () => void];
/**
* **`useScreenWakeLock`**: Hook to use [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useScreenWakeLock)
* @param {(evt?:Event)=>void} [onRelease] - function that will be executed on release event.
* @returns {[{isSupported: boolean, type: "screen"|null, isActive: boolean|null}, ()=>Promise<void>, ()=>Promise<void>]} result - An array with three element:
* - 1. __info__: object with these properties:
* - _isSupported_: returns a boolean to know if API is available.
* - _type_: returns a string representation of the currently acquired WakeLock type.
* - _isActive_: returns a boolean indicating whether the WakeLockSentinel has been activated.
* - 2. __acquire__: function to request a WakeLock.
* - 3. __release__: function to release a WakeLock.
*/
export declare const useScreenWakeLock: (onRelease?: (evt?: Event) => void) => [{
isSupported: boolean;
type: "screen" | null;
isActive: boolean | null;
}, () => Promise<void>, () => Promise<void>];
export declare interface UseScript {
(attributes: UseScriptProps["attributes"], options: UseScriptProps["options"]): [status: UseScriptStatus, (attributes?: UseScriptProps["attributes"], iframe?: HTMLIFrameElement) => void, () => void];
}
/**
* **`useScript`**: Hook to dinamically load an external script like Google Analitycs. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useScript)
* @param {{ src?: string, async?: boolean, crossorigin?: "anonymous" | "use-credentials" | "", defer?: boolean, fetchpriority?: "high" | "low" | "auto", integrity?: string, nomodule?: boolean, nonce?: string, referrerpolicy?: "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url", type?: string }} attributes - script attributes.
* @param {{ handleAppending?: boolean, removeOnUnmount?: boolean, iframe?: HTMLIFrameElement }} options - to handle appending and removing script, to automatically remove script when component unmount and to append script to an iframe.
* @returns {[status: UseScriptStatus, (attributes: UseScriptProps["attributes"], iframe?: HTMLIFrameElement) => void, () => void]} array - first element returns script status and second and thirds elements allow to manually handle script.
*/
export declare const useScript: UseScript;
export declare interface UseScriptProps {
attributes: {
src?: string;
async?: boolean;
crossorigin?: "anonymous" | "use-credentials" | "";
defer?: boolean;
fetchpriority?: "high" | "low" | "auto";
integrity?: string;
nomodule?: boolean;
nonce?: string;
referrerpolicy?: "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url";
type?: string;
};
options: {
handleAppending?: boolean;
removeOnUnmount?: boolean;
iframe?: HTMLIFrameElement;
};
}
export declare type UseScriptStatus = "idle" | "loading" | "error" | "ready";
/**
* **`useScrollIntoView`**: Hook to scroll an element into view. [See demo](https://react-tools.ndria.dev/#/hooks/events/useScrollIntoView)
* @param {Object} param
* @param {number} [param.duration=1000] - animation duration in milliseconds.
* @param {"x"|"y"} [param.axis="x"] - scrolling axis.
* @param {(t:number)=>number} [param.animation=easeInOutSine] - easing animation function. Refer to [https://easings.net/](https://easings.net/).
* @param {number} [param.offset=0] - additional distance.
* @param {boolean} [param.cancelable=false] - to establish if animation can be interrupted by user scroll.
* @param {()=>void} [param.onFinish] - callback to be executed when animation ends.
* @param {(()=>E)|E|React.RefObject<E|null>} [param.scrollableElement] - scrollable parent element, ref or function that returns element.
* @returns {{targetRef: React.MutableRefObject<T|null>, scroll: (alignment?: "start"|"center"|"end")=>void, cancel: ()=>void}} result - a __targetRef__ to target element, a __scroll__ function to start scrolling, a __cancel__ function to cancel scrolling.
*/
export declare const useScrollIntoView: <T extends Element, E extends Element | null = null>({ duration, axis, animation, offset, cancelable, onFinish, scrollableElement }: {
duration?: number;
axis?: "x" | "y";
animation?: (t: number) => number;
offset?: number;
cancelable?: boolean;
onFinish?: () => void;
scrollableElement: (() => E) | E | React.RefObject<E | null>;
}) => {
targetRef: React.MutableRefObject<T | null>;
scroll: (alignment?: "start" | "center" | "end") => void;
cancel: () => void;
};
/**
* ___useSessionStorageState___: Custom _useState_ hook implementation using _sessionStorage_, with immutable _getter state_ function and to _remove_ key from sessionStorage. [See demo](https://react-tools.ndria.dev/#/hooks/state/useSessionStorageState)
* @param {Object} params
* @param {string} params.key - item key in session storage.
* @param {T | () => T} [params.initialState] - value or a function , optional.
* @param {{serializer: (item: T)=> string, deserializer: (item: string)=> T, mode?: "read" | "write" | "read/write"}} [params.opts={serializer: JSON.stringify, deserializer: jSON.parse, mode: "read/write"}] - object with serializer and deserializer function to handle values in sessionStorage and mode property to use hook only to read, write or both.
* @returns {[T, () => T, () => void] | [Dispatch<SetStateAction<T>>, () => T, () => void] | [T, Dispatch<SetStateAction<T>>, () => T, () => void]}
*/
export declare function useSessionStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: undefined;
};
}): [T, Dispatch<SetStateAction<T>>, () => T, () => void];
export declare function useSessionStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "read";
};
}): [T, () => T, () => void];
export declare function useSessionStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "write";
};
}): [Dispatch<SetStateAction<T>>, () => T, () => void];
export declare function useSessionStorageState<T>({ key, initialState, opts }: {
key: string;
initialState?: T | (() => T);
opts?: {
serializer?: (item: T) => string;
deserializer?: (item: string) => T;
mode?: "read/write";
};
}): [T, Dispatch<SetStateAction<T>>, () => T, () => void];
/**
* __`useSet`__: Hook to use _Set data structure_ to handle component state with all Set methods. [See demo](https://react-tools.ndria.dev/#/hooks/state/useSet)
* @param {Iterable<T> | (() => Iterable<T>)} [initialState] - An iterable object whose elements are added to Set, or function that returns it.
* @returns {Set<T>}
*/
export declare const useSet: <T>(initialState?: Iterable<T> | (() => Iterable<T>)) => Set<T>;
/**
* **`useShare`**: Hook to use [Web Share Api](https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useShare)
* @returns {{isSupported: boolean, share: (data?: ShareData) => Promise<void>}} object - __isSupported__ to known if share API is supported and __share__ function to use Web share API.
*/
export declare const useShare: () => {
isSupported: boolean;
share: (data?: ShareData) => Promise<void>;
};
/**
* **`useSpeechRecognition`**: Hook to use _SpeechRecognition API_. Refer to [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useSpeechRecognition)
* @param {UseSpeechRecognitionProps} opts - options.
* @param {boolean} [opts.alreadyStarted=false] - istant start SpeechRecognition if it is available.
* @param {Object} [opts.defaultConfig] - config parameters for current SpeechRecognition.
* @param {SpeechGrammarList} [opts.defaultConfig.grammars] - a _SpeechGrammarList_ containing the SpeechGrammar objects that represent your grammar for your app.
* @param {LanguageBCP47Tags} [opts.defaultConfig.lang] - a string representing the BCP 47 language tag for the current SpeechRecognition.
* @param {boolean} [opts.defaultConfig.continuous] - a boolean value representing the current SpeechRecognition's continuous status. true means continuous, and false means not continuous (single result each time.).
* @param {boolean} [opts.defaultConfig.interimResults] - a boolean value representing the state of the current SpeechRecognition's interim results. true means interim results are returned, and false means they aren't.
* @param {number} [opts.defaultConfig.maxAlternatives] - a number representing the maximum returned alternatives for each result.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onAudioStart] - function that will be executed when _audiostart_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onAudioEnd] - function that will be executed when _audioend_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onEnd] - function that will be executed when _end_ event is dispatched.
* @param {((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null} [opts.onError] - function that will be executed when _error_ event is dispatched.
* @param {((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null} [opts.onNoMatch] - function that will be executed when _nomatch_ event is dispatched.
* @param {((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null} [opts.onResult] - function that will be executed when _result_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onSoundStart] - function that will be executed when _soundstart_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onSoundEnd] - function that will be executed when _soundend_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onSpeechStart] - function that will be executed when _speechstart_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onSpeechEnd] - function that will be executed when _speechend_ event is dispatched.
* @param {((this: SpeechRecognition, ev: Event) => void) | null} [opts.onStart] - function that will be executed when _start_ event is dispatched.
* @returns {[SpeechRecognitionState, (config?: SpeechRecognitionConfig)=>void, ()=>void, (resultAlso?:boolean)=>void]} result - An array with four element:
* - 1. __state__: object with these properties:
* - _isSupported_: returns a boolean to know if API is available.
* - _isListening_: returns a boolean indicating current SpeechRecognition execution or not.
* - _result_: returns result of SpeechRecognition execution.
* - 2. __start__: function to start SpeechRecognition.
* - 3. __stop__: function to stop SpeechRecognition.
* - 4. __reset__: function to reset SpeechRecognition with optional parameter to reset results also.
*/
export declare const useSpeechRecognition: ({ alreadyStarted, defaultConfig, onAudioStart, onAudioEnd, onEnd, onError, onNoMatch, onResult, onSoundStart, onSoundEnd, onSpeechStart, onSpeechEnd, onStart }: UseSpeechRecognitionProps) => [SpeechRecognitionState, (config?: SpeechRecognitionConfig) => void, () => void, (resultAlso?: boolean) => void];
export declare interface UseSpeechRecognitionProps {
alreadyStarted?: boolean;
defaultConfig?: SpeechRecognitionConfig;
onAudioStart?: SpeechRecognition["onaudiostart"];
onAudioEnd?: SpeechRecognition["onaudioend"];
onEnd?: SpeechRecognition["onend"];
onError?: SpeechRecognition["onerror"];
onNoMatch?: SpeechRecognition["onnomatch"];
onResult?: SpeechRecognition["onresult"];
onSoundStart?: SpeechRecognition["onsoundstart"];
onSoundEnd?: SpeechRecognition["onsoundend"];
onSpeechStart?: SpeechRecognition["onspeechstart"];
onSpeechEnd?: SpeechRecognition["onspeechend"];
onStart?: SpeechRecognition["onstart"];
}
export declare interface UseSpeechSynthesis {
(props?: UseSpeechSynthesisProps): {
state: {
/**Returns a boolean value indicating SpeechSynthesis availability.*/
isSupported: boolean;
/**Returns the current status of SpeechSynthesis.*/
status: "ready" | "speaking" | "paused" | "error" | "end" | "unavailable";
/**Returns a boolean indicating the presence of texts to speech.*/
hasPending: boolean;
/**Returns the list of available voices.*/
voices: SpeechSynthesisVoice[] | null;
};
/**Function to start speaking.*/
speak: (param: SpeechSynthesisSpeakParam) => void;
/**Function to keep in pause speaking.*/
pause: () => void;
/**Function to resume speaking.*/
resume: () => void;
/**Function to cancel speaking.*/
cancel: () => void;
};
}
/**
* **`useSpeechSynthesis`**: Hook to use _SpeechSynthesis API_. Refer to [Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useSpeechSynthesis)
* @param {UseSpeechSynthesisProps} [opts] - options.
* @param {() => void} [opts.onSpeak] - function that will be executed when _speak_ event is fired.
* @param {SpeechSynthesisUtterance["onstart"]} [opts.onStart] - function that will be executed when _start_ event is fired.
* @param {SpeechSynthesisUtterance["onpause"]} [opts.onPause] - function that will be executed when _pause_ event is fired.
* @param {SpeechSynthesisUtterance["onresume"]} [opts.onResume] - function that will be executed when _resume_ event is fired.
* @param {SpeechSynthesisUtterance["onboundary"]} [opts.onBoundary] - function that will be executed when _boundary_ event is fired.
* @param {SpeechSynthesisUtterance["onmark"]} [opts.onMark] - function that will be executed when _mark_ event is fired.
* @param {SpeechSynthesisUtterance["onerror"]} [opts.onError] - function that will be executed when _error_ event is fired.
* @param {SpeechSynthesisUtterance["onend"]} [opts.onEnd] - function that will be executed when _end_ event is fired.
* @param {SpeechSynthesisonCancel} [opts.onCancel] - function that will be executed when _cancel_ event is fired.
* @param {LanguageBCP47Tags} [opts.lang] - [MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/lang).
* @param {SpeechSynthesisUtterance["pitch"]} [opts.pitch] - [MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/pitch).
* @param {SpeechSynthesisUtterance["rate"]} [opts.rate] - [MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/rate).
* @param {SpeechSynthesisUtterance["voice"]} [opts.voice] - [MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/voice).
* @param {SpeechSynthesisUtterance["volume"]} [opts.volume] - [MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/volume).
* @returns {ReturnType<UseSpeechSynthesis>} return - Object with these properties:
* - __state__: object with these properties:
* - _isSupported_: Returns a boolean value indicating SpeechSynthesis availability.
* - _status_: Returns the current status of SpeechSynthesis between: _ready_ _speaking_ _paused_ _error_ _end_ and _unavailable_.
* - _hasPending_: Returns a boolean indicating the presence of texts to speech.
* - _voices_: Returns the list of available voices.
* - __speak__: Function to start speaking.
* - __pause__: Function to keep in pause speaking.
* - __resume__: Function to resume speaking.
* - __cancel__: Function to cancel speaking.
*/
export declare const useSpeechSynthesis: (opts?: UseSpeechSynthesisProps) => ReturnType<UseSpeechSynthesis>;
export declare interface UseSpeechSynthesisProps {
/**function that will be executed when __speak__ method of _SpeechSynthesis_ will be invoked.*/
onSpeak?: () => void;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/start_event).*/
onStart?: SpeechSynthesisUtterance["onstart"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/pause_event).*/
onPause?: SpeechSynthesisUtterance["onpause"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/resume_event).*/
onResume?: SpeechSynthesisUtterance["onresume"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/boundary_event).*/
onBoundary?: SpeechSynthesisUtterance["onboundary"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/mark_event).*/
onMark?: SpeechSynthesisUtterance["onmark"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/error_event).*/
onError?: SpeechSynthesisUtterance["onerror"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/end_event).*/
onEnd?: SpeechSynthesisUtterance["onend"];
onCancel?: SpeechSynthesisonCancel;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/lang).*/
lang?: LanguageBCP47Tags;
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/pitch).*/
pitch?: SpeechSynthesisUtterance["pitch"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/rate).*/
rate?: SpeechSynthesisUtterance["rate"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/voice).*/
voice?: SpeechSynthesisUtterance["voice"];
/**[MDN Reference](https://developer.mozilla.org/docs/Web/API/SpeechSynthesisUtterance/volume).*/
volume?: SpeechSynthesisUtterance["volume"];
}
/**
* **`useStateGetReset`**: Custom useState with get and reset state functions. [See demo](https://react-tools.ndria.dev/#/hooks/state/useStateGetReset)
* @param {T | () => T} initialState - value or a function.
* @returns {[T, Dispatch<SetStateAction<T>>, () => T, ()=>void]} array
*/
export declare function useStateGetReset<T = undefined>(initialState?: undefined): [T | undefined, Dispatch<SetStateAction<T | undefined>>, () => T | undefined, () => void];
export declare function useStateGetReset<T>(initialState?: T | (() => T)): [T, Dispatch<SetStateAction<T>>, () => T, () => void];
/**
* **`useStateHistory`**: custom useState that tracks and allows to use previous values. [See demo](https://react-tools.ndria.dev/#/hooks/state/useStateHistory)
* @param {T | () => T} initialState - value or a function.
* @param {number | "no-limit"} [capacity="no-limit"] - history capacity (default 'no-limit').
* @returns {[T, Dispatch<SetStateAction<T>>, {history: readonly T[], presentPointer: number, trackUpdate: (enable:boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: T) => void}]} array
*/
export declare const useStateHistory: <T>(initialState: T | (() => T), capacity?: number | "no-limit") => [T, Dispatch<SetStateAction<T>>, {
history: readonly T[];
presentPointer: number;
trackUpdate: (enable: boolean) => void;
canUndo: boolean;
canRedo: boolean;
undo: () => void;
redo: () => void;
go: (index: number) => void;
clear: (value?: T) => void;
}];
/**
* **`useStateHistoryGetter`**: custom useState with getter state function and that tracks and allows to use previous values. [See demo](https://react-tools.ndria.dev/#/hooks/state/useStateHistoryGetter)
* @param {T | () => T} initialState - value or a function.
* @param {number | "no-limit"} [capacity="no-limit"] - history capacity (default 'no-limit').
* @returns {[T, Dispatch<SetStateAction<T>>, () => T, {history: readonly T[], presentPointer: number, trackUpdate: (enable:boolean) => void, canUndo: boolean, canRedo: boolean, undo: () => void, redo: () => void, go: (index: number) => void, clear: (value?: T) => void}]} array
*/
export declare const useStateHistoryGetter: <T>(initialState: T | (() => T), capacity?: number | "no-limit") => [T, Dispatch<SetStateAction<T>>, () => T, ReturnType<typeof useStateHistory<T>>[2]];
/**
* **`useStateValidator`**: custom _useState_ hook that validates state on every update. [See demo](https://react-tools.ndria.dev/#/hooks/state/useStateValidator)
* @param {T | () => T} initialState - value or a function.
* @param {StateValidator} validator - function that will be executed to validate state.
* @returns {[T, Dispatch<SetStateAction<T>>, T extends object ? {[k in keyof T]:{invalid: boolean, message?: string}} : {invalid: boolean, message?: string}]} invalid
* Array with:
* - first element: __state__ value.
* - second element: __setState__ function to update state.
* - third element: __valid__ validation value/object for state.
*/
export declare const useStateValidator: <T>(initialState: T | (() => T), validator: StateValidator<T>) => [T, Dispatch<SetStateAction<T>>, T extends object ? { [k in keyof T]: {
invalid: boolean;
message?: string | undefined;
}; } : {
invalid: boolean;
message?: string | undefined;
}];
/**
* **`useSwipe`**: hook to handle swipe gesture. [See demo](https://react-tools.ndria.dev/#/hooks/events/useSwipe)
* @param {UseSwipeProps} param - object
* @param {RefObject<Element>|Element} param.target - element on which attach swipe event.
* @param {(e: MouseEvent|TouchEvent) => void} [param.onSwipeStart] - callback that will be executed when swipe starts.
* @param {(e: MouseEvent|TouchEvent, direction: SwipeDirection, delta: {x: number, y: number}) => void} [param.onSwipe] - callback that will be executed when swipe moves.
* @param {(e: MouseEvent|TouchEvent, direction: SwipeDirection, delta: { x: number, y: number }) => void} [param.onSwipeEnd] - callback that will be executed when swipe ends.
* @param {Object} [param.options] - object to set option for listener.
* @param {boolean} [param.options.passive=true] - if true, handler callback never calls _preventDefault_ method.
* @param {threshold} [param.options.threshold=0] - a threshold value for swipe event.
* @returns {UseSwipeResult} - callback that stops listener.
*/
export declare const useSwipe: ({ target, onSwipeStart, onSwipe, onSwipeEnd, options }: UseSwipeProps) => UseSwipeResult;
export declare interface UseSwipeProps {
/**Element swipable*/
target: RefObject<Element> | Element;
/**Callback that will be executed on swipe starts*/
onSwipeStart?: (e: MouseEvent | TouchEvent) => void;
/**Callback that will be executed on swipe moves*/
onSwipe?: (e: MouseEvent | TouchEvent, direction: SwipeDirection, delta: {
x: number;
y: number;
}) => void;
/**Callback that will be executed on swipe ends*/
onSwipeEnd?: (e: MouseEvent | TouchEvent, direction: SwipeDirection, delta: {
x: number;
y: number;
}) => void;
/**Options configurable for swipe listeners*/
options?: {
/**If true, listener never invokes _preventDefault_ method.*/
passive?: boolean;
/**A threshold value for swipe event.*/
threshold?: number;
};
}
export declare interface UseSwipeResult {
/**Callback to stop swipe event listening.*/
(): void;
}
export declare const useSyncExternalStore: typeof useSyncExternalStore_2;
/**
* **`useTextSelection`**: Hook to track text selection. Refers to [Selection API](https://developer.mozilla.org/en-US/docs/Web/API/Selection). [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useTextSelection)
* @param {Object} param - object with selection properties
* @param {RefObject<HTMLElement> | HTMLElement} [param.target] - element in which allow selection. Default is _document.body_.
* @param {(evt: Event) => void} [param.onStart] - function to execute when selection starts.
* @param {(evt: Event) => void} [param.onChange] - function to execute while selection changes.
* @param {(evt: Event) => void} [param.onEnd] - function to execute while selection ends.
* @returns {{text: string, direction: "forward"|"backward", outsideRectangle: DOMRect, innerRectangles: DOMRect[]}} TextSelection - object with: _text_: selected text; _direction_: selection direction; _outsideRectangle_: a __DOMRect__ of selection rectangle; _innerRectangles_: list of __DOMRect__ representing the selection slices.
*/
export declare const useTextSelection: ({ target, onStart, onChange, onEnd }?: {
target?: RefObject<HTMLElement> | HTMLElement;
onStart?: (evt: Event) => void;
onChange?: (evt: Event) => void;
onEnd?: (evt: Event) => void;
}) => TextSelection | null;
/**
* **`useThrottle`**: Hook to limit function execution frequency. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useThrottle)
* @param {T extends (...args: unknown[]) => void} fn - The function to handle.
* @param {Object} opts - options for throttle behaviors.
* @param {number} [opts.delay] - time in milliseconds to limit next function execution.
* @param {boolean} [opts.waitFn] - if true, next function execution taking place when current has finished.
* @returns {[(...args: unknown[]) => void, ()=>void, (...args: unknown[]) => void]} - array with throttled function, cancel function to allow other execution and immediate function to execute function immediately.
*/
export declare const useThrottle: <T extends unknown[]>(fn: (...args: T) => void | Promise<void>, opts: {
delay?: number;
waitFn?: boolean;
}) => [(...args: T) => void, () => void, (...args: T) => void];
/**
* **`useTimeout`**: Hook to handle setTimeout timer function with the possibility to clear and promisify execution. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useTimeout)
* @param {(...args: unknown[])=>void} callback - Function to call when the timer elapses.
* @param {number} delay - The number of milliseconds to wait before calling the `callback`.
* @returns {[(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>]} - array: first element is the function to call setTimeout; second element is the function to clearTimeout; thrid element promisify setTimeout.
*/
export declare const useTimeout: <TArgs extends unknown[]>(callback: (...args: TArgs) => void, delay: number) => [(...args: TArgs) => void, () => void, (...args: TArgs) => Promise<void>];
/**
* **`useTitle`**: Hook to handling app page title. It works _outside Component_ also and it returns array of two functions to read and write title. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useTitle)
* @param {string} [title]
* @returns {[() => string, (title: string) => void]} array
*/
export declare const useTitle: (title?: string) => [() => string, (title: string) => void];
/**
* **`useVibrate`**: Hook to use device vibration hardware. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useVibrate)
* @returns {{isSupported: boolean, vibrate: ((pattern: number | number[]) => void), cancel: ()=>void}} result - object with:
* - _isSupported_: boolean to detect if vibration is supported or not.
* - _vibrate_: function to activate device vibration hardware.
* - _cancel_: function to stop vibration running.
*/
export declare const useVibrate: () => {
isSupported: boolean;
vibrate: ((pattern: number | number[]) => void);
cancel: () => void;
};
/**
* **`useVideo`**: Hook to use an HTML video element. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useVideo)
* @param {UseVideoProps} param - Media HTML Attributes of an html video element.
* @returns {UseVideoResult} result
* Object with these properties:
* - __state__: object with current video properties:
* - _buffered_: array of objects, with __start__ and __end__ properties, or null. It indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed.
- _duration_: a read-only double-precision floating-point value indicating the total duration of the media in seconds. If no media data is available, the returned value is NaN.
- _paused_: returns a boolean that indicates whether the media element is paused.
- _muted_: boolean that determines whether video is muted. true if the video is muted and false otherwise.
- _time_: value indicating the current playback time in seconds; if the media has not started to play and has not been seeked, this value is the media's initial playback time. Setting this value seeks the media to the new time. The time is specified relative to the media's timeline.
- _volume_: double indicating the video volume, from 0.0 (silent) to 1.0 (loudest).
- _playbackRate_: double that indicates the rate at which the media is being played back.
- _playing_: boolean indicating if video is playing or not.
* - __controls__: object with current video properties:
* - _play_: function to set video.
* - _pause_: function to pause video.
* - _mute_: function to mute video.
* - _unmute_: function to unmute video.
* - _playbackRate_: function to set video playbackRate.
* - _volume_: function to set video volume.
* - _seek_: function to seek to the given time with low precision.
* - MediaElement: HTMLVideoElement to render.
* - ref: ref to HTMLVideoElement.
*/
export declare const useVideo: (props: MediaHTMLAttributes<HTMLVideoElement>) => {
MediaElement: ReactElement<DetailedReactHTMLElement<HTMLAttributes_2<HTMLAudioElement>, HTMLAudioElement>, string | JSXElementConstructor<any>>;
state: HTMLMediaState;
controls: {
play: () => Promise<void> | undefined;
pause: () => void;
seek: (time: number) => void;
playbackRate: (playbackRate: number) => void;
volume: (volume: number) => void;
mute: () => void;
unmute: () => void;
};
ref: MutableRefObject<HTMLVideoElement | null>;
};
export declare type UseVideoProps = MediaHTMLAttributes<HTMLVideoElement>;
export declare interface UseVideoResult {
state: HTMLMediaState;
controls: HTMLMediaControls;
MediaElement: DetailedReactHTMLElement<HTMLAttributes_2<HTMLVideoElement>, HTMLVideoElement>;
ref: MutableRefObject<HTMLVideoElement | null>;
}
/**
* **`useVisible`**: Hook to know if an element is visible and optionally the visible area ration of the element. [See demo](https://react-tools.ndria.dev/#/hooks/events/useVisible)
* @param {{root?: Element|Document|null, rootMargin?: string, threshold?: number|number[], withRatio?: boolean}} opts - object to set options to observation.
* @returns {[RefCallback<T>, boolean] | [RefCallback<T>, boolean, number]} result - callback for ref element attribute to observe, a boolean to known if element is visible or not and eventually the element ratio.
*/
export declare function useVisible<T extends Element>(opts?: undefined): [RefCallback<T>, boolean];
export declare function useVisible<T extends Element>(opts?: IntersectionObserverInit & {
withRatio?: undefined;
}): [RefCallback<T>, boolean];
export declare function useVisible<T extends Element>(opts?: IntersectionObserverInit & {
withRatio?: true;
}): [RefCallback<T>, boolean, number];
/**
* **`useWebSocket`**: Hook for creating and managing a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) connection to a server, as well as for sending and receiving data on the connection. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useWebSocket)
* @param {UseWebSocketProps} param - object
* @param {UseWebSocketProps} [param.url] - the URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @param {UseWebSocketProps} [param.protocols] - either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols.
* @param {UseWebSocketProps} [param.binaryType] - the type of binary data being received over the WebSocket connection.
* @param {UseWebSocketProps} [param.immediateConnection] - boolean to open webSocket connection immediatly.
* @param {UseWebSocketProps} [param.onOpen] - function that will be executed when webSocket connection has been opened.
* @param {UseWebSocketProps} [param.onMessage] - function that will be executed when message arrived from webSocket.
* @param {UseWebSocketProps} [param.onError] - function that will be executed when an error occurred.
* @param {UseWebSocketProps} [param.onClose] - function that will be executed when webSocket connection has been closed.
* @param {UseWebSocketProps} [param.bufferingData] - boolean that indicates to use a buffer to keep data sent if connection aren't already opened.
* @param {UseWebSocketProps} [param.autoReconnect] - boolean or object with properties __retries__, __delay__ and __onFailed__. If an error closes connection and its value isn't false or undefined, a connection will be restored every _delay_ milliseconds for __retries__ time: if connection won't be restored __onFailed__ function will be executed if it is present.
* @returns {UseWebSocketResult} result
* Object with these properties:
* - __status__: string rapresenting webSocket state connection: __READY__ __CONNECTING__ __OPENED__ or __CLOSED__.
* - __data__: last data value arrived from webSocket.
* - __open__: function that opens connection with optional _url_ param .
* - __send__: function that sends data by webSocket.
* - __close__: function that closes connection with optional _code_ and _reason_ params.
*/
export declare const useWebSocket: <T = string | ArrayBuffer | Blob>({ url, protocols, binaryType, onOpen, onMessage, onError, onClose, immediateConnection, bufferingData, autoReconnect }: UseWebSocketProps) => UseWebSocketResult<T>;
export declare interface UseWebSocketProps {
url?: string | URL;
protocols?: string | string[];
binaryType?: "blob" | "arraybuffer";
immediateConnection?: boolean;
onOpen?: (evt: Event) => void;
onMessage?: <T = string | ArrayBuffer | Blob>(evt: MessageEvent<T>) => void;
onError?: (evt: Event) => void;
onClose?: (evt: CloseEvent) => void;
bufferingData?: boolean;
autoReconnect?: boolean | {
retries: number;
delay: number;
onFailed?: () => void;
};
}
export declare interface UseWebSocketResult<T = string | ArrayBuffer | Blob> {
status: "READY" | "CONNECTING" | "OPENED" | "CLOSED";
data: T | null;
open: (url?: string | URL) => void;
send: (data: string | ArrayBuffer | Blob | TypedArray) => void;
close: (code?: number, reason?: string) => void;
}
/**
* **`useWebWorker`**: Hook to use [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API), handling registration and communication. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useWebWorker)
* @param {UseWebWorkerProps} param - object
* @param {string|URL} [param.url] - A string representing the URL of the script the worker will execute. It must obey the same-origin policy.
* @param {WorkerOptions} [param.options] - An object containing option properties that can be set when creating the object instance.
* @param {(e: MessageEvent)=>void} [param.onMessage] - function that will be executed when a message occurred.
* @param {(e: MessageEvent)=>void} [param.onMessageError] - function that will be executed when a messageError occurred.
* @param {(e: Event)=>void} [param.onError] - function that will be executed when an error occurred.
* @returns {UseWebWorkerResult} result
* Object with these properties:
* - __send__: function to send a message to worker.
* - __terminate__: function to terminate worker.
*/
export declare const useWebWorker: ({ url, options, onMessage, onError, onMessageError }: UseWebWorkerProps) => UseWebWorkerResult;
/**
* **`useWebWorkerFn`**: Hook to run expensive functions using a Web Worker without blocking the UI handling execution as Promise. [See demo](https://react-tools.ndria.dev/#/hooks/api-dom/useWebWorkerFn)
* @param {UseWebWorkerFnProps["fn"]} fn - Expensive function to be executed in worker.
* @param {UseWebWorkerFnProps["deps"]} [deps] - An array that contains the external dependencies needed to run the worker.
* @returns {UseWebWorkerFnResult} execute - function to execute expansive function: return a promise.
*/
export declare const useWebWorkerFn: <T extends (...args: unknown[]) => unknown>(fn: UseWebWorkerFnProps<T>["fn"], deps?: UseWebWorkerFnProps<T>["deps"]) => UseWebWorkerFnResult<T>;
export declare interface UseWebWorkerFnProps<T extends (...args: unknown[]) => unknown> {
fn: T;
deps?: string[];
}
export declare interface UseWebWorkerFnResult<T extends (...args: unknown[]) => unknown> {
(...args: Parameters<T>): Promise<ReturnType<T>>;
}
export declare interface UseWebWorkerProps {
/**A string representing the URL of the script the worker will execute. It must obey the same-origin policy.*/
url: string | URL;
/**An object containing option properties that can be set when creating the object instance.*/
options?: WorkerOptions;
/**The message event is fired on a Worker object when the worker's parent receives a message from its worker.*/
onMessage?: (e: MessageEvent) => void;
/**The messageerror event is fired on a Worker object when it receives a message that can't be deserialized.*/
onMessageError?: (e: MessageEvent) => void;
/**The error event of the Worker interface fires when an error occurs in the worker.*/
onError?: (e: Event) => void;
}
export declare interface UseWebWorkerResult {
/**The postMessage() method of the Worker interface sends a message to the worker.*/
send: <T>(message: T, transfer?: Transferable[] | StructuredSerializeOptions) => void;
/**The terminate() method of the Worker interface immediately terminates the Worker.*/
terminate: Worker["terminate"];
}
export { }