UNPKG

@ndriadev/react-tools

Version:

A React library of hooks, components, utils and types ready to use

800 lines (732 loc) 164 kB
import { AriaAttributes } from 'react'; import { ComponentPropsWithRef } 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 { HTMLAttributes } from 'react'; import { JSXElementConstructor } from 'react'; import { KeyboardEvent as KeyboardEvent_2 } from 'react'; import { MediaHTMLAttributes } from 'react'; import { MutableRefObject } from 'react'; import { PropsWithChildren } from 'react'; import { ReactElement } 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'; /** * Utility type that constructs an array of __`T`__ with one element at least. */ declare type ArrayMinLength1<T> = { 0: T; } & Array<T>; declare interface BatteryStatus { isSupported: boolean; level: number; charging: boolean; chargingTime: number; dischargingTime: number; } /**Provides properties of a particular BluetoothRemoteGATTCharacteristic.*/ 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; } declare type BluetoothCharacteristicUUID = number | string; declare type BluetoothDescriptorUUID = number | string; /**Represents a Bluetooth device inside a particular script execution environment.*/ 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; } 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.*/ 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.*/ 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.*/ 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.*/ 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[]>; } 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; }; 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().*/ 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; } /** * **`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`. */ declare interface CompareFn<T = unknown> { (oldDeps: DependencyListTyped<T>, newDeps: DependencyListTyped<T>): boolean; } 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">; /** * Utility type that works like __DependencyList__ react type but it can be specified dependencies list element types. */ declare type DependencyListTyped<T = unknown> = ReadonlyArray<T>; declare interface DeviceMotionProps { isSupported: boolean; acceleration: DeviceMotionEventAcceleration | null; accelerationIncludingGravity: DeviceMotionEventAcceleration | null; rotationRate: DeviceMotionEventRotationRate | null; interval: number | null; } declare interface DeviceOrientationProps { isSupported: boolean; absolute: boolean | null; alpha: number | null; beta: number | null; gamma: number | null; } declare interface DocumentPictureInPictureEvent extends Event { window: Window; } declare interface DocumentPIPOptions { window?: { width: number; height: number; }; inheritCSS?: boolean; } /** * Utility type that given an array extracts a new array with all elements from array expect first. */ declare type ExtractTail<T extends unknown[]> = T extends [unknown, ...infer Tail] ? Tail : never; declare type GeoLocationObject = ({ isSupported: true; position?: GeolocationPosition; }) | ({ isSupported: false; position?: never; }); declare interface HTMLAttributes_2<T> extends AriaAttributes, DOMAttributes<T> { popover?: "auto" | "manual"; } declare interface HTMLMediaState { buffered: { start: number; end: number; }[] | null; duration: number; paused: boolean; muted: boolean; time: number; volume: number; playbackRate: number; playing: boolean; } /** * Utility type for Language BCP-47 tags. */ 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"; declare type OrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; 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"; 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; }; } declare interface ScreenDetails { readonly currentScreen: ScreenDetail; readonly screens: ScreenDetail[] | undefined; } /**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.*/ 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.*/ 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.*/ 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; } 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; } declare type SpeechRecognitionErrorCode = 'aborted' | 'audio-capture' | 'bad-grammar' | 'language-not-supported' | 'network' | 'no-speech' | 'not-allowed' | 'service-not-allowed'; declare interface SpeechRecognitionErrorEvent extends Event { readonly error: SpeechRecognitionErrorCode; readonly message?: string; } 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.*/ 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; 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"]; }); 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; } declare type SwipeDirection = "up" | "right" | "down" | "left" | "none"; declare type TDisplayMediaStreamOptions = DisplayMediaStreamOptions & { controller?: CaptureController; }; declare interface TextSelection { text: string; direction: "forward" | "backward"; outsideRectangle: DOMRect; innerRectangles: DOMRect[]; } declare type TPermissionName = PermissionName | PermissionNamePolyfill; declare type TPermissionState = PermissionState | "not supported" | "asking"; /** * Utility type for __`Typed Arrays`__. */ declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; /** * **`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>; 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; } 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<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>; }; /** * **`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, re