@pivanov/utils
Version:
A focused collection of TypeScript utilities for modern web development
83 lines (82 loc) • 2.91 kB
TypeScript
/**
* Returns true when running in a browser-like environment.
*
* Checks for both `window` and `document` so service-worker and
* partially-mocked contexts are correctly reported as non-browser.
*
* @example
* ```ts
* if (isBrowser()) window.addEventListener('resize', onResize);
* ```
*/
export declare const isBrowser: () => boolean;
/**
* Sets CSS custom properties on an element. Safely no-ops when element is null.
*
* @example
* ```ts
* setStyleProperties(el, { '--primary': '#3b82f6', '--gap': '1rem' });
* ```
*/
export declare const setStyleProperties: (el: HTMLElement | null, cssVars: Record<string, string>) => void;
interface CheckVisibilityOptions {
/** Require the element to intersect the viewport. Default: true. */
checkViewport?: boolean;
/** Require computed `display` to be non-"none". Default: true. */
checkDisplay?: boolean;
/** Require computed `visibility` to be "visible". Default: true. */
checkVisibility?: boolean;
/** Require computed `opacity` to be > 0. Default: true. */
checkOpacity?: boolean;
}
/**
* Checks whether an element is visible to the user.
*
* By default verifies: attached to DOM, `display` not `none`,
* `visibility` is `visible`, `opacity > 0`, and intersects the viewport
* on both axes. Each check can be toggled via options.
*
* @example
* ```ts
* if (checkVisibility(el)) el.classList.add('seen');
* checkVisibility(el, { checkViewport: false }); // visible per CSS only
* ```
*/
export declare const checkVisibility: (element: HTMLElement, options?: CheckVisibilityOptions) => boolean;
/**
* @internal Resets the cached canvas - for tests only.
*/
export declare const __resetTextMeasurementCache: () => void;
interface IViewportOptions {
/** Require vertical intersection. Default: true. */
vertical?: boolean;
/** Require horizontal intersection. Default: true. */
horizontal?: boolean;
}
/**
* Returns true when the element's bounding rect intersects the viewport.
* Pure geometry - ignores CSS visibility. Use `checkVisibility` for a full
* visibility check.
*
* Zero-sized rects (no layout yet) return true - we can't clip against
* nothing, and failing them would produce false negatives in test environments.
*
* @example
* ```ts
* if (isInViewport(el)) track();
* isInViewport(el, { horizontal: false }); // vertical only
* ```
*/
export declare const isInViewport: (element: HTMLElement, options?: IViewportOptions) => boolean;
/**
* Measures the rendered width of text in pixels using a cached off-screen
* canvas. Returns `0` when 2D context is unavailable.
*
* @example
* ```ts
* calculateRenderedTextWidth('Hello World', 16);
* calculateRenderedTextWidth('Hi', 14, true, 'Arial');
* ```
*/
export declare const calculateRenderedTextWidth: (text: string, fontSize: number, isUppercase?: boolean, fontFamily?: string) => number;
export {};