@ndriadev/react-tools
Version:
A React library of hooks, components, utils and types ready to use
782 lines (701 loc) • 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 attribut