@alessiofrittoli/web-utils
Version:
Common TypeScript web utilities
1,268 lines (1,255 loc) • 63.9 kB
text/typescript
import { UrlInput } from '@alessiofrittoli/url-utils';
/**
* The `NetworkInformation` interface of the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API)
* provides information about the connection a device is using to
* communicate with the network and provides a means for scripts to be notified if the connection type changes.
*
* The `NetworkInformation` interface cannot be instantiated.
* It is instead accessed through the `connection` property of the [`Navigator`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator)
* interface or the [`WorkerNavigator`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerNavigator) interface.
*
* ⚠️ Will be replaced by official [NetworkInformation](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation) interface.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation)
*/
interface NetworkInformation extends EventTarget {
/**
* Returns the effective bandwidth estimate in megabits per second, rounded to the nearest multiple of 25 kilobits per seconds.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink)
*/
readonly downlink: number;
/**
* Returns the maximum downlink speed, in megabits per second (Mbps), for the underlying connection technology.
*
* ⚠️ Experimental - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlinkMax#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlinkMax)
*/
readonly downlinkMax?: number;
/**
* Returns the effective type of the connection.
* This value is determined using a combination of recently observed round-trip time and downlink values.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType)
*/
readonly effectiveType: 'slow-2g' | '2g' | '3g' | '4g';
/**
* Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/rtt#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/rtt)
*/
readonly rtt: number;
/**
* Returns `true` if the user has set a reduced data usage option on the user agent.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData)
*/
readonly saveData: boolean;
/**
* Returns the type of connection a device is using to communicate with the network.
*
* ⚠️ Experimental - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type)
*/
readonly type?: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';
}
/**
* Defiens network status and `NetworkInformation`.
*
*/
interface Connection {
/**
* The `NetworkInformation` interface of the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API)
* provides information about the connection a device is using to
* communicate with the network and provides a means for scripts to be notified if the connection type changes.
*
* The `NetworkInformation` interface cannot be instantiated.
* It is instead accessed through the `connection` property of the [`Navigator`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator)
* interface or the [`WorkerNavigator`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerNavigator) interface.
*
* ⚠️ Will be replaced by official [NetworkInformation](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation) interface.
*
* ⚠️ Limited availability - [See full compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation#browser_compatibility)
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation)
*/
readonly network?: NetworkInformation;
/**
* Indicates whether the device is connected to the network.
*
* - See [Listening for changes in network status](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#listening_for_changes_in_network_status).
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine)
*/
readonly onLine: boolean;
}
/**
* Get current Network status and information.
*
* @returns An object defining network status and `NetworkInformation`. See {@link Connection} for more info.
*/
declare const getConnection: () => Connection;
/**
* Safely executes `window.matchMedia()` in server and browser environments.
*
* @param query The Media Query string to check.
* @returns `false` if `window` is not defined or if the `document` currently doesn't matches the given `query`. `true` otherwise.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/matches)
*/
declare const getMediaMatches: (query: string) => boolean;
/**
* Prevent Element Overflow.
*
* @param target (Optional) The target HTMLElement. Default: `Document.documentElement`.
*/
declare const blockScroll: (target?: HTMLElement) => void;
/**
* Restore Element Overflow.
*
* @param target (Optional) The target HTMLElement. Default: `Document.documentElement`.
*/
declare const restoreScroll: (target?: HTMLElement) => void;
/**
* Represents a URL stylesheet as a simple URL input, URL object or as an object
* with URL and fetch configuration options.
*/
type UrlStylesheet = UrlInput | {
/**
* The URL string or a URL object of the stylesheet to load.
*
*/
url: UrlInput;
/**
* Indicates whether to fetch the given URL.
*
* @default false
*/
fetch?: boolean;
};
/**
* Represents a style input.
*
* @property {UrlStylesheet} - A URL string or input pointing to a stylesheet file URL.
* @property {HTMLStyleElement} - An HTML style element containing CSS rules.
* @property {CSSStyleSheet} - A CSS stylesheet object.
* @property {StyleSheetList} - A collection of CSS stylesheets.
*/
type Style = UrlStylesheet | HTMLStyleElement | CSSStyleSheet | StyleSheetList;
/**
* Represents a single style object or an array of style objects.
*
* @typeParam Style The style object type. See {@link Style}.
*/
type Styles = Style | Style[];
type CloneStyleSheetsReturn = (HTMLStyleElement | HTMLLinkElement)[];
/**
* Clones a StyleSheetList or array of CSSStyleSheets into an array of `HTMLStyleElement` objects.
*
* This function extracts CSS rules from each stylesheet and creates corresponding `<style>`
* elements containing the serialized CSS text. If an error occurs while processing a stylesheet,
* the error is logged and that stylesheet is skipped.
*
* @param styles The source `StyleSheetList` or array of `CSSStyleSheet` objects to clone.
*
* @returns An array of `HTMLStyleElement` objects, each containing the CSS rules from the source stylesheets.
* Failed stylesheets are filtered out and not included in the result.
*
* @example
*
* ```ts
* const styles = cloneStyleSheetList( document.styleSheets )
* styles.forEach( style => shadowRoot.appendChild( style ) )
* ```
*/
declare const cloneStyleSheetList: (styles: StyleSheetList | CSSStyleSheet[]) => HTMLStyleElement[];
/**
* Clones style sheets from various sources into new HTMLStyleElement nodes.
*
* @param styles A style source or array of style sources. Style source an be:
* - `StyleSheetList`: A list of stylesheets.
* - `CSSStyleSheet` A single stylesheet object.
* - `HTMLStyleElement`: A style DOM element.
* - `UrlStylesheet`: A URL stylesheet as a simple URL input, URL object or as an object with URL and fetch configuration options.
*
* @returns A promise that resolves to an array of cloned HTMLStyleElement and HTMLLinkElement nodes.
* For inline styles and StyleSheetLists, returns HTMLStyleElement nodes.
* For URL-based stylesheets, returns HTMLLinkElement nodes (or HTMLStyleElement if fetch is true).
* Failed operations are silently ignored.
*
* @remarks
* - When a URL stylesheet has `fetch: true`, the stylesheet content is fetched and embedded as inline CSS.
* - When `fetch: false` (default), a link element is created instead.
* - URL parsing is handled through the Url utility with support for both string and `UrlInput` object formats.
*/
declare const cloneStyleSheets: (styles: Styles) => Promise<CloneStyleSheetsReturn>;
/**
* Represents valid input types for specifying dimensions.
*
* Can be provided as:
* - A single number value
* - A string value where dimesions are extracte from
* - A tuple containing `width` and `height` values
*/
type InputDimensions = string | number | [xy: Dimensions[number]] | Dimensions;
/**
* Represents a tuple of two optional numeric values.
*
*/
type Dimensions = [x: number | undefined, y: number | undefined];
/**
* Extracts and normalizes dimensions from various input formats.
*
* @param dimensions The input dimensions.
*
* @returns A tuple containing `[ number, number ]` where either value can be `undefined`.
*
* @example
* ```ts
* const [ width, height ] = getDimensions() // [ undefined, undefined ]
* const [ width, height ] = getDimensions( 100 ) // [ 100, 100 ]
* const [ width, height ] = getDimensions( [ 200, 300 ] ) // [ 200, 300 ]
* const [ width, height ] = getDimensions( [ 200 ] ) // [ 200, 200 ]
* const [ width, height ] = getDimensions( '200x300' ) // [ 200, 300 ]
* ```
*/
declare const getDimensions: (dimensions?: InputDimensions) => Dimensions;
/**
* Checks if the Document Picture-in-Picture API is supported by the current browser.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Document_Picture-in-Picture_API)
*
* @returns `true` if Document Picture-in-Picture is supported, `false` otherwise.
*/
declare const isDocumentPictureInPictureSupported: () => boolean;
/**
* Validates that the Document Picture-in-Picture API is supported by the current browser.
*
* @throws {Exception} Throws a new Exception if the Document Picture-in-Picture API is not supported.
*/
declare const requiresDocumentPictureInPictureAPI: () => void;
/**
* Defines configuration options for opening a Document Picture-in-Picture window.
*
*/
interface OpenDocumentPictureInPictureOptions {
/**
* A tuple defining non-negative numbers representing the width and the height to set for the Picture-in-Picture window's viewport, in pixels.
*
* @default [ 250, 250 ]
*/
sizes?: InputDimensions;
/**
* Hints to the browser that it should not display a UI control that enables the user to return to the originating tab and close the Picture-in-Picture window.
*
* @default false
*/
disallowReturnToOpener?: boolean;
/**
* Defines whether the Picture-in-Picture window will always appear back at the position and size it initially opened at,
* when it is closed and then reopened.
*
* By contrast, if `preferInitialWindowPlacement` is `false` the Picture-in-Picture window's size and position will be remembered
* when closed and reopened — it will reopen at its previous position and size, for example as set by the user.
*
* @default false
*/
preferInitialWindowPlacement?: boolean;
/**
* Custom styles to load inside the Picture-in-Picture window.
*
* ⚠️ To keep consistent styling with your web-app, document styles are automatically cloned.
*/
styles?: Styles;
/**
* A callback to execute when Picture-in-Picture window is closed.
*
*/
onQuit?: () => void;
}
/**
* Defines the returned result of opening a Document Picture-in-Picture window.
*
*/
interface OpenDocumentPictureInPicture {
/**
* The browsing context inside the Document Picture-in-Picture window.
*
*/
window: Window;
}
/**
* Opens a Document Picture-in-Picture window.
*
* @param options Configuration options for opening a new Document Picture-in-Picture window.
* See {@link OpenDocumentPictureInPictureOptions} for more info.
*
* @returns A new Promise that resolves to the Document Picture-in-Picture result containing the `window` of the new browsing context.
* See {@link OpenDocumentPictureInPicture} for more info.
*
* @throws {Exception} Throws a new Exception if the Document Picture-in-Picture API is not supported.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Document_Picture-in-Picture_API)
*/
declare const openDocumentPictureInPicture: (options?: OpenDocumentPictureInPictureOptions) => Promise<OpenDocumentPictureInPicture>;
type Truthy = 'yes' | '1' | 'true';
type Falsey = 'no' | '0' | 'false';
interface WindowFeatures {
/**
* Indicates that you want the browser to send an [Attribution-Reporting-Eligible](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Attribution-Reporting-Eligible) header along with the `open()` call.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#attributionsrc)
*/
attributionsrc?: Truthy;
/**
* By default, window.open opens the page in a new tab. If popup is set to true, it requests that a minimal popup window be used.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#popup)
*/
popup?: Truthy | Falsey;
/**
* Specifies the width of the content area, including scrollbars. The minimum required value is 100.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#width)
*/
width?: string;
/**
* Specifies the height of the content area, including scrollbars. The minimum required value is 100.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#height)
*/
height?: string;
/**
* Specifies the distance in pixels from the left side of the work area as defined by the user's operating system where the new window will be generated.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#left)
*/
left?: string;
/**
* Specifies the distance in pixels from the top side of the work area as defined by the user's operating system where the new window will be generated.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#top)
*/
top?: string;
/**
* If this feature is set, the new window will not have access to the originating window via `Window.opener` and returns `null`.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noopener)
*/
noopener?: '_top' | '_self' | '_parent';
/**
* If this feature is set, the browser will omit the [Referer](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referer) header, as well as set `noopener` to true.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#noreferrer)
*/
noreferrer?: Truthy | Falsey;
}
type OptionsFeatures = (Omit<WindowFeatures, ('popup' | 'width' | 'height' | 'innerWidth' | 'innerHeight')>);
interface OpenBrowserPopUpOptions {
/**
* The URL or path of the resource to be loaded.
*
* If an empty string ("") is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.
*/
url?: UrlInput;
/** The PopUp width. Default: `600`. */
width?: number;
/** The PopUp height. Default: `800`. */
height?: number;
/** A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. */
context?: string;
/** Additional custom PopUp features. */
features?: OptionsFeatures;
}
/**
* Open Window PopUp.
*
* @param options An object defining custom PopUp options. See {@link OpenBrowserPopUpOptions} interface for more informations.
*
* @returns If the browser successfully opens the new browsing context, a WindowProxy object is returned.
* The returned reference can be used to access properties and methods of the new context as long as it complies
* with the same-origin policy security requirements.
* `null` is returned if the browser fails to open the new browsing context, for example because it was blocked
* by a browser popup blocker.
*
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/open)
*/
declare const openBrowserPopUp: (options?: OpenBrowserPopUpOptions) => WindowProxy | null;
/**
* Make first letter uppercase.
*
* @param input The input string to convert.
* @returns The processed string.
*/
declare const ucFirst: (input: string) => string;
/**
* Make first letter lowercase.
*
* @param input The input string to convert.
* @returns The processed string.
*/
declare const lcFirst: (input: string) => string;
/**
* Convert string to camelCase.
*
* @param input The input string to convert.
* @returns The converted string to camelCase.
*/
declare const toCamelCase: (input: string) => string;
/**
* Convert string to kebab-case string.
*
* @param input The input string to convert.
* @returns The converted string to kebab-case.
*/
declare const toKebabCase: (input: string) => string;
/**
* Stringify value.
*
* @param input The value to stringify.
* @returns The stringified `input`.
*/
declare const stringifyValue: (input?: any) => string;
/**
* Parse stringified value.
*
* @param input The value to parse.
* @returns The parsed `input`.
*/
declare const parseValue: <T>(input?: string) => T | undefined;
/**
* Add leading character to a string.
*
* The given `input` won't be modified if it already contains the given `character`.
*
* @param input The string to process.
* @param character The character to add.
* @param search ( Optional ) A custom search expression. Default `character`.
*
* @returns The given string with leading character.
*/
declare const addLeadingCharacter: (input: string, character: string, search?: string | RegExp) => string;
/**
* Remove leading character from a string.
*
* @param input The string to process.
* @param character The character to remove.
*
* @returns The given string with leading character removed.
*/
declare const removeLeadingCharacter: (input: string, character: string | RegExp) => string;
/**
* Add trailing character to a string.
*
* The given `input` won't be modified if it already contains the given `character`.
*
* @param input The string to process.
* @param character The character to add.
* @param search ( Optional ) A custom search expression. Default `character`.
*
* @returns The given string with trailing character.
*/
declare const addTrailingCharacter: (input: string, character: string, search?: string | RegExp) => string;
/**
* Remove trailing character from a string.
*
* @param input The string to process.
* @param character The character to remove.
*
* @returns The given string with trailing character removed.
*/
declare const removeTrailingCharacter: (input: string, character: string | RegExp) => string;
type Recipient = string | {
/**
* The recipient name.
*
*/
name?: string;
/**
* The recipient email address.
*
*/
email: string;
};
type Recipients = Recipient | Recipient[];
/**
* Converts a single recipient or an array of recipients into a comma-separated string.
*
* Each recipient can be either a string (email address) or an object with at least an `email` property,
* and optionally a `name` property. If the recipient is an object and has a `name`, the output will be
* formatted as `"Name<email>"`. If the `name` is missing, only the email will be used.
*
* @param recipients A single `Recipient` or an array of `Recipient`. Each recipient can be a string or an object with `email` and optional `name`.
* @returns A comma-separated string of recipients formatted as `"Name<email>"` or just `"email"`.
*/
declare const recipientsToString: (recipients: Recipients) => string;
interface EmailData {
/**
* The email recipients.
*
*/
to?: Recipients;
/**
* The email carbon copy recipients.
*
*/
cc?: Recipients;
/**
* The email blind carbon copy recipients.
*
*/
bcc?: Recipients;
/**
* The email subject.
*
*/
subject?: string;
/**
* The email body.
*
*/
body?: string;
}
/**
* Converts an `EmailData` object into a properly formatted mailto URL string.
*
* This function constructs a mailto link using the provided email data, including
* recipients, subject, body, CC, and BCC fields. It encodes the parameters as URL
* search parameters and concatenates them to form a valid mailto URI.
*
* @param data The email data to convert. If omitted, defaults to an empty object.
* @returns A string representing the mailto URL.
*/
declare const emailDataToString: (data?: EmailData) => string;
/**
* Represents a value that can be used as a parameter in string operations.
*
*/
type ParameterizedValue = string | boolean | number | bigint;
/**
* Represents a parameterized string with its corresponding values.
*
* @property {string} 0 - The template string
* @property {ParameterizedValue[]} 1 - Array of values to be substituted into the template string
*/
type Parameterized = [string, ParameterizedValue[]];
/**
* Creates a parameterized string with placeholder values.
*
* @param strings - The template string parts from a template literal.
* @param values - One or more parameter values or arrays of values to be substituted into the template.
* @returns A tuple containing the normalized string with `?` placeholders and an array of parameter values.
*
* @example
* ```ts
* const [ string, params ] = parameterized`
* SELECT * FROM users WHERE id = ${ 1 } AND status IN ( ${ [ 'active', 'pending' ] } )
* ` )
*
* // string: "SELECT * FROM users WHERE id = ? AND status IN ( ?, ? )"
* // params: [ 1, 'active', 'pending' ]
* ```
*
* @remarks
* - Whitespace is normalized (multiple spaces reduced to single space, trimmed).
* - Undefined values are skipped.
* - Array values are expanded into comma-separated placeholders.
* - Single values are replaced with a single `?` placeholder.
*/
declare const parameterized: (strings: TemplateStringsArray, ...values: (ParameterizedValue | ParameterizedValue[])[]) => Parameterized;
/**
* @see {@link globalThis.ShareData}
*/
interface ShareData {
/**
* The URL to share.
*
*/
url?: UrlInput;
/**
* An array of `File` objects representing files to be shared. See [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share#shareable_file_types) for shareable file types.
*
*/
files?: File[];
/**
* A string representing text to be shared.
*
*/
text?: string;
/**
* A string representing a title to be shared. May be ignored by the target.
*
*/
title?: string;
}
type ClassicSharerPopUpOptions = Omit<OpenBrowserPopUpOptions, 'context'>;
interface SharerPopUpOptions extends ClassicSharerPopUpOptions {
/**
* The shared content title.
*
*/
title?: string;
}
interface OpenSharerPopUpOptions extends ClassicSharerPopUpOptions {
/**
* The base sharer provider URL.
*
*/
sharer: UrlInput;
/**
* Custom URLSearchParam name where URL to share get stored.
*
* @default 'url'
*/
urlParam?: string;
}
interface PinterestSharerPopUpOptions extends ClassicSharerPopUpOptions {
/**
* The media URL.
*
* @default url
*/
media?: UrlInput;
/**
* The media description.
*
*/
description?: string;
}
interface WhatsAppSharerPopUpOptions extends ClassicSharerPopUpOptions {
/**
* Additional custom WhatsApp message.
*
*/
text?: string;
}
/**
* Check whether the web page can leverage share APIs.
*
* @returns `true` if web page is running in a secure context (HTTPS) and can leverage share APIs.
*/
declare const canWebApiShare: () => boolean;
/**
* Check whether the web page can share the given data.
*
* @param data (Optional) The data that is going to be shared.
* @returns `true` if web page is running in a secure context (HTTPS) and can share the given data, `false` otherwise.
*/
declare const canWebApiShareData: (data?: globalThis.ShareData) => boolean;
/**
* Share data using the native sharing mechanism of the device to share data such as text, URLs, or files.
*
* Available only in secure contexts.
*
* @param data (Optional) The data to share. If no data is provided, then the current location URL is used.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Navigator/share)
*/
declare const share: (data?: ShareData) => Promise<false | void>;
/**
* Share data via Email.
*
*/
declare const shareViaEmail: (data?: EmailData) => void;
/**
* Open sharer browser PopUp.
*
* @param options An object defining share options. See {@link OpenSharerPopUpOptions}.
* @returns The result of {@link openBrowserPopUp}.
*/
declare const openSharerPopUp: (options: OpenSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Facebook.
*
* @param options (Optional) The data to share. See {@link SharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnFacebook: (options?: SharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Workplace.
*
* @param options (Optional) The data to share. See {@link SharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnWorkplace: (options?: SharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Reddit.
*
* @param options (Optional) The data to share. See {@link SharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnReddit: (options?: SharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Weibo.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnWeibo: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on VK.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnVK: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Tumblr.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnTumblr: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Line.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnLine: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on X.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnX: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on LinkedIn.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnLinkedIn: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Telegram.
*
* @param options (Optional) The data to share. See {@link ClassicSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnTelegram: (options?: ClassicSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL on Pinterest.
*
* @param options (Optional) The data to share. See {@link PinterestSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnPinterest: (options?: PinterestSharerPopUpOptions) => Window | null;
/**
* Share URL or current page URL via WhatsApp.
*
* @param options (Optional) The data to share. See {@link WhatsAppSharerPopUpOptions} for more info.
* @returns The `WindowProxy` object of the new context, `null` otherwise. See {@link openBrowserPopUp} for more info.
*/
declare const shareOnWhatsApp: (options?: WhatsAppSharerPopUpOptions) => Window | null;
/**
* A type-safe extension of the Map class that enforces key-value relationships based on a provided type.
*
* @template T The object type defining the key-value relationships.
* @template P Defines whether the `Map.get()` method should return a possibily undefined value.
* @template K Internal - The subset of keys in T that are allowed in the Map. Defaults to all keys of T.
*/
interface TypedMap<T, P extends boolean = true, K extends keyof T = keyof T> extends Map<K, T[K]> {
/**
* Executes a provided function once per each key/value pair in the Map, in insertion order.
*/
forEach<K extends keyof T>(callbackfn: (value: T[K], key: K, map: TypedMap<T, P, K>) => void, thisArg?: any): void;
/**
* Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
* @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
*/
get<K extends keyof T>(key: K): P extends true ? T[K] | undefined : T[K];
/**
* Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
*/
set<K extends keyof T>(key: K, value: T[K]): this;
}
/**
* Creates a new instance of a type-safe Map with the given type.
*
* @template T The object type defining the key-value relationships.
* @template P Defines whether the `Map.get()` method should return a possibily undefined value.
*
* @param iterable Initial `Map` constructor iterable object.
*
* @returns A new instance of a type-safe Map.
*/
declare const getTypedMap: <T, P extends boolean = true, K extends keyof T = keyof T>(iterable?: Iterable<readonly [K, T[K]]> | null) => TypedMap<T, P, K>;
/** The Cookie Priority. */
declare enum Priority {
/** Low priority. */
Low = "Low",
/** Medium priority (default). */
Medium = "Medium",
/** High priority. */
High = "High"
}
/**
* Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)).
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)
*/
declare enum SameSite {
/**
* The browser sends the cookie only for same-site requests.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#strict)
*/
Strict = "Strict",
/**
* The cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site.
*
* @warning Not all browsers set SameSite=Lax by default. See [Browser compatibility](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#browser_compatibility) for details.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#lax)
*/
Lax = "Lax",
/**
* The browser sends the cookie with both cross-site and same-site requests.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#none)
*/
None = "None"
}
/**
* Interface representing Cookie properties before it get parsed.
*
*/
interface RawCookie<K = string, V = unknown> {
/**
* The Cookie name.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)
*/
name: K;
/**
* The Cookie value.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie-namecookie-value)
*/
value?: V;
/**
* Defines the host to which the cookie will be sent.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#domaindomain-value)
*/
domain?: string;
/**
* Indicates the maximum lifetime of the cookie.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#expiresdate)
*/
expires?: string | number | Date;
/**
* Forbids JavaScript from accessing the cookie, for example, through the [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) property.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly)
*/
httpOnly?: boolean;
/**
* Indicates the number of seconds until the cookie expires.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#max-agenumber)
*/
maxAge?: number;
/**
* Indicates that the cookie should be stored using partitioned storage.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#partitioned)
*/
partitioned?: boolean;
/**
* Indicates the path that must exist in the requested URL for the browser to send the `Cookie` header.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#pathpath-value)
*/
path?: string;
/**
* Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks ([CSRF](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)).
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)
*/
sameSite?: SameSite;
/**
* Indicates that the cookie is sent to the server only when a request is made with the https: scheme.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#secure)
*/
secure?: boolean;
/**
* Defines the Cookie priority.
*
*/
priority?: Priority;
}
/**
* Interface representing Cookie properties after it get parsed.
*
*/
interface ParsedCookie<K = string, V = unknown> extends Omit<RawCookie<K, V>, 'expires'> {
/**
* Indicates the maximum lifetime of the cookie.
*
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#expiresdate)
*/
expires?: Date;
}
/**
* Map representation of a parsed Cookie.
*
*/
type ParsedCookieMap<K = string, V = unknown> = TypedMap<ParsedCookie<K, V>, false>;
/**
* Easly handle cookies.
*
*/
declare class Cookie {
/**
* Get a cookie by cookie name from `Document.cookie`.
*
* @param name The name of the cookie.
* @returns The found parsed cookie or `undefined` if no cookie has been found in `Document.cookie`.
*/
static get<T, K extends string | number | symbol = string>(name: K): (K extends infer T_1 extends keyof Record<K, T> ? { [P in T_1]: ParsedCookieMap<P, Record<K, T>[P]>; } : never)[K] | undefined;
/**
* Get all cookies from `Document.cookie`.
*
* @returns The parsed cookie found in `Document.cookie`.
*/
static getAll<T extends Record<string, unknown>>(): TypedMap<keyof T extends infer T_1 extends keyof T ? { [P in T_1]: ParsedCookieMap<P, T[P]>; } : never, true, keyof T>;
/**
* Set a cookie to `Document.cookie`.
*
* @param options The cookie options or a parsed Cookie Map.
* @returns The set Cookie Map if successful, `false` otherwise.
*/
static set<K = string, V = unknown>(options: RawCookie<K, V> | ParsedCookieMap<K, V>): false | ParsedCookieMap<K, V>;
/**
* Delete a cookie by cookie name from `Document.cookie`.
*
* @param name The name of the cookie.
* @returns `true` if successful, `false` otherwise.
*/
static delete(name: string): boolean;
/**
* Parse the given cookie options to a Cookie Map.
*
* @param options The cookie options or a parsed Cookie Map.
* @returns The parsed Cookie Map.
*/
static parse<K = string, V = unknown>(options: RawCookie<K, V> | ParsedCookieMap<K, V>): ParsedCookieMap<K, V>;
/**
* Stringify a Cookie ready to be stored.
*
* @param options The cookie options or a parsed Cookie Map.
* @returns The stringified Cookie ready to be stored.
*/
static toString<K = string, V = unknown>(options: RawCookie<K, V> | ParsedCookieMap<K, V>): string;
/**
* Parse a cookie string to a Cookie Map.
*
* @param cookie The cookie string.
* @returns The parsed Cookie Map or `null` if parsing fails.
*/
static fromString<K = string, V = unknown>(cookie: string): ParsedCookieMap<K, V> | null;
/**
* Parse a cookie list string to a Map of cookies.
*
* @param list The cookie list string.
* @returns The Map of parsed cookies indexed by the Cookie name.
*/
static fromListString<T extends Record<string, unknown>, K extends keyof T = keyof T>(list: string): TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }, true, K>;
/**
* Parse a value based on the key.
*
* @param value The value to parse.
* @param key The key associated with the value.
*
* @returns The parsed value.
*/
private static parseValue;
}
/**
* A browser-compatible implementation of [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). Data is stored
* unencrypted in the file specified by the `--localstorage-file` CLI flag.
* The maximum amount of data that can be stored is 10 MB.
* Any modification of this data outside of the Web Storage API is not supported.
* Enable this API with the `--experimental-webstorage` CLI flag.
* `localStorage` data is not stored per user or per request when used in the context
* of a server, it is shared across all users and requests.
*/
declare class LocalStorage {
/**
* Get the current value associated with the given `key`, or `undefined` if the given `key` does not exist.
*
* @param key The item name.
* @returns The current value associated with the given `key`, or `undefined` if the given `key` does not exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/getItem)
*/
static get<T>(key: string): T | undefined;
/**
* Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
*
* Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* @param key The item name.
* @param value The item value.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/setItem)
*/
static set<T>(key: string, value: T): void;
/**
* Removes the key/value pair with the given key, if a key/value pair with the given key exists.
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* @param key The item name.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/removeItem)
*/
static delete(key: string): void;
/**
* Removes all key/value pairs, if there are any.
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/clear)
*/
static clear(): void;
/**
* Get storage item name by item numeric index.
*
* @param index The item index in the storage.
* @returns The name of the nth key, or `null` if n is greater than or equal to the number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/key)
*/
static key(index: number): string | null;
/**
* Get the number of key/value pairs.
*
* @returns The number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/length)
*/
static getLength(): number;
}
/**
* A browser-compatible implementation of [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage). Data is stored in
* memory, with a storage quota of 10 MB. `sessionStorage` data persists only within
* the currently running process, and is not shared between workers.
*/
declare class SessionStorage {
/**
* Get the current value associated with the given `key`, or `undefined` if the given `key` does not exist.
*
* @param key The item name.
* @returns The current value associated with the given `key`, or `undefined` if the given `key` does not exist.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/getItem)
*/
static get<T>(key: string): T | undefined;
/**
* Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
*
* Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* @param key The item name.
* @param value The item value.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/setItem)
*/
static set<T>(key: string, value: T): void;
/**
* Removes the key/value pair with the given key, if a key/value pair with the given key exists.
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* @param key The item name.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/removeItem)
*/
static delete(key: string): void;
/**
* Removes all key/value pairs, if there are any.
*
* Dispatches a storage event on Window objects holding an equivalent Storage object.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/clear)
*/
static clear(): void;
/**
* Get storage item name by item numeric index.
*
* @param index The item index in the storage.
* @returns The name of the nth key, or `null` if n is greater than or equal to the number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/key)
*/
static key(index: number): string | null;
/**
* Get the number of key/value pairs.
*
* @returns The number of key/value pairs.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Storage/length)
*/
static getLength(): number;
}
/**
* Removes duplicate values from an array.
*
* @param array The input array.
* @returns The filtered array.
*/
declare const arrayUnique: <T>(array: T[]) => T[];
/**
* Removes duplicate entries from an array referencing an object key.
*
* @param array An array of objects.
* @param property The Object property to refer to.
* @returns The filtered array.
*/
declare const arrayObjectUnique: <T>(array: T[], property: keyof T) => T[];
/**
* Convert a stringified Array to Array object.
*
* @param string The string to convert. ( e.g. `value1, value2` or `value1,value2` )
* @returns The converted string Array.
*/
declare const listToArray: (string: string) => string[];
type ChunkIntoOptions = ({
/**
* Will split the given Array in a way to ensure each chunk length is, whenever possible, equal to the given value.
*
*/
size: number;
count?: never;
} | {
/**
* Will split the given Array in a way to ensure n chunks as the given value.
*
*/
count: number;
size?: never;
});
/**
* Split Array into chunks.
*
* @template T The input `array` type.
*
* @param array The original Array.
* @param options An object defining split criteria. See {@link ChunkIntoOptions} for more info.
*
* @returns An Array of chunks.
*/
declare function chunkInto<T extends unknown[]>(array: T, options: ChunkIntoOptions): T[];
/**
* Shuffle the elements of an array in place using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
*
* @template T The type of elements in the array.
* @param array The array to shuffle.
*
* @returns The shuffled array.
*/
declare const shuffle: <T>(array: Array<T>) => T[];
/**
* Copy and shuffle the elements of an array in place using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle).
*
* @template T The type of elements in the array.
* @param array The array to shuffle.
*
* @returns The shuffled array.
*/
declare const shuffleCopy: <T>(array: Array<T>) => T[];
/**
* Normalize negative indexes to a positive value.
*
* @param index The index.
* @param length The array length.
*
* @returns The normalized index.
*/
declare const normalizeIndex: (index: number, length: number) => number;
/**
* Get the previous index.
*
* @param length The array length.
* @param index The index.
*
* @returns The previous index.
*/
declare const getPreviousIndex: (length: number, index?: number) => number;
/**
* Get the next index.
*
* @param length The array length.
* @param index The index.
*
* @returns The next index.
*/
declare const getNextIndex: (length: number, index?: number) => number;
/**
* Inserts one or more items into an array at the specified index position.
*
* @template T The type of elements in the array.
*
* @param array The original array to insert items into.
* @param item A single item or an array of items to insert.
* @param index The index after which to insert the item(s). Default: `-1`.
*
* @returns A new array with the item(s) inserted at the specified position.
*
* @example
* ```ts
* insertAfter( [ 1, 2, 4 ], 3, 1 ) // [ 1, 2, 3, 4 ]
* insertAfter( [ 1, 2 ], [ 3, 4 ], 1 ) // [ 1, 2, 3, 4 ]
* ```
*/
declare const insertAfter: <T>(array: T[], item: T | T[], index?: number) => T[];
/**
* Options for locating the index of the first object whose field matches a value.
*
* @template T The object type stored in the array.
* @template U The key of `T` used for the comparison.
*/
interface FindInxeByOptions<T extends object, U extends keyof T = keyof T> {
/**
* The collection to search.
*
*/
items: T[];
/**
* The object field to compare against `value`.
*
*/
field: U;
/**
* The value that must match the selected field.
*
*/
value: T[U];
}
/**
* Finds the index of the first object whose selected field strictly equals the provided value.
*
* @param options The search options.
* @returns The index of the matching item, or `-1` when no match is found.