modella Volver a la guía de desarrolloReferencia del código

Source: lottie/components/usePreviewPlayer.js

/**
 * Crea y destruye el reproductor WASM; cambia de WebGL a Canvas cuando falla la inicialización o se pierde el contexto.
 * @module lottie/components/usePreviewPlayer
 */
import { useEffect, useRef, useState } from 'react';
import { DotLottie as CanvasPlayer } from '@lottiefiles/dotlottie-web';
import { DotLottie as WebGLPlayer } from '@lottiefiles/dotlottie-web/webgl';
import canvasWasmUrl from '@lottiefiles/dotlottie-web/dotlottie-player.wasm?url';
import webglWasmUrl from '@lottiefiles/dotlottie-web/webgl/dotlottie-player.wasm?url';

CanvasPlayer.setWasmUrl(canvasWasmUrl);
WebGLPlayer.setWasmUrl(webglWasmUrl);

const compatibilityMessage = 'Modo de compatibilidad: algunas imágenes pueden mostrar un pequeño salto al iniciar el giro.';

// Consumers must key their canvas by backend. A WebGL canvas cannot be reused
// as a 2D canvas, including when WASM initialization fails after context creation.
/**
 * Crea y destruye el reproductor WASM; cambia de WebGL a Canvas cuando falla la inicialización o se pierde el contexto.
 *
 * El consumidor debe remontar el canvas con una key basada en backend: un canvas WebGL no puede reutilizarse como Canvas 2D. Destruye la instancia y retira listeners al desmontar. Publica onRender en una microtarea después del dibujo síncrono y limita la densidad de píxeles a 2 por defecto.
 * @param {object} canvas Referencia React al canvas del reproductor.
 * @param {object} callbacks Observadores onReady, onLoad, onRender y onError.
 * @param {object} [options] Opciones específicas de la operación o del reproductor.
 * @returns {object} Referencia player, backend elegido y aviso warning de compatibilidad.
 * @throws {Error} Si los datos o la operación incumplen las validaciones descritas.
 */
export default function usePreviewPlayer(canvas, callbacks, options = {}) {
    const player = useRef(null), latest = useRef(null);
    const [backend, setBackend] = useState('webgl');
    const [warning, setWarning] = useState('');
    latest.current = { callbacks, options };

    useEffect(() => {
        const target = canvas.current;
        let active = true, instance, readyTimer, publicationPending = false, readyDelivered = false;
        const fallback = () => {
            if (!active || backend !== 'webgl') return;
            setWarning(compatibilityMessage);
            setBackend('canvas');
        };
        const failed = (event) => {
            if (!active) return;
            if (backend === 'webgl') fallback();
            else latest.current.callbacks.onError?.(event);
        };
        const ready = () => {
            if (!active || readyDelivered) return;
            readyDelivered = true;
            clearTimeout(readyTimer);
            latest.current.callbacks.onReady?.();
        };
        const loaded = () => {
            if (active) latest.current.callbacks.onLoad?.();
        };
        const rendered = () => {
            if (!active || publicationPending) return;
            publicationPending = true;
            // render precedes the synchronous draw. Keep the WebGL buffer until
            // the microtask copies a completed frame to the visible 2D canvas.
            queueMicrotask(() => {
                publicationPending = false;
                if (active) latest.current.callbacks.onRender?.();
            });
        };
        const lost = (event) => {
            event.preventDefault();
            fallback();
        };
        try {
            if (backend === 'webgl') {
                const gl = target.getContext('webgl2', { preserveDrawingBuffer: true });
                if (!gl || gl.isContextLost()) throw new Error('WebGL2 no disponible.');
                target.addEventListener('webglcontextlost', lost);
            }
            const Player = backend === 'webgl' ? WebGLPlayer : CanvasPlayer;
            instance = new Player({
                canvas: target,
                autoplay: false,
                loop: false,
                ...latest.current.options,
                renderConfig: {
                    autoResize: true,
                    devicePixelRatio: Math.min(window.devicePixelRatio || 1, 2),
                    freezeOnOffscreen: false,
                    ...latest.current.options.renderConfig,
                },
            });
            player.current = instance;
            instance.addEventListener('ready', ready);
            instance.addEventListener('load', loaded);
            instance.addEventListener('render', rendered);
            instance.addEventListener('loadError', failed);
            instance.addEventListener('renderError', failed);
            if (backend === 'webgl') readyTimer = setTimeout(() => {
                if (!instance.isReady) fallback();
            }, 10000);
            if (instance.isReady) ready();
        } catch (error) {
            failed({ error });
        }
        return () => {
            active = false;
            clearTimeout(readyTimer);
            target.removeEventListener('webglcontextlost', lost);
            instance?.destroy();
            if (player.current === instance) player.current = null;
        };
    }, [backend]);

    return { player, backend, warning };
}