/**
* Coordina la selección rectangular de fotogramas clave y los menús contextuales de la línea de tiempo.
* @module lottie/components/useKeyframeMarquee
*/
import { useEffect, useRef, useState } from 'react';
const identity = (k) => `${k.layerId}:${k.key}:${k.t}`;
const pickedKey = (node) => ({ layerId: node.dataset.layerId, key: node.dataset.key, t: Number(node.dataset.time) });
/**
* Coordina la selección rectangular de fotogramas clave y los menús contextuales de la línea de tiempo.
* @param {object} props Propiedades y acciones del componente o hook.
* @param {object} props.container Referencia React al contenedor de la selección rectangular.
* @param {Array<object>} props.selection Fotogramas clave seleccionados con capa, propiedad y tiempo.
* @param {Function} props.setSelection Actualiza la selección de fotogramas clave.
* @param {Function} props.selectLayers Selecciona las capas correspondientes a los fotogramas.
* @param {Function} props.setPlaying Actualiza el estado de reproducción.
* @param {number} props.frames Duración de la composición en fotogramas.
* @param {number} props.zoom Escala del lienzo o de la línea de tiempo.
* @param {Function} props.openMenu Abre el menú contextual en las coordenadas indicadas.
* @returns {object} Estado y manejadores de selección rectangular de la línea de tiempo.
*/
export default function useKeyframeMarquee({ container, selection, setSelection, selectLayers, setPlaying, frames, zoom, openMenu }) {
const gesture = useRef(null), animation = useRef(null), ignoreClick = useRef(false), ignoreContext = useRef(false);
const [rectangle, setRectangle] = useState(null);
const coordinates = (x, y) => {
const el = container.current, box = el.getBoundingClientRect();
return { x: x - box.left + el.scrollLeft, y: y - box.top + el.scrollTop };
};
const menu = (event) => {
const node = event.target.closest('.keyframe'), track = event.target.closest('[data-keyframe-track]');
if (!track) return;
let keys = selection;
if (node) {
const key = pickedKey(node);
if (node.disabled) keys = [];
else if (!keys.some((k) => identity(k) === identity(key))) keys = [key];
setSelection(keys);
if (keys.length) selectLayers([...new Set(keys.map((k) => k.layerId))]);
}
const line = track.getBoundingClientRect();
const time = node ? Number(node.dataset.time) : Math.max(0, Math.min(frames - 1, Math.round((event.clientX - line.left) / zoom)));
openMenu({ x: event.clientX, y: event.clientY, layerId: track.dataset.layerId, key: track.dataset.key, time });
};
const update = () => {
const g = gesture.current;
if (!g?.moved) return;
const end = coordinates(g.clientX, g.clientY);
const box = { left: Math.min(g.start.x, end.x), top: Math.min(g.start.y, end.y), width: Math.abs(end.x - g.start.x), height: Math.abs(end.y - g.start.y) };
const hits = [];
container.current.querySelectorAll('.keyframe:not(:disabled)').forEach((node) => {
const bounds = node.getBoundingClientRect(), center = coordinates(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2);
if (center.x >= box.left && center.x <= box.left + box.width && center.y >= box.top && center.y <= box.top + box.height) hits.push(pickedKey(node));
});
const ids = new Set(hits.map(identity));
g.selection = g.subtract ? g.previous.filter((k) => !ids.has(identity(k)))
: [...new Map([...g.base, ...hits].map((k) => [identity(k), k])).values()];
setSelection(g.selection);
setRectangle(box);
};
const autoScroll = () => {
const g = gesture.current, el = container.current;
if (!g || !el) return;
if (g.moved) {
const box = el.getBoundingClientRect(), oldX = el.scrollLeft, oldY = el.scrollTop;
if (g.clientX > box.right - 24) el.scrollLeft += 10;
else if (g.clientX < box.left + 214) el.scrollLeft -= 10;
if (g.clientY > box.bottom - 24) el.scrollTop += 8;
else if (g.clientY < box.top + 24) el.scrollTop -= 8;
if (el.scrollLeft !== oldX || el.scrollTop !== oldY) update();
}
animation.current = requestAnimationFrame(autoScroll);
};
const cancel = () => {
const g = gesture.current;
if (g) setSelection(g.previous);
gesture.current = null;
cancelAnimationFrame(animation.current);
setRectangle(null);
};
useEffect(() => () => cancelAnimationFrame(animation.current), []);
return {
rectangle,
handlers: {
onPointerDownCapture: (e) => {
if (![0, 2].includes(e.button) || !e.target.closest('[data-keyframe-track]')) return;
if (e.button === 0 && e.target.closest('button')) return;
if (e.button === 2) e.preventDefault();
e.stopPropagation();
ignoreContext.current = false;
setPlaying(false);
openMenu(null);
const start = coordinates(e.clientX, e.clientY);
gesture.current = { start, clientX: e.clientX, clientY: e.clientY, previous: selection, base: e.shiftKey ? selection : [], subtract: e.ctrlKey || e.metaKey, button: e.button, target: e.target, moved: false };
e.currentTarget.focus({ preventScroll: true });
animation.current = requestAnimationFrame(autoScroll);
},
onPointerMove: (e) => {
const g = gesture.current;
if (!g) return false;
const point = coordinates(e.clientX, e.clientY);
g.clientX = e.clientX; g.clientY = e.clientY;
if (Math.hypot(point.x - g.start.x, point.y - g.start.y) >= 4) g.moved = true;
if (g.moved && !e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.setPointerCapture(e.pointerId);
update();
return true;
},
onPointerUp: (e) => {
const g = gesture.current;
if (!g) return false;
cancelAnimationFrame(animation.current);
ignoreClick.current = g.button === 0 && g.moved;
ignoreContext.current = g.button === 2;
setTimeout(() => { ignoreContext.current = false; }, 0);
if (g.moved) {
update();
if (g.selection?.length) selectLayers([...new Set(g.selection.map((k) => k.layerId))]);
} else if (g.button === 2) menu({ target: g.target, clientX: e.clientX, clientY: e.clientY });
else setSelection([]);
gesture.current = null;
setRectangle(null);
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
return true;
},
onPointerCancel: cancel,
onClickCapture: (e) => {
if (ignoreClick.current) { ignoreClick.current = false; e.preventDefault(); e.stopPropagation(); }
},
onContextMenuCapture: (e) => {
if (!e.target.closest('[data-keyframe-track]')) return;
e.preventDefault(); e.stopPropagation();
if (!gesture.current && !ignoreContext.current) menu(e);
},
onKeyDownCapture: (e) => {
if (e.key === 'Escape' && gesture.current) { e.preventDefault(); e.stopPropagation(); cancel(); }
},
},
};
}