UNPKG

@remotion/gif

Version:

Embed GIFs in a Remotion video

80 lines (79 loc) 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.GifForDevelopment = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); /* eslint-disable no-console */ const react_1 = require("react"); const canvas_1 = require("./canvas"); const gif_cache_1 = require("./gif-cache"); const is_cors_error_1 = require("./is-cors-error"); const react_tools_1 = require("./react-tools"); const resolve_gif_source_1 = require("./resolve-gif-source"); const useCurrentGifIndex_1 = require("./useCurrentGifIndex"); exports.GifForDevelopment = (0, react_1.forwardRef)(({ src, width, height, onError, loopBehavior = 'loop', playbackRate = 1, onLoad, fit = 'fill', ...props }, ref) => { const resolvedSrc = (0, resolve_gif_source_1.resolveGifSource)(src); const [state, update] = (0, react_1.useState)(() => { var _a; const parsedGif = (_a = gif_cache_1.volatileGifCache.get(resolvedSrc)) !== null && _a !== void 0 ? _a : gif_cache_1.manuallyManagedGifCache.get(resolvedSrc); if (parsedGif === undefined) { return { delays: [], frames: [], width: 0, height: 0, }; } return parsedGif; }); const [error, setError] = (0, react_1.useState)(null); const currentOnLoad = (0, react_1.useRef)(onLoad); const currentOnError = (0, react_1.useRef)(onError); currentOnLoad.current = onLoad; currentOnError.current = onError; (0, react_1.useEffect)(() => { let done = false; let aborted = false; const { prom, cancel } = (0, react_tools_1.parseWithWorker)(resolvedSrc); prom .then((parsed) => { var _a; (_a = currentOnLoad.current) === null || _a === void 0 ? void 0 : _a.call(currentOnLoad, parsed); update(parsed); gif_cache_1.volatileGifCache.set(resolvedSrc, parsed); done = true; }) .catch((err) => { if (aborted) { return; } if (currentOnError.current) { currentOnError.current(err); } else { setError(err); } }); return () => { if (!done) { aborted = true; cancel(); } }; }, [resolvedSrc]); if (error) { console.error(error.stack); if ((0, is_cors_error_1.isCorsError)(error)) { throw new Error(`Failed to render GIF with source ${src}: "${error.message}". You must enable CORS for this URL. Open the Developer Tools to see exactly why this fetch failed.`); } throw new Error(`Failed to render GIF with source ${src}: "${error.message}".`); } const index = (0, useCurrentGifIndex_1.useCurrentGifIndex)({ delays: state.delays, loopBehavior, playbackRate, }); if (index === -1) { return null; } return (jsx_runtime_1.jsx(canvas_1.Canvas, { fit: fit, index: index, frames: state.frames, width: width, height: height, ...props, ref: ref })); });