Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: add CtxMenuItem component for context menu interactions

CristianOlivera1b8368a95933b
diff --git a/app/components/ui/editor/ContextMenu.tsx b/app/components/ui/editor/ContextMenu.tsx
new file mode 100644
index 0000000..a42803e
--- /dev/null
+++ b/app/components/ui/editor/ContextMenu.tsx
@@ -0,0 +1,107 @@
+import CtxMenuItem from "@/components/ui/CtxMenuItem";
+import { ContextMenuProps } from "@/types/layers.types";
+import { useRef, useState, useEffect } from "react";
+
+export default function ContextMenu({
+ x,
+ y,
+ selectedIds,
+ canGroup,
+ canUngroup,
+ onBringToFront,
+ onSendToBack,
+ onDelete,
+ onDeleteSelected,
+ onGroup,
+ onUngroup,
+ onClose,
+}: ContextMenuProps) {
+ const menuRef = useRef<HTMLDivElement>(null);
+ const [pos, setPos] = useState({ x, y });
+ const isMulti = selectedIds.length > 1;
+
+ useEffect(() => {
+ const menu = menuRef.current;
+ if (!menu) return;
+ const { width, height } = menu.getBoundingClientRect();
+ setPos({
+ x: Math.min(x, window.innerWidth - width - 8),
+ y: Math.min(y, window.innerHeight - height - 8),
+ });
+ }, [x, y]);
+
+ return (
+ <div
+ ref={menuRef}
+ data-ctx-menu
+ className="fixed z-9999 bg-black border border-white/15 rounded-xl shadow-2xl py-1 min-w-43 overflow-hidden"
+ style={{ left: pos.x, top: pos.y }}
+ >
+ {!isMulti && (
+ <>
+ <CtxMenuItem
+ icon="qlementine-icons:bring-to-front-16"
+ label="Traer al frente"
+ onClick={() => {
+ onBringToFront();
+ onClose();
+ }}
+ />
+ <CtxMenuItem
+ icon="qlementine-icons:bring-to-back-16"
+ label="Enviar atrás"
+ onClick={() => {
+ onSendToBack();
+ onClose();
+ }}
+ />
+ <div className="my-1 h-px bg-white/6" />
+ <CtxMenuItem
+ icon="solar:trash-bin-trash-bold"
+ label="Eliminar capa"
+ onClick={() => {
+ onDelete();
+ onClose();
+ }}
+ danger
+ />
+ </>
+ )}
+
+ {isMulti && (
+ <>
+ {canGroup && onGroup && (
+ <CtxMenuItem
+ icon="solar:layers-minimalistic-bold"
+ label={`Agrupar (${selectedIds.length})`}
+ onClick={() => {
+ onGroup();
+ onClose();
+ }}
+ />
+ )}
+ {canUngroup && onUngroup && (
+ <CtxMenuItem
+ icon="solar:layers-bold"
+ label="Desagrupar"
+ onClick={() => {
+ onUngroup();
+ onClose();
+ }}
+ />
+ )}
+ {(canGroup || canUngroup) && <div className="my-1 h-px bg-white/6" />}
+ <CtxMenuItem
+ icon="solar:trash-bin-trash-bold"
+ label={`Eliminar ${selectedIds.length} capas`}
+ onClick={() => {
+ onDeleteSelected();
+ onClose();
+ }}
+ danger
+ />
+ </>
+ )}
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/LayersPanel.tsx b/app/components/ui/editor/LayersPanel.tsx
new file mode 100644
index 0000000..1b615ef
--- /dev/null
+++ b/app/components/ui/editor/LayersPanel.tsx
@@ -0,0 +1,801 @@
+"use client";
+
+import { useState, useEffect, useRef, useCallback, useMemo } from "react";
+import { createPortal } from "react-dom";
+import { Icon } from "@iconify/react";
+import type { CanvasElement } from "@/types/canvas-elements.types";
+import { LayersPanelProps, CtxMenuState, TYPE_ICON, PointerDragState } from "@/types/layers.types";
+import { buildLayerNames, buildGroupNumbers } from "@/lib/layers.utils";
+import ContextMenu from "./ContextMenu";
+import { useTranslations } from "next-intl";
+import { TooltipAction } from "@/components/ui/tooltip-action";
+
+export function LayersPanel({
+ elements,
+ selectedId,
+ selectedMultiIds,
+ onSelect,
+ onMultiSelect,
+ onDelete,
+ onReorder,
+ onToggleVisible,
+ onToggleLock,
+ onBringToFront,
+ onSendToBack,
+ onGroup,
+ onUngroup,
+ onSetGroupId,
+ toolbar,
+}: LayersPanelProps) {
+ const t = useTranslations("editor")
+ const [isOpen, setIsOpen] = useState(true);
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const selectedIdsRef = useRef<string[]>([]);
+ selectedIdsRef.current = selectedIds;
+ const [ctxMenu, setCtxMenu] = useState<CtxMenuState | null>(null);
+ const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set());
+
+ const [pointerDrag, setPointerDrag] = useState<PointerDragState | null>(null);
+ const pointerDragRef = useRef<PointerDragState | null>(null);
+ pointerDragRef.current = pointerDrag;
+
+ const listRef = useRef<HTMLDivElement>(null);
+ const rowRefs = useRef<Map<string, HTMLDivElement>>(new Map());
+ const isDraggingRef = useRef(false);
+ const ignoreSyncUntilRef = useRef<number>(0);
+
+ const syncKey = elements.map((e) => e.id + ":" + e.zIndex + ":" + (e.groupId ?? "")).join(",");
+
+ const [displayOrder, setDisplayOrder] = useState<string[]>(() =>
+ [...elements].sort((a, b) => b.zIndex - a.zIndex).map((e) => e.id)
+ );
+
+ useEffect(() => {
+ if (isDraggingRef.current) return;
+ if (Date.now() < ignoreSyncUntilRef.current) return;
+
+ const sortedIncoming = [...elements]
+ .sort((a, b) => b.zIndex - a.zIndex)
+ .map((e) => e.id);
+ setDisplayOrder(sortedIncoming);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [syncKey]);
+
+ useEffect(() => {
+ if (selectedId) {
+ setSelectedIds((prev) => (prev.includes(selectedId) ? prev : [selectedId]));
+ } else {
+ setSelectedIds([]);
+ }
+ }, [selectedId]);
+
+ const multiIdsKey = selectedMultiIds ? selectedMultiIds.join(",") : "";
+ useEffect(() => {
+ if (selectedMultiIds && selectedMultiIds.length > 0) {
+ setSelectedIds(selectedMultiIds);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [multiIdsKey]);
+
+ useEffect(() => {
+ if (!ctxMenu) return;
+ const close = (e: PointerEvent) => {
+ if ((e.target as HTMLElement).closest("[data-ctx-menu]")) return;
+ setCtxMenu(null);
+ };
+ window.addEventListener("pointerdown", close);
+ return () => window.removeEventListener("pointerdown", close);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [!!ctxMenu]);
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key !== "Delete" && e.key !== "Backspace") return;
+ const tag = (e.target as HTMLElement).tagName;
+ if (tag === "INPUT" || tag === "TEXTAREA" || (e.target as HTMLElement).isContentEditable)
+ return;
+
+ const ids = selectedIdsRef.current;
+ if (ids.length > 0) {
+ e.stopPropagation();
+ e.preventDefault();
+ onDelete(ids.length === 1 ? ids[0] : [...ids]);
+ setSelectedIds([]);
+ onSelect(null);
+ }
+ };
+ window.addEventListener("keydown", handleKeyDown, true);
+ return () => window.removeEventListener("keydown", handleKeyDown, true);
+ }, [onDelete, onSelect]);
+
+ const handleRowClick = useCallback(
+ (e: React.MouseEvent, id: string) => {
+ if (e.shiftKey) {
+ const prev = selectedIdsRef.current;
+ const next = prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id];
+ setSelectedIds(next);
+ onMultiSelect?.(next);
+ } else {
+ setSelectedIds([id]);
+ onSelect(id);
+ onMultiSelect?.([id]);
+ }
+ },
+ [onSelect, onMultiSelect]
+ );
+
+ const elementsById = useMemo(
+ () => Object.fromEntries(elements.map((e) => [e.id, e])),
+ [elements]
+ );
+ const layerNames = useMemo(() => buildLayerNames(elements), [elements]);
+ const groupNumbers = useMemo(() => buildGroupNumbers(elements), [elements]);
+
+ type VisualRow =
+ | { kind: "element"; id: string }
+ | { kind: "group"; groupId: string };
+
+ const visualRows = useMemo<VisualRow[]>(() => {
+ const renderedGroupIds = new Set<string>();
+ const rows: VisualRow[] = [];
+
+ for (const id of displayOrder) {
+ const el = elementsById[id];
+ if (!el) continue;
+
+ if (el.groupId) {
+ if (!renderedGroupIds.has(el.groupId)) {
+ renderedGroupIds.add(el.groupId);
+ rows.push({ kind: "group", groupId: el.groupId });
+
+ if (!collapsedGroups.has(el.groupId)) {
+ const members = displayOrder
+ .map((mid) => elementsById[mid])
+ .filter((m): m is CanvasElement => !!m && m.groupId === el.groupId);
+ members.forEach((m) => rows.push({ kind: "element", id: m.id }));
+ }
+ }
+ } else {
+ rows.push({ kind: "element", id: el.id });
+ }
+ }
+ return rows;
+ }, [displayOrder, elementsById, collapsedGroups]);
+
+ useEffect(() => {
+ if (!pointerDrag) return;
+ const MOVE_THRESHOLD = 5;
+
+ const onMove = (e: MouseEvent) => {
+ const drag = pointerDragRef.current;
+ if (!drag) return;
+
+ const moved = Math.abs(e.clientY - drag.startY) > MOVE_THRESHOLD;
+ if (!moved && !drag.active) return;
+
+ let dropIdx = drag.dropIndex;
+ let bestDist = Infinity;
+ let intoGroupId: string | null = null;
+ const INTO_ZONE = 0.30;
+
+ visualRows.forEach((row, i) => {
+ const key = row.kind === "element" ? row.id : `group:${row.groupId}`;
+ if (key === drag.id) return;
+ const el = rowRefs.current.get(key);
+ if (!el) return;
+ const rect = el.getBoundingClientRect();
+
+ if (row.kind === "group" && !drag.isGroup) {
+ const midTop = rect.top + rect.height * INTO_ZONE;
+ const midBot = rect.bottom - rect.height * INTO_ZONE;
+ if (e.clientY >= midTop && e.clientY <= midBot) {
+ const dist = Math.abs(e.clientY - (rect.top + rect.height / 2));
+ if (dist < bestDist) {
+ bestDist = dist;
+ intoGroupId = row.groupId;
+ dropIdx = i;
+ }
+ return;
+ }
+ }
+
+ const topDist = Math.abs(e.clientY - rect.top);
+ if (topDist < bestDist) {
+ bestDist = topDist;
+ dropIdx = i;
+ intoGroupId = null;
+ }
+ if (i === visualRows.length - 1) {
+ const bottomDist = Math.abs(e.clientY - rect.bottom);
+ if (bottomDist < bestDist) {
+ bestDist = bottomDist;
+ dropIdx = i + 1;
+ intoGroupId = null;
+ }
+ }
+ });
+
+ const updated: PointerDragState = {
+ ...drag,
+ x: e.clientX,
+ y: e.clientY,
+ dropIndex: dropIdx,
+ dropTargetGroupId: intoGroupId,
+ active: true,
+ };
+ pointerDragRef.current = updated;
+ setPointerDrag(updated);
+ };
+
+ const onUp = () => {
+ const drag = pointerDragRef.current;
+ if (drag?.active) {
+ applyReorder(drag);
+ }
+ isDraggingRef.current = false;
+ setPointerDrag(null);
+ };
+
+ window.addEventListener("mousemove", onMove);
+ window.addEventListener("mouseup", onUp);
+
+ return () => {
+ window.removeEventListener("mousemove", onMove);
+ window.removeEventListener("mouseup", onUp);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [!!pointerDrag, visualRows]);
+
+ const applyReorder = useCallback(
+ (drag: PointerDragState) => {
+ const { id, isGroup, dropIndex, dropTargetGroupId } = drag;
+
+ let movingIds: string[];
+ if (isGroup) {
+ const gid = id.replace("group:", "");
+ movingIds = displayOrder.filter((did) => elementsById[did]?.groupId === gid);
+ } else {
+ movingIds = [id];
+ }
+ const movingSet = new Set(movingIds);
+
+ if (dropTargetGroupId && !isGroup && onSetGroupId) {
+ const dragged = elementsById[id];
+ if (dragged && dragged.groupId !== dropTargetGroupId) {
+ ignoreSyncUntilRef.current = Date.now() + 1000;
+ onSetGroupId(id, dropTargetGroupId);
+ }
+ return;
+ }
+
+ let pendingGroupChange: { id: string; groupId: string | undefined } | null = null;
+ if (!isGroup && onSetGroupId) {
+ const dragged = elementsById[id];
+ if (dragged?.groupId) {
+ const anchorVRow = visualRows[dropIndex];
+ let targetGid: string | undefined;
+ if (anchorVRow?.kind === "element") {
+ targetGid = elementsById[anchorVRow.id]?.groupId;
+ }
+ if (targetGid !== dragged.groupId) {
+ pendingGroupChange = { id, groupId: targetGid };
+ }
+ }
+ }
+
+ const isRowDragged = (r: VisualRow) => {
+ if (r.kind === "element") return movingSet.has(r.id);
+ if (r.kind === "group") {
+ const firstMember = displayOrder.find(
+ (did) => elementsById[did]?.groupId === r.groupId
+ );
+ return firstMember ? movingSet.has(firstMember) : false;
+ }
+ return false;
+ };
+
+ let nonDraggedCount = 0;
+ for (let i = 0; i < dropIndex; i++) {
+ if (!isRowDragged(visualRows[i])) nonDraggedCount++;
+ }
+
+ const without = displayOrder.filter((did) => !movingSet.has(did));
+ const visualRowsWithout = visualRows.filter((r) => !isRowDragged(r));
+ const anchorRow = visualRowsWithout[nonDraggedCount];
+ let insertAt = without.length;
+
+ if (anchorRow) {
+ if (anchorRow.kind === "element") {
+ insertAt = without.indexOf(anchorRow.id);
+ } else if (anchorRow.kind === "group") {
+ const firstMember = without.find(
+ (did) => elementsById[did]?.groupId === anchorRow.groupId
+ );
+ if (firstMember) insertAt = without.indexOf(firstMember);
+ }
+ }
+
+ const next = [...without.slice(0, insertAt), ...movingIds, ...without.slice(insertAt)];
+ const changed = next.some((val, i) => val !== displayOrder[i]);
+
+ if (pendingGroupChange) {
+ ignoreSyncUntilRef.current = Date.now() + 1500;
+ onSetGroupId!(pendingGroupChange.id, pendingGroupChange.groupId);
+ }
+ if (changed) {
+ ignoreSyncUntilRef.current = Math.max(ignoreSyncUntilRef.current, Date.now() + 1500);
+ setDisplayOrder(next);
+ onReorder(next);
+ }
+ },
+ [displayOrder, elementsById, visualRows, onReorder, onSetGroupId]
+ );
+
+ const startPointerDrag = useCallback(
+ (e: React.MouseEvent, id: string, isGroup: boolean) => {
+ if (e.button !== 0) return;
+ const vIdx = visualRows.findIndex((r) =>
+ r.kind === "element" ? r.id === id : `group:${r.groupId}` === id
+ );
+ isDraggingRef.current = true;
+ const drag: PointerDragState = {
+ id, isGroup,
+ x: e.clientX, y: e.clientY, startY: e.clientY,
+ dropIndex: vIdx >= 0 ? vIdx : 0,
+ dropTargetGroupId: null,
+ active: false,
+ };
+ pointerDragRef.current = drag;
+ setPointerDrag(drag);
+ e.preventDefault();
+ },
+ [visualRows]
+ );
+
+ const ctxId = ctxMenu?.id ?? null;
+ const handleCtxBringToFront = useCallback(() => {
+ if (ctxId) onBringToFront(ctxId);
+ setCtxMenu(null);
+ }, [ctxId, onBringToFront]);
+
+ const handleCtxSendToBack = useCallback(() => {
+ if (ctxId) onSendToBack(ctxId);
+ setCtxMenu(null);
+ }, [ctxId, onSendToBack]);
+
+ const handleCtxDelete = useCallback(() => {
+ if (ctxId) {
+ onDelete(ctxId);
+ setSelectedIds((p) => p.filter((x) => x !== ctxId));
+ }
+ setCtxMenu(null);
+ }, [ctxId, onDelete]);
+
+ const handleCtxDeleteSelected = useCallback(() => {
+ onDelete([...selectedIds]);
+ setSelectedIds([]);
+ setCtxMenu(null);
+ }, [selectedIds, onDelete]);
+
+ const renderLayerRow = useCallback(
+ (el: CanvasElement, isGroupChild: boolean, vIdx: number) => {
+ const id = el.id;
+ const isSelected = selectedIds.includes(id);
+ const isDraggingThis = pointerDrag?.active && pointerDrag.id === id;
+ const isDropTarget = pointerDrag?.active && pointerDrag.dropIndex === vIdx;
+
+ const isVisible = el.visible !== false;
+ const isLocked = el.locked === true;
+
+ return (
+ <div
+ key={id}
+ ref={(node) => {
+ if (node) rowRefs.current.set(id, node);
+ else rowRefs.current.delete(id);
+ }}
+ onMouseDown={(e) => {
+ if (isLocked) return;
+ if ((e.target as HTMLElement).closest("button")) return;
+ startPointerDrag(e, id, false);
+ }}
+ onClick={(e) => {
+ if (pointerDragRef.current?.active) return;
+ handleRowClick(e, id);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ if (!selectedIds.includes(id)) {
+ setSelectedIds([id]);
+ onSelect(id);
+ }
+ setCtxMenu({ x: e.clientX, y: e.clientY, id });
+ }}
+ data-layer-row={id}
+ className={[
+ "group relative flex items-center gap-1.5 h-7 rounded-md cursor-pointer select-none transition-all duration-100",
+ isGroupChild ? "pl-5 pr-2" : "px-2",
+ isDraggingThis ? "opacity-30 pointer-events-none" : "",
+ isSelected
+ ? "bg-[#00A3FF]/15 text-white"
+ : "text-neutral-400 hover:bg-white/5 hover:text-neutral-200",
+ ].join(" ")}
+ >
+ {isDropTarget && (
+ <div className="absolute -top-px left-0 right-0 h-0.5 rounded-full bg-blue-400 pointer-events-none z-10" />
+ )}
+ <div
+ className={`shrink-0 cursor-grab active:cursor-grabbing transition-opacity opacity-0 group-hover:opacity-100 ${isLocked ? "invisible" : ""
+ }`}
+ >
+ <Icon icon="icon-park-outline:drag" className="size-3 text-neutral-500" />
+ </div>
+ <Icon
+ icon={TYPE_ICON[el.type]}
+ className={`size-3.5 shrink-0 ${isSelected ? "text-[#00A3FF]" : "text-neutral-500"}`}
+ />
+ <span
+ className={`flex-1 text-[11px] truncate ${isVisible ? "" : "opacity-40 line-through"
+ }`}
+ >
+ {layerNames.get(id) ?? id}
+ </span>
+ <div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity">
+ <TooltipAction label={isVisible ? t("layerPanel.tooltips.hide") : t("layerPanel.tooltips.show")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleVisible(id, !isVisible);
+ }}
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-white/10"
+ >
+ <Icon
+ icon={isVisible ? "solar:eye-bold" : "solar:eye-closed-bold"}
+ className="size-3"
+ />
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label={isLocked ? t("layerPanel.tooltips.unlock") : t("layerPanel.tooltips.lock")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleLock(id, !isLocked);
+ }}
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-white/10"
+ >
+ <Icon
+ icon={isLocked ? "gravity-ui:lock-fill" : "icon-park-solid:unlock"}
+ className="size-3"
+ />
+ </button>
+ </TooltipAction>
+
+ <TooltipAction label={t("layerPanel.tooltips.delete")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(id);
+ setSelectedIds((p) => p.filter((x) => x !== id));
+ }}
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-red-500/20"
+ >
+ <Icon icon="solar:trash-bin-trash-bold" className="size-3 hover:text-red-400" />
+ </button>
+ </TooltipAction>
+ </div>
+ {!isVisible && (
+ <Icon
+ icon="solar:eye-closed-bold"
+ className="size-3 text-neutral-500 shrink-0 group-hover:hidden"
+ />
+ )}
+ {isLocked && (
+ <Icon
+ icon="solar:lock-bold"
+ className="size-3 text-neutral-500 shrink-0 group-hover:hidden"
+ />
+ )}
+ </div>
+ );
+ },
+ [
+ selectedIds,
+ pointerDrag,
+ layerNames,
+ startPointerDrag,
+ handleRowClick,
+ onSelect,
+ onToggleVisible,
+ onToggleLock,
+ onDelete,
+ t
+ ]
+ );
+
+ if (!isOpen) {
+ return (
+ <div className="flex flex-col items-center py-2 px-1 bg-[#111113] border-l border-white/6 gap-1">
+ <TooltipAction label={t("layerPanel.tooltips.showLayers")}>
+ <button
+ onClick={() => setIsOpen(true)}
+ className="flex items-center justify-center w-6 h-6 rounded hover:bg-white/10 transition-colors text-neutral-500 hover:text-neutral-200"
+ >
+ <Icon icon="solar:layers-minimalistic-bold" className="size-3.5" />
+ </button>
+ </TooltipAction>
+ <span className="text-[9px] text-neutral-500 [writing-mode:vertical-rl] rotate-180 mt-1 tracking-widest uppercase">
+ {t("layerPanel.layers")}
+ </span>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className="flex flex-col bg-[#111113] border-l border-white/6 select-none h-full"
+ style={{ width: toolbar ? "auto" : "210px", minWidth: "210px" }}
+ >
+ {toolbar && <div className="shrink-0 border-b border-white/6">{toolbar}</div>}
+ <div className="flex items-center justify-between px-3 py-2 border-b border-white/6 shrink-0">
+ <span className="text-[11px] font-semibold text-neutral-300 tracking-wide uppercase">
+ {t("layerPanel.layers")}
+ </span>
+ <TooltipAction label={t("layerPanel.tooltips.hideLayers")}>
+ <button
+ onClick={() => setIsOpen(false)}
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-white/10 transition-colors text-neutral-500 hover:text-neutral-200"
+ >
+ <Icon icon="solar:sidebar-minimalistic-bold" className="size-3.5" />
+ </button>
+ </TooltipAction>
+ </div>
+ <div
+ ref={listRef}
+ className="flex-1 overflow-y-auto overflow-x-hidden py-1 px-1 relative"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) {
+ onSelect(null);
+ setSelectedIds([]);
+ }
+ }}
+ >
+ {displayOrder.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-16 gap-2 text-neutral-500">
+ <Icon icon="solar:layers-minimalistic-bold" className="size-5" />
+ <span className="text-[10px]">{t("layerPanel.noLayers")}</span>
+ </div>
+ ) : (
+ (() => {
+ const renderedGroupIds = new Set<string>();
+ const rows: React.ReactNode[] = [];
+ let groupCounter = 0;
+ let vIdx = 0;
+ for (const id of displayOrder) {
+ const el = elementsById[id];
+ if (!el) continue;
+ if (el.groupId) {
+ if (renderedGroupIds.has(el.groupId)) {
+ continue;
+ } else {
+ renderedGroupIds.add(el.groupId);
+ groupCounter++;
+ const gid = el.groupId;
+ const groupKey = `group:${gid}`;
+ const groupMembers = displayOrder
+ .map((mid) => elementsById[mid])
+ .filter((e): e is CanvasElement => !!e && e.groupId === gid);
+ const isCollapsed = collapsedGroups.has(gid);
+ const thisGroupNum = groupNumbers.get(gid) ?? groupCounter;
+ const isDraggingThisGroup = pointerDrag?.active && pointerDrag.id === groupKey;
+ const currentGroupVIdx = vIdx++;
+ const isGroupDropTarget =
+ pointerDrag?.active && pointerDrag.dropIndex === currentGroupVIdx;
+
+ rows.push(
+ <div
+ key={`group-${gid}`}
+ ref={(node) => {
+ if (node) rowRefs.current.set(groupKey, node);
+ else rowRefs.current.delete(groupKey);
+ }}
+ onMouseDown={(e) => {
+ if ((e.target as HTMLElement).closest("button")) return;
+ startPointerDrag(e, groupKey, true);
+ }}
+ onClick={() => {
+ if (pointerDragRef.current?.active) return;
+ const memberIds = groupMembers.map((m) => m.id);
+ setSelectedIds(memberIds);
+ onMultiSelect?.(memberIds);
+ if (memberIds.length > 0) onSelect(memberIds[0]);
+ }}
+ data-layer-row={groupKey}
+ className={[
+ "group relative flex items-center gap-1.5 h-7 px-2 rounded-md cursor-pointer select-none transition-all duration-100 text-neutral-400 hover:bg-white/5 hover:text-neutral-200",
+ isDraggingThisGroup ? "opacity-30 pointer-events-none" : "",
+ pointerDrag?.active && pointerDrag.dropTargetGroupId === gid
+ ? "ring-1 ring-blue-400 bg-blue-400/10"
+ : "",
+ ].join(" ")}
+ >
+ {isGroupDropTarget && !pointerDrag?.dropTargetGroupId && (
+ <div className="absolute -top-px left-0 right-0 h-0.5 rounded-full bg-blue-400 pointer-events-none z-10" />
+ )}
+ <div className="shrink-0 cursor-grab active:cursor-grabbing transition-opacity opacity-0 group-hover:opacity-100">
+ <Icon icon="icon-park-outline:drag" className="size-3 text-neutral-500" />
+ </div>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ setCollapsedGroups((prev) => {
+ const next = new Set(prev);
+ if (next.has(gid)) next.delete(gid);
+ else next.add(gid);
+ return next;
+ });
+ }}
+ className="flex items-center justify-center w-3.5 h-3.5 shrink-0"
+ >
+ <Icon
+ icon={isCollapsed ? "solar:alt-arrow-right-bold" : "solar:alt-arrow-down-bold"}
+ className="size-3 text-neutral-500"
+ />
+ </button>
+ <Icon icon="solar:folder-bold" className="size-3.5 shrink-0 text-yellow-500/70" />
+ <span className="flex-1 text-[11px] truncate">
+ {t("layerPanel.group")} {thisGroupNum}
+ </span>
+ <div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity">
+ <TooltipAction label={t("layerPanel.tooltips.deleteGroup")}>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onDelete(groupMembers.map((m) => m.id));
+ setSelectedIds((p) => p.filter((x) => !groupMembers.find((m) => m.id === x)));
+ }}
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-red-500/20"
+ >
+ <Icon icon="solar:trash-bin-trash-bold" className="size-3 hover:text-red-400" />
+ </button>
+ </TooltipAction>
+ </div>
+ <span className="text-[9px] text-neutral-500 group-hover:hidden">
+ {groupMembers.length}
+ </span>
+ </div>
+ );
+ if (!isCollapsed) {
+ for (const member of groupMembers) {
+ const childVIdx = vIdx++;
+ rows.push(renderLayerRow(member, true, childVIdx));
+ }
+ }
+ }
+ } else {
+ const currentVIdx = vIdx++;
+ rows.push(renderLayerRow(el, false, currentVIdx));
+ }
+ }
+ if (pointerDrag?.active && pointerDrag.dropIndex === visualRows.length) {
+ rows.push(
+ <div key="drop-indicator-bottom" className="relative">
+ <div className="absolute top-0 left-0 right-0 h-0.5 rounded-full bg-blue-400 pointer-events-none z-10" />
+ </div>
+ );
+ }
+ return rows;
+ })()
+ )}
+ </div>
+
+ {selectedIds.length > 1 && (
+ <div className="shrink-0 border-t border-white/6 px-2 py-1.5 flex items-center gap-1">
+ <span className="flex-1 text-[10px] text-neutral-500">
+ {selectedIds.length} {t("layerPanel.selected")}
+ </span>
+ {onGroup && (
+ <TooltipAction label={t("layerPanel.tooltips.groupSelected")}>
+ <button
+ onClick={() => onGroup(selectedIds)}
+ className="flex items-center gap-1 px-1.5 py-0.5 text-[10px] text-neutral-400 hover:text-white hover:bg-white/10 rounded transition-colors"
+ >
+ <Icon icon="solar:layers-minimalistic-bold" className="size-3" /> {t("layerPanel.groupAction")}
+ </button>
+ </TooltipAction>
+ )}
+ {onUngroup && selectedIds.some((id) => elementsById[id]?.groupId) && (
+ <TooltipAction label={t("layerPanel.tooltips.ungroup")}>
+ <button
+ onClick={() => onUngroup(selectedIds)}
+ className="flex items-center gap-1 px-1.5 py-0.5 text-[10px] text-neutral-400 hover:text-white hover:bg-white/10 rounded transition-colors"
+ >
+ <Icon icon="solar:layers-bold" className="size-3" /> {t("layerPanel.ungroupAction")}
+ </button>
+ </TooltipAction>
+ )}
+ </div>
+ )}
+
+ {ctxMenu &&
+ (() => {
+ const allInSameGroup =
+ selectedIds.length > 1 &&
+ selectedIds.every((id) => {
+ const el = elementsById[id];
+ return el?.groupId && el.groupId === elementsById[selectedIds[0]]?.groupId;
+ });
+ const anyHasGroup = selectedIds.some((id) => elementsById[id]?.groupId);
+
+ return (
+ <ContextMenu
+ x={ctxMenu.x}
+ y={ctxMenu.y}
+ id={ctxMenu.id}
+ selectedIds={selectedIds}
+ canGroup={selectedIds.length > 1 && !allInSameGroup}
+ canUngroup={selectedIds.length > 1 && anyHasGroup}
+ onBringToFront={handleCtxBringToFront}
+ onSendToBack={handleCtxSendToBack}
+ onDelete={handleCtxDelete}
+ onDeleteSelected={handleCtxDeleteSelected}
+ onGroup={
+ onGroup
+ ? () => {
+ onGroup(selectedIds);
+ setCtxMenu(null);
+ }
+ : undefined
+ }
+ onUngroup={
+ onUngroup
+ ? () => {
+ onUngroup(selectedIds);
+ setCtxMenu(null);
+ }
+ : undefined
+ }
+ onClose={() => setCtxMenu(null)}
+ />
+ );
+ })()}
+
+ {pointerDrag?.active &&
+ typeof document !== "undefined" &&
+ (() => {
+ let ghostLabel = "";
+ let ghostIcon = "solar:layers-minimalistic-bold";
+ if (pointerDrag.isGroup) {
+ const gid = pointerDrag.id.replace("group:", "");
+ const gNum = groupNumbers.get(gid);
+ ghostLabel = `${t("layerPanel.group")} ${gNum ?? ""}`;
+ ghostIcon = "solar:folder-bold";
+ } else {
+ const dragEl = elementsById[pointerDrag.id];
+ if (dragEl) {
+ ghostLabel = layerNames.get(pointerDrag.id) ?? pointerDrag.id;
+ ghostIcon = TYPE_ICON[dragEl.type];
+ }
+ }
+
+ return createPortal(
+ <div
+ className="fixed z-99999 pointer-events-none"
+ style={{
+ left: pointerDrag.x + 14,
+ top: pointerDrag.y - 14,
+ }}
+ >
+ <div className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-[#1c1c1f]/90 border border-white/10 shadow-2xl backdrop-blur-sm">
+ <Icon icon={ghostIcon} className="size-3.5 text-[#00A3FF]" />
+ <span className="text-[11px] text-white font-medium max-w-30 truncate">
+ {ghostLabel}
+ </span>
+ </div>
+ </div>,
+ document.body
+ );
+ })()}
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 29f05ff..4ca3454 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -21,6 +21,8 @@ import { RotationHandleIcon } from "@/components/ui/RotationHandleIcon";
import { CanvasElementsLayer } from "./CanvasElementsLayer";
import { EditorHoverTooltip } from "./EditorHoverTooltip";
import DropImage from "@/components/ui/DropImage";
+import { LayersPanel } from "./LayersPanel";
+import { Icon } from "@iconify/react";
export type { VideoCanvasHandle, VideoCanvasProps };
export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(function VideoCanvas({
@@ -64,11 +66,13 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
selectedElementId = null,
onElementUpdate,
onElementSelect,
+ onElementDelete,
cameraUrl = null,
cameraConfig = null,
onCameraConfigChange,
onCameraClick,
videoMaskConfig,
+ layersPanelToolbar,
}, ref) {
const wallpaperUrl = getWallpaperUrl(selectedWallpaper);
@@ -235,6 +239,11 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const [isDraggingElement, setIsDraggingElement] = useState(false);
const [isDraggingElementRotation, setIsDraggingElementRotation] = useState(false);
const elementDragStart = useRef({ x: 0, y: 0, initialX: 0, initialY: 0, initialRotation: 0 });
+ // Positions of ALL selected elements captured once at drag-start (stable ref, never updated during drag)
+ const multiDragStartRef = useRef<Map<string, { x: number; y: number }>>(new Map());
+ // When clicking a multi-selected element, track potential collapse to single (cleared on actual drag)
+ const pendingCollapseRef = useRef<string | null>(null);
+ const wasDragRef = useRef(false);
// Smart guides state for element alignment
const [alignmentGuides, setAlignmentGuides] = useState<{
@@ -262,6 +271,20 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const [isDraggingOver, setIsDraggingOver] = useState(false);
const canvasContainerRef = useRef<HTMLDivElement>(null);
+ // Multi-select and canvas right-click context menu
+ const [canvasSelectedIds, setCanvasSelectedIds] = useState<string[]>([]);
+ const [canvasCtxMenu, setCanvasCtxMenu] = useState<{ x: number; y: number } | null>(null);
+
+ useEffect(() => {
+ if (!canvasCtxMenu) return;
+ const close = (e: PointerEvent) => {
+ if ((e.target as HTMLElement).closest("[data-canvas-ctx-menu]")) return;
+ setCanvasCtxMenu(null);
+ };
+ window.addEventListener("pointerdown", close);
+ return () => window.removeEventListener("pointerdown", close);
+ }, [!!canvasCtxMenu]); // eslint-disable-line react-hooks/exhaustive-deps
+
// Calculate mask styles — selects video or image mask based on mediaType
const maskStyles = useMemo(() => {
const config = mediaType === "video" ? videoMaskConfig : imageMaskConfig;
@@ -498,6 +521,18 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
};
}, [videoRef, cameraUrl]);
+ // Capture start positions of all selected elements ONCE when drag begins
+ useEffect(() => {
+ if (!isDraggingElement) return;
+ const snapshot = new Map<string, { x: number; y: number }>();
+ canvasSelectedIds.forEach((id) => {
+ const el = canvasElements.find((e) => e.id === id);
+ if (el) snapshot.set(id, { x: el.x, y: el.y });
+ });
+ multiDragStartRef.current = snapshot;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isDraggingElement]); // intentionally only fires when drag state changes
+
// Canvas elements drag & drop handlers
useEffect(() => {
if (!isDraggingElement && !isDraggingElementRotation) return;
@@ -528,40 +563,65 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const rect = container.getBoundingClientRect();
const deltaX = e.clientX - elementDragStart.current.x;
const deltaY = e.clientY - elementDragStart.current.y;
+
+ // Only commit to drag after 3px threshold — avoids jitter on click
+ if (!wasDragRef.current && Math.abs(deltaX) < 3 && Math.abs(deltaY) < 3) return;
+ wasDragRef.current = true;
+ pendingCollapseRef.current = null; // confirmed drag — cancel pending click-collapse
+
const percentX = (deltaX / rect.width) * 100;
const percentY = (deltaY / rect.height) * 100;
- let newX = Math.max(0, Math.min(100, elementDragStart.current.initialX + percentX));
- let newY = Math.max(0, Math.min(100, elementDragStart.current.initialY + percentY));
+ if (canvasSelectedIds.length > 1) {
+ // Multi-element drag: move all selected elements by the same delta
+ // Use the stable ref (captured once at drag start) to avoid cumulative drift
+ multiDragStartRef.current.forEach((startPos, id) => {
+ const el = canvasElements.find(e => e.id === id);
+ if (!el || el.locked) return;
+ const newX = Math.max(0, Math.min(100, startPos.x + percentX));
+ const newY = Math.max(0, Math.min(100, startPos.y + percentY));
+ onElementUpdate(id, { x: newX, y: newY });
+ });
+ } else {
+ let newX = Math.max(0, Math.min(100, elementDragStart.current.initialX + percentX));
+ let newY = Math.max(0, Math.min(100, elementDragStart.current.initialY + percentY));
+
+ // Smart guides: snap to center (horizontal and vertical)
+ const SNAP_THRESHOLD = 2;
+ const centerX = 50;
+ const centerY = 50;
+ const guides: { vertical: number[]; horizontal: number[] } = { vertical: [], horizontal: [] };
+
+ // Check horizontal center alignment
+ if (Math.abs(newX - centerX) < SNAP_THRESHOLD) {
+ newX = centerX;
+ guides.vertical.push(centerX);
+ }
- // Smart guides: snap to center (horizontal and vertical)
- const SNAP_THRESHOLD = 2;
- const centerX = 50;
- const centerY = 50;
- const guides: { vertical: number[]; horizontal: number[] } = { vertical: [], horizontal: [] };
+ // Check vertical center alignment
+ if (Math.abs(newY - centerY) < SNAP_THRESHOLD) {
+ newY = centerY;
+ guides.horizontal.push(centerY);
+ }
- // Check horizontal center alignment
- if (Math.abs(newX - centerX) < SNAP_THRESHOLD) {
- newX = centerX;
- guides.vertical.push(centerX);
- }
+ setAlignmentGuides(guides);
- // Check vertical center alignment
- if (Math.abs(newY - centerY) < SNAP_THRESHOLD) {
- newY = centerY;
- guides.horizontal.push(centerY);
+ onElementUpdate(selectedElementId, {
+ x: newX,
+ y: newY,
+ });
}
-
- setAlignmentGuides(guides);
-
- onElementUpdate(selectedElementId, {
- x: newX,
- y: newY,
- });
}
};
const handleMouseUp = () => {
+ // If the mouse barely moved: treat as a click → collapse multi-selection to the clicked element
+ if (pendingCollapseRef.current && !wasDragRef.current) {
+ const id = pendingCollapseRef.current;
+ setCanvasSelectedIds([id]);
+ }
+ pendingCollapseRef.current = null;
+ wasDragRef.current = false;
setIsDraggingElement(false);
setIsDraggingElementRotation(false);
setAlignmentGuides({ vertical: [], horizontal: [] });
@@ -573,7 +633,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
- }, [isDraggingElement, isDraggingElementRotation, selectedElementId, canvasElements, onElementUpdate]);
+ }, [isDraggingElement, isDraggingElementRotation, selectedElementId, canvasElements, canvasSelectedIds, onElementUpdate]);
// Image zoom with mouse wheel (photo mode only)
useEffect(() => {
@@ -606,6 +666,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
// Drag & drop handlers for images
const handleDragOver = (e: React.DragEvent) => {
if (mediaType !== "image" || !onImageDrop) return;
+ if (!e.dataTransfer.types.includes("Files")) return;
e.preventDefault();
e.stopPropagation();
@@ -622,6 +683,7 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
const handleDrop = (e: React.DragEvent) => {
if (mediaType !== "image" || !onImageDrop) return;
+ if (!e.dataTransfer.types.includes("Files")) return;
e.preventDefault();
e.stopPropagation();
@@ -1053,9 +1115,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
));
if (hasVideoMask) {
- // Draw video+mockup onto an offscreen layer (no zoom) then apply the mask,
- // and finally composite back to the main canvas WITH zoom applied.
- // This mirrors the CSS behaviour: mask is on the element, zoom is on the outer wrapper.
const videoLayer = document.createElement('canvas');
videoLayer.width = canvasWidth;
videoLayer.height = canvasHeight;
@@ -1065,7 +1124,6 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
vlCtx.imageSmoothingQuality = 'high';
drawMockupAndMedia(vlCtx, containerX, containerY, containerWidth, containerHeight, video!, false);
- // Apply each gradient mask using destination-in (= CSS maskComposite: intersect)
vlCtx.globalCompositeOperation = 'destination-in';
const vm = videoMaskConfig!;
const [cX, cY, cW, cH] = [containerX, containerY, containerWidth, containerHeight];
@@ -1256,6 +1314,16 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
getExportCanvas: () => exportCanvasRef.current,
drawFrame,
getPreviewContainer: () => previewContainerRef.current,
+ clearAllSelection: () => {
+ const prev = { multiIds: [...canvasSelectedIds], videoSelected: isVideoSelected };
+ setCanvasSelectedIds([]);
+ setIsVideoSelected(false);
+ return prev;
+ },
+ restoreSelectionState: (state: { multiIds: string[]; videoSelected: boolean }) => {
+ setCanvasSelectedIds(state.multiIds);
+ setIsVideoSelected(state.videoSelected);
+ },
}));
return (
@@ -1264,12 +1332,108 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
+ onContextMenu={(e) => {
+ if (canvasElements.length === 0) return;
+ const target = e.target as HTMLElement;
+ if (!target.closest('[data-canvas-element]')) return;
+ e.preventDefault();
+ setCanvasCtxMenu({ x: e.clientX, y: e.clientY });
+ }}
>
{mediaType === "image" && isDraggingOver && (
<DropImage />
-
)}
+ {canvasCtxMenu && (() => {
+ const ids = canvasSelectedIds.length > 0 ? canvasSelectedIds : (selectedElementId ? [selectedElementId] : []);
+ const isMulti = ids.length > 1;
+ const singleId = ids[0] ?? null;
+ return (
+ <div
+ data-canvas-ctx-menu
+ className="fixed z-[9999] bg-black border border-white/15 rounded-xl shadow-2xl py-1 min-w-45 overflow-hidden"
+ style={{ left: Math.min(canvasCtxMenu.x, window.innerWidth - 196), top: Math.min(canvasCtxMenu.y, window.innerHeight - 160) }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ {!isMulti && singleId && (
+ <>
+ <button
+ className="w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] text-neutral-300 hover:bg-white/6 transition-colors text-left"
+ onClick={() => {
+ const maxZ = Math.max(...canvasElements.map(e => e.zIndex), VIDEO_Z_INDEX);
+ if (onElementUpdate) onElementUpdate(singleId, { zIndex: maxZ + 1 });
+ setCanvasCtxMenu(null);
+ }}
+ >
+ <Icon icon="qlementine-icons:bring-to-front-16" className="size-3.5 shrink-0 opacity-70" />
+ Traer al frente
+ </button>
+ <button
+ className="w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] text-neutral-300 hover:bg-white/6 transition-colors text-left"
+ onClick={() => {
+ const el = canvasElements.find(e => e.id === singleId);
+ if (!el || !onElementUpdate) return;
+ if (el.zIndex >= VIDEO_Z_INDEX) {
+ onElementUpdate(singleId, { zIndex: VIDEO_Z_INDEX - 1 });
+ } else {
+ const minZ = Math.min(...canvasElements.map(e => e.zIndex));
+ onElementUpdate(singleId, { zIndex: Math.max(1, minZ - 1) });
+ }
+ setCanvasCtxMenu(null);
+ }}
+ >
+ <Icon icon="qlementine-icons:bring-to-back-16" className="size-3.5 shrink-0 opacity-70" />
+ Enviar atrás
+ </button>
+ <div className="my-1 h-px bg-white/6" />
+ </>
+ )}
+ {isMulti && (
+ <>
+ <button
+ className="w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] text-neutral-300 hover:bg-white/6 transition-colors text-left"
+ onClick={() => {
+ const newGroupId = crypto.randomUUID();
+ ids.forEach(id => { if (onElementUpdate) onElementUpdate(id, { groupId: newGroupId }); });
+ setCanvasCtxMenu(null);
+ }}
+ >
+ <Icon icon="solar:layers-minimalistic-bold" className="size-3.5 shrink-0 opacity-70" />
+ Agrupar ({ids.length})
+ </button>
+ <button
+ className="w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] text-neutral-300 hover:bg-white/6 transition-colors text-left"
+ onClick={() => {
+ const groupIds = new Set(
+ ids.map(id => canvasElements.find(e => e.id === id)?.groupId).filter(Boolean)
+ );
+ canvasElements
+ .filter(e => e.groupId && groupIds.has(e.groupId))
+ .forEach(e => { if (onElementUpdate) onElementUpdate(e.id, { groupId: undefined }); });
+ setCanvasCtxMenu(null);
+ }}
+ >
+ <Icon icon="solar:layers-bold" className="size-3.5 shrink-0 opacity-70" />
+ Desagrupar
+ </button>
+ <div className="my-1 h-px bg-white/6" />
+ </>
+ )}
+ <button
+ className="w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] text-red-400 hover:bg-red-500/10 transition-colors text-left"
+ onClick={() => {
+ if (onElementDelete) onElementDelete(ids.length === 1 ? ids[0] : [...ids]);
+ setCanvasSelectedIds([]);
+ setCanvasCtxMenu(null);
+ }}
+ >
+ <Icon icon="solar:trash-bin-trash-bold" className="size-3.5 shrink-0 opacity-70" />
+ {isMulti ? `Eliminar ${ids.length} elementos` : "Eliminar"}
+ </button>
+ </div>
+ );
+ })()}
+
<div className="absolute inset-0 pointer-events-none z-0"
style={{ backgroundImage: 'radial-gradient(rgb(39, 39, 42) 1px, transparent 1px)', backgroundSize: '24px 24px' }}>
</div>
@@ -1278,468 +1442,525 @@ export const VideoCanvas = forwardRef<VideoCanvasHandle, VideoCanvasProps>(funct
className="hidden"
/>
- {/* Preview visual - contenedor con tamaño dinámico según aspect ratio */}
- <div
- ref={previewContainerRef}
- className={`relative shrink-0 overflow-hidden transition-all duration-300 ${mediaType === "image" && imageUrl
- ? ""
- : "border border-white/20 rounded-xl"
- }`}
- style={{
- aspectRatio: getAspectRatioStyle(aspectRatio, customAspectRatio ?? undefined),
- maxWidth: getMaxWidth(aspectRatio, customAspectRatio ?? undefined),
- width: '100%',
- height: 'auto',
- maxHeight: '100%',
- containerType: 'size',
- }}
- onClick={(e) => {
- if (
- !(e.target as HTMLElement).closest('[data-canvas-element]') &&
- !(e.target as HTMLElement).closest('[data-camera-overlay]') &&
- !(e.target as HTMLElement).closest('[data-video-container]')
- ) {
- if (onElementSelect) onElementSelect(null);
- setIsVideoSelected(false);
- }
- }}
- >
- {/* Zoom container - applies zoom to entire composition (background + video) */}
- <div className="absolute inset-0"
- style={{
- perspective: mediaType === "image" && imageTransform && apply3DToBackground ? `${imageTransform.perspective || 600}px` : 'none',
- perspectiveOrigin: 'center center',
- }}
- >
- {!(mediaType === "image" && apply3DToBackground) && (
- <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
- <div className="absolute transition-all duration-200" style={{ inset: backgroundBlur > 0 ? `-${backgroundBlur}px` : '0', ...(shouldShowCustomColor && backgroundColorCss ? backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb') ? { backgroundColor: backgroundColorCss } : { backgroundImage: backgroundColorCss } : (shouldShowCustomImage || shouldShowUnsplashOverride) ? { backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : shouldShowWallpaper ? { backgroundImage: `url('${wallpaperUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : { backgroundColor: 'transparent' }), filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none', }} />
- </div>
- )}
-
- {/* Zoom + translate layer (+ 3D transform for image mode when apply3DToBackground is true) */}
- <div className="absolute inset-0 origin-center"
+ {/* ── Canvas + Layers panel side-by-side ── */}
+ <div className="flex items-stretch min-h-0 min-w-0 w-full h-full justify-center gap-0">
+
+ {/* Preview visual - contenedor con tamaño dinámico según aspect ratio */}
+ <div className="flex-1 flex items-center justify-center min-h-0 min-w-0">
+ <div
+ ref={previewContainerRef}
+ className={`relative shrink-0 overflow-hidden transition-all duration-300 ${mediaType === "image" && imageUrl
+ ? ""
+ : "border border-white/20 rounded-xl"
+ }`}
style={{
- transform: mediaType === "image" && imageTransform && apply3DToBackground
- ? `rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) scale(${imageTransform.scale * imageZoomScale}) translateY(${imageTransform.translateY}%)`
- : `scale(${zoomTransform.scale}) translate(${zoomTransform.translateX}%, ${zoomTransform.translateY}%)`,
- perspective: !(mediaType === "image" && apply3DToBackground) && zoomTransform.perspective > 0
- ? `${(zoomTransform.perspective / 10.8).toFixed(1)}cqh` : 'none',
- transformStyle: mediaType === "image" && apply3DToBackground ? 'preserve-3d' : undefined,
- transition: mediaType === "image" && apply3DToBackground
- ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
- : zoomTransform.isMoving ? `transform ${zoomTransform.transitionMs}ms linear` : `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
+ aspectRatio: getAspectRatioStyle(aspectRatio, customAspectRatio ?? undefined),
+ maxWidth: getMaxWidth(aspectRatio, customAspectRatio ?? undefined),
+ width: '100%',
+ height: 'auto',
+ maxHeight: '100%',
+ containerType: 'size',
+ }}
+ onClick={(e) => {
+ if (
+ !(e.target as HTMLElement).closest('[data-canvas-element]') &&
+ !(e.target as HTMLElement).closest('[data-camera-overlay]') &&
+ !(e.target as HTMLElement).closest('[data-video-container]')
+ ) {
+ if (onElementSelect) onElementSelect(null);
+ setIsVideoSelected(false);
+ setCanvasSelectedIds([]);
+ }
}}
>
- {/* FONDO 3D: Solo se renderiza aquí adentro cuando el modo imagen 3D está activo */}
- {(mediaType === "image" && apply3DToBackground) && (
- <div className="absolute inset-0 overflow-hidden pointer-events-none" style={{ zIndex: 0, transform: 'translateZ(-1px)' }}>
- <div className="absolute transition-all duration-200" style={{ inset: '-50%', ...(shouldShowCustomColor && backgroundColorCss ? backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb') ? { backgroundColor: backgroundColorCss } : { backgroundImage: backgroundColorCss } : (shouldShowCustomImage || shouldShowUnsplashOverride) ? { backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : shouldShowWallpaper ? { backgroundImage: `url('${wallpaperUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : { backgroundColor: 'transparent' }), filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none', }} />
- </div>
- )}
- {/* Capa 2A: Canvas elements BEHIND video — sin rotación 3D */}
- <CanvasElementsLayer
- canvasContainerRef={canvasContainerRef}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- hoveredElementId={hoveredElementId}
- isDraggingElement={isDraggingElement}
- behindVideo={true}
- onElementSelect={handleElementSelect}
- onElementUpdate={onElementUpdate}
- setHoveredElementId={setHoveredElementId}
- setIsDraggingElement={setIsDraggingElement}
- setIsDraggingElementRotation={setIsDraggingElementRotation}
- elementDragStart={elementDragStart}
- layerZIndex={1}
- elementCorners={elementCorners}
- setElementCorners={setElementCorners}
- />
-
- {/* 3D rotation layer — solo envuelve el mockup, el fondo queda plano */}
- <div
- className="absolute inset-0 origin-center"
+ {/* Zoom container - applies zoom to entire composition (background + video) */}
+ <div className="absolute inset-0"
style={{
- transform: zoomTransform.perspective > 0 ? `rotateX(${zoomTransform.rotateX}deg) rotateY(${zoomTransform.rotateY}deg)` : 'none',
- transition: `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
- willChange: zoomTransform.perspective > 0 ? 'transform' : 'auto',
- transformStyle: 'preserve-3d',
- zIndex: isVideoSelected ? 101 : 2,
- pointerEvents: 'none',
+ perspective: mediaType === "image" && imageTransform && apply3DToBackground ? `${imageTransform.perspective || 600}px` : 'none',
+ perspectiveOrigin: 'center center',
}}
>
- {/* Capa 2B: Video con padding, esquinas redondeadas y sombras */}
- <div
- className="absolute inset-0 flex items-center justify-center transition-all duration-200"
+ {!(mediaType === "image" && apply3DToBackground) && (
+ <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
+ <div className="absolute transition-all duration-200" style={{ inset: backgroundBlur > 0 ? `-${backgroundBlur}px` : '0', ...(shouldShowCustomColor && backgroundColorCss ? backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb') ? { backgroundColor: backgroundColorCss } : { backgroundImage: backgroundColorCss } : (shouldShowCustomImage || shouldShowUnsplashOverride) ? { backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : shouldShowWallpaper ? { backgroundImage: `url('${wallpaperUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : { backgroundColor: 'transparent' }), filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none', }} />
+ </div>
+ )}
+
+ {/* Zoom + translate layer (+ 3D transform for image mode when apply3DToBackground is true) */}
+ <div className="absolute inset-0 origin-center"
style={{
- padding: `${padding * 0.5}%`,
- zIndex: isVideoSelected ? 101 : 2,
- pointerEvents: 'none',
- ...(mediaType === "image" && imageTransform && !apply3DToBackground ? {
- perspective: `${imageTransform.perspective || 600}px`,
- perspectiveOrigin: 'center center',
- } : {})
+ transform: mediaType === "image" && imageTransform && apply3DToBackground
+ ? `rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) scale(${imageTransform.scale * imageZoomScale}) translateY(${imageTransform.translateY}%)`
+ : `scale(${zoomTransform.scale}) translate(${zoomTransform.translateX}%, ${zoomTransform.translateY}%)`,
+ perspective: !(mediaType === "image" && apply3DToBackground) && zoomTransform.perspective > 0
+ ? `${(zoomTransform.perspective / 10.8).toFixed(1)}cqh` : 'none',
+ transformStyle: mediaType === "image" && apply3DToBackground ? 'preserve-3d' : undefined,
+ transition: mediaType === "image" && apply3DToBackground
+ ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
+ : zoomTransform.isMoving ? `transform ${zoomTransform.transitionMs}ms linear` : `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
}}
>
+ {/* FONDO 3D: Solo se renderiza aquí adentro cuando el modo imagen 3D está activo */}
+ {(mediaType === "image" && apply3DToBackground) && (
+ <div className="absolute inset-0 overflow-hidden pointer-events-none" style={{ zIndex: 0, transform: 'translateZ(-1px)' }}>
+ <div className="absolute transition-all duration-200" style={{ inset: '-50%', ...(shouldShowCustomColor && backgroundColorCss ? backgroundColorCss.startsWith('#') || backgroundColorCss.startsWith('rgb') ? { backgroundColor: backgroundColorCss } : { backgroundImage: backgroundColorCss } : (shouldShowCustomImage || shouldShowUnsplashOverride) ? { backgroundImage: `url('${shouldShowCustomImage ? selectedImageUrl : unsplashOverrideUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : shouldShowWallpaper ? { backgroundImage: `url('${wallpaperUrl}')`, backgroundSize: 'cover', backgroundPosition: 'center', } : { backgroundColor: 'transparent' }), filter: backgroundBlur > 0 ? `blur(${backgroundBlur * 0.4}px)` : 'none', }} />
+ </div>
+ )}
+ {/* Capa 2A: Canvas elements BEHIND video — sin rotación 3D */}
+ <CanvasElementsLayer
+ canvasContainerRef={canvasContainerRef}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ selectedElementIds={canvasSelectedIds}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={true}
+ onElementSelect={handleElementSelect}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={1}
+ elementCorners={elementCorners}
+ setElementCorners={setElementCorners}
+ />
+
+ {/* 3D rotation layer — solo envuelve el mockup, el fondo queda plano */}
<div
- ref={videoContainerRef}
- data-video-container
- className="relative flex w-full h-full items-center justify-center max-w-full max-h-full"
+ className="absolute inset-0 origin-center"
style={{
- transform: mediaType === "image" && imageTransform && !apply3DToBackground
- ? `
- translate(${videoTransform.translateX}%, ${videoTransform.translateY}%)
- rotate(${videoTransform.rotation}deg)
- rotateX(${imageTransform.rotateX}deg)
- rotateY(${imageTransform.rotateY}deg)
- rotateZ(${imageTransform.rotateZ}deg)
- scale(${imageTransform.scale * imageZoomScale})
- translateY(${imageTransform.translateY}%)
- `
- : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
- cursor: isDraggingVideo ? 'move' : (isVideoHovered && hasMedia ? 'move' : 'default'),
- transition: (mediaType === "image" && imageTransform && !apply3DToBackground)
- ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
- : isDraggingVideo || isDraggingRotation ? 'none' : 'transform 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
- pointerEvents: 'auto',
- transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
+ transform: zoomTransform.perspective > 0 ? `rotateX(${zoomTransform.rotateX}deg) rotateY(${zoomTransform.rotateY}deg)` : 'none',
+ transition: `transform ${zoomTransform.transitionMs}ms ${ZOOM_EASING}`,
+ willChange: zoomTransform.perspective > 0 ? 'transform' : 'auto',
+ transformStyle: 'preserve-3d',
+ zIndex: isVideoSelected ? 101 : 2,
+ pointerEvents: 'none',
}}
- onMouseEnter={() => hasMedia && setIsVideoHovered(true)}
- onMouseLeave={() => {
- setIsVideoHovered(false);
- setVideoHoverCorner(null);
- }}
- onMouseDown={(e) => {
- if (!hasMedia || !onVideoTransformChange) return;
- // Only start dragging if not clicking on rotation handle
- if ((e.target as HTMLElement).closest('[data-rotation-handle]')) return;
-
- e.preventDefault();
- setIsVideoSelected(true);
- if (onElementSelect) onElementSelect(null);
- setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation));
- setIsDraggingVideo(true);
- dragStartPos.current = {
- x: e.clientX,
- y: e.clientY,
- initialRotation: videoTransform.rotation,
- initialTranslateX: videoTransform.translateX,
- initialTranslateY: videoTransform.translateY,
- };
- }}
- onMouseMove={(e) => { if (hasMedia) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}
>
- <div className="relative">
- {isVideoSelected && videoHoverCorner && hasMedia && onVideoTransformChange && !isDraggingVideo && !isDraggingRotation && (
- <div
- data-rotation-handle
- style={getCornerStyle(videoHoverCorner, -14)}
- onMouseDown={(e) => {
- e.preventDefault();
- e.stopPropagation();
- lastAngleRef.current = null;
- setIsDraggingRotation(true);
- dragStartPos.current = {
- x: e.clientX,
- y: e.clientY,
- initialRotation: videoTransform.rotation,
- initialTranslateX: videoTransform.translateX,
- initialTranslateY: videoTransform.translateY,
- };
- }}
- >
- <div style={{
- transform: `scale(${mediaType === "image" && imageTransform && !apply3DToBackground
- ? 1 / (imageTransform.scale * imageZoomScale)
- : 1
- })`,
- transformOrigin: "center center"
- }}>
- <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />
- </div>
- </div>
- )}
- {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && (
- <div
- className={`absolute -inset-px border pointer-events-none z-10 opacity-80 ${isVideoSelected ? 'border-blue-500' : 'border-white'}`}
- style={{ borderRadius: `${roundedCorners + 1}px` }}
- />
- )}
-
- {/* Wrapper for mask: applies to entire mockup if mockup exists */}
+ {/* Capa 2B: Video con padding, esquinas redondeadas y sombras */}
+ <div
+ className="absolute inset-0 flex items-center justify-center transition-all duration-200"
+ style={{
+ padding: `${padding * 0.5}%`,
+ zIndex: isVideoSelected ? 101 : 2,
+ pointerEvents: 'none',
+ ...(mediaType === "image" && imageTransform && !apply3DToBackground ? {
+ perspective: `${imageTransform.perspective || 600}px`,
+ perspectiveOrigin: 'center center',
+ } : {})
+ }}
+ >
<div
- className="w-full h-full"
- style={hasMask && hasMockup ? maskStyles : {}}
+ ref={videoContainerRef}
+ data-video-container
+ className="relative flex w-full h-full items-center justify-center max-w-full max-h-full"
+ style={{
+ transform: mediaType === "image" && imageTransform && !apply3DToBackground
+ ? `
+ translate(${videoTransform.translateX}%, ${videoTransform.translateY}%)
+ rotate(${videoTransform.rotation}deg)
+ rotateX(${imageTransform.rotateX}deg)
+ rotateY(${imageTransform.rotateY}deg)
+ rotateZ(${imageTransform.rotateZ}deg)
+ scale(${imageTransform.scale * imageZoomScale})
+ translateY(${imageTransform.translateY}%)
+ `
+ : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
+ cursor: isDraggingVideo ? 'move' : (isVideoHovered && hasMedia ? 'move' : 'default'),
+ transition: (mediaType === "image" && imageTransform && !apply3DToBackground)
+ ? 'transform 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94)'
+ : isDraggingVideo || isDraggingRotation ? 'none' : 'transform 0.15s cubic-bezier(0.25, 0.46, 0.45, 0.94)',
+ pointerEvents: 'auto',
+ transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
+ }}
+ onMouseEnter={() => hasMedia && setIsVideoHovered(true)}
+ onMouseLeave={() => {
+ setIsVideoHovered(false);
+ setVideoHoverCorner(null);
+ }}
+ onMouseDown={(e) => {
+ if (!hasMedia || !onVideoTransformChange) return;
+ if ((e.target as HTMLElement).closest('[data-rotation-handle]')) return;
+
+ e.preventDefault();
+ setIsVideoSelected(true);
+ if (onElementSelect) onElementSelect(null);
+ setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation));
+ setIsDraggingVideo(true);
+ dragStartPos.current = {
+ x: e.clientX,
+ y: e.clientY,
+ initialRotation: videoTransform.rotation,
+ initialTranslateX: videoTransform.translateX,
+ initialTranslateY: videoTransform.translateY,
+ };
+ }}
+ onMouseMove={(e) => { if (hasMedia) setVideoHoverCorner(getNearestCorner(e, videoTransform.rotation)); }}
>
- <MockupWrapper
- mockupId={mockupId}
- config={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
- roundedCorners={roundedCorners}
- shadows={shadows}
- >
- {hasMedia ? (
- <div className="relative flex items-center justify-center overflow-hidden w-full h-full rounded-[inherit]">
- {mediaType === "video" && videoUrl ? (
- <>
- <video
- key={videoUrl}
- ref={videoRef}
- preload="auto"
- playsInline
- className="w-full h-full object-contain"
- style={{
- ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)
- ? { objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)` }
- : {}),
- ...(hasMask && !hasMockup ? maskStyles : {}),
- opacity: currentThumbnail ? 0 : 1,
- }}
- onTimeUpdate={onTimeUpdate}
- onLoadedMetadata={onLoadedMetadata}
- onEnded={onEnded}
- />
- {currentThumbnail && (
- <img
- src={currentThumbnail.dataUrl}
- alt="Preview"
- crossOrigin="anonymous"
- className="absolute inset-0 w-full h-full object-contain"
- style={hasMask && !hasMockup ? maskStyles : {}}
- />
- )}
- </>
- ) : mediaType === "image" && imageUrl ? (
- <>
- <img
- ref={imageRef as React.RefObject<HTMLImageElement>}
- src={imageUrl}
- alt="Editing image"
- crossOrigin="anonymous"
- className="w-full h-full object-contain"
- style={{
- ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0) ? {
- objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)`
- } : {}),
- ...(hasMask && !hasMockup ? maskStyles : {}),
- }}
- onLoad={onLoadedMetadata}
- />
- <div
- className="absolute inset-0 pointer-events-none transition-opacity duration-300"
- style={{
- background: "radial-gradient(circle at center, transparent 30%, rgba(0, 0, 0, 0.75) 100%)",
- opacity: isVideoHovered ? 1 : 0,
- zIndex: 10
- }}
- />
- </>
- ) : null}
- </div>
- ) : (
- <div className="w-full h-full aspect-video min-w-75 bg-[#1E1E1E] border border-white/10 flex flex-col overflow-hidden">
- <PlaceholderEditor
- onVideoUpload={mediaType === "video" ? onVideoUpload : onImageUpload}
- isUploading={isUploading}
- mediaType={mediaType}
- />
+ <div className="relative">
+ {isVideoSelected && videoHoverCorner && hasMedia && onVideoTransformChange && !isDraggingVideo && !isDraggingRotation && (
+ <div
+ data-rotation-handle
+ style={getCornerStyle(videoHoverCorner, -14)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ lastAngleRef.current = null;
+ setIsDraggingRotation(true);
+ dragStartPos.current = {
+ x: e.clientX,
+ y: e.clientY,
+ initialRotation: videoTransform.rotation,
+ initialTranslateX: videoTransform.translateX,
+ initialTranslateY: videoTransform.translateY,
+ };
+ }}
+ >
+ <div style={{
+ transform: `scale(${mediaType === "image" && imageTransform && !apply3DToBackground
+ ? 1 / (imageTransform.scale * imageZoomScale)
+ : 1
+ })`,
+ transformOrigin: "center center"
+ }}>
+ <RotationHandleIcon corner={videoHoverCorner} color="#e5e7eb" />
+ </div>
</div>
)}
- </MockupWrapper>
+ {(isVideoSelected || isVideoHovered) && hasMedia && !isDraggingRotation && (
+ <div
+ className={`absolute -inset-px border pointer-events-none z-10 opacity-80 ${isVideoSelected ? 'border-blue-500' : 'border-white'}`}
+ style={{ borderRadius: `${roundedCorners + 1}px` }}
+ />
+ )}
+
+ <div
+ className="w-full h-full"
+ style={hasMask && hasMockup ? maskStyles : {}}
+ >
+ <MockupWrapper
+ mockupId={mockupId}
+ config={mockupConfig ?? DEFAULT_MOCKUP_CONFIG}
+ roundedCorners={roundedCorners}
+ shadows={shadows}
+ >
+ {hasMedia ? (
+ <div className="relative flex items-center justify-center overflow-hidden w-full h-full rounded-[inherit]">
+ {mediaType === "video" && videoUrl ? (
+ <>
+ <video
+ key={videoUrl}
+ ref={videoRef}
+ preload="auto"
+ playsInline
+ className="w-full h-full object-contain"
+ style={{
+ ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)
+ ? { objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)` }
+ : {}),
+ ...(hasMask && !hasMockup ? maskStyles : {}),
+ opacity: currentThumbnail ? 0 : 1,
+ }}
+ onTimeUpdate={onTimeUpdate}
+ onLoadedMetadata={onLoadedMetadata}
+ onEnded={onEnded}
+ />
+ {currentThumbnail && (
+ <img
+ src={currentThumbnail.dataUrl}
+ alt="Preview"
+ crossOrigin="anonymous"
+ className="absolute inset-0 w-full h-full object-contain"
+ style={hasMask && !hasMockup ? maskStyles : {}}
+ />
+ )}
+ </>
+ ) : mediaType === "image" && imageUrl ? (
+ <>
+ <img
+ ref={imageRef as React.RefObject<HTMLImageElement>}
+ src={imageUrl}
+ alt="Editing image"
+ crossOrigin="anonymous"
+ className="w-full h-full object-contain"
+ style={{
+ ...(cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0) ? {
+ objectViewBox: `inset(${cropArea.y}% ${100 - cropArea.x - cropArea.width}% ${100 - cropArea.y - cropArea.height}% ${cropArea.x}%)`
+ } : {}),
+ ...(hasMask && !hasMockup ? maskStyles : {}),
+ }}
+ onLoad={onLoadedMetadata}
+ />
+ <div
+ className="absolute inset-0 pointer-events-none transition-opacity duration-300"
+ style={{
+ background: "radial-gradient(circle at center, transparent 30%, rgba(0, 0, 0, 0.75) 100%)",
+ opacity: isVideoHovered ? 1 : 0,
+ zIndex: 10
+ }}
+ />
+ </>
+ ) : null}
+ </div>
+ ) : (
+ <div className="w-full h-full aspect-video min-w-75 bg-[#1E1E1E] border border-white/10 flex flex-col overflow-hidden">
+ <PlaceholderEditor
+ onVideoUpload={mediaType === "video" ? onVideoUpload : onImageUpload}
+ isUploading={isUploading}
+ mediaType={mediaType}
+ />
+ </div>
+ )}
+ </MockupWrapper>
+ </div>
+ </div>
+ </div>
+ <div
+ className="absolute inset-0 flex items-center justify-center pointer-events-none z-50 transition-transform"
+ style={{
+ transform: mediaType === "image" && imageTransform && !apply3DToBackground
+ ? `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg) rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) translateY(${imageTransform.translateY}%)`
+ : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
+ transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
+ }}
+ >
+ <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
</div>
</div>
</div>
- <div
- className="absolute inset-0 flex items-center justify-center pointer-events-none z-50 transition-transform"
- style={{
- transform: mediaType === "image" && imageTransform && !apply3DToBackground
- ? `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg) rotateX(${imageTransform.rotateX}deg) rotateY(${imageTransform.rotateY}deg) rotateZ(${imageTransform.rotateZ}deg) translateY(${imageTransform.translateY}%)`
- : `translate(${videoTransform.translateX}%, ${videoTransform.translateY}%) rotate(${videoTransform.rotation}deg)`,
- transformStyle: mediaType === "image" && !apply3DToBackground ? 'preserve-3d' : undefined,
- }}
- >
- <EditorHoverTooltip show={isVideoHovered && mediaType === "image"} />
- </div>
- </div>
- </div>
- {/* Capa 3: Canvas elements ABOVE video (zIndex >= VIDEO_Z_INDEX) */}
- <CanvasElementsLayer
- canvasContainerRef={undefined}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- hoveredElementId={hoveredElementId}
- isDraggingElement={isDraggingElement}
- behindVideo={false}
- onElementSelect={handleElementSelect}
- onElementUpdate={onElementUpdate}
- setHoveredElementId={setHoveredElementId}
- setIsDraggingElement={setIsDraggingElement}
- setIsDraggingElementRotation={setIsDraggingElementRotation}
- elementDragStart={elementDragStart}
- layerZIndex={3}
- elementCorners={elementCorners}
- setElementCorners={setElementCorners}
- />
-
- {/* Capa HIT: invisible, todos los elementos, para recibir eventos */}
- <CanvasElementsLayer
- canvasContainerRef={undefined}
- canvasElements={canvasElements}
- selectedElementId={selectedElementId}
- hoveredElementId={hoveredElementId}
- isDraggingElement={isDraggingElement}
- behindVideo={true}
- onElementSelect={handleElementSelect}
- onElementUpdate={onElementUpdate}
- setHoveredElementId={setHoveredElementId}
- setIsDraggingElement={setIsDraggingElement}
- setIsDraggingElementRotation={setIsDraggingElementRotation}
- elementDragStart={elementDragStart}
- layerZIndex={100}
- hitTestOnly={true}
- elementCorners={elementCorners}
- setElementCorners={setElementCorners}
- />
-
- </div>
- {/* End perspective wrapper div */}
- {(isDraggingElement && (alignmentGuides.vertical.length > 0 || alignmentGuides.horizontal.length > 0)) && (
- <>
- {alignmentGuides.vertical.map((x, index) => (
- <div
- key={`v-${index}`}
- className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
- style={{
- left: `${x}%`,
- zIndex: VIDEO_Z_INDEX + 100,
- }}
- />
- ))}
- {alignmentGuides.horizontal.map((y, index) => (
- <div
- key={`h-${index}`}
- className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
- style={{
- top: `${y}%`,
- zIndex: VIDEO_Z_INDEX + 100,
- }}
+ {/* Capa 3: Canvas elements ABOVE video (zIndex >= VIDEO_Z_INDEX) */}
+ <CanvasElementsLayer
+ canvasContainerRef={undefined}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ selectedElementIds={canvasSelectedIds}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={false}
+ onElementSelect={handleElementSelect}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={3}
+ elementCorners={elementCorners}
+ setElementCorners={setElementCorners}
/>
- ))}
- </>
- )}
-
- {/* Smart alignment guides for mockup (video/image) */}
- {(isDraggingVideo && (mockupAlignmentGuides.vertical.length > 0 || mockupAlignmentGuides.horizontal.length > 0)) && (
- <>
- {/* Vertical guides */}
- {mockupAlignmentGuides.vertical.map((x, index) => (
- <div
- key={`mockup-v-${index}`}
- className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
- style={{
- left: `${x}%`,
- zIndex: VIDEO_Z_INDEX + 100,
- }}
- />
- ))}
- {/* Horizontal guides */}
- {mockupAlignmentGuides.horizontal.map((y, index) => (
- <div
- key={`mockup-h-${index}`}
- className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
- style={{
- top: `${y}%`,
- zIndex: VIDEO_Z_INDEX + 100,
- }}
- />
- ))}
- </>
- )}
-
- {/* Capa 4: Camera overlay for preview — only in video mode */}
- {mediaType !== "image" && cameraUrl && cameraConfig?.enabled && (
- <div data-camera-overlay className="absolute inset-0 pointer-events-none" style={{ zIndex: 4 }}>
- <div
- tabIndex={0}
- onClick={() => {
- if (onCameraClick) {
- onCameraClick();
- }
- }}
- onPointerDown={(e) => {
- if (!onCameraConfigChange || !cameraConfig) return;
- if (e.button !== 0) return;
- const container = previewContainerRef.current;
- if (!container) return;
- const rect = container.getBoundingClientRect();
- e.currentTarget.setPointerCapture(e.pointerId);
- cameraDragRef.current = {
- pointerId: e.pointerId,
- startX: e.clientX,
- startY: e.clientY,
- initialX: cameraConfig.position.x,
- initialY: cameraConfig.position.y,
- rect,
- };
- setIsDraggingCamera(true);
- }}
- onPointerMove={(e) => {
- const drag = cameraDragRef.current;
- if (!drag || drag.pointerId !== e.pointerId || !onCameraConfigChange) return;
- const dx = (e.clientX - drag.startX) / drag.rect.width;
- const dy = (e.clientY - drag.startY) / drag.rect.height;
- const nextX = Math.min(1, Math.max(0, drag.initialX + dx));
- const nextY = Math.min(1, Math.max(0, drag.initialY + dy));
- onCameraConfigChange({
- position: { x: nextX, y: nextY },
- corner: "custom",
- });
- }}
- onPointerUp={(e) => {
- const drag = cameraDragRef.current;
- if (!drag || drag.pointerId !== e.pointerId) return;
- e.currentTarget.releasePointerCapture(e.pointerId);
- cameraDragRef.current = null;
- setIsDraggingCamera(false);
- }}
- onPointerCancel={(e) => {
- const drag = cameraDragRef.current;
- if (!drag || drag.pointerId !== e.pointerId) return;
- e.currentTarget.releasePointerCapture(e.pointerId);
- cameraDragRef.current = null;
- setIsDraggingCamera(false);
- }}
- className={`absolute pointer-events-auto select-none outline-none group ${onCameraConfigChange ? (isDraggingCamera ? "cursor-grabbing" : "cursor-grab") : ""
- }`}
- style={{
- width: `${cameraConfig.size * 100}cqmin`,
- aspectRatio: "1 / 1",
- left: `clamp(0px, calc(${cameraConfig.position.x * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
- top: `clamp(0px, calc(${cameraConfig.position.y * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
- transition: isDraggingCamera ? "none" : "left 120ms ease, top 120ms ease",
- touchAction: "none",
- }}
- >
- <video
- ref={cameraVideoRef}
- muted
- playsInline
- preload="auto"
- className={`size-full object-cover shadow-[0_8px_30px_rgba(0,0,0,0.45)] transition-shadow duration-200 ring-1 ring-white/15 group-hover:ring-1 group-hover:ring-white group-focus:ring-1 group-focus:ring-white ${cameraConfig.shape === "squircle" ? "squircle-element-camera" : ""}`}
- style={{
- borderRadius:
- cameraConfig.shape === "circle"
- ? "50%"
- : cameraConfig.shape === "squircle"
- ? `${Math.round(20 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`
- : `${Math.round(6 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`,
- transform: cameraConfig.mirror ? "scaleX(-1)" : undefined,
+
+ {/* Capa HIT: invisible, todos los elementos, para recibir eventos */}
+ <CanvasElementsLayer
+ canvasContainerRef={undefined}
+ canvasElements={canvasElements}
+ selectedElementId={selectedElementId}
+ selectedElementIds={canvasSelectedIds}
+ hoveredElementId={hoveredElementId}
+ isDraggingElement={isDraggingElement}
+ behindVideo={true}
+ onElementSelect={(id) => {
+ handleElementSelect(id);
+ if (id) {
+ if (!canvasSelectedIds.includes(id)) {
+ setCanvasSelectedIds([id]);
+ pendingCollapseRef.current = null;
+ } else if (canvasSelectedIds.length > 1) {
+ pendingCollapseRef.current = id;
+ }
+ } else {
+ setCanvasSelectedIds([]);
+ pendingCollapseRef.current = null;
+ }
}}
+ onMultiSelect={setCanvasSelectedIds}
+ onElementUpdate={onElementUpdate}
+ setHoveredElementId={setHoveredElementId}
+ setIsDraggingElement={setIsDraggingElement}
+ setIsDraggingElementRotation={setIsDraggingElementRotation}
+ elementDragStart={elementDragStart}
+ layerZIndex={100}
+ hitTestOnly={true}
+ elementCorners={elementCorners}
+ setElementCorners={setElementCorners}
/>
+
</div>
+ {/* End perspective wrapper div */}
+ {(isDraggingElement && (alignmentGuides.vertical.length > 0 || alignmentGuides.horizontal.length > 0)) && (
+ <>
+ {alignmentGuides.vertical.map((x, index) => (
+ <div
+ key={`v-${index}`}
+ className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
+ style={{ left: `${x}%`, zIndex: VIDEO_Z_INDEX + 100 }}
+ />
+ ))}
+ {alignmentGuides.horizontal.map((y, index) => (
+ <div
+ key={`h-${index}`}
+ className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
+ style={{ top: `${y}%`, zIndex: VIDEO_Z_INDEX + 100 }}
+ />
+ ))}
+ </>
+ )}
+
+ {(isDraggingVideo && (mockupAlignmentGuides.vertical.length > 0 || mockupAlignmentGuides.horizontal.length > 0)) && (
+ <>
+ {mockupAlignmentGuides.vertical.map((x, index) => (
+ <div
+ key={`mockup-v-${index}`}
+ className="absolute top-0 bottom-0 w-0.5 bg-white/30 pointer-events-none"
+ style={{ left: `${x}%`, zIndex: VIDEO_Z_INDEX + 100 }}
+ />
+ ))}
+ {mockupAlignmentGuides.horizontal.map((y, index) => (
+ <div
+ key={`mockup-h-${index}`}
+ className="absolute left-0 right-0 h-0.5 bg-white/30 pointer-events-none"
+ style={{ top: `${y}%`, zIndex: VIDEO_Z_INDEX + 100 }}
+ />
+ ))}
+ </>
+ )}
+
+ {/* Capa 4: Camera overlay for preview — only in video mode */}
+ {mediaType !== "image" && cameraUrl && cameraConfig?.enabled && (
+ <div data-camera-overlay className="absolute inset-0 pointer-events-none" style={{ zIndex: 4 }}>
+ <div
+ tabIndex={0}
+ onClick={() => { if (onCameraClick) onCameraClick(); }}
+ onPointerDown={(e) => {
+ if (!onCameraConfigChange || !cameraConfig) return;
+ if (e.button !== 0) return;
+ const container = previewContainerRef.current;
+ if (!container) return;
+ const rect = container.getBoundingClientRect();
+ e.currentTarget.setPointerCapture(e.pointerId);
+ cameraDragRef.current = {
+ pointerId: e.pointerId,
+ startX: e.clientX,
+ startY: e.clientY,
+ initialX: cameraConfig.position.x,
+ initialY: cameraConfig.position.y,
+ rect,
+ };
+ setIsDraggingCamera(true);
+ }}
+ onPointerMove={(e) => {
+ const drag = cameraDragRef.current;
+ if (!drag || drag.pointerId !== e.pointerId || !onCameraConfigChange) return;
+ const dx = (e.clientX - drag.startX) / drag.rect.width;
+ const dy = (e.clientY - drag.startY) / drag.rect.height;
+ const nextX = Math.min(1, Math.max(0, drag.initialX + dx));
+ const nextY = Math.min(1, Math.max(0, drag.initialY + dy));
+ onCameraConfigChange({ position: { x: nextX, y: nextY }, corner: "custom" });
+ }}
+ onPointerUp={(e) => {
+ const drag = cameraDragRef.current;
+ if (!drag || drag.pointerId !== e.pointerId) return;
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ cameraDragRef.current = null;
+ setIsDraggingCamera(false);
+ }}
+ onPointerCancel={(e) => {
+ const drag = cameraDragRef.current;
+ if (!drag || drag.pointerId !== e.pointerId) return;
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ cameraDragRef.current = null;
+ setIsDraggingCamera(false);
+ }}
+ className={`absolute pointer-events-auto select-none outline-none group ${onCameraConfigChange ? (isDraggingCamera ? "cursor-grabbing" : "cursor-grab") : ""}`}
+ style={{
+ width: `${cameraConfig.size * 100}cqmin`,
+ aspectRatio: "1 / 1",
+ left: `clamp(0px, calc(${cameraConfig.position.x * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
+ top: `clamp(0px, calc(${cameraConfig.position.y * 100}% - ${cameraConfig.size * 50}cqmin), calc(100% - ${cameraConfig.size * 100}cqmin))`,
+ transition: isDraggingCamera ? "none" : "left 120ms ease, top 120ms ease",
+ touchAction: "none",
+ }}
+ >
+ <video
+ ref={cameraVideoRef}
+ muted
+ playsInline
+ preload="auto"
+ className={`size-full object-cover shadow-[0_8px_30px_rgba(0,0,0,0.45)] transition-shadow duration-200 ring-1 ring-white/15 group-hover:ring-1 group-hover:ring-white group-focus:ring-1 group-focus:ring-white ${cameraConfig.shape === "squircle" ? "squircle-element-camera" : ""}`}
+ style={{
+ borderRadius:
+ cameraConfig.shape === "circle"
+ ? "50%"
+ : cameraConfig.shape === "squircle"
+ ? `${Math.round(20 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`
+ : `${Math.round(6 * (0.5 + (cameraConfig.size * 100 - 20) / 40))}px`,
+ transform: cameraConfig.mirror ? "scaleX(-1)" : undefined,
+ }}
+ />
+ </div>
+ </div>
+ )}
</div>
- )}
+ </div>
</div>
+
+ {/* ── Layers panel — pegado al lado derecho del canvas ── */}
+ <div className="flex-shrink-0 self-stretch flex items-stretch z-10">
+ <LayersPanel
+ elements={canvasElements}
+ selectedId={selectedElementId}
+ selectedMultiIds={canvasSelectedIds}
+ onSelect={(id) => { if (handleElementSelect) handleElementSelect(id); }}
+ onMultiSelect={(ids) => {
+ setCanvasSelectedIds(ids);
+ if (ids.length === 1) handleElementSelect(ids[0]);
+ else if (ids.length === 0) handleElementSelect(null);
+ }}
+ onDelete={(idOrIds) => { if (onElementDelete) onElementDelete(idOrIds); }}
+ onReorder={(orderedIds) => {
+ orderedIds.forEach((id, pos) => {
+ if (onElementUpdate) onElementUpdate(id, { zIndex: VIDEO_Z_INDEX + 500 - pos });
+ });
+ }}
+ onSetGroupId={(id, groupId) => {
+ if (onElementUpdate) onElementUpdate(id, { groupId });
+ }}
+ onToggleVisible={(id, visible) => {
+ if (onElementUpdate) onElementUpdate(id, { visible });
+ }}
+ onToggleLock={(id, locked) => {
+ if (onElementUpdate) onElementUpdate(id, { locked });
+ }}
+ onBringToFront={(id) => {
+ const maxZ = Math.max(...canvasElements.map(e => e.zIndex), VIDEO_Z_INDEX);
+ if (onElementUpdate) onElementUpdate(id, { zIndex: maxZ + 1 });
+ }}
+ onSendToBack={(id) => {
+ const el = canvasElements.find(e => e.id === id);
+ if (!el || !onElementUpdate) return;
+ if (el.zIndex >= VIDEO_Z_INDEX) {
+ onElementUpdate(id, { zIndex: VIDEO_Z_INDEX - 1 });
+ } else {
+ const minZ = Math.min(...canvasElements.map(e => e.zIndex));
+ onElementUpdate(id, { zIndex: Math.max(1, minZ - 1) });
+ }
+ }}
+ onGroup={(ids) => {
+ const newGroupId = crypto.randomUUID();
+ ids.forEach(id => { if (onElementUpdate) onElementUpdate(id, { groupId: newGroupId }); });
+ }}
+ onUngroup={(ids) => {
+ const groupIds = new Set(
+ ids.map(id => canvasElements.find(e => e.id === id)?.groupId).filter(Boolean)
+ );
+ canvasElements
+ .filter(e => e.groupId && groupIds.has(e.groupId))
+ .forEach(e => { if (onElementUpdate) onElementUpdate(e.id, { groupId: undefined }); });
+ }}
+ toolbar={layersPanelToolbar}
+ />
+ </div>
+
</div>
</div>
);
-});
+});
\ No newline at end of file
diff --git a/components/ui/CtxMenuItem.tsx b/components/ui/CtxMenuItem.tsx
new file mode 100644
index 0000000..7f2de3a
--- /dev/null
+++ b/components/ui/CtxMenuItem.tsx
@@ -0,0 +1,24 @@
+import { Icon } from "@iconify/react";
+
+export default function CtxMenuItem({
+ icon,
+ label,
+ onClick,
+ danger = false,
+}: {
+ icon: string;
+ label: string;
+ onClick: () => void;
+ danger?: boolean;
+}) {
+ return (
+ <button
+ onClick={onClick}
+ className={`w-full flex items-center gap-2.5 px-3 py-1.5 text-[11.5px] transition-colors text-left ${danger ? "text-red-400 hover:bg-red-500/10" : "text-neutral-300 hover:bg-white/6"
+ }`}
+ >
+ <Icon icon={icon} className="size-3.5 shrink-0 opacity-70" />
+ {label}
+ </button>
+ );
+}
\ No newline at end of file