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

Source: lottie/Editor.jsx

/**
 * Editor conservado: modifica documento e historial local; persiste mediante la API REST.
 * @module lottie/Editor
 */
import { Head } from '@/platform/ui';
import { Link } from '@/platform/router';
import { paths } from '@/platform/paths';
import {
    useCallback,
    useEffect,
    useMemo,
    useReducer,
    useRef,
    useState,
} from 'react';
import axios from '@/platform/api';
import {
    ArrowLeft,
    ArrowDown,
    ArrowUp,
    Check,
    CircleAlert,
    ChevronRight,
    Copy,
    Download,
    Eye,
    EyeOff,
    Film,
    FolderOpen,
    Group,
    Ungroup,
    HelpCircle,
    Image,
    Layers,
    LockKeyhole,
    LoaderCircle,
    Redo2,
    Save,
    Sparkles,
    Settings2,
    Trash2,
    Undo2,
    UnlockKeyhole,
    Upload,
    Type,
    X,
} from '@/platform/icons';
import Stage from './components/Stage';
import Timeline from './components/Timeline';
import TimelineSettings from './components/TimelineSettings';
import CompositionSettings from './components/CompositionSettings';
import ResourceLibrary from './components/ResourceLibrary';
import { resizeTimeline, editLayerTiming } from './core/timing.mjs';
import {
    ungroupLayers,
    ungroupTargets,
    addToGroup,
    removeFromGroup,
    availableGroups,
    removableGroupMembers,
} from './core/ungroup.mjs';
import {
    setPositionKeyType,
    applyPositionCurvePreset,
} from './core/motionPath.mjs';
import { layerTreeRows } from './core/layerTree.mjs';
import { centerLayerAnchor } from './core/anchor.mjs';
import { buildText, loadTextFont, DEFAULT_TEXT } from './core/text.mjs';
import Inspector from './components/Inspector';
import { changeVectorColor } from './core/vectorColors.mjs';
import Dialog from './components/Dialog';
import AnimationPresets from './components/AnimationPresets';
import usePersistence from './components/usePersistence';
import {
    clone,
    layersIn,
    updateLayers,
    setKey,
    normalizeDocument,
    setExpression,
    resizeComposition,
    selectionRoots,
    selectionBounds,
    setValue,
    valueAt,
    groupLayers,
    duplicateLayers,
    deleteLayers,
    historyReducer,
    uid,
    newLayer,
    worldMatrix,
    inverse,
    point,
    multiply,
} from './core/document.mjs';
import { compile, importLottie } from './core/compiler.mjs';
import { transformKeyframes } from './core/keyframes.mjs';
import { prepareJsonImages } from './core/exportImages.mjs';
import { importSvg, maskPaths } from './core/svg.mjs';
import { readPackage, writePackage } from './core/package.mjs';
import './editor.css';
const dataUrl = (blob) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject(reader.error);
        reader.readAsDataURL(blob);
    });
const download = (data, name, mime = 'application/json') => {
    const url = URL.createObjectURL(new Blob([data], { type: mime })),
        a = window.document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 10000);
};
const isInput = (el) =>
    el.isContentEditable ||
    ['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName);
/**
 * Editor conservado: modifica documento e historial local; persiste mediante la API REST.
 * @param {object} props Propiedades y acciones del componente o hook.
 * @param {object} props.auth Identidad autenticada del editor.
 * @param {object} props.project Proyecto persistido con identificador, documento, nombre y revisión.
 * @param {Array<object>} props.resources Metadatos de recursos disponibles en el proyecto.
 * @param {string} props.installationId Identificador de instalación para aislar los borradores locales.
 * @param {Array<object>} [props.fonts] Catálogo de fuentes locales autorizadas.
 * @returns {React.ReactElement|null} Contenido del componente; null cuando no corresponde mostrarlo.
 * @throws {Error} Si los datos o la operación incumplen las validaciones descritas.
 */
export default function Editor({
    auth,
    project,
    resources: initialResources,
    installationId,
    fonts = [],
}) {
    const [history, dispatch] = useReducer(historyReducer, {
            present: normalizeDocument(project.document),
            past: [],
            future: [],
        }),
        doc = history.present;
    const [name, setName] = useState(project.name),
        [selected, setSelected] = useState([]),
        [keySelection, setKeySelection] = useState([]),
        [keyClipboard, setKeyClipboard] = useState(null),
        [frame, setFrame] = useState(0),
        [playing, setPlaying] = useState(false),
        [loop, setLoop] = useState(true),
        [speed, setSpeed] = useState(1),
        [zoom, setZoom] = useState(1),
        [autoKey, setAutoKey] = useState(false),
        [compositionId, setCompositionId] = useState(null),
        [collapsedGroups, setCollapsedGroups] = useState(() => new Set()),
        [gestureDoc, setGestureDoc] = useState(null),
        [resources, setResources] = useState(initialResources),
        [assetData, setAssetData] = useState({}),
        [thumbnails, setThumbnails] = useState({}),
        [busy, setBusy] = useState(false),
        [error, setError] = useState(''),
        [pending, setPending] = useState(null),
        [dialog, setDialog] = useState(null),
        [imageExportMode, setImageExportMode] = useState('embedded'),
        [imageExportUrls, setImageExportUrls] = useState({}),
        [exportError, setExportError] = useState(''),
        [panel, setPanel] = useState('layers'),
        [inspectorOpen, setInspectorOpen] = useState(false),
        [curvesOpen, setCurvesVisible] = useState(false),
        [curvesDock, setCurvesDock] = useState('timeline'),
        [rightTab, setRightTab] = useState('curves'),
        [curvesHost, setCurvesHost] = useState(null),
        [transportHost, setTransportHost] = useState(null),
        [timelineSettings, setTimelineSettings] = useState(false),
        [compositionSettings, setCompositionSettings] = useState(false),
        [leftWidth, setLeftWidth] = useState(240),
        [rightWidth, setRightWidth] = useState(320);
    const fileInput = useRef(null),
        replaceRef = useRef(null),
        clipboard = useRef(null),
        current = useRef(null),
        resourceCache = useRef(new Map());
    const report = useCallback((message) => setError(String(message)), []);
    const setCurvesOpen = (value) => {
        const open = typeof value === 'function' ? value(curvesOpen) : value;
        setCurvesVisible(open);
        if (open) setRightTab('curves');
    };
    const layers = layersIn(doc, compositionId),
        activeComposition = compositionId
            ? {
                  ...doc.composition,
                  ...doc.compositions.find((c) => c.id === compositionId),
              }
            : doc.composition,
        effective = gestureDoc || doc,
        layer = layers.find((l) => l.id === selected[0]);
    const layerRows = useMemo(
        () => layerTreeRows(layers, collapsedGroups),
        [layers, collapsedGroups],
    );
    const toggleGroup = (id) =>
        setCollapsedGroups((current) => {
            const next = new Set(current);
            if (next.has(id)) next.delete(id);
            else next.add(id);
            return next;
        });
    useEffect(() => {
        setSelected((ids) => {
            const valid = ids.filter((id) => layers.some((l) => l.id === id));
            return valid.length === ids.length ? ids : valid;
        });
        setKeySelection((keys) => {
            const valid = keys.filter((k) =>
                layers
                    .find((l) => l.id === k.layerId)
                    ?.tracks[k.key]?.keys.some((key) => key.t === k.t),
            );
            return valid.length === keys.length ? keys : valid;
        });
    }, [doc, compositionId]);
    const commit = useCallback((document) => {
        dispatch({ type: 'commit', document: normalizeDocument(document) });
        setPlaying(false);
        setError('');
    }, []);
    const restore = useCallback((draft) => {
        dispatch({
            type: 'reset',
            document: normalizeDocument(draft.document),
        });
        setName(draft.name);
        setCompositionId(null);
        setSelected([]);
        setKeySelection([]);
    }, []);
    const persistence = usePersistence({
        project,
        document: doc,
        name,
        installationId,
        userId: auth.user.id,
        report,
        restore,
    });
    const select = (ids) => {
        setSelected([...new Set(ids)]);
        setKeySelection([]);
    };
    // Timeline selects keys and layers together; do not clear key selection on this path.
    const selectTimeline = (ids) => setSelected([...new Set(ids)]);
    const apply = (callback) => {
        try {
            commit(callback(clone(doc)));
        } catch (e) {
            report(e.message);
        }
    };
    const structure = () => {
        if (doc.structureLocked)
            throw new Error(
                'Esta animación usa mattes dependientes del orden. La estructura de capas se conserva para evitar pérdidas.',
            );
    };
    const changeLayer = (id, changes) =>
        apply((d) => {
            const ls = layersIn(d, compositionId),
                l = ls.find((l) => l.id === id);
            if (l.locked && !Object.hasOwn(changes, 'locked'))
                throw new Error('La capa está bloqueada.');
            if (Object.hasOwn(changes, 'name')) structure();
            Object.assign(l, changes);
            return d;
        });
    const changeText = (id, geometry) =>
        apply((d) => {
            const layer = layersIn(d, compositionId).find(
                (item) => item.id === id,
            );
            if (!layer?.text || layer.locked)
                throw new Error('El texto no está disponible para edición.');
            Object.assign(layer, geometry);
            return d;
        });
    const changeColor = (id, colorId, color) =>
        apply((d) => changeVectorColor(d, id, colorId, color, compositionId));
    const addText = async () => {
        setBusy(true);
        try {
            const font = await loadTextFont(DEFAULT_TEXT.fontFile, fonts);
            const next = clone(current.current.history.present);
            if (next.structureLocked)
                throw new Error('Esta animación no permite añadir capas.');
            if (current.current.compositionId !== compositionId)
                throw new Error(
                    'La composición cambió. Vuelve a añadir el texto.',
                );
            const geometry = buildText(DEFAULT_TEXT, font);
            const layer = newLayer('Texto', 'shape', {
                ...geometry,
                end: next.composition.frames,
            });
            layer.tracks.a.value = [
                geometry.bounds.x + geometry.bounds.width / 2,
                geometry.bounds.y + geometry.bounds.height / 2,
            ];
            const target = compositionId
                ? next.compositions.find((c) => c.id === compositionId)
                : next.composition;
            layer.tracks.p.value = [target.width / 2, target.height / 2];
            layersIn(next, compositionId).unshift(layer);
            commit(next);
            setSelected([layer.id]);
            setKeySelection([]);
            setRightTab('properties');
            setInspectorOpen(true);
        } catch (error) {
            report(error.message);
        } finally {
            setBusy(false);
        }
    };
    const changeTrack = (id, key, value) =>
        apply((d) => {
            const l = layersIn(d, compositionId).find((l) => l.id === id);
            if (l.locked) throw new Error('La capa está bloqueada.');
            l.tracks[key] = setValue(l.tracks[key], frame, value, autoKey);
            return d;
        });
    const changeExpression = (id, key, source) => {
        // Errors stay beside the expression and preserve the draft.
        const next = clone(doc);
        const layer = layersIn(next, compositionId).find((l) => l.id === id);
        if (!layer || layer.locked) throw new Error('La capa está bloqueada.');
        layer.tracks[key] = setExpression(
            layer.tracks[key],
            source,
            doc.composition.fps,
            doc.composition.frames,
        );
        commit(next);
    };
    const addKey = (id, key, t) =>
        apply((d) => {
            const l = layersIn(d, compositionId).find((l) => l.id === id);
            if (l.locked || l.tracks[key].readonly)
                throw new Error('La propiedad está bloqueada.');
            l.tracks[key] = setKey(l.tracks[key], t);
            setFrame(t);
            setSelected([id]);
            setKeySelection([{ layerId: id, key, t }]);
            return d;
        });
    const centerAnchor = (id) =>
        apply((d) => centerLayerAnchor(d, id, compositionId, frame, autoKey));
    const changePositionCurvePreset = (preset) =>
        apply((d) =>
            applyPositionCurvePreset(d, keySelection, preset, compositionId),
        );
    const changePositionKeyType = (mode) =>
        apply((d) => setPositionKeyType(d, keySelection, mode, compositionId));
    const changeKeys = (changes) =>
        apply((d) => {
            const ls = layersIn(d, compositionId);
            for (const picked of keySelection) {
                const l = ls.find((l) => l.id === picked.layerId),
                    track = l?.tracks[picked.key];
                if (!track || l.locked || track.readonly) continue;
                const key = track.keys.find((k) => k.t === picked.t);
                if (key) {
                    Object.assign(key, clone(changes));
                    track.edited = true;
                }
            }
            return d;
        });
    const operateKeyframes = (
        action,
        options = {},
        selection = keySelection,
    ) => {
        try {
            if (action === 'copy' || action === 'cut') {
                copy();
                if (action === 'copy') return { ok: true };
                action = 'delete';
            }
            if (action === 'paste') {
                if (clipboard.current?.type !== 'keys')
                    throw new Error(
                        'Copia primero los keyframes que quieras pegar.',
                    );
                options = { ...options, keys: clipboard.current.keys };
            }
            const result = transformKeyframes(
                doc,
                compositionId,
                selection,
                action,
                { time: frame, ...options },
            );
            if (!result.changed) {
                setKeySelection(result.selection);
                return { ok: true };
            }
            const notices = [];
            if (result.conflicts)
                notices.push(
                    `Esta operación reemplazará ${result.conflicts} keyframe(s) existentes en las pistas afectadas.`,
                );
            if (result.requiredFrames > doc.composition.frames)
                notices.push(
                    `La composición debe ampliarse de ${doc.composition.frames} a ${result.requiredFrames} fotogramas.`,
                );
            if (
                notices.length &&
                !confirm(notices.join('\n') + '\n¿Aplicar la operación?')
            )
                return { ok: false };
            if (result.requiredFrames > doc.composition.frames) {
                result.document.composition.frames = result.requiredFrames;
                if (doc.composition.workEnd === doc.composition.frames - 1)
                    result.document.composition.workEnd =
                        result.requiredFrames - 1;
            }
            commit(result.document);
            setKeySelection(result.selection);
            return { ok: true };
        } catch (error) {
            report(error.message);
            return { ok: false, error: error.message };
        }
    };
    const moveSelectedKeys = (selection, delta) =>
        operateKeyframes('move', { delta }, selection);
    const remove = () => {
        if (keySelection.length) {
            apply((d) => {
                for (const picked of keySelection) {
                    const l = layersIn(d, compositionId).find(
                        (l) => l.id === picked.layerId,
                    );
                    if (l && !l.locked && !l.tracks[picked.key].readonly) {
                        const t = l.tracks[picked.key];
                        if (t.keys.length === 1)
                            t.value = clone(t.keys[0].value);
                        t.keys = t.keys.filter((k) => k.t !== picked.t);
                        t.edited = true;
                    }
                }
                return d;
            });
            setKeySelection([]);
        } else if (selected.length) {
            apply((d) => {
                structure();
                return updateLayers(d, compositionId, (ls) =>
                    deleteLayers(ls, selected),
                );
            });
            setSelected([]);
        }
    };
    const duplicate = () =>
        apply((d) => {
            structure();
            const result = duplicateLayers(
                layersIn(d, compositionId),
                selected,
            );
            setSelected(result.ids);
            return updateLayers(d, compositionId, () => result.layers);
        });
    const group = (precomp) =>
        apply((d) => {
            structure();
            const result = groupLayers(d, selected, compositionId, precomp);
            setSelected([result.id]);
            setKeySelection([]);
            return result.document;
        });
    const ungroup = () =>
        apply((d) => {
            structure();
            const result = ungroupLayers(d, selected, compositionId);
            setSelected(result.ids);
            setKeySelection([]);
            return result.document;
        });
    const changeGroup = (groupId) =>
        apply((d) => {
            structure();
            const result = groupId
                ? addToGroup(d, [layer.id], groupId, frame, compositionId)
                : removeFromGroup(d, [layer.id], compositionId);
            setSelected(result.ids);
            setKeySelection([]);
            if (groupId)
                setCollapsedGroups((current) => {
                    const expanded = new Set(current);
                    let parent = layersIn(result.document, compositionId).find(
                        (l) => l.id === groupId,
                    );
                    while (parent) {
                        expanded.delete(parent.id);
                        parent = layersIn(result.document, compositionId).find(
                            (l) => l.id === parent.parentId,
                        );
                    }
                    return expanded;
                });
            return result.document;
        });
    const reorder = (id, direction) =>
        apply((d) => {
            structure();
            const ls = layersIn(d, compositionId),
                i = ls.findIndex((l) => l.id === id),
                j = i + direction;
            if (j >= 0 && j < ls.length) [ls[i], ls[j]] = [ls[j], ls[i]];
            return d;
        });
    const align = (mode) =>
        apply((d) => {
            const ls = layersIn(d, compositionId),
                roots = new Set(selectionRoots(ls, selected)),
                chosen = ls.filter((l) => roots.has(l.id) && !l.locked);
            if (!chosen.length) return d;
            const boxes = chosen.map((l) => {
                const b = selectionBounds(l, ls, frame),
                    m = worldMatrix(l, ls, frame),
                    corners = [
                        [b.x, b.y],
                        [b.x + b.width, b.y],
                        [b.x + b.width, b.y + b.height],
                        [b.x, b.y + b.height],
                    ].map((p) => point(m, p));
                return {
                    l,
                    x: Math.min(...corners.map((p) => p[0])),
                    y: Math.min(...corners.map((p) => p[1])),
                    right: Math.max(...corners.map((p) => p[0])),
                    bottom: Math.max(...corners.map((p) => p[1])),
                };
            });
            const groupBox =
                boxes.length > 1
                    ? {
                          x: Math.min(...boxes.map((b) => b.x)),
                          y: Math.min(...boxes.map((b) => b.y)),
                          right: Math.max(...boxes.map((b) => b.right)),
                          bottom: Math.max(...boxes.map((b) => b.bottom)),
                      }
                    : {
                          x: 0,
                          y: 0,
                          right: d.composition.width,
                          bottom: d.composition.height,
                      };
            const distribution = mode === 'horizontal' || mode === 'vertical';
            if (distribution && boxes.length < 3)
                throw new Error(
                    'Selecciona al menos tres capas para distribuir.',
                );
            if (distribution)
                boxes.sort((a, b) =>
                    mode === 'horizontal' ? a.x - b.x : a.y - b.y,
                );
            for (const [index, b] of boxes.entries()) {
                let dx = 0,
                    dy = 0;
                if (mode === 'left') dx = groupBox.x - b.x;
                if (mode === 'right') dx = groupBox.right - b.right;
                if (mode === 'center')
                    dx = (groupBox.x + groupBox.right - b.x - b.right) / 2;
                if (mode === 'top') dy = groupBox.y - b.y;
                if (mode === 'bottom') dy = groupBox.bottom - b.bottom;
                if (mode === 'middle')
                    dy = (groupBox.y + groupBox.bottom - b.y - b.bottom) / 2;
                if (distribution) {
                    const axis = mode === 'horizontal' ? 'x' : 'y',
                        end = mode === 'horizontal' ? 'right' : 'bottom',
                        total = boxes.reduce(
                            (sum, b) => sum + b[end] - b[axis],
                            0,
                        ),
                        gap =
                            (groupBox[end] - groupBox[axis] - total) /
                            (boxes.length - 1),
                        target =
                            groupBox[axis] +
                            boxes
                                .slice(0, index)
                                .reduce(
                                    (sum, b) => sum + b[end] - b[axis] + gap,
                                    0,
                                );
                    if (axis === 'x') dx = target - b.x;
                    else dy = target - b.y;
                }
                const parent = ls.find((l) => l.id === b.l.parentId),
                    inv = parent
                        ? inverse(worldMatrix(parent, ls, frame))
                        : [1, 0, 0, 1, 0, 0];
                if (!inv)
                    throw new Error('No se puede alinear con escala cero.');
                const local = point(inv, [dx, dy]),
                    origin = point(inv, [0, 0]),
                    p = valueAt(b.l.tracks.p, frame);
                b.l.tracks.p = setValue(
                    b.l.tracks.p,
                    frame,
                    p.map((v, i) => v + local[i] - origin[i]),
                    autoKey,
                );
            }
            return d;
        });
    const addMask = (targetId, sourceId) =>
        apply((d) => {
            const ls = layersIn(d, compositionId),
                target = ls.find((l) => l.id === targetId),
                source = ls.find((l) => l.id === sourceId);
            const paths = maskPaths(source);
            if (!paths.length)
                throw new Error('La capa no contiene trazados estáticos.');
            const inv = inverse(worldMatrix(target, ls, frame));
            if (!inv) throw new Error('La capa destino tiene escala cero.');
            const matrix = multiply(inv, worldMatrix(source, ls, frame));
            const convert = (path) => ({
                ...path,
                v: path.v.map((p) => point(matrix, p)),
                i: path.i.map((p) => [
                    matrix[0] * p[0] + matrix[2] * p[1],
                    matrix[1] * p[0] + matrix[3] * p[1],
                ]),
                o: path.o.map((p) => [
                    matrix[0] * p[0] + matrix[2] * p[1],
                    matrix[1] * p[0] + matrix[3] * p[1],
                ]),
            });
            if (target.source?.masksProperties?.length && !target.masks)
                throw new Error(
                    'Las máscaras importadas se conservan; prepara una capa nueva para añadir máscaras editables.',
                );
            target.masks = [
                ...(target.masks || []),
                ...paths.map((path) => ({
                    id: uid(),
                    name: source.name,
                    mode: 'a',
                    path: convert(path),
                    opacity: { value: 100, keys: [] },
                })),
            ];
            return d;
        });
    const copy = () => {
        if (keySelection.length) {
            const min = Math.min(...keySelection.map((k) => k.t));
            clipboard.current = {
                type: 'keys',
                keys: keySelection.map((p) => ({
                    ...p,
                    relative: p.t - min,
                    value: clone(
                        layers
                            .find((l) => l.id === p.layerId)
                            .tracks[p.key].keys.find((k) => k.t === p.t),
                    ),
                })),
            };
        } else
            clipboard.current = {
                type: 'layers',
                layers: clone(layers),
                ids: selected,
            };
        setKeyClipboard(
            clipboard.current?.type === 'keys' ? clipboard.current.keys : null,
        );
    };
    const paste = () => {
        const clip = clipboard.current;
        if (!clip) return;
        if (clip.type === 'keys')
            return operateKeyframes('paste', { time: frame });
        return apply((d) => {
            const ls = layersIn(d, compositionId);
            structure();
            const result = duplicateLayers(clip.layers, clip.ids);
            const newLayers = result.layers.slice(
                0,
                result.layers.length - clip.layers.length,
            );
            newLayers.forEach((l) => {
                if (
                    l.parentId &&
                    !newLayers.some((p) => p.id === l.parentId) &&
                    !ls.some((p) => p.id === l.parentId)
                )
                    l.parentId = null;
            });
            ls.unshift(...newLayers);
            setSelected(result.ids);
            return d;
        });
    };
    const fetchResource = async (id) => {
        if (resourceCache.current.has(id)) return resourceCache.current.get(id);
        const { data } = await axios.get(paths.resourceApi(project.id, id), {
            responseType: 'blob',
        });
        resourceCache.current.set(id, data);
        return data;
    };
    useEffect(() => {
        let canceled = false;
        Promise.all(
            doc.assets
                .filter((a) => a.resourceId && !assetData[a.id])
                .map(async (a) => [
                    a.id,
                    await dataUrl(await fetchResource(a.resourceId)),
                ]),
        )
            .then((entries) => {
                if (!canceled && entries.length)
                    setAssetData((current) => ({
                        ...current,
                        ...Object.fromEntries(entries),
                    }));
            })
            .catch((e) => {
                if (!canceled)
                    report(
                        'No se pudieron cargar los recursos privados. Recarga o vuelve a importar el archivo.',
                    );
            });
        return () => {
            canceled = true;
        };
    }, [doc.assets]);
    useEffect(() => {
        let canceled = false;
        Promise.all(
            resources
                .filter((r) => r.mime.startsWith('image/') && !thumbnails[r.id])
                .map(async (r) => [
                    r.id,
                    await dataUrl(await fetchResource(r.id)),
                ]),
        )
            .then((entries) => {
                if (!canceled && entries.length)
                    setThumbnails((current) => ({
                        ...current,
                        ...Object.fromEntries(entries),
                    }));
            })
            .catch(() => {});
        return () => {
            canceled = true;
        };
    }, [resources]);
    const compiled = useMemo(() => {
        try {
            return {
                json: compile(effective, assetData, compositionId),
                error: null,
            };
        } catch (e) {
            return { json: null, error: e.message };
        }
    }, [effective, assetData, compositionId]);
    useEffect(() => {
        if (!playing) return;
        let animation,
            origin = performance.now(),
            start = frame;
        const tick = (now) => {
            const c = doc.composition;
            let next =
                start + Math.floor(((now - origin) * c.fps * speed) / 1000);
            if (next > c.workEnd) {
                if (loop) {
                    next =
                        c.workStart +
                        ((next - c.workStart) % (c.workEnd - c.workStart + 1));
                } else {
                    setFrame(c.workEnd);
                    setPlaying(false);
                    return;
                }
            }
            setFrame(next);
            animation = requestAnimationFrame(tick);
        };
        animation = requestAnimationFrame(tick);
        return () => cancelAnimationFrame(animation);
    }, [playing, loop, speed, doc.composition]);
    current.current = {
        remove,
        copy,
        paste,
        duplicate,
        group,
        ungroup,
        save: persistence.save,
        history,
        playing,
        compositionId,
    };
    useEffect(() => {
        const keyboard = (e) => {
            if (
                e.defaultPrevented ||
                isInput(e.target) ||
                window.document.querySelector(
                    '[role="dialog"][aria-modal="true"]',
                )
            )
                return;
            // Native disclosure controls must keep Enter/Space instead of starting playback.
            if (e.target.closest('summary') && ['Enter', ' '].includes(e.key))
                return;
            const command = e.ctrlKey || e.metaKey;
            if (command && e.key.toLowerCase() === 's') {
                e.preventDefault();
                current.current.save();
            } else if (command && e.key.toLowerCase() === 'z') {
                e.preventDefault();
                dispatch({ type: e.shiftKey ? 'redo' : 'undo' });
            } else if (command && e.key.toLowerCase() === 'y') {
                e.preventDefault();
                dispatch({ type: 'redo' });
            } else if (command && e.key.toLowerCase() === 'c') {
                e.preventDefault();
                current.current.copy();
            } else if (command && e.key.toLowerCase() === 'v') {
                e.preventDefault();
                current.current.paste();
            } else if (command && e.key.toLowerCase() === 'd') {
                e.preventDefault();
                current.current.duplicate();
            } else if (command && e.key.toLowerCase() === 'g') {
                e.preventDefault();
                if (e.shiftKey) current.current.ungroup();
                else current.current.group(false);
            } else if (e.key === 'Delete' || e.key === 'Backspace') {
                e.preventDefault();
                current.current.remove();
            } else if (e.key === 'Escape') {
                setSelected([]);
                setKeySelection([]);
                setPlaying(false);
            } else if (e.key === 'ArrowRight') {
                e.preventDefault();
                setFrame((f) => Math.min(doc.composition.frames - 1, f + 1));
            } else if (e.key === 'ArrowLeft') {
                e.preventDefault();
                setFrame((f) => Math.max(0, f - 1));
            } else if (e.key === 'Enter' && e.target.tagName !== 'BUTTON') {
                e.preventDefault();
                setPlaying((v) => !v);
            }
        };
        window.addEventListener('keydown', keyboard);
        return () => window.removeEventListener('keydown', keyboard);
    }, [doc.composition.frames]);
    useEffect(() => {
        setFrame((f) => Math.min(f, doc.composition.frames - 1));
    }, [doc.composition.frames]);
    const readFile = async (
        file,
        separate = true,
        animationId = null,
        existingResource = null,
    ) => {
        setBusy(true);
        setError('');
        try {
            if (file.size > 20 * 1024 * 1024)
                throw new Error('El archivo supera 20 MB.');
            const extension = file.name.split('.').at(-1).toLowerCase();
            if (replaceRef.current) {
                const target = layers.find((l) => l.id === replaceRef.current);
                const allowed =
                    target?.type === 'shape'
                        ? ['svg']
                        : ['png', 'jpg', 'jpeg', 'webp'];
                if (!allowed.includes(extension))
                    throw new Error(
                        target?.type === 'shape'
                            ? 'La sustitución de esta capa requiere un SVG.'
                            : 'La sustitución requiere PNG, JPG o WebP.',
                    );
                if (target.locked)
                    throw new Error(
                        'Desbloquea la capa antes de sustituir su recurso.',
                    );
                separate = false;
            }
            let result;
            if (extension === 'svg') {
                result = importSvg(
                    await file.text(),
                    file.name,
                    doc.composition.frames,
                    separate,
                );
            } else if (extension === 'json') {
                result = importLottie(JSON.parse(await file.text()));
            } else if (extension === 'lottie') {
                result = await readPackage(
                    new Uint8Array(await file.arrayBuffer()),
                    null,
                    animationId,
                );
            } else if (['png', 'jpg', 'jpeg', 'webp'].includes(extension)) {
                const bitmap = await createImageBitmap(file);
                if (
                    bitmap.width > 8192 ||
                    bitmap.height > 8192 ||
                    bitmap.width * bitmap.height > 32000000
                )
                    throw new Error('Imagen demasiado grande.');
                result = {
                    width: bitmap.width,
                    height: bitmap.height,
                    warnings: [],
                    image: true,
                };
                bitmap.close();
            } else
                throw new Error(
                    'Usa SVG, PNG, JPG, WebP, Lottie JSON o .lottie.',
                );
            setPending({
                file,
                extension,
                result,
                separate,
                animationId,
                existingResource,
            });
            setDialog('import');
        } catch (e) {
            report(e.message || 'No se pudo leer el archivo.');
        } finally {
            setBusy(false);
        }
    };
    const confirmImport = async () => {
        const entry = pending;
        if (entry.result.blocked) return;
        setBusy(true);
        try {
            if (
                entry.result.document &&
                doc.layers.length &&
                !confirm(
                    'Importar esta animación reemplazará la composición actual. Podrás deshacerlo.',
                )
            )
                return;
            let resource = entry.existingResource;
            if (!resource) {
                const form = new FormData();
                form.append('file', entry.file);
                const response = await axios.post(
                    paths.resourceApi(project.id),
                    form,
                );
                resource = response.data;
                setResources((rs) => [...rs, resource]);
            }
            let result = entry.result;
            if (entry.extension === 'svg')
                result = importSvg(
                    await (await fetchResource(resource.id)).text(),
                    entry.file.name,
                    doc.composition.frames,
                    entry.separate,
                );
            if (entry.extension === 'svg' && result.layers)
                result.layers.forEach((l) => {
                    l.resourceId = resource.id;
                });
            let next = clone(doc);
            if (result.document) {
                next = result.document;
                if (entry.extension === 'lottie')
                    next.imports[0].packageResourceId = resource.id;
                else next.imports[0].resourceId = resource.id;
                setCompositionId(null);
                setSelected([]);
                setFrame(0);
            } else if (result.image) {
                const id = uid(),
                    data = await dataUrl(entry.file),
                    asset = {
                        id,
                        resourceId: resource.id,
                        name: entry.file.name,
                        width: result.width,
                        height: result.height,
                    };
                const importedLayer = {
                    id: uid(),
                    name: entry.file.name,
                    type: 'image',
                    parentId: null,
                    refId: id,
                    hidden: false,
                    locked: false,
                    start: 0,
                    end: doc.composition.frames,
                    bounds: {
                        x: 0,
                        y: 0,
                        width: result.width,
                        height: result.height,
                    },
                    tracks: {
                        p: {
                            value: [
                                doc.composition.width / 2,
                                doc.composition.height / 2,
                            ],
                            keys: [],
                        },
                        s: { value: [100, 100], keys: [] },
                        a: {
                            value: [result.width / 2, result.height / 2],
                            keys: [],
                        },
                        r: { value: 0, keys: [] },
                        o: { value: 100, keys: [] },
                    },
                };
                next.assets.push(asset);
                setAssetData((current) => ({ ...current, [id]: data }));
                if (replaceRef.current) {
                    const existing = layersIn(next, compositionId).find(
                        (l) => l.id === replaceRef.current,
                    );
                    existing.refId = id;
                    const oldBounds = existing.bounds,
                        ratios = [
                            result.width / oldBounds.width,
                            result.height / oldBounds.height,
                        ];
                    for (const key of ['s', 'a']) {
                        const track = existing.tracks[key];
                        if (track.readonly)
                            throw new Error(
                                'La animación importada no permite adaptar tamaño/anclaje.',
                            );
                        const transform = (value) =>
                            value.map((v, i) =>
                                key === 's' ? v / ratios[i] : v * ratios[i],
                            );
                        existing.tracks[key] = {
                            ...track,
                            edited: true,
                            value: transform(track.value),
                            keys: track.keys.map((k) => ({
                                ...k,
                                value: transform(k.value),
                            })),
                        };
                    }
                    existing.bounds = importedLayer.bounds;
                } else {
                    layersIn(next, compositionId).unshift(importedLayer);
                    setSelected([importedLayer.id]);
                }
            } else {
                if (result.blocked) throw new Error(result.warnings.join(' '));
                if (replaceRef.current) {
                    const existing = layersIn(next, compositionId).find(
                            (l) => l.id === replaceRef.current,
                        ),
                        replacement = result.layers[0];
                    if (!replacement)
                        throw new Error(
                            'El SVG no contiene geometría visible.',
                        );
                    const old = existing.bounds,
                        b = replacement.bounds;
                    existing.resourceId = resource.id;
                    existing.shapes = [
                        {
                            ty: 'gr',
                            nm: 'Recurso sustituido',
                            it: [
                                ...replacement.shapes,
                                {
                                    ty: 'tr',
                                    p: { a: 0, k: [old.x, old.y] },
                                    a: { a: 0, k: [b.x, b.y] },
                                    s: {
                                        a: 0,
                                        k: [
                                            (old.width / b.width) * 100,
                                            (old.height / b.height) * 100,
                                        ],
                                    },
                                    r: { a: 0, k: 0 },
                                    o: { a: 0, k: 100 },
                                },
                            ],
                        },
                    ];
                } else {
                    if (!next.layers.length && !compositionId) {
                        next.composition.width = result.width;
                        next.composition.height = result.height;
                    }
                    layersIn(next, compositionId).unshift(...result.layers);
                    setSelected(
                        result.layers
                            .filter((l) => l.type !== 'null')
                            .map((l) => l.id),
                    );
                }
            }
            commit(next);
            setKeySelection([]);
            setDialog(null);
            setPending(null);
            replaceRef.current = null;
        } catch (e) {
            report(
                e.response?.data?.errors?.file?.[0] ||
                    e.response?.data?.message ||
                    e.message,
            );
        } finally {
            setBusy(false);
        }
    };
    const addAsset = (asset) =>
        apply((d) => {
            structure();
            const target = compositionId
                ? d.compositions.find((c) => c.id === compositionId)
                : d.composition;
            const image = newLayer(asset.name || 'Imagen', 'image', {
                refId: asset.id,
                end: d.composition.frames,
                bounds: {
                    x: 0,
                    y: 0,
                    width: asset.width,
                    height: asset.height,
                },
            });
            image.tracks.p.value = [target.width / 2, target.height / 2];
            image.tracks.a.value = [asset.width / 2, asset.height / 2];
            layersIn(d, compositionId).unshift(image);
            setSelected([image.id]);
            setKeySelection([]);
            return d;
        });
    const addResource = async (resource) => {
        setBusy(true);
        try {
            replaceRef.current = null;
            const blob = await fetchResource(resource.id);
            await readFile(
                new File([blob], resource.name, { type: resource.mime }),
                true,
                null,
                resource,
            );
        } catch (e) {
            report(e.message);
        } finally {
            setBusy(false);
        }
    };
    const changeTiming = (id, mode, delta) =>
        apply((d) => {
            const layers = layersIn(d, compositionId),
                index = layers.findIndex((l) => l.id === id);
            layers[index] = editLayerTiming(
                layers[index],
                mode,
                delta,
                d.composition.frames,
            );
            return d;
        });
    const changeComposition = (changes) =>
        apply((d) => {
            const { width, height, ...timing } = changes;
            if (
                Object.hasOwn(changes, 'width') ||
                Object.hasOwn(changes, 'height')
            )
                d = resizeComposition(d, compositionId, {
                    ...(width !== undefined ? { width } : {}),
                    ...(height !== undefined ? { height } : {}),
                });
            if (
                Object.hasOwn(changes, 'frames') ||
                Object.hasOwn(changes, 'fps')
            )
                d = resizeTimeline(
                    d,
                    changes.frames ?? d.composition.frames,
                    changes.fps ?? d.composition.fps,
                );
            Object.assign(d.composition, timing);
            return d;
        });
    const applyCompositionSettings = (dimensions) => {
        try {
            commit(resizeComposition(doc, compositionId, dimensions));
            setCompositionSettings(false);
        } catch (e) {
            report(e.message);
        }
    };
    const applyTimelineSettings = (frames, fps, mode) => {
        try {
            commit(resizeTimeline(doc, frames, fps, mode));
            setKeySelection([]);
            setTimelineSettings(false);
        } catch (e) {
            report(e.message);
        }
    };
    const exportFile = async (format) => {
        setBusy(true);
        setExportError('');
        try {
            const json = compile(doc, assetData),
                filename =
                    name.replace(/[^\p{L}\p{N}_-]/gu, '_') || 'animation';
            json.nm = name;
            if (format === 'json')
                download(
                    JSON.stringify(
                        prepareJsonImages(
                            json,
                            imageExportMode,
                            imageExportUrls,
                        ),
                    ),
                    `${filename}.json`,
                );
            else if (format === 'project')
                download(
                    JSON.stringify({ name, document: doc }),
                    `${filename}.project.json`,
                );
            else {
                const imported = doc.imports.find((i) => i.packageResourceId),
                    bytes = imported
                        ? new Uint8Array(
                              await (
                                  await fetchResource(
                                      imported.packageResourceId,
                                  )
                              ).arrayBuffer(),
                          )
                        : null;
                download(
                    await writePackage(json, imported, bytes),
                    `${filename}.lottie`,
                    'application/zip',
                );
            }
            setDialog(null);
        } catch (e) {
            setExportError(e.message || 'No se pudo exportar.');
            report(e.message || 'No se pudo exportar.');
        } finally {
            setBusy(false);
        }
    };
    const addMarker = () => {
        const name = prompt('Nombre del marcador');
        if (name?.trim())
            apply((d) => {
                d.markers.push({ name: name.trim().slice(0, 160), t: frame });
                return d;
            });
    };
    const openComposition = (id) => {
        setCompositionId(id);
        setSelected([]);
        setKeySelection([]);
        setFrame(0);
        setPlaying(false);
    };
    const closeDialog = useCallback(() => {
        if (!busy) {
            setDialog(null);
            setPending(null);
            replaceRef.current = null;
        }
    }, [busy]);
    const saveState =
        persistence.status === 'saved' && persistence.dirty
            ? 'dirty'
            : persistence.status;
    const status = {
        saved: 'Todos los cambios guardados',
        dirty: 'Cambios pendientes',
        saving: 'Guardando…',
        error: 'Error de guardado',
        conflict: 'Conflicto de revisión',
    }[saveState];
    const saveLabel = {
        saved: 'Guardado',
        dirty: 'Guardar cambios',
        saving: 'Guardando…',
        error: 'Reintentar guardado',
        conflict: 'Revisar conflicto',
    }[saveState];
    const sideCurvesOpen = curvesOpen && curvesDock === 'sidebar';
    return (
        <>
            <Head title={`${name} · Lottie`} />
            <main
                className={`lottie-editor ${inspectorOpen || (curvesOpen && curvesDock === 'sidebar') ? 'inspector-open' : ''}`}
                style={{
                    '--timeline-height': '300px',
                    '--left-width': `${leftWidth}px`,
                    '--right-width': `${rightWidth}px`,
                }}
            >
                <header className="lottie-topbar">
                    <Link
                        to={paths.projects}
                        aria-label="Volver a proyectos"
                        onClick={(e) => {
                            if (
                                persistence.dirty &&
                                !confirm(
                                    'Hay cambios sin guardar. ¿Volver a proyectos?',
                                )
                            )
                                e.preventDefault();
                        }}
                    >
                        <ArrowLeft size={18} />
                    </Link>
                    <div className="editor-brand">
                        <Film size={18} />
                        <span>LOTTIE</span>
                    </div>
                    <input
                        className="project-name"
                        aria-label="Nombre del proyecto"
                        value={name}
                        maxLength="160"
                        onChange={(e) => setName(e.target.value)}
                    />
                    <span
                        id="lottie-save-status"
                        className={`save-status ${saveState}`}
                        role="status"
                        aria-atomic="true"
                    >
                        {saveState === 'saved' && (
                            <Check size={12} aria-hidden="true" />
                        )}{' '}
                        {status}
                    </span>
                    <div
                        className="lottie-header-transport"
                        ref={setTransportHost}
                    />
                    <div className="topbar-actions">
                        <button
                            type="button"
                            title="Deshacer (Ctrl/⌘ Z)"
                            aria-label="Deshacer"
                            disabled={!history.past.length}
                            onClick={() => dispatch({ type: 'undo' })}
                        >
                            <Undo2 size={17} />
                        </button>
                        <button
                            type="button"
                            title="Rehacer"
                            aria-label="Rehacer"
                            disabled={!history.future.length}
                            onClick={() => dispatch({ type: 'redo' })}
                        >
                            <Redo2 size={17} />
                        </button>
                        <button
                            type="button"
                            onClick={() => setDialog('help')}
                            aria-label="Ayuda"
                        >
                            <HelpCircle size={18} />
                        </button>
                        <button
                            type="button"
                            className={`save-button ${saveState}`}
                            disabled={
                                busy ||
                                persistence.status === 'saving' ||
                                persistence.status === 'conflict'
                            }
                            onClick={persistence.save}
                            aria-label="Guardar"
                            aria-describedby="lottie-save-status"
                            aria-busy={saveState === 'saving'}
                            title={`${saveLabel} · ${status} (Ctrl/⌘ S)`}
                        >
                            {saveState === 'saving' ? (
                                <LoaderCircle
                                    size={16}
                                    className="save-spinner"
                                    aria-hidden="true"
                                />
                            ) : saveState === 'saved' ? (
                                <Check size={16} aria-hidden="true" />
                            ) : saveState === 'error' ||
                              saveState === 'conflict' ? (
                                <CircleAlert size={16} aria-hidden="true" />
                            ) : (
                                <Save size={16} aria-hidden="true" />
                            )}
                            <span>{saveLabel}</span>
                            {saveState === 'dirty' && (
                                <i
                                    className="save-pending-dot"
                                    aria-hidden="true"
                                />
                            )}
                        </button>
                        <button
                            type="button"
                            className="primary"
                            disabled={busy}
                            onClick={() => setDialog('export')}
                            aria-label="Exportar"
                        >
                            <Download size={16} />
                            <span>Exportar</span>
                        </button>
                    </div>
                </header>
                {(error || compiled.error) && (
                    <div className="lottie-error" role="alert">
                        <span>{error || compiled.error}</span>
                        <button
                            type="button"
                            aria-label="Cerrar aviso"
                            onClick={() => setError('')}
                        >
                            <X size={15} />
                        </button>
                    </div>
                )}
                {persistence.recovery && (
                    <div className="lottie-recovery" role="status">
                        <span>
                            Hay un borrador local de{' '}
                            {new Date(persistence.recovery.date).toLocaleString(
                                'es-ES',
                            )}
                            .
                        </span>
                        <button
                            type="button"
                            onClick={persistence.restoreRecovery}
                        >
                            Recuperar
                        </button>
                        <button
                            type="button"
                            onClick={persistence.discardRecovery}
                        >
                            Descartar borrador
                        </button>
                    </div>
                )}
                {persistence.status === 'conflict' && (
                    <div className="lottie-recovery">
                        <span>
                            Otra sesión cambió el proyecto. Descarga tu borrador
                            antes de recargar.
                        </span>
                        <button
                            type="button"
                            onClick={() => exportFile('project')}
                        >
                            Descargar borrador
                        </button>
                        <button
                            type="button"
                            onClick={() =>
                                confirm(
                                    '¿Recargar y descartar los cambios de esta sesión?',
                                ) && location.reload()
                            }
                        >
                            Recargar
                        </button>
                    </div>
                )}
                <div className="lottie-toolstrip">
                    <button
                        type="button"
                        disabled={busy}
                        onClick={() => {
                            replaceRef.current = null;
                            fileInput.current.click();
                        }}
                    >
                        <Upload size={15} />
                        Importar recursos
                    </button>
                    <button
                        type="button"
                        disabled={busy || doc.structureLocked || !fonts.length}
                        onClick={addText}
                    >
                        <Type size={15} /> Añadir texto
                    </button>
                    <button
                        type="button"
                        disabled={busy || !selected.length}
                        onClick={() => {
                            setPlaying(false);
                            setDialog('presets');
                        }}
                    >
                        <Sparkles size={15} />
                        Animaciones
                    </button>
                    <span className="tool-divider" />
                    <button
                        type="button"
                        disabled={!selected.length || doc.structureLocked}
                        onClick={() => group(false)}
                    >
                        <Group size={15} />
                        Agrupar
                    </button>
                    <button
                        type="button"
                        disabled={
                            doc.structureLocked ||
                            !ungroupTargets(layers, selected).length
                        }
                        onClick={ungroup}
                        title="Desagrupar (Ctrl/⌘ Shift G)"
                    >
                        <Ungroup size={15} />
                        Desagrupar
                    </button>
                    <button
                        type="button"
                        disabled={!selected.length || doc.structureLocked}
                        onClick={() => group(true)}
                    >
                        <FolderOpen size={15} />
                        Precomponer
                    </button>
                    <button
                        type="button"
                        disabled={!selected.length || doc.structureLocked}
                        onClick={duplicate}
                        aria-label="Duplicar capas"
                    >
                        <Copy size={15} />
                    </button>
                    <button
                        type="button"
                        disabled={!selected.length && !keySelection.length}
                        onClick={remove}
                        aria-label="Eliminar selección"
                    >
                        <Trash2 size={15} />
                    </button>
                    <span className="tool-divider" />
                    <button
                        type="button"
                        className={autoKey ? 'active' : ''}
                        aria-pressed={autoKey}
                        onClick={() => setAutoKey((v) => !v)}
                    >
                        <span className={`auto-dot ${autoKey ? 'on' : ''}`} />
                        Keyframes automáticos
                    </button>
                    <button type="button" onClick={addMarker}>
                        + Marcador
                    </button>
                    <button
                        type="button"
                        className="mobile-properties"
                        aria-expanded={inspectorOpen || sideCurvesOpen}
                        onClick={() => {
                            if (curvesOpen && curvesDock === 'sidebar') {
                                setRightTab('properties');
                                setInspectorOpen(true);
                            } else setInspectorOpen((v) => !v);
                        }}
                    >
                        Propiedades
                    </button>
                    <div className="composition-breadcrumb">
                        <button
                            type="button"
                            onClick={() => openComposition(null)}
                        >
                            Composición
                        </button>
                        {compositionId && (
                            <>
                                <ChevronRight size={12} />
                                <span>
                                    {doc.compositions
                                        .find((c) => c.id === compositionId)
                                        ?.id.slice(0, 12)}
                                </span>
                            </>
                        )}
                        <button
                            type="button"
                            aria-label="Ajustes de composición"
                            title="Cambiar ancho y alto de la composición abierta"
                            onClick={() => {
                                setError('');
                                setCompositionSettings(true);
                            }}
                        >
                            <Settings2 size={14} />
                            {activeComposition.width} ×{' '}
                            {activeComposition.height}
                        </button>
                    </div>
                </div>
                <input
                    ref={fileInput}
                    type="file"
                    hidden
                    accept={
                        replaceRef.current
                            ? '.svg,.png,.jpg,.jpeg,.webp'
                            : '.svg,.png,.jpg,.jpeg,.webp,.json,.lottie'
                    }
                    onChange={(e) => {
                        if (e.target.files[0]) readFile(e.target.files[0]);
                        e.target.value = '';
                    }}
                />
                <div className="lottie-workspace">
                    <div
                        className="panel-resize left-resize"
                        role="separator"
                        aria-label="Ancho del panel de capas"
                        aria-orientation="vertical"
                        tabIndex="0"
                        onKeyDown={(e) => {
                            if (e.key === 'ArrowRight')
                                setLeftWidth((w) => Math.min(400, w + 20));
                            if (e.key === 'ArrowLeft')
                                setLeftWidth((w) => Math.max(185, w - 20));
                        }}
                        onPointerDown={(e) =>
                            e.currentTarget.setPointerCapture(e.pointerId)
                        }
                        onPointerMove={(e) => {
                            if (e.buttons === 1)
                                setLeftWidth(
                                    Math.max(185, Math.min(400, e.clientX)),
                                );
                        }}
                    />
                    <div
                        className="panel-resize right-resize"
                        role="separator"
                        aria-label="Ancho del inspector"
                        aria-orientation="vertical"
                        tabIndex="0"
                        onKeyDown={(e) => {
                            if (e.key === 'ArrowRight')
                                setRightWidth((w) => Math.max(220, w - 20));
                            if (e.key === 'ArrowLeft')
                                setRightWidth((w) => Math.min(400, w + 20));
                        }}
                        onPointerDown={(e) =>
                            e.currentTarget.setPointerCapture(e.pointerId)
                        }
                        onPointerMove={(e) => {
                            if (e.buttons === 1)
                                setRightWidth(
                                    Math.max(
                                        220,
                                        Math.min(
                                            400,
                                            window.innerWidth - e.clientX,
                                        ),
                                    ),
                                );
                        }}
                    />
                    <aside className="lottie-layer-panel">
                        <div className="panel-tabs">
                            <button
                                type="button"
                                className={panel === 'layers' ? 'active' : ''}
                                onClick={() => setPanel('layers')}
                            >
                                <Layers size={14} />
                                Capas
                            </button>
                            <button
                                type="button"
                                className={panel === 'assets' ? 'active' : ''}
                                onClick={() => setPanel('assets')}
                            >
                                <Image size={14} />
                                Recursos
                            </button>
                        </div>
                        {panel === 'layers' ? (
                            <div className="layer-list">
                                {layerRows.map(
                                    ({ layer: l, depth, hasChildren }) => {
                                        return (
                                            <div
                                                key={l.id}
                                                className={`layer-item ${selected.includes(l.id) ? 'selected' : ''}`}
                                                style={{
                                                    paddingLeft: 6 + depth * 14,
                                                }}
                                            >
                                                {hasChildren ? (
                                                    <button
                                                        type="button"
                                                        className="layer-disclosure"
                                                        aria-label={`${collapsedGroups.has(l.id) ? 'Expandir' : 'Contraer'} grupo ${l.name}`}
                                                        aria-expanded={
                                                            !collapsedGroups.has(
                                                                l.id,
                                                            )
                                                        }
                                                        onClick={() =>
                                                            toggleGroup(l.id)
                                                        }
                                                        title={`${collapsedGroups.has(l.id) ? 'Mostrar' : 'Plegar'} elementos de ${l.name}`}
                                                    >
                                                        <ChevronRight
                                                            size={14}
                                                            className={
                                                                collapsedGroups.has(
                                                                    l.id,
                                                                )
                                                                    ? ''
                                                                    : 'expanded'
                                                            }
                                                        />
                                                    </button>
                                                ) : (
                                                    <span
                                                        className="layer-disclosure-spacer"
                                                        aria-hidden="true"
                                                    />
                                                )}
                                                <button
                                                    type="button"
                                                    className="layer-select"
                                                    onClick={(e) =>
                                                        select(
                                                            e.shiftKey
                                                                ? selected.includes(
                                                                      l.id,
                                                                  )
                                                                    ? selected.filter(
                                                                          (
                                                                              id,
                                                                          ) =>
                                                                              id !==
                                                                              l.id,
                                                                      )
                                                                    : [
                                                                          ...selected,
                                                                          l.id,
                                                                      ]
                                                                : [l.id],
                                                        )
                                                    }
                                                    onDoubleClick={() =>
                                                        l.type === 'precomp' &&
                                                        openComposition(l.refId)
                                                    }
                                                >
                                                    <span className="layer-kind">
                                                        {l.text
                                                            ? 'T'
                                                            : {
                                                                  shape: '◇',
                                                                  image: '▧',
                                                                  null: '▱',
                                                                  precomp: '▣',
                                                                  original: '◈',
                                                              }[l.type]}
                                                    </span>
                                                    <span>{l.name}</span>
                                                </button>
                                                <button
                                                    type="button"
                                                    aria-label={`${l.hidden ? 'Mostrar' : 'Ocultar'} ${l.name}`}
                                                    onClick={() =>
                                                        changeLayer(l.id, {
                                                            hidden: !l.hidden,
                                                        })
                                                    }
                                                >
                                                    {l.hidden ? (
                                                        <EyeOff size={13} />
                                                    ) : (
                                                        <Eye size={13} />
                                                    )}
                                                </button>
                                                <button
                                                    type="button"
                                                    aria-label={`${l.locked ? 'Desbloquear' : 'Bloquear'} ${l.name}`}
                                                    onClick={() =>
                                                        changeLayer(l.id, {
                                                            locked: !l.locked,
                                                        })
                                                    }
                                                >
                                                    {l.locked ? (
                                                        <LockKeyhole
                                                            size={13}
                                                        />
                                                    ) : (
                                                        <UnlockKeyhole
                                                            size={13}
                                                        />
                                                    )}
                                                </button>
                                            </div>
                                        );
                                    },
                                )}
                                {!layers.length && (
                                    <p className="panel-empty">
                                        Importa un SVG o una imagen para crear
                                        tus primeras capas.
                                    </p>
                                )}
                                {layer && (
                                    <div className="layer-operations">
                                        <button
                                            type="button"
                                            disabled={doc.structureLocked}
                                            onClick={() =>
                                                reorder(layer.id, -1)
                                            }
                                            aria-label="Subir capa"
                                        >
                                            <ArrowUp size={14} />
                                        </button>
                                        <button
                                            type="button"
                                            disabled={doc.structureLocked}
                                            onClick={() => reorder(layer.id, 1)}
                                            aria-label="Bajar capa"
                                        >
                                            <ArrowDown size={14} />
                                        </button>
                                        {layer.type === 'precomp' && (
                                            <button
                                                type="button"
                                                onClick={() =>
                                                    openComposition(layer.refId)
                                                }
                                            >
                                                Abrir composición
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>
                        ) : (
                            <ResourceLibrary
                                document={doc}
                                resources={resources}
                                assetData={assetData}
                                thumbnails={thumbnails}
                                busy={busy}
                                layer={layer}
                                onAddAsset={addAsset}
                                onAddResource={addResource}
                                onImport={() => {
                                    replaceRef.current = null;
                                    fileInput.current.click();
                                }}
                                onReplace={() => {
                                    replaceRef.current = layer.id;
                                    fileInput.current.click();
                                }}
                            />
                        )}
                    </aside>
                    <Stage
                        document={effective}
                        json={compiled.json}
                        compositionId={compositionId}
                        frame={frame}
                        selected={selected}
                        keySelection={keySelection}
                        select={select}
                        commit={commit}
                        preview={setGestureDoc}
                        autoKey={autoKey}
                        zoom={zoom}
                        setZoom={setZoom}
                        report={report}
                        playing={playing}
                    />
                    <div className="lottie-inspector lottie-right-panel">
                        {sideCurvesOpen && (
                            <div
                                className="right-panel-tabs"
                                role="tablist"
                                aria-label="Panel derecho"
                                onKeyDown={(e) => {
                                    if (
                                        ![
                                            'ArrowLeft',
                                            'ArrowRight',
                                            'Home',
                                            'End',
                                        ].includes(e.key)
                                    )
                                        return;
                                    e.preventDefault();
                                    e.stopPropagation();
                                    const next =
                                        e.key === 'Home'
                                            ? 'properties'
                                            : e.key === 'End'
                                              ? 'curves'
                                              : rightTab === 'properties'
                                                ? 'curves'
                                                : 'properties';
                                    setRightTab(next);
                                    e.currentTarget
                                        .querySelector(`[data-tab="${next}"]`)
                                        .focus();
                                }}
                            >
                                {[
                                    ['properties', 'Propiedades'],
                                    ['curves', 'Curvas'],
                                ].map(([id, label]) => (
                                    <button
                                        key={id}
                                        type="button"
                                        role="tab"
                                        id={`lottie-${id}-tab`}
                                        data-tab={id}
                                        aria-controls={`lottie-${id}-panel`}
                                        aria-selected={rightTab === id}
                                        tabIndex={rightTab === id ? 0 : -1}
                                        onClick={() => setRightTab(id)}
                                    >
                                        {label}
                                    </button>
                                ))}
                            </div>
                        )}
                        <div
                            id="lottie-properties-panel"
                            className="right-panel-content"
                            role={sideCurvesOpen ? 'tabpanel' : undefined}
                            aria-labelledby={
                                sideCurvesOpen
                                    ? 'lottie-properties-tab'
                                    : undefined
                            }
                            hidden={sideCurvesOpen && rightTab !== 'properties'}
                        >
                            <Inspector
                                embedded
                                closePanel={() => {
                                    setInspectorOpen(false);
                                    if (curvesDock === 'sidebar')
                                        setCurvesOpen(false);
                                    document
                                        .querySelector('.mobile-properties')
                                        ?.focus();
                                }}
                                fonts={fonts}
                                changeText={changeText}
                                changeColor={changeColor}
                                openPresets={() => {
                                    setPlaying(false);
                                    setDialog('presets');
                                }}
                                layer={
                                    layer
                                        ? {
                                              ...layer,
                                              bounds: selectionBounds(
                                                  layer,
                                                  layers,
                                                  frame,
                                              ),
                                          }
                                        : layer
                                }
                                layers={layers}
                                composition={activeComposition}
                                frame={frame}
                                changeLayer={changeLayer}
                                changeTrack={changeTrack}
                                changeExpression={changeExpression}
                                centerAnchor={centerAnchor}
                                groupChoices={
                                    layer
                                        ? availableGroups(layers, [layer.id])
                                        : []
                                }
                                canRemoveFromGroup={Boolean(
                                    layer &&
                                        removableGroupMembers(layers, [
                                            layer.id,
                                        ]).length,
                                )}
                                structureLocked={doc.structureLocked}
                                changeGroup={changeGroup}
                                addKey={addKey}
                                keySelection={keySelection}
                                changeKeys={changeKeys}
                                changePositionKeyType={changePositionKeyType}
                                changeComposition={changeComposition}
                                align={align}
                                addMask={addMask}
                                report={report}
                            />
                        </div>
                        <div
                            id="lottie-curves-panel"
                            className="right-panel-content"
                            role={sideCurvesOpen ? 'tabpanel' : undefined}
                            aria-labelledby={
                                sideCurvesOpen ? 'lottie-curves-tab' : undefined
                            }
                            hidden={!sideCurvesOpen || rightTab !== 'curves'}
                        >
                            <aside
                                ref={setCurvesHost}
                                className="lottie-inspector-content lottie-curves-sidebar"
                                aria-label="Curvas de animación"
                            />
                        </div>
                    </div>
                </div>
                <div
                    className="timeline-resize"
                    role="separator"
                    aria-label="Cambiar altura de timeline"
                    aria-orientation="horizontal"
                    tabIndex="0"
                    onKeyDown={(e) => {
                        if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
                            const root =
                                    e.currentTarget.closest('.lottie-editor'),
                                height = parseInt(
                                    root.style.getPropertyValue(
                                        '--timeline-height',
                                    ),
                                );
                            root.style.setProperty(
                                '--timeline-height',
                                `${Math.max(160, Math.min(600, height + (e.key === 'ArrowUp' ? 20 : -20)))}px`,
                            );
                        }
                    }}
                    onPointerDown={(e) => {
                        e.currentTarget.setPointerCapture(e.pointerId);
                    }}
                    onPointerMove={(e) => {
                        if (e.buttons === 1)
                            e.currentTarget
                                .closest('.lottie-editor')
                                .style.setProperty(
                                    '--timeline-height',
                                    `${Math.max(160, Math.min(window.innerHeight * 0.65, window.innerHeight - e.clientY))}px`,
                                );
                    }}
                />
                <Timeline
                    curvesOpen={curvesOpen}
                    setCurvesOpen={setCurvesOpen}
                    curvesDock={curvesDock}
                    setCurvesDock={(dock) => {
                        setCurvesDock(dock);
                        setRightTab('curves');
                    }}
                    curvesHost={curvesHost}
                    transportHost={transportHost}
                    layers={layers}
                    collapsedGroups={collapsedGroups}
                    toggleGroup={toggleGroup}
                    composition={doc.composition}
                    frame={frame}
                    setFrame={setFrame}
                    playing={playing}
                    setPlaying={setPlaying}
                    loop={loop}
                    setLoop={setLoop}
                    speed={speed}
                    setSpeed={setSpeed}
                    selected={selected}
                    select={selectTimeline}
                    keySelection={keySelection}
                    setKeySelection={setKeySelection}
                    addKey={addKey}
                    moveSelectedKeys={moveSelectedKeys}
                    operateKeyframes={operateKeyframes}
                    canPasteKeys={!!keyClipboard?.length}
                    changeKeys={changeKeys}
                    changePositionKeyType={changePositionKeyType}
                    changePositionCurvePreset={changePositionCurvePreset}
                    removeKeys={() => {
                        if (keySelection.length) remove();
                    }}
                    changeLayerTiming={changeTiming}
                    onSettings={() => {
                        setError('');
                        setTimelineSettings(true);
                    }}
                    changeComposition={changeComposition}
                    markers={doc.markers}
                    changeMarkers={(markers) =>
                        apply((d) => ({ ...d, markers }))
                    }
                />
                {timelineSettings && (
                    <TimelineSettings
                        composition={doc.composition}
                        onApply={applyTimelineSettings}
                        onClose={() => setTimelineSettings(false)}
                        error={error}
                    />
                )}
                {compositionSettings && (
                    <CompositionSettings
                        composition={activeComposition}
                        nested={!!compositionId}
                        onApply={applyCompositionSettings}
                        onClose={() => setCompositionSettings(false)}
                        error={error}
                    />
                )}
                {dialog === 'presets' && (
                    <AnimationPresets
                        document={doc}
                        selected={selected}
                        compositionId={compositionId}
                        frame={frame}
                        assetData={assetData}
                        onClose={closeDialog}
                        onApply={(result) => {
                            commit(result.document);
                            setFrame(result.start);
                            setKeySelection([]);
                            setDialog(null);
                        }}
                    />
                )}
                {dialog && dialog !== 'presets' && (
                    <Dialog
                        title={
                            dialog === 'import'
                                ? 'Revisar importación'
                                : dialog === 'export'
                                  ? 'Exportar animación'
                                  : 'Guía del editor'
                        }
                        onClose={closeDialog}
                    >
                        {dialog === 'import' && pending && (
                            <>
                                <p className="import-filename">
                                    {pending.file.name}
                                </p>
                                {pending.extension === 'svg' &&
                                    !replaceRef.current && (
                                        <label className="check-field">
                                            <input
                                                type="checkbox"
                                                checked={pending.separate}
                                                disabled={busy}
                                                onChange={(e) => {
                                                    const separate =
                                                        e.target.checked;
                                                    setPending((current) => ({
                                                        ...current,
                                                        separate,
                                                    }));
                                                    readFile(
                                                        pending.file,
                                                        separate,
                                                        pending.animationId,
                                                        pending.existingResource,
                                                    );
                                                }}
                                            />
                                            Separar grupos y elementos en capas
                                        </label>
                                    )}
                                {pending.extension === 'lottie' &&
                                    pending.result.document.imports[0]
                                        .animationIds.length > 1 && (
                                        <label className="field-label">
                                            Animación activa
                                            <select
                                                disabled={busy}
                                                value={
                                                    pending.result.document
                                                        .imports[0].animationId
                                                }
                                                onChange={(e) =>
                                                    readFile(
                                                        pending.file,
                                                        true,
                                                        e.target.value,
                                                    )
                                                }
                                            >
                                                {pending.result.document.imports[0].animationIds.map(
                                                    (id) => (
                                                        <option key={id}>
                                                            {id}
                                                        </option>
                                                    ),
                                                )}
                                            </select>
                                        </label>
                                    )}
                                <p>
                                    {pending.result.document
                                        ? `${pending.result.document.layers.length} capas en la composición principal`
                                        : pending.result.image
                                          ? `Imagen de ${pending.result.width} × ${pending.result.height} px`
                                          : `${pending.result.layers.length} capas vectoriales`}
                                </p>
                                {pending.result.warnings.length > 0 && (
                                    <div className="import-warnings">
                                        <strong>
                                            {pending.result.blocked
                                                ? 'Es necesario preparar el SVG antes de importar'
                                                : 'Contenido conservado con limitaciones'}
                                        </strong>
                                        <ul>
                                            {pending.result.warnings.map(
                                                (w, i) => (
                                                    <li key={i}>{w}</li>
                                                ),
                                            )}
                                        </ul>
                                    </div>
                                )}
                                <button
                                    type="button"
                                    className="primary"
                                    disabled={busy || pending.result.blocked}
                                    onClick={confirmImport}
                                >
                                    {busy
                                        ? 'Importando…'
                                        : 'Confirmar importación'}
                                </button>
                            </>
                        )}
                        {dialog === 'export' && (
                            <>
                                <p>
                                    El archivo utiliza la misma composición que
                                    la previsualización. Por defecto, las
                                    imágenes quedan incrustadas en Base64 en el
                                    JSON.
                                </p>
                                {doc.assets.length > 0 && (
                                    <>
                                        <label className="field-label">
                                            Imágenes del Lottie JSON
                                            <select
                                                value={imageExportMode}
                                                disabled={busy}
                                                onChange={(e) => {
                                                    setImageExportMode(
                                                        e.target.value,
                                                    );
                                                    setExportError('');
                                                }}
                                            >
                                                <option value="embedded">
                                                    Incrustar en Base64
                                                    (predeterminado)
                                                </option>
                                                <option value="external">
                                                    Usar enlaces externos
                                                </option>
                                            </select>
                                        </label>
                                        {imageExportMode === 'external' && (
                                            <>
                                                <p className="inspector-note">
                                                    Indica una URL pública HTTP
                                                    o HTTPS para cada imagen. El
                                                    JSON necesitará esos enlaces
                                                    para reproducirse; el
                                                    servidor debe permitir su
                                                    carga desde la web donde lo
                                                    uses.
                                                </p>
                                                {doc.assets.map((asset) => (
                                                    <label
                                                        className="field-label"
                                                        key={asset.id}
                                                    >
                                                        URL de{' '}
                                                        {asset.name || asset.id}
                                                        <input
                                                            type="url"
                                                            placeholder="https://ejemplo.com/imagen.png"
                                                            value={
                                                                imageExportUrls[
                                                                    asset.id
                                                                ] || ''
                                                            }
                                                            disabled={busy}
                                                            onChange={(e) => {
                                                                const url =
                                                                    e.target
                                                                        .value;
                                                                setImageExportUrls(
                                                                    (urls) => ({
                                                                        ...urls,
                                                                        [asset.id]:
                                                                            url,
                                                                    }),
                                                                );
                                                                setExportError(
                                                                    '',
                                                                );
                                                            }}
                                                        />
                                                    </label>
                                                ))}
                                            </>
                                        )}
                                    </>
                                )}
                                {exportError && (
                                    <p role="alert">{exportError}</p>
                                )}
                                <div className="export-options">
                                    <button
                                        type="button"
                                        disabled={busy}
                                        onClick={() => exportFile('json')}
                                    >
                                        <Download />
                                        <strong>Lottie JSON</strong>
                                        <span>
                                            {imageExportMode === 'external' &&
                                            doc.assets.length
                                                ? 'Animación con imágenes enlazadas.'
                                                : 'Una animación autónoma para la web.'}
                                        </span>
                                    </button>
                                    <button
                                        type="button"
                                        disabled={busy}
                                        onClick={() => exportFile('lottie')}
                                    >
                                        <Download />
                                        <strong>dotLottie · .lottie</strong>
                                        <span>
                                            Paquete con imágenes incorporadas;
                                            conserva las demás animaciones del
                                            archivo original.
                                        </span>
                                    </button>
                                </div>
                                {doc.imports.some(
                                    (i) => i.protectedReferences,
                                ) && (
                                    <p className="inspector-note">
                                        El paquete conserva temas y máquinas de
                                        estados. Cambiar la estructura de capas
                                        puede bloquear su exportación.
                                    </p>
                                )}
                            </>
                        )}
                        {dialog === 'help' && (
                            <div className="editor-help">
                                <p>
                                    1. Importa tus SVG preparados como trazados
                                    o imágenes. Revisa el informe antes de
                                    confirmar. También puedes usar «Añadir
                                    texto» y editar su tipografía desde
                                    Propiedades.
                                </p>
                                <p>
                                    2. Selecciona una capa y despliega sus
                                    pistas en el timeline. Sitúa el cabezal y
                                    pulsa el diamante de una propiedad.
                                </p>
                                <p>
                                    3. Avanza a otro fotograma y añade otro
                                    keyframe. Activa «Keyframes automáticos»
                                    para registrar cambios desde el lienzo.
                                </p>
                                <p>
                                    4. Selecciona keyframes para ajustar las
                                    curvas. Activa los tiradores de trayectoria
                                    para moverlos sobre el lienzo.
                                </p>
                                <p>
                                    5. Selecciona varias capas con Shift para
                                    agrupar, alinear o precomponer. Abre una
                                    precomposición con doble clic.
                                </p>
                                <p>
                                    6. Usa una capa SVG como geometría de
                                    máscara. Las máscaras son estáticas; su modo
                                    y opacidad son editables.
                                </p>
                                <p>
                                    <strong>Atajos:</strong> Ctrl/⌘ Z deshacer ·
                                    Shift Ctrl/⌘ Z rehacer · Ctrl/⌘ S guardar ·
                                    Ctrl/⌘ C/V copiar/pegar · Ctrl/⌘ D duplicar
                                    · Ctrl/⌘ G agrupar · Shift Ctrl/⌘ G
                                    desagrupar · Supr eliminar · Enter
                                    reproducir · flechas avanzar · Espacio +
                                    arrastrar desplazar lienzo.
                                </p>
                                <p>
                                    El guardado automático espera dos segundos
                                    de inactividad. Una revisión en conflicto
                                    conserva el borrador y exige recargar
                                    explícitamente.
                                </p>
                            </div>
                        )}
                    </Dialog>
                )}
            </main>
        </>
    );
}