type Vec3 = [number, number, number]; /** * Active colors for the gradient. */ interface MeshGradientToggleColorsConfig { 1?: boolean; 2?: boolean; 3?: boolean; 4?: boolean; } /** * Colors in hex format. * @example ['#ff0080', '#0080ff', '#80ff00', '#ff8000'] */ type MeshGradientColorsConfig = [string, string, string, string]; interface MeshGradientFrequencyConfig { x?: number; y?: number; /** Added to `y` in the vec2 `noiseFreq` uniform (second frequency component). Defaults to `0`. */ delta?: number; } type MeshGradientReducedMotion = 'auto' | 'ignore' | 'force-static'; /** Optional lifecycle hooks (do not store heavy closures if you destroy often). */ interface MeshGradientCallbacks { onReady?: () => void; onError?: (error: Error) => void; onResize?: (size: { cssWidth: number; cssHeight: number; }) => void; } interface MeshGradientUpdateOptions { /** * Enable fade transition when updating gradient. * @default true */ transition?: boolean; /** * Duration of fade transition in milliseconds. * @default 300 */ transitionDuration?: number; } interface MeshGradientInitOptions { /** * Appearance mode. `smooth` enables smooth appearance transition when gradient is initialized. * @default 'smooth' */ appearance?: 'smooth' | 'default'; /** * Duration of appearance transition in milliseconds. * @default 300 */ appearanceDuration?: number; } interface MeshGradientOptions { /** * If no canvas was resolved from `init(selector)`, fall back to `document.querySelector('canvas')`. * Off by default — enable only for legacy pages without a clear target element. */ allowDocumentCanvasFallback?: boolean; /** * Device pixel ratio for the backing store. Default: `min(window.devicePixelRatio, 2)` in browser. */ pixelRatio?: number; /** * Cap mesh segments per axis (after density math) to limit cost on huge layouts. */ maxSegments?: number; /** * Target render rate for time updates. Omit to match ~legacy ~30fps pacing (skip every other RAF when at 60Hz). */ targetFps?: number; /** * Respect `prefers-reduced-motion`: `auto` enables static output when the OS requests reduced motion. * @default 'auto' */ reducedMotion?: MeshGradientReducedMotion; /** Darken top gradient pass (prefer this over empty `data-js-darken-top` on canvas). */ darkenTop?: boolean; /** * Merged into `HTMLCanvasElement.getContext` for WebGL/webgl2. */ webglContextAttributes?: WebGLContextAttributes; /** * Scene mesh density `[xSegScale, ySegScale]` multiplied by CSS size during resize. */ density?: [number, number]; /** Wireframe (debug-style) drawing when supported by renderer. */ wireframe?: boolean; zoom?: number; rotation?: number; presetName?: string; callbacks?: MeshGradientCallbacks; /** * Legacy: add `isLoaded` to canvas and parent after init. Prefer `callbacks.onReady`. * @default true */ useLegacyLoadedClassBehavior?: boolean; /** * Seed for the gradient. It needs to generate the same gradient pattern on every page load. * @default random value */ seed?: number; /** * Animation speed multiplier. Higher values make animation faster, lower values make it slower. Performance remains constant regardless of speed value. * @default 1.0 */ animationSpeed?: number; /** * Frequency for the gradient: scalar (x = y), or an object with `delta` added to the `y` component in the `noiseFreq` uniform (defaults to 0 if omitted). * @default x/y match built-in constants; `delta` is not applied */ frequency?: number | MeshGradientFrequencyConfig; /** * Active colors for the gradient. * @default { 1: true, 2: true, 3: true, 4: true } */ activeColors?: MeshGradientToggleColorsConfig; /** * Static mode. If true, the gradient will not animate. Optimized for performance. * @default false */ isStatic?: boolean; /** * Auto pause when gradient goes out of viewport. Powered by `Intersection Observer` API. * @default true */ pauseOnOutsideViewport?: boolean; /** * Intersection observer options for pause on outside viewport option. * @default `{ root: null (viewport), rootMargin: '0px', threshold: 0.05 }` */ pauseObserverOptions?: IntersectionObserverInit; /** * Resize delay after canvas is resized. Helps to optimize performance. * @default 300 ms */ resizeDelay?: number; /** * Colors in hex format. Should be an array of 4 colors in hex format. * @example ['#ff0080', '#0080ff', '#80ff00', '#ff8000'] */ colors?: MeshGradientColorsConfig; /** * Fallback to CSS variables instead of random colors if colors are not provided. * @example * ```css * :root { * --mesh-gradient-color-1: #ff0080; * --mesh-gradient-color-2: #0080ff; * --mesh-gradient-color-3: #80ff00; * --mesh-gradient-color-4: #ff8000; * } * ``` * @default false */ cssVariablesFallback?: boolean; } /** * Converts HEX color to normalized RGB array (0-1) * @param hexCode - HEX color code * @returns RGB array [r, g, b] in range 0-1 */ declare function normalizeColor(hexCode: number): Vec3; /** * Generates four saturated colors in hex (HSL-based for more pleasing palettes). */ declare function genRandomColors(rand?: () => number): MeshGradientColorsConfig; type InitOptions = MeshGradientOptions & MeshGradientInitOptions; /** * Gradient class for creating animated mesh gradients * Manages WebGL rendering of animated gradient effects */ declare class MeshGradient { static isSupported(contextAttributes?: WebGLContextAttributes): boolean; /** * Whether the gradient is been initialized by calling `init` method. * @default false */ isInitialized: boolean; private destroyed; private instanceTimers; /** Serializes chained fade transitions from `update` */ private fadeGeneration; private pollCssVarsCanceled; private animationRafId; private resizeObserver?; /** Backing-store scale for `MiniGl#setSize(cssW, cssH, pr)`. */ private pixelRatioBacking; /** Optional FPS cap (`targetFps` option). */ private targetFpsCap?; private skipEveryOtherFrame; private lastFpsGateTime; /** Last successful `init` / merged options snapshot for context restore */ private lastInitOptions; /** Runtime hooks */ private callbacks?; private allowDocumentFallback; private darkenTopFromOptions?; /** @see MeshGradientOptions['webglContextAttributes'] — stored per init */ private webGlUserAttributes?; /** @see MeshGradientOptions['useLegacyLoadedClassBehavior'] */ private useLegacyLoadedClass; /** @see MeshGradientOptions['maxSegments'] */ private maxSegments?; private reducedMotion; private el?; private amp; private seed; private freqX; private freqY; /** Offset added to `freqY` in the `noiseFreq` uniform when `frequency` is an object with `delta` (0 by default). */ private freqDelta; private activeColors; private isStatic; private animationSpeed; private autoPauseOnInvisible; private minigl?; private angle; private isLoadedClass; private resizeTimeout?; private resizeDelay; private isIntersecting; private wasPlayingBeforeInvisible; private intersectionObserver?; private pauseObserverOptions; private width?; private height?; private shaderFiles?; private vertexShader?; private sectionColors?; private configColors?; private appearanceMode; private appearanceDuration; private computedCanvasStyle?; private conf?; private uniforms?; private mesh?; private material?; private geometry?; private t; private last; private frame; private xSegCount?; private ySegCount?; constructor(); init(selector: string | HTMLCanvasElement, options?: InitOptions): MeshGradient; /** * Completely destroys the gradient and cleans up all resources. * This method should be called when the gradient is no longer needed */ destroy(): void; /** * Updates the gradient with new configuration. Supports fade transition if enabled. * @param config - New configuration options */ update(config?: MeshGradientOptions & MeshGradientUpdateOptions): void; /** * Fast path — colors / booleans / animation seed without tearing down GL. * Returns false when shader rebuild or sizing changes are needed. */ private tryApplyHotPatch; setColors(colors: MeshGradientColorsConfig): void; setActiveColors(cfg: MeshGradientOptions['activeColors']): void; setFrequency(freq: MeshGradientOptions['frequency']): void; setSeed(value: number | undefined): void; private patchUniformColors; private patchGlobalNoiseFreq; private patchNoiseSeedUniforms; /** * Updates gradient with smooth fade transition * @param config - New configuration options */ private updateWithFadeTransition; /** * Manually start gradient animation */ play(): void; private scheduleAnimate; /** * Manually pause gradient animation */ pause(): void; /** * Set animation speed multiplier * @param speed - Speed multiplier (1.0 is normal speed, 0.5 is half speed, 2.0 is double speed) */ setAnimationSpeed(speed: number): void; /** * Get current animation speed multiplier * @returns Current animation speed */ getAnimationSpeed(): number; /** * Enable or disable auto-pause when gradient goes out of viewport * @param enabled - Whether to enable auto-pause functionality */ toggleAutoPause(enabled: boolean): void; /** * Stops animation and clears all active timers */ private stopAnimationAndTimers; /** * Removes CSS classes from canvas and its parent */ private removeCssClasses; /** * Cleans up all WebGL resources including shaders, buffers, and context */ private cleanupWebGLResources; /** * Cleans up all meshes from MiniGL */ private cleanupMiniGlMeshes; /** * Cleans up WebGL context, shaders and buffers */ private cleanupWebGLContext; /** * Deletes shaders and program from WebGL context */ private deleteShaders; /** * Deletes geometry buffers from WebGL context */ private deleteBuffers; /** * Clears canvas using 2D context as fallback */ private clearCanvasAsFallback; /** * Clears all object references to prevent memory leaks */ private clearObjectReferences; /** * Initialize all gradient properties with default values via `Object.assign`. */ private initializeProperties; private onResizeDebounced; private motionIsStaticEffective; private animateFrame; private addIsLoadedClass; private onVisibility; private handleContextLost; private handleContextRestored; private mountMiniGl; private attachLayoutListeners; private detachLayoutListeners; /** * Performs actual resize operations (used by debounced resize handler) */ private performResize; /** * Establishes WebGL connection and initializes shaders */ private connect; private disconnect; /** * Initialize intersection observer for auto-pause functionality */ private initIntersectionObserver; private initMaterial; /** * Creates basic uniforms (time, shadow, darken, active colors) */ private createBasicUniforms; /** * Creates global uniform with noise frequency and speed settings */ private createGlobalUniform; /** * Creates vertex deformation uniform for geometry animation */ private createVertexDeformUniform; /** * Creates color uniforms for base color and wave layers */ private createColorUniforms; /** * Creates wave layers uniforms for multi-color gradient effects */ private createWaveLayersUniforms; /** * Builds vertex shader by combining noise, blend, and vertex shader files */ private buildVertexShader; /** * Initialize mesh with material and geometry */ private initMesh; /** * Determines if current frame should be skipped for performance * @param e - Current time * @returns true if frame should be skipped */ private shouldSkipFrame; /** * Initialize gradient system - colors, mesh, and animation */ private initSystem; /** * Waits for CSS variables to be loaded before initializing * Uses Promise-based approach with timeout instead of recursive retries */ private waitForCssVars; /** * Checks if CSS variables are loaded and contain valid color values */ private areCssVarsLoaded; /** * Polls for CSS variables with exponential backoff and timeout */ private pollForCssVars; /** * Uses fallback colors when CSS variables are not available */ private useFallbackColors; /** * Initialize gradient colors with fallback priority: * 1. Colors from configuration (highest priority) * 2. Colors from CSS variables * 3. Random generated colors (fallback if neither above are available) */ private initGradientColors; } interface MiniGlInitOptions { debug?: boolean; contextAttributes?: WebGLContextAttributes; } export { MeshGradient, type MeshGradientCallbacks, type MeshGradientColorsConfig, type MeshGradientFrequencyConfig, type MeshGradientInitOptions, type MeshGradientOptions, type MeshGradientReducedMotion, type MeshGradientToggleColorsConfig, type MeshGradientUpdateOptions, type MiniGlInitOptions, genRandomColors, normalizeColor };