UNPKG

tiny-essentials

Version:

Collection of small, essential scripts designed to be used across various projects. These simple utilities are crafted for speed, ease of use, and versatility.

241 lines 10.9 kB
/** * Reads the contents of a file using the specified FileReader method. * * @param {File} file - The file to be read. * @param {'readAsArrayBuffer'|'readAsDataURL'|'readAsText'|'readAsBinaryString'} method - * The FileReader method to use for reading the file. * @returns {Promise<any>} - A promise that resolves with the file content, according to the chosen method. * @throws {Error} - If an unexpected error occurs while handling the result. * @throws {DOMException} - If the FileReader encounters an error while reading the file. */ export function readFileBlob(file: File, method: "readAsArrayBuffer" | "readAsDataURL" | "readAsText" | "readAsBinaryString"): Promise<any>; /** * Reads a file as a Base64 string using FileReader, and optionally formats it as a full data URL. * * Performs strict validation to ensure the result is a valid Base64 string or a proper data URL. * * @param {File} file - The file to be read. * @param {boolean|string} [isDataUrl=false] - If true, returns a full data URL; if false, returns only the Base64 string; * if a string is passed, it is used as the MIME type in the data URL. * @returns {Promise<string>} - A promise that resolves with the Base64 string or data URL. * * @throws {TypeError} - If the result is not a string or if `isDataUrl` is not a valid type. * @throws {Error} - If the result does not match the expected data URL format or Base64 structure. * @throws {DOMException} - If the FileReader fails to read the file. */ export function readBase64Blob(file: File, isDataUrl?: boolean | string): Promise<string>; /** * Reads a file and strictly validates its content as proper JSON using FileReader. * * Performs several checks to ensure the file contains valid, parsable JSON data. * * @param {File} file - The file to be read. It must contain valid JSON as plain text. * @returns {Promise<Record<string|number|symbol, any>|any[]>} - A promise that resolves with the parsed JSON object. * * @throws {SyntaxError} - If the file content is not valid JSON syntax. * @throws {TypeError} - If the result is not a string or does not represent a JSON value. * @throws {Error} - If the result is empty or structurally invalid as JSON. * @throws {DOMException} - If the FileReader fails to read the file. */ export function readJsonBlob(file: File): Promise<Record<string | number | symbol, any> | any[]>; /** * Saves a JSON object as a downloadable file. * @param {string} filename * @param {any} data * @param {number} [spaces=2] */ export function saveJsonFile(filename: string, data: any, spaces?: number): void; /** * @typedef {Object} FetchTemplateOptions * @property {string} [method="GET"] - HTTP method to use (GET, POST, etc.). * @property {any} [body] - Request body (only for methods like POST, PUT). * @property {number} [timeout=0] - Timeout in milliseconds (ignored if signal is provided). * @property {number} [retries=0] - Number of retry attempts (ignored if signal is provided). * @property {Headers|Record<string, *>} [headers={}] - Additional headers. * @property {AbortSignal|null} [signal] - External AbortSignal; disables timeout and retries. * @property {FetchOnProgressResult} [onProgress] - Track the load progress. */ /** * Callback function used to report the progress of a data download. * * @callback FetchOnProgressResult * @param {number} loaded - The amount of bytes currently loaded. * @param {number} total - The total amount of bytes to be loaded (0 if unknown). * @returns {void} */ /** * Intercepts a standard Fetch API Response to track the download progress * of its body stream. * * This function returns a new Response object with a monitored ReadableStream, * allowing the provided callback to receive updates on the number of bytes loaded. * * @param {Response} response - The original response object to be tracked. * @param {FetchOnProgressResult} onProgress - The callback function to handle progress events. * @returns {Response} A new Response object with the tracked stream. */ export function trackFetchProgress(response: Response, onProgress: FetchOnProgressResult): Response; /** * Loads and parses a JSON from a remote URL using Fetch API. * * @param {string} url - The full URL to fetch JSON from. * @param {FetchTemplateOptions} [options] - Optional settings. * @returns {Promise<any[] | Record<string | number | symbol, unknown>>} Parsed JSON object. * @throws {Error} Throws if fetch fails, times out, or returns invalid JSON. */ export function fetchJson(url: string, options?: FetchTemplateOptions): Promise<any[] | Record<string | number | symbol, unknown>>; /** * Loads a remote file as a Blob using Fetch API. * * @param {string} url - The full URL to fetch the file from. * @param {FetchTemplateOptions} [options] - Optional fetch options. * @param {string[]} [allowedMimeTypes] - Optional list of accepted MIME types (e.g., ['image/jpeg']). * @returns {Promise<Blob>} - The fetched file as a Blob. * @throws {Error} Throws if fetch fails, response is not ok, or MIME type is not allowed. */ export function fetchBlob(url: string, allowedMimeTypes?: string[], options?: FetchTemplateOptions): Promise<Blob>; /** * Loads a remote file as a text using Fetch API. * * @param {string} url - The full URL to fetch the file from. * @param {FetchTemplateOptions} [options] - Optional fetch options. * @param {string[]} [allowedMimeTypes] - Optional list of accepted MIME types (e.g., ['image/jpeg']). * @returns {Promise<string>} - The fetched file as a text. * @throws {Error} Throws if fetch fails, response is not ok, or MIME type is not allowed. */ export function fetchText(url: string, allowedMimeTypes?: string[], options?: FetchTemplateOptions): Promise<string>; /** * Represents the final state and metadata of an attempted image load. * @typedef {Object} ImageLoadResult * @property {HTMLImageElement} element The image element instance used for loading. * @property {Event} event The browser event triggered by the final lifecycle state. * @property {ImageLoadStatus} status The specific outcome string of the loading process. * @property {boolean} isSuccess Indicates if the image was successfully loaded without errors. * @property {number} loadTimeMs The total duration in milliseconds from start to finish. * @property {Object} dimensions An object containing the rendered and intrinsic sizes of the image. * @property {number} dimensions.width The current layout width of the image element. * @property {number} dimensions.height The current layout height of the image element. * @property {number} dimensions.naturalWidth The intrinsic width of the image source in pixels. * @property {number} dimensions.naturalHeight The intrinsic height of the image source in pixels. */ /** * Describes the possible resolution states for the image loading attempt. * @typedef {'loaded'|'aborted'} ImageLoadStatus */ /** * Loads an image asynchronously, capturing critical lifecycle events. * It normalizes errors and success states into a consistent result structure. * * @param {Object} options * @param {string} options.url * @param {string} [options.crossOrigin="anonymous"] * @param {(event: Event, startTime: number) => void} [options.onLoading] * @returns {Promise<ImageLoadResult>} */ export function loadImage({ url, onLoading, crossOrigin }: { url: string; crossOrigin?: string | undefined; onLoading?: ((event: Event, startTime: number) => void) | undefined; }): Promise<ImageLoadResult>; /** * Installs a script that toggles CSS classes on a given element * based on the page's visibility or focus state, and optionally * triggers callbacks on visibility changes. * * @param {Object} [settings={}] * @param {Element} [settings.element=document.body] - The element to receive visibility classes. * @param {string} [settings.hiddenClass='windowHidden'] - CSS class applied when the page is hidden. * @param {string} [settings.visibleClass='windowVisible'] - CSS class applied when the page is visible. * @param {(data: { type: string; oldType: string; oldClass: string; }) => void} [settings.onVisible] - Callback called when page becomes visible. * @param {(data: { type: string; oldType: string; oldClass: string; }) => void} [settings.onHidden] - Callback called when page becomes hidden. * @returns {() => void} Function that removes all installed event listeners. * @throws {TypeError} If any provided setting is invalid. */ export function installWindowHiddenScript({ element, hiddenClass, visibleClass, onVisible, onHidden, }?: { element?: Element | undefined; hiddenClass?: string | undefined; visibleClass?: string | undefined; onVisible?: ((data: { type: string; oldType: string; oldClass: string; }) => void) | undefined; onHidden?: ((data: { type: string; oldType: string; oldClass: string; }) => void) | undefined; }): () => void; export type FetchTemplateOptions = { /** * - HTTP method to use (GET, POST, etc.). */ method?: string | undefined; /** * - Request body (only for methods like POST, PUT). */ body?: any; /** * - Timeout in milliseconds (ignored if signal is provided). */ timeout?: number | undefined; /** * - Number of retry attempts (ignored if signal is provided). */ retries?: number | undefined; /** * - Additional headers. */ headers?: Headers | Record<string, any> | undefined; /** * - External AbortSignal; disables timeout and retries. */ signal?: AbortSignal | null | undefined; /** * - Track the load progress. */ onProgress?: FetchOnProgressResult | undefined; }; /** * Callback function used to report the progress of a data download. */ export type FetchOnProgressResult = (loaded: number, total: number) => void; /** * Represents the final state and metadata of an attempted image load. */ export type ImageLoadResult = { /** * The image element instance used for loading. */ element: HTMLImageElement; /** * The browser event triggered by the final lifecycle state. */ event: Event; /** * The specific outcome string of the loading process. */ status: ImageLoadStatus; /** * Indicates if the image was successfully loaded without errors. */ isSuccess: boolean; /** * The total duration in milliseconds from start to finish. */ loadTimeMs: number; /** * An object containing the rendered and intrinsic sizes of the image. */ dimensions: { width: number; height: number; naturalWidth: number; naturalHeight: number; }; }; /** * Describes the possible resolution states for the image loading attempt. */ export type ImageLoadStatus = "loaded" | "aborted"; //# sourceMappingURL=html.d.mts.map