@unlazy/core
Version:
Universal lazy loading library for placeholder images leveraging native browser APIs
182 lines (177 loc) • 7.82 kB
text/typescript
//#region src/types.d.ts
interface UnLazyLoadOptions {
/**
* Whether to generate a blurry placeholder from a [BlurHash](https://blurha.sh)
* or [ThumbHash](https://github.com/evanw/thumbhash) string. The placeholder
* image will be inlined as a data URI in the `src` attribute.
*
* @remarks
* If this option is set to `true`, the `data-blurhash` or `data-thumbhash`
* attributes will be used for the hash string. If you pass a single element
* as the `selectorsOrElements` argument, you can also pass a string to this
* option to override the hash string.
*/
hash?: string | boolean;
/**
* Specify the hash type to use for generating the blurry placeholder.
*
* @remarks
* This option is ignored if the `hash` option is set to a boolean value.
* In these cases, the `data-blurhash` or `data-thumbhash` attributes will
* be used to determine the hash type.
*
* @default 'blurhash'
*/
hashType?: 'blurhash' | 'thumbhash';
/**
* The size of the longer edge (width or height) of the BlurHash image to be
* decoded, depending on the aspect ratio.
*
* @remarks
* This option is ignored if the `hashType` option is set to `thumbhash`.
*
* @default 32
*/
placeholderSize?: number;
/**
* Whether `data-sizes="auto"` should retrack the rendered image width on
* viewport resize. Applies to both `<img>` elements and their `<source>`
* siblings inside a `<picture>`. Internally delegates to `autoSizes`.
*
* @default false
*/
updateSizesOnResize?: boolean;
/**
* A callback function to run when an image is loaded.
*/
onImageLoad?: (image: HTMLImageElement) => void;
/**
* A callback function to run when an image fails to load.
*/
onImageError?: (image: HTMLImageElement, error: Event) => void;
}
interface TriggerLoadOptions {
/**
* A callback function to run when the image finishes loading.
*/
onImageLoad?: (image: HTMLImageElement) => void;
/**
* A callback function to run when the image fails to load. A synthetic
* `error` event is also dispatched on the visible `<img>` before this fires.
*/
onImageError?: (image: HTMLImageElement, error: Event) => void;
}
interface AutoSizesOptions {
/**
* Whether `data-sizes="auto"` should retrack the rendered width on viewport
* resize. Sets up a debounced `ResizeObserver` per call; the returned
* cleanup function disconnects it.
*
* @default false
*/
updateOnResize?: boolean;
}
interface UnLazySource {
/** Image source set for the `<source>` element. Will be applied lazily via `data-srcset`. */
srcSet: string;
/**
* Media query that selects this source, e.g. `(max-width: 600px)`. Use this for art
* direction across breakpoints.
*/
media?: string;
/** MIME type for format negotiation, e.g. `image/avif` or `image/webp`. */
type?: string;
/**
* Explicit `sizes` value. When unset and the parent has automatic sizing enabled, the
* source falls back to `sizes="auto"` (resolved to a numeric pixel width).
*/
sizes?: string;
/**
* Intrinsic width in pixels. When the matching `<source>` is selected, the browser uses
* this together with `height` to set the rendered `<img>`'s aspect ratio. Prevents
* layout shift when the breakpoint changes.
*/
width?: number;
/** Intrinsic height in pixels. Pairs with `width` to prevent layout shift across breakpoints. */
height?: number;
}
//#endregion
//#region src/lazyLoad.d.ts
declare function lazyLoad<T extends HTMLImageElement>(
/**
* A CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements to lazy-load.
*
* @default 'img[loading="lazy"], img[loading="eager"][data-src], img[loading="eager"][data-srcset]'
*/
selectorsOrElements?: string | T | NodeListOf<T> | T[], options?: UnLazyLoadOptions): () => void;
/**
* Resolves `data-sizes="auto"` to a numeric pixel width. Given an `<img>`
* inside a `<picture>`, walks to every `<source data-sizes="auto">` sibling and
* resolves them too. With `{ updateOnResize: true }`, a debounced
* `ResizeObserver` retracks the rendered width on viewport changes.
*
* @returns A cleanup function that disconnects every observer created by this call.
* Calling it on a one-shot invocation is a no-op.
*/
declare function autoSizes<T extends HTMLImageElement | HTMLSourceElement>(
/**
* A CSS selector, a DOM element, a list of DOM elements, or an array of DOM elements to calculate the `sizes` attribute for.
*
* @default 'img[data-sizes="auto"], source[data-sizes="auto"]'
*/
selectorsOrElements?: string | T | NodeListOf<T> | T[], options?: AutoSizesOptions): () => void;
/**
* Triggers the loading of a lazy image by swapping `data-src`/`data-srcset` to `src`/`srcset`.
*
* @returns A cleanup function that detaches listeners and, for standalone images, aborts any
* in-flight network fetch by clearing the temporary image's `src`. Calling it after the
* load completes is a no-op.
*
* @remarks
* For standalone `<img>` elements, the image is preloaded via a temporary `Image` before
* the swap; `onImageLoad` fires on success and `onImageError` on failure. On failure unlazy
* also dispatches a synthetic `error` event on the visible `<img>` so consumers using
* native `addEventListener('error', …)` or framework-native `onError` / `@error` get notified.
*
* For `<img>` elements inside `<picture>`, the browser handles source selection. Listeners
* are attached on the visible `<img>` before the swap so the queued `load` task is caught
* once the browser resolves a source. If `data-src` resolves to the URL already on the
* `<img>`, the browser fires no `load` event and the callback never runs.
*
* `triggerLoad` does not install a `ResizeObserver`. Pair it with
* `autoSizes(img, { updateOnResize: true })` for ongoing source-size tracking.
*/
declare function triggerLoad(image: HTMLImageElement, options?: TriggerLoadOptions): () => void;
declare function createPlaceholderFromHash(options?: {
/** If present, the hash will be extracted from the image's `data-blurhash` or `data-thumbhash` attribute and ratio will be calculated from the image's actual dimensions. */image?: HTMLImageElement;
hash?: string;
hashType?: 'blurhash' | 'thumbhash'; /** @default 32 */
size?: number; /** Will be calculated from the image's actual dimensions if image is provided and ratio is not. */
ratio?: number;
}): string | undefined;
//#endregion
//#region src/utils/png.d.ts
/**
* Encodes an RGBA image to a PNG data URI. RGB should not be premultiplied by A.
*
* @remarks
* This is optimized for speed and simplicity and does not optimize for size
* at all. This does not do any compression (all values are stored uncompressed).
*
* @see https://github.com/evanw/thumbhash
* @author Evan Wallace
* @license MIT
*/
declare function rgbaToDataUri(/** The width of the input image. Must be ≤100px. */
w: number, /** The height of the input image. Must be ≤100px. */
h: number, /** The pixels in the input image, row-by-row. Must have w*h*4 elements. */
rgba: ArrayLike<number>): string;
//#endregion
//#region src/utils/index.d.ts
declare const isSSR: boolean;
declare const isCrawler: boolean;
declare function toElementArray<T extends HTMLElement>(target: string | T | NodeListOf<T> | T[], parentElement?: Element | Document): T[];
declare function createIndexedImagePlaceholder(index: number): string;
declare function debounce<T extends (...args: any[]) => void>(fn: T, delay: number): (...args: Parameters<T>) => void;
//#endregion
export { AutoSizesOptions, TriggerLoadOptions, UnLazyLoadOptions, UnLazySource, autoSizes, createIndexedImagePlaceholder, createPlaceholderFromHash, debounce, isCrawler, isSSR, lazyLoad, rgbaToDataUri, toElementArray, triggerLoad };