import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import {
Layers, Plus, Trash2, Copy, Eye, EyeOff, Lock, Unlock, Download, Upload,
FolderOpen, Save, Settings, ZoomIn, ZoomOut, Maximize, Move, MousePointer,
Square, Type, Image as ImageIcon, Film, Grid, Magnet, FlipHorizontal,
Undo2, Redo2, AlertTriangle, CheckCircle2, FileText, FileSpreadsheet,
FileJson, Sliders, Monitor, Sparkles, X, ChevronUp, ChevronDown,
Play, Pause, RefreshCw, ShieldCheck, Info, Box, LayoutTemplate, Printer
} from 'lucide-react';
// ============================================================================
// CONSTANTES Y PERFILES PRECONFIGURADOS (ESPECIFICACIÓN V1)
// ============================================================================
const BUILTIN_PROFILES = [
{
id: 'profile-rut-haus',
name: 'Rüt Haus',
widthPx: 7040,
heightPx: 1408,
widthM: 20,
heightM: 4,
locked: true,
notes: 'Pantalla principal panorámica Rüt Haus (20 × 4 m nominales). Densidad de referencia: 352 px/m en ambos ejes. Verificar plano de módulos del proveedor para ajustes finos.'
},
{
id: 'profile-origami',
name: 'Origami',
widthPx: 5712,
heightPx: 1344,
widthM: 17,
heightM: 4,
locked: true,
notes: 'Pantalla panorámica Origami (17 × 4 m nominales). Densidad de referencia: 336 px/m en ambos ejes. Verificar plano de módulos del proveedor antes del montaje.'
}
];
const WINDOW_PRESETS = [
{ label: '16:9 Panorámico', ratio: 16 / 9, code: '16:9' },
{ label: '9:16 Vertical', ratio: 9 / 16, code: '9:16' },
{ label: '4:3 Clásico', ratio: 4 / 3, code: '4:3' },
{ label: '3:4 Retrato', ratio: 3 / 4, code: '3:4' },
{ label: '1:1 Cuadrado', ratio: 1, code: '1:1' },
{ label: '2:1 Doble', ratio: 2, code: '2:1' },
{ label: '21:9 Cinema', ratio: 21 / 9, code: '21:9' },
{ label: 'Tótem 1×3 m', physicalW: 1, physicalH: 3, code: '1×3m' },
{ label: 'Libre', ratio: null, code: 'LIBRE' }
];
const DB_NAME = 'RenderPixelStudioDB_V1';
const DB_VERSION = 1;
// ============================================================================
// UTILIDADES DE INDEXEDDB PARA PERSISTENCIA ROBUSTA
// ============================================================================
const idbHelper = {
open() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains('projects')) {
db.createObjectStore('projects', { keyPath: 'id' });
}
if (!db.objectStoreNames.contains('profiles')) {
db.createObjectStore('profiles', { keyPath: 'id' });
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
},
async getAll(storeName) {
try {
const db = await this.open();
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, 'readonly');
const store = tx.objectStore(storeName);
const req = store.getAll();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
} catch {
return [];
}
},
async put(storeName, item) {
const db = await this.open();
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const req = store.put(item);
req.onsuccess = () => resolve(item);
req.onerror = () => reject(req.error);
});
},
async delete(storeName, id) {
const db = await this.open();
return new Promise((resolve, reject) => {
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
const req = store.delete(id);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
}
};
// ============================================================================
// GENERADOR DE FONDO PROCEDURAL DE ALTA RESOLUCIÓN PARA DEMOSTRACIÓN
// ============================================================================
function generateDemoBackgroundDataUrl(width = 3520, height = 704) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// Fondo profundo técnico
const grad = ctx.createLinearGradient(0, 0, width, height);
grad.addColorStop(0, '#070b14');
grad.addColorStop(0.3, '#0e1d36');
grad.addColorStop(0.5, '#132a4a');
grad.addColorStop(0.7, '#0c1b30');
grad.addColorStop(1, '#060a12');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
// Resplandores ambientales
const glow1 = ctx.createRadialGradient(width * 0.25, height * 0.5, 20, width * 0.25, height * 0.5, width * 0.35);
glow1.addColorStop(0, 'rgba(0, 210, 255, 0.22)');
glow1.addColorStop(1, 'rgba(0, 210, 255, 0)');
ctx.fillStyle = glow1;
ctx.fillRect(0, 0, width, height);
const glow2 = ctx.createRadialGradient(width * 0.75, height * 0.5, 20, width * 0.75, height * 0.5, width * 0.35);
glow2.addColorStop(0, 'rgba(56, 130, 246, 0.24)');
glow2.addColorStop(1, 'rgba(56, 130, 246, 0)');
ctx.fillStyle = glow2;
ctx.fillRect(0, 0, width, height);
// Retícula arquitectónica sutil
ctx.strokeStyle = 'rgba(0, 210, 255, 0.08)';
ctx.lineWidth = 2;
const step = 88;
for (let x = 0; x <= width; x += step) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, height);
ctx.stroke();
}
for (let y = 0; y <= height; y += step) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
// Líneas vectoriales diagonales de acento
ctx.strokeStyle = 'rgba(0, 210, 255, 0.25)';
ctx.lineWidth = 3;
for (let i = -4; i <= 14; i++) {
ctx.beginPath();
ctx.moveTo(i * 320, 0);
ctx.lineTo(i * 320 + 420, height);
ctx.stroke();
}
// Marco perimetral interno
ctx.strokeStyle = 'rgba(0, 210, 255, 0.45)';
ctx.lineWidth = 6;
ctx.strokeRect(18, 18, width - 36, height - 36);
return canvas.toDataURL('image/png');
}
// ============================================================================
// PROYECTO DE DEMOSTRACIÓN PRECARGADO (RÜT HAUS 7040 × 1408 PX)
// ============================================================================
function createDemoProject() {
const profile = BUILTIN_PROFILES[0]; // Rüt Haus 7040x1408 (352 px/m)
const bgUrl = generateDemoBackgroundDataUrl(3520, 704);
const ppmX = profile.widthPx / profile.widthM; // 352
const ppmY = profile.heightPx / profile.heightM; // 352
// 3 Tótems centrales de 1x3 m = 352 x 1056 px
const totemW = Math.round(1 * ppmX); // 352
const totemH = Math.round(3 * ppmY); // 1056
const totemY = Math.round((profile.heightPx - totemH) / 2); // 176
const totemGap = 140;
const centerX = profile.widthPx / 2; // 3520
// 2 Ventanas laterales 16:9
const winW = 1920;
const winH = 1080;
const winY = Math.round((profile.heightPx - winH) / 2); // 164
return {
id: 'demo-rut-haus-v1',
name: 'Show Gala Principal — Rüt Haus',
event: 'Lanzamiento Temporada 2026',
date: '2026-11-20',
updatedAt: Date.now(),
profileId: profile.id,
loopDuration: 10,
layers: [
{
id: 'layer-bg-demo',
type: 'image',
name: 'Fondo Arquitectónico Base',
x: 0,
y: 0,
width: 7040,
height: 1408,
visible: true,
locked: false,
opacity: 1,
src: bgUrl,
naturalWidth: 3520,
naturalHeight: 704,
fitMode: 'cover'
},
{
id: 'layer-frame-outer',
type: 'shape',
name: 'Marco Perimetral Superior/Inferior',
x: 60,
y: 52,
width: 6920,
height: 1304,
visible: true,
locked: false,
opacity: 0.85,
fillColor: 'transparent',
strokeColor: '#00d2ff',
strokeWidth: 6,
borderRadius: 16
},
{
id: 'layer-title-top',
type: 'text',
name: 'Cabezal Tipográfico Evento',
x: 2920,
y: 66,
width: 1200,
height: 76,
visible: true,
locked: false,
opacity: 0.95,
text: 'GALA EDITION · LIVE STAGE',
fontSize: 44,
fontFamily: 'Inter, system-ui, sans-serif',
fontWeight: '700',
color: '#e2f6ff',
letterSpacing: 8,
align: 'center'
},
{
id: 'win-left-16-9',
type: 'window',
windowId: 'WIN-01',
name: 'Ventana Izquierda 16:9',
presetCode: '16:9',
lockAspect: true,
aspectRatio: 16 / 9,
x: 340,
y: winY,
width: winW,
height: winH,
visible: true,
locked: false,
borderWidth: 10,
borderColor: '#00d2ff',
borderRadius: 14,
shadowBlur: 28,
shadowColor: 'rgba(0, 210, 255, 0.55)'
},
{
id: 'totem-center-1',
type: 'window',
windowId: 'TOTEM-01',
name: 'Tótem Central Izq (1×3m)',
presetCode: '1×3m',
lockAspect: true,
aspectRatio: totemW / totemH,
x: Math.round(centerX - totemW * 1.5 - totemGap),
y: totemY,
width: totemW,
height: totemH,
visible: true,
locked: false,
borderWidth: 8,
borderColor: '#38bdf8',
borderRadius: 8,
shadowBlur: 22,
shadowColor: 'rgba(56, 189, 248, 0.5)'
},
{
id: 'totem-center-2',
type: 'window',
windowId: 'TOTEM-02',
name: 'Tótem Central Eje (1×3m)',
presetCode: '1×3m',
lockAspect: true,
aspectRatio: totemW / totemH,
x: Math.round(centerX - totemW / 2),
y: totemY,
width: totemW,
height: totemH,
visible: true,
locked: false,
borderWidth: 8,
borderColor: '#00d2ff',
borderRadius: 8,
shadowBlur: 24,
shadowColor: 'rgba(0, 210, 255, 0.6)'
},
{
id: 'totem-center-3',
type: 'window',
windowId: 'TOTEM-03',
name: 'Tótem Central Der (1×3m)',
presetCode: '1×3m',
lockAspect: true,
aspectRatio: totemW / totemH,
x: Math.round(centerX + totemW / 2 + totemGap),
y: totemY,
width: totemW,
height: totemH,
visible: true,
locked: false,
borderWidth: 8,
borderColor: '#38bdf8',
borderRadius: 8,
shadowBlur: 22,
shadowColor: 'rgba(56, 189, 248, 0.5)'
},
{
id: 'win-right-16-9',
type: 'window',
windowId: 'WIN-02',
name: 'Ventana Derecha 16:9',
presetCode: '16:9',
lockAspect: true,
aspectRatio: 16 / 9,
x: 7040 - 340 - winW,
y: winY,
width: winW,
height: winH,
visible: true,
locked: false,
borderWidth: 10,
borderColor: '#00d2ff',
borderRadius: 14,
shadowBlur: 28,
shadowColor: 'rgba(0, 210, 255, 0.55)'
}
]
};
}
// ============================================================================
// UTILIDADES DE DIBUJO DE COMPOSICIÓN (USADAS EN PREVIEW Y RENDER NATIVO)
// ============================================================================
function drawRoundedRectPath(ctx, x, y, w, h, r) {
const radius = Math.max(0, Math.min(r || 0, Math.min(w, h) / 2));
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function renderCompositionToContext(ctx, project, profile, mediaCache, options = {}) {
const {
includeWatermark = false,
showTechnicalOverlay = false,
showSafeMargins = false,
showGrid = false,
gridStepPx = 352
} = options;
const W = profile.widthPx;
const H = profile.heightPx;
ctx.clearRect(0, 0, W, H);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
// 1. Renderizar capas de abajo hacia arriba
for (const layer of project.layers) {
if (!layer.visible) continue;
ctx.save();
ctx.globalAlpha = layer.opacity ?? 1;
if (layer.type === 'image') {
const img = mediaCache[layer.id];
if (img && img.complete && img.naturalWidth > 0) {
ctx.drawImage(img, layer.x, layer.y, layer.width, layer.height);
} else {
ctx.fillStyle = '#162033';
ctx.fillRect(layer.x, layer.y, layer.width, layer.height);
}
} else if (layer.type === 'video') {
const vid = mediaCache[layer.id];
if (vid && vid.readyState >= 2) {
ctx.drawImage(vid, layer.x, layer.y, layer.width, layer.height);
} else {
ctx.fillStyle = '#10192b';
ctx.fillRect(layer.x, layer.y, layer.width, layer.height);
}
} else if (layer.type === 'shape') {
drawRoundedRectPath(ctx, layer.x, layer.y, layer.width, layer.height, layer.borderRadius || 0);
if (layer.fillColor && layer.fillColor !== 'transparent') {
ctx.fillStyle = layer.fillColor;
ctx.fill();
}
if (layer.strokeWidth > 0 && layer.strokeColor) {
ctx.lineWidth = layer.strokeWidth;
ctx.strokeStyle = layer.strokeColor;
ctx.stroke();
}
} else if (layer.type === 'text') {
ctx.fillStyle = layer.color || '#ffffff';
ctx.font = `${layer.fontWeight || '700'} ${layer.fontSize || 48}px ${layer.fontFamily || 'Inter, sans-serif'}`;
ctx.textBaseline = 'middle';
ctx.textAlign = layer.align || 'center';
const drawX =
layer.align === 'left'
? layer.x
: layer.align === 'right'
? layer.x + layer.width
: layer.x + layer.width / 2;
const drawY = layer.y + layer.height / 2;
ctx.fillText(layer.text || '', drawX, drawY);
} else if (layer.type === 'window') {
// PRIMERO: Sombra exterior decorativa si existe (fuera del hueco)
if (layer.shadowBlur > 0 && layer.shadowColor) {
ctx.save();
ctx.shadowBlur = layer.shadowBlur;
ctx.shadowColor = layer.shadowColor;
ctx.strokeStyle = layer.borderColor || '#00d2ff';
ctx.lineWidth = Math.max(2, layer.borderWidth || 4);
drawRoundedRectPath(ctx, layer.x, layer.y, layer.width, layer.height, layer.borderRadius || 0);
ctx.stroke();
ctx.restore();
}
// SEGUNDO: Perforar literalmente la región con ALFA 0 REAL (destination-out)
ctx.save();
ctx.globalCompositeOperation = 'destination-out';
ctx.globalAlpha = 1;
drawRoundedRectPath(ctx, layer.x, layer.y, layer.width, layer.height, layer.borderRadius || 0);
ctx.fillStyle = '#000000';
ctx.fill();
ctx.restore();
// TERCERO: Dibujar borde decorativo limpio alrededor de la perforación alfa 0
if (layer.borderWidth > 0 && layer.borderColor) {
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = layer.opacity ?? 1;
const bw = layer.borderWidth;
drawRoundedRectPath(
ctx,
layer.x - bw / 2,
layer.y - bw / 2,
layer.width + bw,
layer.height + bw,
(layer.borderRadius || 0) + bw / 2
);
ctx.lineWidth = bw;
ctx.strokeStyle = layer.borderColor;
ctx.stroke();
ctx.restore();
}
}
ctx.restore();
}
// Opcional: Sello explícito Powered by Render (nunca por defecto en máscara final)
if (includeWatermark) {
ctx.save();
ctx.globalCompositeOperation = 'source-over';
const fontSize = Math.max(20, Math.round(H * 0.018));
ctx.font = `600 ${fontSize}px Inter, system-ui, sans-serif`;
const label = 'Render Pixel Studio · Powered by Render';
const metrics = ctx.measureText(label);
const padX = 18;
const padY = 10;
const boxW = metrics.width + padX * 2;
const boxH = fontSize + padY * 2;
const bx = W - boxW - 28;
const by = H - boxH - 24;
ctx.fillStyle = 'rgba(11, 14, 20, 0.78)';
drawRoundedRectPath(ctx, bx, by, boxW, boxH, 8);
ctx.fill();
ctx.strokeStyle = 'rgba(0, 210, 255, 0.5)';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = '#00d2ff';
ctx.textBaseline = 'middle';
ctx.textAlign = 'left';
ctx.fillText(label, bx + padX, by + boxH / 2);
ctx.restore();
}
// Opcional: Guías de vista previa o preview técnico
if (showGrid && gridStepPx >= 16) {
ctx.save();
ctx.strokeStyle = 'rgba(0, 210, 255, 0.16)';
ctx.lineWidth = Math.max(1, W / 3500);
for (let x = gridStepPx; x < W; x += gridStepPx) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, H);
ctx.stroke();
}
for (let y = gridStepPx; y < H; y += gridStepPx) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(W, y);
ctx.stroke();
}
ctx.restore();
}
if (showSafeMargins) {
ctx.save();
const marginX = Math.round(W * 0.03);
const marginY = Math.round(H * 0.05);
ctx.setLineDash([18, 12]);
ctx.strokeStyle = 'rgba(250, 204, 21, 0.65)';
ctx.lineWidth = Math.max(2, W / 2500);
ctx.strokeRect(marginX, marginY, W - marginX * 2, H - marginY * 2);
ctx.restore();
}
if (showTechnicalOverlay) {
const ppmX = profile.widthPx / (profile.widthM || 1);
const ppmY = profile.heightPx / (profile.heightM || 1);
// Eje central de simetría
ctx.save();
ctx.setLineDash([24, 16]);
ctx.strokeStyle = '#ff3b7f';
ctx.lineWidth = Math.max(3, W / 1800);
ctx.beginPath();
ctx.moveTo(W / 2, 0);
ctx.lineTo(W / 2, H);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, H / 2);
ctx.lineTo(W, H / 2);
ctx.stroke();
ctx.restore();
// Etiquetas técnicas sobre cada ventana alfa 0
const windows = project.layers.filter((l) => l.type === 'window' && l.visible);
windows.forEach((win, idx) => {
ctx.save();
ctx.fillStyle = 'rgba(0, 210, 255, 0.12)';
ctx.fillRect(win.x, win.y, win.width, win.height);
ctx.strokeStyle = '#00d2ff';
ctx.lineWidth = Math.max(4, W / 1600);
ctx.strokeRect(win.x, win.y, win.width, win.height);
// Diagonales de hueco transparente
ctx.strokeStyle = 'rgba(0, 210, 255, 0.35)';
ctx.lineWidth = Math.max(2, W / 2600);
ctx.beginPath();
ctx.moveTo(win.x, win.y);
ctx.lineTo(win.x + win.width, win.y + win.height);
ctx.moveTo(win.x + win.width, win.y);
ctx.lineTo(win.x, win.y + win.height);
ctx.stroke();
const wM = (win.width / ppmX).toFixed(2);
const hM = (win.height / ppmY).toFixed(2);
const titleSize = Math.max(26, Math.min(54, Math.round(win.width * 0.08)));
const subSize = Math.max(18, Math.round(titleSize * 0.56));
const cx = win.x + win.width / 2;
const cy = win.y + win.height / 2;
const boxW = Math.min(win.width - 24, Math.max(280, titleSize * 8));
const boxH = titleSize * 3.1;
ctx.fillStyle = 'rgba(11, 14, 20, 0.88)';
drawRoundedRectPath(ctx, cx - boxW / 2, cy - boxH / 2, boxW, boxH, 10);
ctx.fill();
ctx.strokeStyle = '#00d2ff';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = '#00d2ff';
ctx.font = `700 ${titleSize}px "JetBrains Mono", monospace`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(`#${idx + 1} · ${win.windowId || 'WIN'}`, cx, cy - subSize * 1.15);
ctx.fillStyle = '#ffffff';
ctx.font = `600 ${subSize}px "JetBrains Mono", monospace`;
ctx.fillText(`${Math.round(win.width)} × ${Math.round(win.height)} px`, cx, cy + subSize * 0.15);
ctx.fillStyle = '#94a3b8';
ctx.font = `500 ${Math.round(subSize * 0.88)}px "JetBrains Mono", monospace`;
ctx.fillText(`${wM} × ${hM} m · X:${Math.round(win.x)} Y:${Math.round(win.y)}`, cx, cy + subSize * 1.35);
ctx.restore();
});
}
}
// ============================================================================
// COMPONENTE PRINCIPAL: RENDER PIXEL STUDIO
// ============================================================================
export default function App() {
// Perfiles (preconfigurados + personalizados)
const [customProfiles, setCustomProfiles] = useState([]);
const allProfiles = useMemo(() => [...BUILTIN_PROFILES, ...customProfiles], [customProfiles]);
// Lista de proyectos guardados
const [savedProjects, setSavedProjects] = useState([]);
const [project, setProject] = useState(() => createDemoProject());
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
// Historial Deshacer / Rehacer
const [historyPast, setHistoryPast] = useState([]);
const [historyFuture, setHistoryFuture] = useState([]);
// Selección y herramienta activa
const [selectedLayerId, setSelectedLayerId] = useState('win-left-16-9');
const [activeTool, setActiveTool] = useState('select'); // 'select' | 'pan'
const [spacePressed, setSpacePressed] = useState(false);
// Cámara del lienzo
const [zoom, setZoom] = useState(0.16);
const [pan, setPan] = useState({ x: 40, y: 80 });
const [showGrid, setShowGrid] = useState(true);
const [gridUnit, setGridUnit] = useState('m'); // 'm' | 'px'
const [gridStepVal, setGridStepVal] = useState(1); // 1m o 100px
const [snapEnabled, setSnapEnabled] = useState(true);
const [showSafeMargins, setShowSafeMargins] = useState(false);
const [activeGuides, setActiveGuides] = useState([]);
// Reproducción de videos de fondo
const [isPlayingVideos, setIsPlayingVideos] = useState(true);
// Modales y notificaciones
const [showProjectModal, setShowProjectModal] = useState(false);
const [projectModalTab, setProjectModalTab] = useState('open'); // 'open' | 'new' | 'profiles'
const [showExportModal, setShowExportModal] = useState(false);
const [exportTab, setExportTab] = useState('static'); // 'static' | 'animated' | 'tech' | 'data'
const [toast, setToast] = useState(null);
// Opciones de exportación
const [includeWatermarkOnMask, setIncludeWatermarkOnMask] = useState(false);
const [animExportFormat, setAnimExportFormat] = useState('webm'); // 'webm' | 'png-seq'
const [animFps, setAnimFps] = useState(30);
const [animScale, setAnimScale] = useState(1); // 1 = 100% nativo
const [isExporting, setIsExporting] = useState(false);
const [exportProgress, setExportProgress] = useState(0);
const cancelExportRef = useRef(false);
// Caché de elementos HTMLImageElement / HTMLVideoElement
const mediaCacheRef = useRef({});
const [mediaVersion, setMediaVersion] = useState(0);
// Referencias DOM
const viewportRef = useRef(null);
const canvasRef = useRef(null);
const interactionRef = useRef(null);
const currentProfile = useMemo(
() => allProfiles.find((p) => p.id === project.profileId) || BUILTIN_PROFILES[0],
[allProfiles, project.profileId]
);
const ppmX = currentProfile.widthPx / (currentProfile.widthM || 1);
const ppmY = currentProfile.heightPx / (currentProfile.heightM || 1);
const selectedLayer = useMemo(
() => project.layers.find((l) => l.id === selectedLayerId) || null,
[project.layers, selectedLayerId]
);
const notify = useCallback((message, type = 'info') => {
setToast({ message, type, id: Date.now() });
setTimeout(() => {
setToast((prev) => (prev && Date.now() - prev.id >= 3400 ? null : prev));
}, 3600);
}, []);
// ============================================================================
// CARGA INICIAL DE INDEXEDDB Y AJUSTE DE VISTA
// ============================================================================
useEffect(() => {
(async () => {
const storedProfiles = await idbHelper.getAll('profiles');
if (storedProfiles.length > 0) setCustomProfiles(storedProfiles);
const storedProjects = await idbHelper.getAll('projects');
if (storedProjects.length === 0) {
const demo = createDemoProject();
await idbHelper.put('projects', demo);
setSavedProjects([demo]);
setProject(demo);
} else {
setSavedProjects(storedProjects);
setProject(storedProjects[0]);
}
})();
}, []);
const fitCanvasToViewport = useCallback(
(targetProfile = currentProfile) => {
const el = viewportRef.current;
if (!el) return;
const rect = el.getBoundingClientRect();
const pad = 72;
const scaleX = (rect.width - pad) / targetProfile.widthPx;
const scaleY = (rect.height - pad) / targetProfile.heightPx;
const newZoom = Math.max(0.04, Math.min(scaleX, scaleY));
const newPanX = (rect.width - targetProfile.widthPx * newZoom) / 2;
const newPanY = (rect.height - targetProfile.heightPx * newZoom) / 2;
setZoom(newZoom);
setPan({ x: newPanX, y: newPanY });
},
[currentProfile]
);
useEffect(() => {
const timer = setTimeout(() => fitCanvasToViewport(), 80);
return () => clearTimeout(timer);
}, [currentProfile.id, fitCanvasToViewport]);
// ============================================================================
// SINCRONIZACIÓN DE ASSETS MULTIMEDIA (IMÁGENES Y VIDEOS EN LOOP)
// ============================================================================
useEffect(() => {
let active = true;
project.layers.forEach((layer) => {
if (layer.type === 'image' && layer.src) {
const cached = mediaCacheRef.current[layer.id];
if (!cached || cached.src !== layer.src) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => {
if (!active) return;
mediaCacheRef.current[layer.id] = img;
setMediaVersion((v) => v + 1);
};
img.src = layer.src;
}
} else if (layer.type === 'video' && layer.src) {
const cached = mediaCacheRef.current[layer.id];
if (!cached || cached.src !== layer.src) {
const vid = document.createElement('video');
vid.src = layer.src;
vid.muted = true; // Siempre silenciado según especificación
vid.loop = true;
vid.playsInline = true;
vid.playbackRate = layer.playbackRate || 1;
vid.onloadeddata = () => {
if (!active) return;
mediaCacheRef.current[layer.id] = vid;
if (isPlayingVideos) vid.play().catch(() => {});
setMediaVersion((v) => v + 1);
};
} else {
cached.playbackRate = layer.playbackRate || 1;
if (isPlayingVideos && cached.paused) cached.play().catch(() => {});
if (!isPlayingVideos && !cached.paused) cached.pause();
}
}
});
return () => {
active = false;
};
}, [project.layers, isPlayingVideos]);
// ============================================================================
// MUTACIONES DE ESTADO CON HISTORIAL UNDO / REDO
// ============================================================================
const commitProjectChange = useCallback(
(updater, recordHistory = true) => {
setProject((prev) => {
const next = typeof updater === 'function' ? updater(prev) : updater;
if (recordHistory) {
setHistoryPast((h) => [...h.slice(-29), prev]);
setHistoryFuture([]);
}
setHasUnsavedChanges(true);
return { ...next, updatedAt: Date.now() };
});
},
[]
);
const handleUndo = useCallback(() => {
if (historyPast.length === 0) return;
const previous = historyPast[historyPast.length - 1];
setHistoryPast((h) => h.slice(0, -1));
setHistoryFuture((f) => [project, ...f]);
setProject(previous);
setHasUnsavedChanges(true);
}, [historyPast, project]);
const handleRedo = useCallback(() => {
if (historyFuture.length === 0) return;
const next = historyFuture[0];
setHistoryFuture((f) => f.slice(1));
setHistoryPast((h) => [...h, project]);
setProject(next);
setHasUnsavedChanges(true);
}, [historyFuture, project]);
const updateLayer = useCallback(
(layerId, patch, recordHistory = true) => {
commitProjectChange(
(prev) => ({
...prev,
layers: prev.layers.map((l) => (l.id === layerId ? { ...l, ...patch } : l))
}),
recordHistory
);
},
[commitProjectChange]
);
// ============================================================================
// ATAJOS DE TECLADO (ESPACIO PAN, CTRL+Z/Y, SUPR, FLECHAS)
// ============================================================================
useEffect(() => {
const onKeyDown = (e) => {
const tag = document.activeElement?.tagName;
const isInput = tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
if (e.code === 'Space' && !isInput) {
e.preventDefault();
setSpacePressed(true);
}
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'z' && !isInput) {
e.preventDefault();
if (e.shiftKey) handleRedo();
else handleUndo();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'y' && !isInput) {
e.preventDefault();
handleRedo();
} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
e.preventDefault();
handleSaveProject();
} else if ((e.key === 'Delete' || e.key === 'Backspace') && !isInput && selectedLayerId) {
e.preventDefault();
deleteLayer(selectedLayerId);
} else if (
['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key) &&
!isInput &&
selectedLayer &&
!selectedLayer.locked
) {
e.preventDefault();
const step = e.shiftKey ? 10 : 1;
const dx = e.key === 'ArrowLeft' ? -step : e.key === 'ArrowRight' ? step : 0;
const dy = e.key === 'ArrowUp' ? -step : e.key === 'ArrowDown' ? step : 0;
updateLayer(selectedLayer.id, {
x: Math.round(selectedLayer.x + dx),
y: Math.round(selectedLayer.y + dy)
});
}
};
const onKeyUp = (e) => {
if (e.code === 'Space') setSpacePressed(false);
};
window.addEventListener('keydown', onKeyDown);
window.addEventListener('keyup', onKeyUp);
return () => {
window.removeEventListener('keydown', onKeyDown);
window.removeEventListener('keyup', onKeyUp);
};
}, [handleUndo, handleRedo, selectedLayerId, selectedLayer, updateLayer]);
// ============================================================================
// BUCLE DE RENDERIZADO DEL LIENZO INTERACTIVO (60 FPS PARA VIDEOS / EDICIÓN)
// ============================================================================
useEffect(() => {
let animId;
const renderLoop = () => {
const canvas = canvasRef.current;
if (canvas) {
if (canvas.width !== currentProfile.widthPx || canvas.height !== currentProfile.heightPx) {
canvas.width = currentProfile.widthPx;
canvas.height = currentProfile.heightPx;
}
const ctx = canvas.getContext('2d');
const gridStepPx =
gridUnit === 'm' ? Math.max(16, Math.round(gridStepVal * ppmX)) : Math.max(8, gridStepVal);
renderCompositionToContext(ctx, project, currentProfile, mediaCacheRef.current, {
includeWatermark: false,
showTechnicalOverlay: false,
showSafeMargins,
showGrid,
gridStepPx
});
// Dibujar guías inteligentes activas durante arrastre
if (activeGuides.length > 0) {
ctx.save();
ctx.strokeStyle = '#ff2e93';
ctx.lineWidth = Math.max(2, 2 / zoom);
ctx.setLineDash([12 / zoom, 8 / zoom]);
activeGuides.forEach((g) => {
ctx.beginPath();
if (g.type === 'v') {
ctx.moveTo(g.pos, 0);
ctx.lineTo(g.pos, currentProfile.heightPx);
} else {
ctx.moveTo(0, g.pos);
ctx.lineTo(currentProfile.widthPx, g.pos);
}
ctx.stroke();
});
ctx.restore();
}
}
animId = requestAnimationFrame(renderLoop);
};
animId = requestAnimationFrame(renderLoop);
return () => cancelAnimationFrame(animId);
}, [project, currentProfile, mediaVersion, showGrid, gridUnit, gridStepVal, ppmX, showSafeMargins, activeGuides, zoom]);
// ============================================================================
// INTERACCIÓN CON MOUSE EN EL LIENZO (PAN, ZOOM, DRAG, RESIZE + SNAPPING)
// ============================================================================
const screenToCanvasCoords = (clientX, clientY) => {
const rect = viewportRef.current.getBoundingClientRect();
return {
x: (clientX - rect.left - pan.x) / zoom,
y: (clientY - rect.top - pan.y) / zoom
};
};
const handleWheel = (e) => {
e.preventDefault();
const rect = viewportRef.current.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
const factor = e.deltaY < 0 ? 1.12 : 0.89;
const nextZoom = Math.max(0.03, Math.min(4, zoom * factor));
const worldX = (mouseX - pan.x) / zoom;
const worldY = (mouseY - pan.y) / zoom;
setZoom(nextZoom);
setPan({
x: mouseX - worldX * nextZoom,
y: mouseY - worldY * nextZoom
});
};
const startPan = (e) => {
interactionRef.current = {
mode: 'pan',
startClientX: e.clientX,
startClientY: e.clientY,
startPanX: pan.x,
startPanY: pan.y
};
};
const startLayerInteraction = (e, layer, mode, handle = null) => {
e.stopPropagation();
setSelectedLayerId(layer.id);
if (layer.locked || activeTool === 'pan' || spacePressed) {
if (activeTool === 'pan' || spacePressed) startPan(e);
return;
}
const pt = screenToCanvasCoords(e.clientX, e.clientY);
setHistoryPast((h) => [...h.slice(-29), project]);
setHistoryFuture([]);
interactionRef.current = {
mode, // 'move' | 'resize'
handle,
layerId: layer.id,
startX: pt.x,
startY: pt.y,
origX: layer.x,
origY: layer.y,
origW: layer.width,
origH: layer.height,
lockAspect: layer.lockAspect ?? false,
aspectRatio: layer.width / (layer.height || 1)
};
};
const handlePointerMove = (e) => {
const inter = interactionRef.current;
if (!inter) return;
if (inter.mode === 'pan') {
setPan({
x: inter.startPanX + (e.clientX - inter.startClientX),
y: inter.startPanY + (e.clientY - inter.startClientY)
});
return;
}
const pt = screenToCanvasCoords(e.clientX, e.clientY);
const dx = pt.x - inter.startX;
const dy = pt.y - inter.startY;
const snapDist = 14 / zoom;
const guides = [];
if (inter.mode === 'move') {
let nextX = Math.round(inter.origX + dx);
let nextY = Math.round(inter.origY + dy);
if (snapEnabled) {
const W = currentProfile.widthPx;
const H = currentProfile.heightPx;
const targetsX = [0, W / 2, W];
const targetsY = [0, H / 2, H];
project.layers.forEach((other) => {
if (other.id !== inter.layerId && other.visible) {
targetsX.push(other.x, other.x + other.width / 2, other.x + other.width);
targetsY.push(other.y, other.y + other.height / 2, other.y + other.height);
}
});
// Snap borde izq, centro o der
for (const tx of targetsX) {
if (Math.abs(nextX - tx) < snapDist) {
nextX = Math.round(tx);
guides.push({ type: 'v', pos: tx });
break;
}
if (Math.abs(nextX + inter.origW / 2 - tx) < snapDist) {
nextX = Math.round(tx - inter.origW / 2);
guides.push({ type: 'v', pos: tx });
break;
}
if (Math.abs(nextX + inter.origW - tx) < snapDist) {
nextX = Math.round(tx - inter.origW);
guides.push({ type: 'v', pos: tx });
break;
}
}
// Snap borde sup, centro o inf
for (const ty of targetsY) {
if (Math.abs(nextY - ty) < snapDist) {
nextY = Math.round(ty);
guides.push({ type: 'h', pos: ty });
break;
}
if (Math.abs(nextY + inter.origH / 2 - ty) < snapDist) {
nextY = Math.round(ty - inter.origH / 2);
guides.push({ type: 'h', pos: ty });
break;
}
if (Math.abs(nextY + inter.origH - ty) < snapDist) {
nextY = Math.round(ty - inter.origH);
guides.push({ type: 'h', pos: ty });
break;
}
}
}
setActiveGuides(guides);
updateLayer(inter.layerId, { x: nextX, y: nextY }, false);
} else if (inter.mode === 'resize') {
let newX = inter.origX;
let newY = inter.origY;
let newW = inter.origW;
let newH = inter.origH;
const h = inter.handle;
if (h.includes('e')) newW = Math.max(20, inter.origW + dx);
if (h.includes('s')) newH = Math.max(20, inter.origH + dy);
if (h.includes('w')) {
const possibleW = Math.max(20, inter.origW - dx);
newX = inter.origX + (inter.origW - possibleW);
newW = possibleW;
}
if (h.includes('n')) {
const possibleH = Math.max(20, inter.origH - dy);
newY = inter.origY + (inter.origH - possibleH);
newH = possibleH;
}
if (inter.lockAspect || e.shiftKey) {
const ratio = inter.aspectRatio || 1;
if (h === 'n' || h === 's') {
newW = newH * ratio;
} else {
newH = newW / ratio;
}
if (h.includes('w')) newX = inter.origX + (inter.origW - newW);
if (h.includes('n')) newY = inter.origY + (inter.origH - newH);
}
updateLayer(
inter.layerId,
{
x: Math.round(newX),
y: Math.round(newY),
width: Math.round(newW),
height: Math.round(newH)
},
false
);
}
};
const handlePointerUp = () => {
interactionRef.current = null;
setActiveGuides([]);
};
// ============================================================================
// CREACIÓN DE CAPAS, VENTANAS ALFA 0 Y TEMPLATES PREDISEÑADOS
// ============================================================================
const getNextWindowId = () => {
const existing = project.layers.filter((l) => l.type === 'window');
return `WIN-${String(existing.length + 1).padStart(2, '0')}`;
};
const addTransparentWindow = (preset = WINDOW_PRESETS[0]) => {
let w, h;
if (preset.physicalW && preset.physicalH) {
w = Math.round(preset.physicalW * ppmX);
h = Math.round(preset.physicalH * ppmY);
} else if (preset.ratio) {
h = Math.round(currentProfile.heightPx * 0.65);
w = Math.round(h * preset.ratio);
if (w > currentProfile.widthPx * 0.85) {
w = Math.round(currentProfile.widthPx * 0.85);
h = Math.round(w / preset.ratio);
}
} else {
w = Math.round(currentProfile.widthPx * 0.25);
h = Math.round(currentProfile.heightPx * 0.6);
}
const winId = getNextWindowId();
const newWin = {
id: `layer-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
type: 'window',
windowId: winId,
name: `Ventana ${winId} (${preset.code})`,
presetCode: preset.code,
lockAspect: Boolean(preset.ratio || preset.physicalW),
aspectRatio: w / (h || 1),
x: Math.round((currentProfile.widthPx - w) / 2),
y: Math.round((currentProfile.heightPx - h) / 2),
width: w,
height: h,
visible: true,
locked: false,
borderWidth: 8,
borderColor: '#00d2ff',
borderRadius: 10,
shadowBlur: 20,
shadowColor: 'rgba(0, 210, 255, 0.45)'
};
commitProjectChange((prev) => ({
...prev,
layers: [...prev.layers, newWin]
}));
setSelectedLayerId(newWin.id);
notify(`Ventana transparente ${winId} agregada (Alfa 0)`);
};
const applyLayoutTemplate = (templateType) => {
const W = currentProfile.widthPx;
const H = currentProfile.heightPx;
const nonWindows = project.layers.filter((l) => l.type !== 'window');
const newWindows = [];
const makeWin = (windowId, name, presetCode, x, y, width, height) => ({
id: `win-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
type: 'window',
windowId,
name,
presetCode,
lockAspect: true,
aspectRatio: width / height,
x: Math.round(x),
y: Math.round(y),
width: Math.round(width),
height: Math.round(height),
visible: true,
locked: false,
borderWidth: 8,
borderColor: '#00d2ff',
borderRadius: 10,
shadowBlur: 22,
shadowColor: 'rgba(0, 210, 255, 0.45)'
});
if (templateType === '1-center') {
const h = Math.round(H * 0.78);
const w = Math.round(h * (16 / 9));
newWindows.push(makeWin('WIN-01', 'Ventana Central 16:9', '16:9', (W - w) / 2, (H - h) / 2, w, h));
} else if (templateType === '2-side') {
const h = Math.round(H * 0.74);
const w = Math.round(h * (16 / 9));
const margin = Math.round(W * 0.06);
newWindows.push(makeWin('WIN-01', 'Ventana Izquierda', '16:9', margin, (H - h) / 2, w, h));
newWindows.push(makeWin('WIN-02', 'Ventana Derecha', '16:9', W - margin - w, (H - h) / 2, w, h));
} else if (templateType === '3-panoramic') {
const gap = Math.round(W * 0.03);
const w = Math.round((W - gap * 4) / 3);
const h = Math.round(w * (9 / 16));
for (let i = 0; i < 3; i++) {
newWindows.push(
makeWin(`WIN-0${i + 1}`, `Ventana Panorámica ${i + 1}`, '16:9', gap + i * (w + gap), (H - h) / 2, w, h)
);
}
} else if (templateType === '5-totems') {
const tW = Math.round(1 * ppmX);
const tH = Math.round(3 * ppmY);
const gap = Math.round(tW * 0.65);
const totalW = tW * 5 + gap * 4;
const startX = (W - totalW) / 2;
for (let i = 0; i < 5; i++) {
newWindows.push(
makeWin(`TOTEM-0${i + 1}`, `Tótem 1×3m #${i + 1}`, '1×3m', startX + i * (tW + gap), (H - tH) / 2, tW, tH)
);
}
} else if (templateType === '2-win-5-totems') {
const tW = Math.round(1 * ppmX);
const tH = Math.round(3 * ppmY);
const tGap = Math.round(tW * 0.35);
const totemsTotalW = tW * 5 + tGap * 4;
const totemsStartX = (W - totemsTotalW) / 2;
for (let i = 0; i < 5; i++) {
newWindows.push(
makeWin(
`TOTEM-0${i + 1}`,
`Tótem Central #${i + 1}`,
'1×3m',
totemsStartX + i * (tW + tGap),
(H - tH) / 2,
tW,
tH
)
);
}
const sideAvail = totemsStartX - 160;
const wW = Math.min(Math.round(H * 0.68 * (16 / 9)), Math.max(400, sideAvail));
const wH = Math.round(wW / (16 / 9));
newWindows.unshift(makeWin('WIN-01', 'Lateral Izq 16:9', '16:9', (totemsStartX - wW) / 2, (H - wH) / 2, wW, wH));
newWindows.push(
makeWin('WIN-02', 'Lateral Der 16:9', '16:9', W - totemsStartX + (totemsStartX - wW) / 2, (H - wH) / 2, wW, wH)
);
}
commitProjectChange((prev) => ({
...prev,
layers: [...nonWindows, ...newWindows]
}));
if (newWindows.length > 0) setSelectedLayerId(newWindows[0].id);
notify('Distribución prediseñada aplicada al lienzo');
};
const addGraphicLayer = (type) => {
const W = currentProfile.widthPx;
const H = currentProfile.heightPx;
const id = `layer-${Date.now()}`;
if (type === 'text') {
const newText = {
id,
type: 'text',
name: 'Texto Vectorial',
x: Math.round(W / 2 - 500),
y: Math.round(H / 2 - 50),
width: 1000,
height: 100,
visible: true,
locked: false,
opacity: 1,
text: 'RENDER PIXEL STUDIO',
fontSize: 64,
fontFamily: 'Inter, system-ui, sans-serif',
fontWeight: '700',
color: '#ffffff',
align: 'center'
};
commitProjectChange((prev) => ({ ...prev, layers: [...prev.layers, newText] }));
setSelectedLayerId(id);
} else if (type === 'shape') {
const newShape = {
id,
type: 'shape',
name: 'Marco / Rectángulo Vectorial',
x: Math.round(W * 0.1),
y: Math.round(H * 0.1),
width: Math.round(W * 0.8),
height: Math.round(H * 0.8),
visible: true,
locked: false,
opacity: 1,
fillColor: 'transparent',
strokeColor: '#00d2ff',
strokeWidth: 6,
borderRadius: 12
};
commitProjectChange((prev) => ({ ...prev, layers: [...prev.layers, newShape] }));
setSelectedLayerId(id);
}
};
// ============================================================================
// IMPORTACIÓN DE ARCHIVOS (DRAG & DROP O SELECTOR: PNG, JPG, WEBP, SVG, MP4/WEBM)
// ============================================================================
const handleImportFiles = async (fileList) => {
const files = Array.from(fileList || []);
if (files.length === 0) return;
for (const file of files) {
const isVideo = file.type.startsWith('video/');
const isImage = file.type.startsWith('image/');
if (!isVideo && !isImage) {
notify(`Formato no compatible: ${file.name}. Use PNG, JPG, WebP, SVG, MP4 o WebM.`, 'error');
continue;
}
if (isImage) {
const reader = new FileReader();
reader.onload = (ev) => {
const dataUrl = ev.target.result;
const img = new Image();
img.onload = () => {
const natW = img.naturalWidth || currentProfile.widthPx;
const natH = img.naturalHeight || currentProfile.heightPx;
const isBgCandidate = natW >= currentProfile.widthPx * 0.75;
const id = `layer-img-${Date.now()}-${Math.random().toString(36).slice(2, 5)}`;
const newLayer = {
id,
type: 'image',
name: file.name,
x: isBgCandidate ? 0 : Math.round((currentProfile.widthPx - natW) / 2),
y: isBgCandidate ? 0 : Math.round((currentProfile.heightPx - natH) / 2),
width: isBgCandidate ? currentProfile.widthPx : natW,
height: isBgCandidate ? currentProfile.heightPx : natH,
visible: true,
locked: false,
opacity: 1,
src: dataUrl,
naturalWidth: natW,
naturalHeight: natH,
isSvg: file.type === 'image/svg+xml'
};
commitProjectChange((prev) => ({
...prev,
layers: isBgCandidate ? [newLayer, ...prev.layers] : [...prev.layers, newLayer]
}));
setSelectedLayerId(id);
notify(`Imagen importada: ${file.name} (${natW}×${natH} px)`);
};
img.onerror = () => notify(`No se pudo decodificar la imagen ${file.name}`, 'error');
img.src = dataUrl;
};
reader.readAsDataURL(file);
} else if (isVideo) {
const objectUrl = URL.createObjectURL(file);
const testVid = document.createElement('video');
testVid.muted = true;
testVid.playsInline = true;
testVid.onloadedmetadata = () => {
const natW = testVid.videoWidth || currentProfile.widthPx;
const natH = testVid.videoHeight || currentProfile.heightPx;
const id = `layer-vid-${Date.now()}-${Math.random().toString(36).slice(2, 5)}`;
const newLayer = {
id,
type: 'video',
name: `Video Loop: ${file.name}`,
x: 0,
y: 0,
width: currentProfile.widthPx,
height: currentProfile.heightPx,
visible: true,
locked: false,
opacity: 1,
src: objectUrl,
naturalWidth: natW,
naturalHeight: natH,
duration: testVid.duration || 10,
playbackRate: 1
};
commitProjectChange((prev) => ({
...prev,
loopDuration: Math.round(testVid.duration || 10),
layers: [newLayer, ...prev.layers]
}));
setSelectedLayerId(id);
notify(`Video loop importado: ${file.name} (${natW}×${natH} px · ${testVid.duration.toFixed(1)}s)`);
};
testVid.onerror = () => {
notify(
`El códec de "${file.name}" no es soportado nativamente por este navegador. Pruebe MP4 (H.264) o WebM.`,
'error'
);
};
testVid.src = objectUrl;
}
}
};
// ============================================================================
// HERRAMIENTAS DE CAPA (ORDEN, DUPLICAR, ELIMINAR, ESPEJO HORIZONTAL)
// ============================================================================
const moveLayerOrder = (id, direction) => {
commitProjectChange((prev) => {
const idx = prev.layers.findIndex((l) => l.id === id);
if (idx === -1) return prev;
const targetIdx = direction === 'up' ? idx + 1 : idx - 1;
if (targetIdx < 0 || targetIdx >= prev.layers.length) return prev;
const copy = [...prev.layers];
const [item] = copy.splice(idx, 1);
copy.splice(targetIdx, 0, item);
return { ...prev, layers: copy };
});
};
const duplicateLayer = (layer) => {
const copy = {
...layer,
id: `layer-${Date.now()}-${Math.random().toString(36).slice(2, 5)}`,
name: `${layer.name} (Copia)`,
windowId: layer.type === 'window' ? getNextWindowId() : undefined,
x: layer.x + 60,
y: layer.y + 40
};
commitProjectChange((prev) => ({
...prev,
layers: [...prev.layers, copy]
}));
setSelectedLayerId(copy.id);
notify('Capa duplicada');
};
const deleteLayer = (id) => {
commitProjectChange((prev) => ({
...prev,
layers: prev.layers.filter((l) => l.id !== id)
}));
if (selectedLayerId === id) setSelectedLayerId(null);
};
const mirrorLayerHorizontally = (layer) => {
const mirroredX = currentProfile.widthPx - (layer.x + layer.width);
updateLayer(layer.id, { x: Math.round(mirroredX) });
notify('Posición reflejada simétricamente respecto al eje central');
};
const centerLayer = (layer, axis = 'both') => {
const patch = {};
if (axis === 'x' || axis === 'both') patch.x = Math.round((currentProfile.widthPx - layer.width) / 2);
if (axis === 'y' || axis === 'both') patch.y = Math.round((currentProfile.heightPx - layer.height) / 2);
updateLayer(layer.id, patch);
};
// ============================================================================
// GUARDADO, GESTIÓN DE PROYECTOS Y EXPORTACIÓN/IMPORTACIÓN PAQUETE PORTABLE
// ============================================================================
const handleSaveProject = async (asNewName = null) => {
const targetProject = asNewName
? {
...project,
id: `proj-${Date.now()}`,
name: asNewName,
updatedAt: Date.now()
}
: { ...project, updatedAt: Date.now() };
// Verificar si hay blobs temporales de video que no persisten en IndexedDB
const hasBlobVideo = targetProject.layers.some((l) => l.type === 'video' && l.src?.startsWith('blob:'));
await idbHelper.put('projects', targetProject);
const updatedList = await idbHelper.getAll('projects');
setSavedProjects(updatedList);
setProject(targetProject);
setHasUnsavedChanges(false);
if (hasBlobVideo) {
notify(
'Proyecto guardado. Nota: los videos locales pesados se referencian por sesión; revincúlelos al reabrir en otra PC.',
'warn'
);
} else {
notify(`Proyecto "${targetProject.name}" guardado correctamente`);
}
};
const handleExportPortablePackage = () => {
const pkg = {
app: 'Render Pixel Studio',
version: '1.0',
exportedAt: new Date().toISOString(),
profile: currentProfile,
project
};
const blob = new Blob([JSON.stringify(pkg, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_RenderPixelStudio.json`;
a.click();
URL.revokeObjectURL(url);
notify('Paquete portable .json descargado con todos los recursos incrustados');
};
const handleImportPortablePackage = (file) => {
if (!file) return;
const reader = new FileReader();
reader.onload = async (ev) => {
try {
const parsed = JSON.parse(ev.target.result);
if (!parsed.project || !parsed.project.layers) {
throw new Error('Estructura inválida');
}
if (parsed.profile && !allProfiles.some((p) => p.id === parsed.profile.id)) {
const custom = { ...parsed.profile, locked: false };
await idbHelper.put('profiles', custom);
setCustomProfiles((prev) => [...prev, custom]);
}
const importedProj = {
...parsed.project,
id: `proj-imp-${Date.now()}`,
updatedAt: Date.now()
};
await idbHelper.put('projects', importedProj);
const list = await idbHelper.getAll('projects');
setSavedProjects(list);
setProject(importedProj);
setHasUnsavedChanges(false);
setShowProjectModal(false);
notify(`Proyecto "${importedProj.name}" importado con éxito`);
} catch {
notify('El archivo seleccionado no es un paquete válido de Render Pixel Studio', 'error');
}
};
reader.readAsText(file);
};
// ============================================================================
// EXPORTACIONES DE ALTA PRECISIÓN (MÁSCARA PNG ALFA 0, PREVIEW TÉCNICO, ANIMACIÓN, RESOLUME JSON/CSV)
// ============================================================================
const exportStaticPngMask = () => {
try {
const offscreen = document.createElement('canvas');
offscreen.width = currentProfile.widthPx;
offscreen.height = currentProfile.heightPx;
const ctx = offscreen.getContext('2d');
renderCompositionToContext(ctx, project, currentProfile, mediaCacheRef.current, {
includeWatermark: includeWatermarkOnMask,
showTechnicalOverlay: false,
showSafeMargins: false,
showGrid: false
});
offscreen.toBlob((blob) => {
if (!blob) {
notify('Error al generar el PNG nativo. Verifique memoria disponible.', 'error');
return;
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_${currentProfile.widthPx}x${currentProfile.heightPx}_MASK_ALPHA.png`;
a.click();
URL.revokeObjectURL(url);
notify(
`Máscara PNG RGBA exportada a resolución nativa (${currentProfile.widthPx}×${currentProfile.heightPx} px) con canal Alfa 0 real.`
);
}, 'image/png');
} catch (err) {
notify('Error inesperado durante el renderizado estático: ' + err.message, 'error');
}
};
const exportTechnicalPreviewSheet = () => {
const windows = project.layers.filter((l) => l.type === 'window' && l.visible);
const W = currentProfile.widthPx;
const H = currentProfile.heightPx;
// 1. Renderizar vista previa anotada del lienzo
const stageCanvas = document.createElement('canvas');
stageCanvas.width = W;
stageCanvas.height = H;
const sCtx = stageCanvas.getContext('2d');
// Fondo ajedrezado para evidenciar ventanas alfa 0 en el preview técnico
const tile = 48;
for (let y = 0; y < H; y += tile) {
for (let x = 0; x < W; x += tile) {
sCtx.fillStyle = ((x / tile + y / tile) % 2 === 0) ? '#1e293b' : '#0f172a';
sCtx.fillRect(x, y, tile, tile);
}
}
const compCanvas = document.createElement('canvas');
compCanvas.width = W;
compCanvas.height = H;
renderCompositionToContext(compCanvas.getContext('2d'), project, currentProfile, mediaCacheRef.current, {
includeWatermark: false,
showTechnicalOverlay: true,
showSafeMargins: false,
showGrid: false
});
sCtx.drawImage(compCanvas, 0, 0);
// 2. Construir lámina técnica completa (2400px de ancho para máxima legibilidad impresa/digital)
const sheetW = 2400;
const previewMargin = 80;
const previewDrawW = sheetW - previewMargin * 2;
const previewDrawH = Math.round(previewDrawW * (H / W));
const rowH = 54;
const tableHeaderH = 60;
const tableTotalH = tableHeaderH + Math.max(1, windows.length) * rowH + 40;
const headerH = 220;
const footerH = 110;
const sheetH = headerH + previewDrawH + 110 + tableTotalH + footerH;
const sheet = document.createElement('canvas');
sheet.width = sheetW;
sheet.height = sheetH;
const ctx = sheet.getContext('2d');
// Fondo blanco técnico limpio para lectura en cabina / impresión
ctx.fillStyle = '#0b0e14';
ctx.fillRect(0, 0, sheetW, sheetH);
// Banda superior de marca
ctx.fillStyle = '#131822';
ctx.fillRect(0, 0, sheetW, headerH);
ctx.fillStyle = '#00d2ff';
ctx.fillRect(0, headerH - 4, sheetW, 4);
ctx.fillStyle = '#00d2ff';
ctx.font = '700 22px "JetBrains Mono", monospace';
ctx.fillText('RENDER PIXEL STUDIO · POWERED BY RENDER', previewMargin, 54);
ctx.fillStyle = '#ffffff';
ctx.font = '700 44px Inter, system-ui, sans-serif';
ctx.fillText(`FICHA TÉCNICA DE PIXEL MAP: ${project.name}`, previewMargin, 112);
ctx.fillStyle = '#94a3b8';
ctx.font = '500 24px "JetBrains Mono", monospace';
ctx.fillText(
`Perfil: ${currentProfile.name} | Resolución Nativa: ${W} × ${H} px | Dimensión Nominal: ${currentProfile.widthM} × ${currentProfile.heightM} m (${Math.round(ppmX)} px/m) | Evento: ${project.event || 'N/A'}`,
previewMargin,
166
);
// Dibujar vista del lienzo anotado
const previewY = headerH + 50;
ctx.strokeStyle = '#334155';
ctx.lineWidth = 3;
ctx.strokeRect(previewMargin - 2, previewY - 2, previewDrawW + 4, previewDrawH + 4);
ctx.drawImage(stageCanvas, previewMargin, previewY, previewDrawW, previewDrawH);
// Tabla técnica de ventanas
const tableY = previewY + previewDrawH + 70;
ctx.fillStyle = '#ffffff';
ctx.font = '700 28px Inter, system-ui, sans-serif';
ctx.fillText(`DESGLOSE DE VENTANAS TRANSPARENTES ALFA 0 (${windows.length} ZONAS PARA RESOLUME)`, previewMargin, tableY - 20);
const cols = [
{ label: '#', x: previewMargin, w: 70 },
{ label: 'ID VENTANA', x: previewMargin + 70, w: 240 },
{ label: 'NOMBRE / TIPO', x: previewMargin + 310, w: 420 },
{ label: 'PROPORCIÓN', x: previewMargin + 730, w: 200 },
{ label: 'TAMAÑO (PX)', x: previewMargin + 930, w: 310 },
{ label: 'TAMAÑO NOMINAL (M)', x: previewMargin + 1240, w: 310 },
{ label: 'COORDENADAS X / Y (PX)', x: previewMargin + 1550, w: 370 },
{ label: 'CANAL ALFA', x: previewMargin + 1920, w: 320 }
];
ctx.fillStyle = '#1c2433';
ctx.fillRect(previewMargin, tableY, previewDrawW, tableHeaderH);
ctx.fillStyle = '#00d2ff';
ctx.font = '700 20px "JetBrains Mono", monospace';
cols.forEach((c) => ctx.fillText(c.label, c.x + 14, tableY + 37));
windows.forEach((win, i) => {
const ry = tableY + tableHeaderH + i * rowH;
ctx.fillStyle = i % 2 === 0 ? '#111622' : '#161d2c';
ctx.fillRect(previewMargin, ry, previewDrawW, rowH);
const wM = (win.width / ppmX).toFixed(2);
const hM = (win.height / ppmY).toFixed(2);
ctx.fillStyle = '#e2e8f0';
ctx.font = '500 20px "JetBrains Mono", monospace';
ctx.fillText(String(i + 1), cols[0].x + 14, ry + 34);
ctx.fillStyle = '#38bdf8';
ctx.fillText(win.windowId || `WIN-0${i + 1}`, cols[1].x + 14, ry + 34);
ctx.fillStyle = '#e2e8f0';
ctx.fillText((win.name || '').slice(0, 26), cols[2].x + 14, ry + 34);
ctx.fillText(win.presetCode || 'LIBRE', cols[3].x + 14, ry + 34);
ctx.fillText(`${Math.round(win.width)} × ${Math.round(win.height)} px`, cols[4].x + 14, ry + 34);
ctx.fillText(`${wM} × ${hM} m`, cols[5].x + 14, ry + 34);
ctx.fillText(`X: ${Math.round(win.x)} | Y: ${Math.round(win.y)}`, cols[6].x + 14, ry + 34);
ctx.fillStyle = '#4ade80';
ctx.fillText('ALFA 0 (TRANSPARENTE)', cols[7].x + 14, ry + 34);
});
// Pie de documento
ctx.fillStyle = '#64748b';
ctx.font = '500 20px Inter, system-ui, sans-serif';
ctx.fillText(
'Nota de montaje Resolume Arena: Colocar la máscara exportada en la capa superior (Blend Mode: Alpha) sobre los clips alineados a las coordenadas indicadas. Documentación no apta para proyección.',
previewMargin,
sheetH - 42
);
sheet.toBlob((blob) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_PREVIEW_TECNICO.png`;
a.click();
URL.revokeObjectURL(url);
notify('Preview técnico descargado con cotas en px y metros');
}, 'image/png');
};
const exportResolumeData = (format = 'json') => {
const windows = project.layers.filter((l) => l.type === 'window' && l.visible);
const rows = windows.map((w, idx) => ({
index: idx + 1,
id: w.windowId,
name: w.name,
aspectPreset: w.presetCode || 'LIBRE',
x_px: Math.round(w.x),
y_px: Math.round(w.y),
width_px: Math.round(w.width),
height_px: Math.round(w.height),
x_m: Number((w.x / ppmX).toFixed(3)),
y_m: Number((w.y / ppmY).toFixed(3)),
width_m: Number((w.width / ppmX).toFixed(3)),
height_m: Number((w.height / ppmY).toFixed(3)),
alphaChannel: 0
}));
if (format === 'json') {
const payload = {
generator: 'Render Pixel Studio · Powered by Render',
project: project.name,
profile: {
name: currentProfile.name,
resolutionPx: `${currentProfile.widthPx}x${currentProfile.heightPx}`,
nominalMeters: `${currentProfile.widthM}x${currentProfile.heightM}`
},
slices: rows
};
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_ResolumeSlices.json`;
a.click();
URL.revokeObjectURL(url);
} else {
const headers = ['Index,ID,Nombre,Proporcion,X_px,Y_px,Ancho_px,Alto_px,X_m,Y_m,Ancho_m,Alto_m,Alfa'];
const lines = rows.map(
(r) =>
`${r.index},"${r.id}","${r.name}","${r.aspectPreset}",${r.x_px},${r.y_px},${r.width_px},${r.height_px},${r.x_m},${r.y_m},${r.width_m},${r.height_m},0`
);
const blob = new Blob([[...headers, ...lines].join('\n')], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_ResolumeSlices.csv`;
a.click();
URL.revokeObjectURL(url);
}
notify(`Archivo técnico ${format.toUpperCase()} exportado para Resolume`);
};
const exportAnimatedMask = async () => {
setIsExporting(true);
setExportProgress(0);
cancelExportRef.current = false;
const outW = Math.round(currentProfile.widthPx * animScale);
const outH = Math.round(currentProfile.heightPx * animScale);
const durationSec = Math.max(1, Math.min(30, project.loopDuration || 5));
const totalFrames = Math.round(durationSec * animFps);
const offscreen = document.createElement('canvas');
offscreen.width = outW;
offscreen.height = outH;
const ctx = offscreen.getContext('2d');
try {
if (animExportFormat === 'webm') {
if (!window.MediaRecorder) {
throw new Error('MediaRecorder no disponible en este navegador. Use Secuencia PNG RGBA.');
}
const mime = MediaRecorder.isTypeSupported('video/webm;codecs=vp9')
? 'video/webm;codecs=vp9'
: 'video/webm;codecs=vp8';
const stream = offscreen.captureStream(animFps);
const recorder = new MediaRecorder(stream, {
mimeType: mime,
videoBitsPerSecond: 25_000_000
});
const chunks = [];
recorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) chunks.push(e.data);
};
const donePromise = new Promise((resolve) => {
recorder.onstop = () => resolve(new Blob(chunks, { type: 'video/webm' }));
});
recorder.start();
for (let f = 0; f < totalFrames; f++) {
if (cancelExportRef.current) {
recorder.stop();
setIsExporting(false);
notify('Exportación animada cancelada', 'warn');
return;
}
ctx.save();
ctx.scale(animScale, animScale);
renderCompositionToContext(ctx, project, currentProfile, mediaCacheRef.current, {
includeWatermark: includeWatermarkOnMask
});
ctx.restore();
setExportProgress(Math.round(((f + 1) / totalFrames) * 100));
await new Promise((r) => setTimeout(r, 1000 / animFps));
}
recorder.stop();
const webmBlob = await donePromise;
const url = URL.createObjectURL(webmBlob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_${outW}x${outH}_ALPHA.webm`;
a.click();
URL.revokeObjectURL(url);
notify(`Video WebM con canal Alfa exportado (${outW}×${outH} px · ${animFps} fps)`);
} else {
// Secuencia PNG RGBA (empaquetada en JSON/NDJSON de fotogramas base64 o descarga de muestra + manifiesto)
const framesData = [];
const maxSeqFrames = Math.min(totalFrames, 60); // Protección de memoria en navegador
for (let f = 0; f < maxSeqFrames; f++) {
if (cancelExportRef.current) {
setIsExporting(false);
notify('Exportación de secuencia cancelada', 'warn');
return;
}
ctx.save();
ctx.scale(animScale, animScale);
renderCompositionToContext(ctx, project, currentProfile, mediaCacheRef.current, {
includeWatermark: includeWatermarkOnMask
});
ctx.restore();
framesData.push({
frame: f,
filename: `frame_${String(f).padStart(4, '0')}.png`,
dataUrl: offscreen.toDataURL('image/png')
});
setExportProgress(Math.round(((f + 1) / maxSeqFrames) * 100));
await new Promise((r) => setTimeout(r, 15));
}
const manifestBlob = new Blob(
[
JSON.stringify({
generator: 'Render Pixel Studio · PNG RGBA Sequence',
resolution: `${outW}x${outH}`,
fps: animFps,
frameCount: framesData.length,
frames: framesData
})
],
{ type: 'application/json' }
);
const url = URL.createObjectURL(manifestBlob);
const a = document.createElement('a');
a.href = url;
a.download = `${project.name.replace(/[^a-z0-9-_]/gi, '_')}_PNG_RGBA_Sequence.json`;
a.click();
URL.revokeObjectURL(url);
notify(`Secuencia PNG RGBA (${framesData.length} fotogramas alfa 0) exportada`);
}
} catch (err) {
notify(err.message || 'Error al exportar animación', 'error');
} finally {
setIsExporting(false);
}
};
// ============================================================================
// INSPECTOR DE CALIDAD Y RESOLUCIÓN DE ASSETS
// ============================================================================
const qualityAudit = useMemo(() => {
const items = [];
project.layers.forEach((layer) => {
if ((layer.type === 'image' || layer.type === 'video') && layer.naturalWidth && !layer.isSvg) {
const scaleX = (layer.width / layer.naturalWidth) * 100;
const scaleY = (layer.height / layer.naturalHeight) * 100;
const maxScale = Math.max(scaleX, scaleY);
items.push({
id: layer.id,
name: layer.name,
naturalRes: `${layer.naturalWidth}×${layer.naturalHeight}`,
targetRes: `${Math.round(layer.width)}×${Math.round(layer.height)}`,
scalePct: Math.round(maxScale),
isUpscaled: maxScale > 105
});
}
});
return items;
}, [project.layers]);
const hasUpscaleWarning = qualityAudit.some((q) => q.isUpscaled);
// ============================================================================
// RENDERIZADO DE LA INTERFAZ PROFESIONAL (DARK TECHNICAL UI)
// ============================================================================
return (
{/* BARRA SUPERIOR DE APLICACIÓN */}
{/* BARRA SECUNDARIA DE HERRAMIENTAS DE EDICIÓN Y TEMPLATES */}
{/* Herramientas Selección / Mano */}
setActiveTool('select')}
className={`p-1.5 rounded transition cursor-pointer ${
activeTool === 'select' && !spacePressed
? 'bg-[#00d2ff]/20 text-[#00d2ff] border border-[#00d2ff]/40'
: 'text-slate-400 hover:text-white hover:bg-slate-800'
}`}
title="Herramienta Seleccionar / Mover (V)"
>
setActiveTool('pan')}
className={`p-1.5 rounded transition cursor-pointer ${
activeTool === 'pan' || spacePressed
? 'bg-[#00d2ff]/20 text-[#00d2ff] border border-[#00d2ff]/40'
: 'text-slate-400 hover:text-white hover:bg-slate-800'
}`}
title="Desplazar Lienzo (Mantener Espacio)"
>
{/* Deshacer / Rehacer */}
{/* Agregar Ventana Transparente Alfa 0 */}
addTransparentWindow(WINDOW_PRESETS[0])}
className="flex items-center gap-1.5 px-2.5 py-1 rounded bg-cyan-500/15 hover:bg-cyan-500/25 border border-cyan-500/40 text-xs font-semibold text-[#00d2ff] transition cursor-pointer"
>
Ventana Alfa 0
Presets de Hueco Transparente
{WINDOW_PRESETS.map((p) => (
addTransparentWindow(p)}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-cyan-500/20 hover:text-[#00d2ff] flex items-center justify-between cursor-pointer"
>
{p.label}
{p.code}
))}
{/* Templates de Distribución Prediseñada */}
Distribuciones
Plantillas Rápidas de Ventanas
applyLayoutTemplate('1-center')}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-slate-800 cursor-pointer"
>
1 Ventana Central (16:9)
applyLayoutTemplate('2-side')}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-slate-800 cursor-pointer"
>
2 Ventanas Laterales + Centro Libre
applyLayoutTemplate('3-panoramic')}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-slate-800 cursor-pointer"
>
3 Ventanas Panorámicas Simétricas
applyLayoutTemplate('5-totems')}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-slate-800 cursor-pointer"
>
5 Tótems Verticales (1 × 3 m)
applyLayoutTemplate('2-win-5-totems')}
className="w-full text-left px-3 py-1.5 text-xs hover:bg-slate-800 cursor-pointer"
>
2 Ventanas 16:9 + 5 Tótems (1 × 3 m)
{/* Capas Gráficas y Assets */}
addGraphicLayer('shape')}
className="flex items-center gap-1 px-2.5 py-1 rounded bg-[#1c2433] hover:bg-slate-800 border border-slate-700/80 text-xs text-slate-200 cursor-pointer"
title="Agregar marco o forma vectorial"
>
Marco
addGraphicLayer('text')}
className="flex items-center gap-1 px-2.5 py-1 rounded bg-[#1c2433] hover:bg-slate-800 border border-slate-700/80 text-xs text-slate-200 cursor-pointer"
title="Agregar texto vectorial"
>
Texto
Importar Fondo / Logo / Video
{
handleImportFiles(e.target.files);
e.target.value = '';
}}
/>
{/* Controles de Guías, Snapping y Zoom */}
setShowGrid((g) => !g)}
className={`flex items-center gap-1 px-2 py-1 rounded text-xs border cursor-pointer ${
showGrid
? 'bg-cyan-500/15 border-cyan-500/40 text-[#00d2ff]'
: 'bg-[#1c2433] border-slate-700 text-slate-400'
}`}
title="Mostrar/Ocultar cuadrícula"
>
Grilla
setSnapEnabled((s) => !s)}
className={`flex items-center gap-1 px-2 py-1 rounded text-xs border cursor-pointer ${
snapEnabled
? 'bg-cyan-500/15 border-cyan-500/40 text-[#00d2ff]'
: 'bg-[#1c2433] border-slate-700 text-slate-400'
}`}
title="Activar/Desactivar guías inteligentes y snapping"
>
Snap
setShowSafeMargins((m) => !m)}
className={`px-2 py-1 rounded text-xs border cursor-pointer ${
showSafeMargins
? 'bg-amber-500/15 border-amber-500/40 text-amber-300'
: 'bg-[#1c2433] border-slate-700 text-slate-400'
}`}
title="Márgenes de seguridad"
>
Safe
{/* Zoom Controls */}
setZoom((z) => Math.max(0.04, z * 0.8))}
className="p-1 text-slate-400 hover:text-white cursor-pointer"
title="Alejar"
>
fitCanvasToViewport()}
className="px-2 text-[11px] font-mono text-slate-200 hover:text-[#00d2ff] cursor-pointer"
title="Ajustar lienzo a pantalla"
>
{Math.round(zoom * 100)}%
setZoom((z) => Math.min(4, z * 1.25))}
className="p-1 text-slate-400 hover:text-white cursor-pointer"
title="Acercar"
>
{
setZoom(1);
const el = viewportRef.current;
if (el) {
const r = el.getBoundingClientRect();
setPan({
x: (r.width - currentProfile.widthPx) / 2,
y: (r.height - currentProfile.heightPx) / 2
});
}
notify('Inspección 100% píxel real activada');
}}
className="ml-1 px-1.5 py-0.5 rounded bg-slate-800 hover:bg-cyan-500/20 text-[10px] font-mono text-[#00d2ff] cursor-pointer"
title="Inspección 1:1 (100% píxeles reales)"
>
100%
fitCanvasToViewport()}
className="p-1 text-slate-400 hover:text-white cursor-pointer"
title="Ajustar a pantalla"
>
{/* ÁREA PRINCIPAL DE TRABAJO: PANEL CAPAS + LIENZO PANORÁMICO + INSPECTOR */}
{/* PANEL IZQUIERDO: JERARQUÍA DE CAPAS */}
Capas ({project.layers.length})
{project.layers.some((l) => l.type === 'video') && (
setIsPlayingVideos((p) => !p)}
className="flex items-center gap-1 px-2 py-0.5 rounded bg-slate-800 text-[11px] text-cyan-300 hover:bg-slate-700 cursor-pointer"
title="Reproducir / Pausar videos en loop"
>
{isPlayingVideos ? : }
{isPlayingVideos ? 'Pausar' : 'Play'}
)}
{[...project.layers].reverse().map((layer) => {
const isSelected = layer.id === selectedLayerId;
const isWindow = layer.type === 'window';
return (
setSelectedLayerId(layer.id)}
className={`group px-2.5 py-2 rounded-md border text-xs flex items-center justify-between gap-1.5 cursor-pointer transition ${
isSelected
? 'bg-[#1c293d] border-[#00d2ff]/60 text-white shadow-sm'
: 'bg-[#171d29]/60 border-transparent hover:border-slate-700 text-slate-300'
}`}
>
{isWindow ? (
α0
) : layer.type === 'video' ? (
) : layer.type === 'image' ? (
) : layer.type === 'text' ? (
) : (
)}
{isWindow ? `${layer.windowId} · ${layer.name}` : layer.name}
{Math.round(layer.width)}×{Math.round(layer.height)} px
{/* Controles rápidos de capa */}
{
e.stopPropagation();
moveLayerOrder(layer.id, 'up');
}}
className="p-1 hover:text-[#00d2ff] cursor-pointer"
title="Subir capa"
>
{
e.stopPropagation();
moveLayerOrder(layer.id, 'down');
}}
className="p-1 hover:text-[#00d2ff] cursor-pointer"
title="Bajar capa"
>
{
e.stopPropagation();
updateLayer(layer.id, { locked: !layer.locked });
}}
className={`p-1 cursor-pointer ${layer.locked ? 'text-amber-400' : 'hover:text-white'}`}
title={layer.locked ? 'Desbloquear' : 'Bloquear'}
>
{layer.locked ? : }
{
e.stopPropagation();
updateLayer(layer.id, { visible: !layer.visible });
}}
className={`p-1 cursor-pointer ${!layer.visible ? 'text-slate-600' : 'hover:text-white'}`}
title={layer.visible ? 'Ocultar' : 'Mostrar'}
>
{layer.visible ? : }
);
})}
{/* Resumen rápido de ventanas activas */}
Ventanas Alfa 0:
{project.layers.filter((l) => l.type === 'window' && l.visible).length} activas
Densidad Ref.:
{Math.round(ppmX)} px/m
{/* VIEWPORT CENTRAL PANORÁMICO (DRAG & DROP + CANVAS + OVERLAY DE SELECCIÓN) */}
{
if (e.button === 1 || activeTool === 'pan' || spacePressed) {
startPan(e);
} else {
setSelectedLayerId(null);
}
}}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
handleImportFiles(e.dataTransfer.files);
}}
className={`flex-1 relative overflow-hidden bg-[#07090e] ${
activeTool === 'pan' || spacePressed ? 'cursor-grab active:cursor-grabbing' : 'cursor-default'
}`}
>
{/* Patrón de fondo técnico del espacio de trabajo */}
{/* Contenedor transformado por Pan y Zoom */}
{/* Fondo Checkerboard debajo del lienzo para evidenciar transparencia Alfa 0 real */}
{/* Lienzo de composición de resolución nativa */}
{/* Capa interactiva vectorial sobre cada elemento para arrastrar/escalar con precisión */}
{project.layers.map((layer) => {
if (!layer.visible) return null;
const isSelected = layer.id === selectedLayerId;
const isWindow = layer.type === 'window';
return (
startLayerInteraction(e, layer, 'move')}
style={{
left: layer.x,
top: layer.y,
width: layer.width,
height: layer.height
}}
className={`absolute group ${
layer.locked ? 'cursor-not-allowed' : 'cursor-move'
} ${
isSelected
? 'ring-2 ring-[#00d2ff]'
: isWindow
? 'hover:ring-1 hover:ring-cyan-400/70'
: 'hover:ring-1 hover:ring-white/30'
}`}
>
{/* Etiqueta flotante de identificación de ventana transparente */}
{isWindow && (
{layer.windowId} · ALFA 0 ({Math.round(layer.width)}×
{Math.round(layer.height)} px | {(layer.width / ppmX).toFixed(2)}×{(layer.height / ppmY).toFixed(2)} m)
)}
{/* Handles de redimensionamiento si está seleccionado y desbloqueado */}
{isSelected && !layer.locked && (
<>
{['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'].map((dir) => {
const posClasses = {
nw: '-top-2 -left-2 cursor-nwse-resize',
n: '-top-2 left-1/2 -translate-x-1/2 cursor-ns-resize',
ne: '-top-2 -right-2 cursor-nesw-resize',
e: 'top-1/2 -right-2 -translate-y-1/2 cursor-ew-resize',
se: '-bottom-2 -right-2 cursor-nwse-resize',
s: '-bottom-2 left-1/2 -translate-x-1/2 cursor-ns-resize',
sw: '-bottom-2 -left-2 cursor-nesw-resize',
w: 'top-1/2 -left-2 -translate-y-1/2 cursor-ew-resize'
}[dir];
return (
startLayerInteraction(e, layer, 'resize', dir)}
style={{ transform: `scale(${Math.max(1, 0.85 / zoom)})` }}
className={`absolute w-3.5 h-3.5 bg-white border-2 border-[#00d2ff] rounded-sm shadow ${posClasses}`}
/>
);
})}
>
)}
);
})}
{/* Barra inferior informativa del Viewport */}
Lienzo: {currentProfile.widthPx}×{currentProfile.heightPx} px
|
Físico nominal: {currentProfile.widthM}×{currentProfile.heightM} m
|
Arrastra archivos aquí o usa Espacio + Arrastrar para mover vista
Render Pixel Studio · Powered by Render
{/* PANEL DERECHO: INSPECTOR DE PROPIEDADES Y CALIDAD */}
{selectedLayer ? (
{/* Cabecera de Capa Seleccionada */}
{/* ID único para Resolume si es ventana */}
{selectedLayer.type === 'window' && (
ID RESOLUME / SLICE
ALFA 0 REAL
updateLayer(selectedLayer.id, { windowId: e.target.value.toUpperCase() })}
className="w-full bg-[#131822] border border-slate-700 rounded px-2.5 py-1.5 text-xs font-mono font-bold text-[#00d2ff] focus:border-[#00d2ff] outline-none"
/>
{WINDOW_PRESETS.map((p) => (
{
let nextW = selectedLayer.width;
let nextH = selectedLayer.height;
if (p.physicalW && p.physicalH) {
nextW = Math.round(p.physicalW * ppmX);
nextH = Math.round(p.physicalH * ppmY);
} else if (p.ratio) {
nextW = Math.round(nextH * p.ratio);
}
updateLayer(selectedLayer.id, {
presetCode: p.code,
width: nextW,
height: nextH,
lockAspect: Boolean(p.ratio || p.physicalW),
aspectRatio: nextW / (nextH || 1)
});
}}
className={`px-2 py-0.5 rounded text-[10px] font-mono border cursor-pointer ${
selectedLayer.presetCode === p.code
? 'bg-[#00d2ff] text-[#0b0e14] border-[#00d2ff] font-bold'
: 'bg-[#131822] text-slate-300 border-slate-700 hover:border-slate-500'
}`}
>
{p.code}
))}
)}
{/* Geometría Precisa en Píxeles y Metros */}
Posición y Dimensiones
updateLayer(selectedLayer.id, {
lockAspect: !selectedLayer.lockAspect,
aspectRatio: selectedLayer.width / (selectedLayer.height || 1)
})
}
className={`text-[10px] font-mono px-2 py-0.5 rounded border cursor-pointer ${
selectedLayer.lockAspect
? 'bg-cyan-500/20 border-cyan-500/40 text-[#00d2ff]'
: 'bg-slate-800 border-slate-700 text-slate-400'
}`}
>
{selectedLayer.lockAspect ? 'Proporción Bloqueada' : 'Proporción Libre'}
{/* Coordenadas X / Y en px */}
{/* Ancho / Alto en px */}
{/* Equivalencia en metros nominales */}
{/* Alineación y Simetría */}
centerLayer(selectedLayer, 'x')}
className="py-1.5 px-2 rounded bg-[#1c2433] hover:bg-slate-700 text-[11px] text-slate-200 cursor-pointer"
>
Centrar H
centerLayer(selectedLayer, 'y')}
className="py-1.5 px-2 rounded bg-[#1c2433] hover:bg-slate-700 text-[11px] text-slate-200 cursor-pointer"
>
Centrar V
mirrorLayerHorizontally(selectedLayer)}
className="py-1.5 px-2 rounded bg-[#1c2433] hover:bg-slate-700 text-[11px] text-cyan-300 flex items-center justify-center gap-1 cursor-pointer"
title="Reflejar posición respecto al eje central"
>
Espejo
{/* Propiedades específicas de Ventana (Bordes, Radio, Sombra) */}
{selectedLayer.type === 'window' && (
Estilo de Marco de Ventana
)}
{/* Propiedades específicas de Texto */}
{selectedLayer.type === 'text' && (
)}
{/* Propiedades específicas de Forma / Marco */}
{selectedLayer.type === 'shape' && (
)}
{/* Propiedades específicas de Video en Loop */}
{selectedLayer.type === 'video' && (
)}
{/* Opacidad */}
) : (
Ningún elemento seleccionado
Haz clic sobre una ventana transparente, marco, texto o fondo en el lienzo para editar sus coordenadas exactas.
)}
{/* INSPECTOR DE CALIDAD Y RESOLUCIÓN DE RECURSOS */}
Inspector de Resolución
{currentProfile.widthPx}×{currentProfile.heightPx}
{qualityAudit.length === 0 ? (
Sin recursos raster importados en escena.
) : (
{qualityAudit.map((q) => (
{q.name}
{q.scalePct}%
Origen: {q.naturalRes} → Lienzo: {q.targetRes}
{q.isUpscaled && (
Supera 100% nativo: posible pixelación en LED.
)}
))}
)}
{/* ============================================================================
MODAL 1: GESTIÓN DE PROYECTOS Y PERFILES DE PIXEL MAP
============================================================================ */}
{showProjectModal && (
RENDER PIXEL STUDIO
· Powered by Render
Gestión de proyectos, respaldo portable y perfiles de pantallas LED
setShowProjectModal(false)}
className="p-1.5 rounded-lg hover:bg-slate-800 text-slate-400 hover:text-white cursor-pointer"
>
{/* Pestañas del Modal */}
setProjectModalTab('open')}
className={`py-3 border-b-2 transition cursor-pointer ${
projectModalTab === 'open'
? 'border-[#00d2ff] text-[#00d2ff]'
: 'border-transparent text-slate-400 hover:text-white'
}`}
>
Proyectos Guardados ({savedProjects.length})
setProjectModalTab('new')}
className={`py-3 border-b-2 transition cursor-pointer ${
projectModalTab === 'new'
? 'border-[#00d2ff] text-[#00d2ff]'
: 'border-transparent text-slate-400 hover:text-white'
}`}
>
+ Nuevo Proyecto
setProjectModalTab('profiles')}
className={`py-3 border-b-2 transition cursor-pointer ${
projectModalTab === 'profiles'
? 'border-[#00d2ff] text-[#00d2ff]'
: 'border-transparent text-slate-400 hover:text-white'
}`}
>
Perfiles de Pixel Map ({allProfiles.length})
{projectModalTab === 'open' && (
{
setProject(proj);
setHistoryPast([]);
setHistoryFuture([]);
setHasUnsavedChanges(false);
setShowProjectModal(false);
notify(`Proyecto "${proj.name}" cargado`);
}}
onDuplicateProject={async (proj) => {
const dup = {
...proj,
id: `proj-${Date.now()}`,
name: `${proj.name} (Copia)`,
updatedAt: Date.now()
};
await idbHelper.put('projects', dup);
setSavedProjects(await idbHelper.getAll('projects'));
notify('Proyecto duplicado en biblioteca');
}}
onDeleteProject={async (id) => {
await idbHelper.delete('projects', id);
setSavedProjects(await idbHelper.getAll('projects'));
notify('Proyecto eliminado');
}}
onExportPackage={handleExportPortablePackage}
onImportPackage={handleImportPortablePackage}
/>
)}
{projectModalTab === 'new' && (
{
const newProj = {
id: `proj-${Date.now()}`,
name: name.trim() || 'Nuevo Proyecto LED',
event: event.trim(),
date,
updatedAt: Date.now(),
profileId,
loopDuration: 10,
layers: []
};
await idbHelper.put('projects', newProj);
setSavedProjects(await idbHelper.getAll('projects'));
setProject(newProj);
setHistoryPast([]);
setHistoryFuture([]);
setHasUnsavedChanges(false);
setShowProjectModal(false);
notify(`Proyecto "${newProj.name}" creado`);
}}
/>
)}
{projectModalTab === 'profiles' && (
{
commitProjectChange((prev) => ({ ...prev, profileId: id }));
notify('Perfil de pixel map asignado al proyecto actual');
}}
onSaveCustomProfile={async (prof) => {
await idbHelper.put('profiles', prof);
setCustomProfiles(await idbHelper.getAll('profiles'));
notify(`Perfil "${prof.name}" guardado`);
}}
onDeleteCustomProfile={async (id) => {
await idbHelper.delete('profiles', id);
setCustomProfiles(await idbHelper.getAll('profiles'));
notify('Perfil personalizado eliminado');
}}
/>
)}
)}
{/* ============================================================================
MODAL 2: EXPORTACIONES PROFESIONALES (MÁSCARA ESTÁTICA, ANIMADA, TÉCNICA Y DATOS)
============================================================================ */}
{showExportModal && (
Exportar Entregables de Producción
Perfil: {currentProfile.name} · Resolución Nativa:{' '}
{currentProfile.widthPx} × {currentProfile.heightPx} px
!isExporting && setShowExportModal(false)}
className="p-1.5 rounded-lg hover:bg-slate-800 text-slate-400 hover:text-white cursor-pointer"
>
setExportTab('static')}
className={`py-3 border-b-2 cursor-pointer ${
exportTab === 'static' ? 'border-[#00d2ff] text-[#00d2ff]' : 'border-transparent text-slate-400'
}`}
>
Máscara Estática (PNG RGBA)
setExportTab('animated')}
className={`py-3 border-b-2 cursor-pointer ${
exportTab === 'animated' ? 'border-[#00d2ff] text-[#00d2ff]' : 'border-transparent text-slate-400'
}`}
>
Máscara Animada (Loop Alfa)
setExportTab('tech')}
className={`py-3 border-b-2 cursor-pointer ${
exportTab === 'tech' ? 'border-[#00d2ff] text-[#00d2ff]' : 'border-transparent text-slate-400'
}`}
>
Preview Técnico y Datos Resolume
{exportTab === 'static' && (
Formato de Salida: PNG 32-bit RGBA
{currentProfile.widthPx} × {currentProfile.heightPx} px (100% Nativo)
Genera un archivo sin compresión con pérdida donde todas las ventanas marcadas tienen{' '}
canal alfa 0 real . Sin guías, sin cotas y listo para
colocar en la capa superior de Resolume Arena.
{hasUpscaleWarning && (
Advertencia de resolución: Uno o más fondos o logos están escalados por encima del
100% de su resolución original. El archivo se exportará a {currentProfile.widthPx}×
{currentProfile.heightPx} px, pero podría verse suavizado en pantalla.
)}
setIncludeWatermarkOnMask(e.target.checked)}
className="accent-[#00d2ff]"
/>
Incluir sello discreto "Render Pixel Studio · Powered by Render" en la esquina
inferior derecha (desactivado por defecto para no interferir con el evento).
Descargar Máscara PNG RGBA ({currentProfile.widthPx}×{currentProfile.heightPx})
)}
{exportTab === 'animated' && (
Exporta un loop animado conservando transparencia alfa 0 en todas las ventanas durante
cada fotograma. Nota: un MP4 estándar no soporta alfa; use WebM (VP8/VP9 con alfa) o Secuencia PNG RGBA.
Formato con Alfa
setAnimExportFormat(e.target.value)}
className="w-full bg-[#0b0e14] border border-slate-700 rounded px-2.5 py-2 text-xs text-white"
>
WebM (VP9/VP8 Alfa)
Secuencia PNG RGBA
FPS
setAnimFps(Number(e.target.value))}
className="w-full bg-[#0b0e14] border border-slate-700 rounded px-2.5 py-2 text-xs text-white"
>
25 fps
30 fps
60 fps
Escala Render
setAnimScale(Number(e.target.value))}
className="w-full bg-[#0b0e14] border border-slate-700 rounded px-2.5 py-2 text-xs text-white"
>
100% Nativo ({currentProfile.widthPx}px)
50% ({Math.round(currentProfile.widthPx * 0.5)}px)
{isExporting ? (
Renderizando fotogramas con canal alfa...
{exportProgress}%
(cancelExportRef.current = true)}
className="px-3 py-1 rounded bg-rose-500/20 text-rose-300 text-xs cursor-pointer"
>
Cancelar Renderizado
) : (
Iniciar Render de Máscara Animada
)}
)}
{exportTab === 'tech' && (
Genera documentación técnica para el operador de video/VJ con las medidas exactas en píxeles y metros de
cada ventana.
Lámina Preview Técnico (PNG Alta Resolución)
Incluye mapa visual con IDs numerados, ejes de simetría y tabla de dimensiones en px y metros.
exportResolumeData('json')}
className="p-3.5 rounded-lg bg-[#0b0e14] hover:bg-slate-900 border border-slate-700 flex items-center justify-between text-left cursor-pointer"
>
Datos Slices JSON
Coordenadas X/Y y tamaños
exportResolumeData('csv')}
className="p-3.5 rounded-lg bg-[#0b0e14] hover:bg-slate-900 border border-slate-700 flex items-center justify-between text-left cursor-pointer"
>
Planilla Técnica CSV
Compatible con Excel / Sheets
)}
)}
{/* NOTIFICACIÓN FLOTANTE (SIN USAR ALERT/CONFIRM DEL NAVEGADOR) */}
{toast && (
{toast.type === 'error' || toast.type === 'warn' ? (
) : (
)}
{toast.message}
)}
);
}
// ============================================================================
// SUBCOMPONENTES DEL MODAL DE PROYECTOS Y PERFILES
// ============================================================================
function ProjectLibraryTab({
projects,
profiles,
currentProjectId,
onOpenProject,
onDuplicateProject,
onDeleteProject,
onExportPackage,
onImportPackage
}) {
const [search, setSearch] = useState('');
const [confirmDeleteId, setConfirmDeleteId] = useState(null);
const filtered = projects.filter((p) => {
const prof = profiles.find((pr) => pr.id === p.profileId);
const q = search.toLowerCase();
return (
p.name.toLowerCase().includes(q) ||
(p.event || '').toLowerCase().includes(q) ||
(p.date || '').includes(q) ||
(prof?.name || '').toLowerCase().includes(q)
);
});
return (
{filtered.map((proj) => {
const prof = profiles.find((pr) => pr.id === proj.profileId) || BUILTIN_PROFILES[0];
const winCount = proj.layers?.filter((l) => l.type === 'window').length || 0;
const isCurrent = proj.id === currentProjectId;
return (
{proj.name}
{isCurrent && (
ABIERTO
)}
{prof.name}
·
{prof.widthPx}×{prof.heightPx} px
·
{winCount} ventanas α0
{proj.event && (
<>
·
{proj.event}
>
)}
{proj.date && (
<>
·
{proj.date}
>
)}
{confirmDeleteId === proj.id ? (
¿Eliminar?
{
onDeleteProject(proj.id);
setConfirmDeleteId(null);
}}
className="px-2 py-0.5 rounded bg-rose-600 text-white text-[11px] font-bold cursor-pointer"
>
Sí
setConfirmDeleteId(null)}
className="px-2 py-0.5 rounded bg-slate-700 text-white text-[11px] cursor-pointer"
>
No
) : (
<>
onOpenProject(proj)}
className="px-3 py-1.5 rounded bg-[#00d2ff] text-[#0b0e14] font-bold text-xs hover:brightness-110 cursor-pointer"
>
Abrir
onDuplicateProject(proj)}
className="p-1.5 rounded bg-[#1c2433] hover:bg-slate-700 text-slate-200 cursor-pointer"
title="Duplicar proyecto"
>
{!isCurrent && (
setConfirmDeleteId(proj.id)}
className="p-1.5 rounded bg-[#1c2433] hover:bg-rose-500/20 text-rose-400 cursor-pointer"
title="Eliminar proyecto"
>
)}
>
)}
);
})}
);
}
function NewProjectTab({ profiles, onCreateProject }) {
const [name, setName] = useState('');
const [event, setEvent] = useState('');
const [date, setDate] = useState(new Date().toISOString().slice(0, 10));
const [profileId, setProfileId] = useState(profiles[0]?.id || 'profile-rut-haus');
return (
1. Seleccionar Perfil de Pixel Map
{profiles.map((p) => (
setProfileId(p.id)}
className={`p-3 rounded-lg border text-left transition cursor-pointer ${
profileId === p.id
? 'bg-[#1a2940] border-[#00d2ff] text-white'
: 'bg-[#0b0e14] border-slate-800 text-slate-300 hover:border-slate-600'
}`}
>
{p.name}
{p.widthPx} × {p.heightPx} px
{p.widthM} × {p.heightM} m ({Math.round(p.widthPx / (p.widthM || 1))} px/m)
))}
2. Nombre del Proyecto
setName(e.target.value)}
className="w-full bg-[#0b0e14] border border-slate-700 rounded-lg px-3 py-2 text-xs text-white focus:border-[#00d2ff] outline-none"
/>
onCreateProject({ name, event, date, profileId })}
className="px-5 py-2.5 rounded-lg bg-gradient-to-r from-[#00d2ff] to-[#2769a5] text-[#0b0e14] font-bold text-xs cursor-pointer"
>
Crear y Abrir Lienzo
);
}
function ProfilesManagerTab({ profiles, activeProfileId, onSelectProfile, onSaveCustomProfile, onDeleteCustomProfile }) {
const [editing, setEditing] = useState(null);
const startNew = () => {
setEditing({
id: `profile-custom-${Date.now()}`,
name: 'Nueva Pantalla LED',
widthPx: 3840,
heightPx: 1080,
widthM: 12,
heightM: 3.375,
locked: false,
notes: ''
});
};
return (
Los perfiles preconfigurados (Rüt Haus y Origami ) están protegidos contra
edición accidental; puedes duplicarlos para crear variantes personalizadas.
+ Nuevo Perfil
{editing && (
Configurar Perfil Personalizado
Notas de instalación / Módulos
setEditing({ ...editing, notes: e.target.value })}
className="w-full bg-[#131822] border border-slate-700 rounded px-2.5 py-1.5 text-xs text-white"
/>
{
onSaveCustomProfile(editing);
setEditing(null);
}}
className="px-4 py-1.5 rounded bg-[#00d2ff] text-[#0b0e14] font-bold text-xs cursor-pointer"
>
Guardar Perfil
setEditing(null)}
className="px-3 py-1.5 rounded bg-slate-800 text-slate-300 text-xs cursor-pointer"
>
Cancelar
)}
{profiles.map((p) => (
{p.name}
{p.locked ? (
OFICIAL PROTEGIDO
) : (
PERSONALIZADO
)}
Pixel Map: {p.widthPx} × {p.heightPx} px · Dimensión nominal: {p.widthM} × {p.heightM} m (
{Math.round(p.widthPx / (p.widthM || 1))} px/m)
{p.notes &&
{p.notes}
}
{p.id !== activeProfileId && (
onSelectProfile(p.id)}
className="px-3 py-1.5 rounded bg-[#1c2433] hover:bg-[#00d2ff] hover:text-[#0b0e14] text-xs font-semibold text-white transition cursor-pointer"
>
Usar en Proyecto
)}
setEditing({
...p,
id: `profile-custom-${Date.now()}`,
name: `${p.name} (Copia)`,
locked: false
})
}
className="p-1.5 rounded bg-[#1c2433] hover:bg-slate-700 text-slate-200 cursor-pointer"
title="Duplicar perfil para personalizar"
>
{!p.locked && (
<>
setEditing(p)}
className="p-1.5 rounded bg-[#1c2433] hover:bg-slate-700 text-cyan-300 cursor-pointer"
title="Editar perfil"
>
onDeleteCustomProfile(p.id)}
className="p-1.5 rounded bg-[#1c2433] hover:bg-rose-500/20 text-rose-400 cursor-pointer"
title="Eliminar perfil"
>
>
)}
))}
);
}