Diseñador de Plantilla

This commit is contained in:
Juan Felipe Zapata Moreno 2025-09-25 00:51:36 -06:00
parent 9fbcc76638
commit 72d4423d67
13 changed files with 880 additions and 3150 deletions

View File

@ -4,6 +4,8 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<title>Holos</title>
</head>
<body>

View File

@ -13,16 +13,24 @@
"@popperjs/core": "^2.11.8",
"@tailwindcss/postcss": "^4.0.9",
"@tailwindcss/vite": "^4.0.9",
"@tiptap/extension-color": "^3.5.2",
"@tiptap/extension-text-align": "^3.5.2",
"@tiptap/extension-text-style": "^3.5.2",
"@tiptap/extension-underline": "^3.5.2",
"@tiptap/starter-kit": "^3.5.2",
"@tiptap/vue-3": "^3.5.2",
"@vitejs/plugin-vue": "^5.2.1",
"@vuepic/vue-datepicker": "^11.0.2",
"apexcharts": "^5.3.5",
"axios": "^1.8.1",
"html-to-pdfmake": "^2.5.31",
"laravel-echo": "^2.0.2",
"luxon": "^3.5.0",
"pdf-lib": "^1.17.1",
"pdfmake": "^0.2.20",
"pinia": "^3.0.1",
"pusher-js": "^8.4.0",
"tailwindcss": "^4.0",
"tiptap-extension-font-size": "^1.2.0",
"toastr": "^2.1.4",
"uuid": "^11.1.0",
"v-calendar": "^3.1.2",

View File

@ -1,606 +0,0 @@
<script setup>
import { ref, computed, nextTick, watch } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
/** Propiedades */
const props = defineProps({
element: {
type: Object,
required: true
},
isSelected: {
type: Boolean,
default: false
}
});
/** Eventos */
const emit = defineEmits(['select', 'delete', 'update', 'move']);
/** Referencias */
const isEditing = ref(false);
const editValue = ref('');
const editInput = ref(null);
const editTextarea = ref(null);
const elementRef = ref(null);
const isDragging = ref(false);
const isResizing = ref(false);
const resizeDirection = ref(null); // 'corner', 'right', 'bottom'
const dragStart = ref({ x: 0, y: 0 });
const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 });
const fileInput = ref(null);
/** Propiedades computadas */
const elementStyles = computed(() => ({
left: `${props.element.x}px`,
top: `${props.element.y}px`,
width: `${props.element.width || 200}px`,
height: `${props.element.height || 40}px`
}));
/** Watchers */
watch(() => props.isSelected, (selected) => {
if (selected && isEditing.value) {
nextTick(() => {
if (props.element.type === 'text' && editInput.value) {
editInput.value.focus();
editInput.value.select();
} else if (props.element.type === 'code' && editTextarea.value) {
editTextarea.value.focus();
editTextarea.value.select();
}
});
}
});
/** Métodos */
const handleSelect = (event) => {
event.stopPropagation();
emit('select', props.element.id);
};
const handleDelete = () => {
emit('delete', props.element.id);
};
const startEditing = () => {
if (props.element.type === 'table' && props.element.content) {
// Deep copy para evitar mutaciones directas
editValue.value = JSON.parse(JSON.stringify(props.element.content));
} else if (props.element.type === 'code') {
editValue.value = props.element.content || 'console.log("Hola mundo");';
} else {
editValue.value = props.element.content || getDefaultEditValue();
}
isEditing.value = true;
nextTick(() => {
if (editTextarea.value) editTextarea.value.focus();
if (editInput.value) editInput.value.focus();
});
};
const finishEditing = () => {
if (isEditing.value) {
isEditing.value = false;
// Para tablas, emitir el objeto completo
if (props.element.type === 'table') {
emit('update', {
id: props.element.id,
content: editValue.value
});
} else {
emit('update', {
id: props.element.id,
content: editValue.value
});
}
}
};
const handleKeydown = (event) => {
if (props.element.type === 'text') {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
finishEditing();
} else if (event.key === 'Escape') {
isEditing.value = false;
editValue.value = props.element.content || 'Nuevo texto';
}
} else if (props.element.type === 'code') {
if (event.key === 'Escape') {
isEditing.value = false;
editValue.value = props.element.content || 'console.log("Hola mundo");';
}
// Para código, permitimos Enter normal y usamos Ctrl+Enter para terminar
if (event.key === 'Enter' && event.ctrlKey) {
event.preventDefault();
finishEditing();
}
} else if (props.element.type === 'table') {
if (event.key === 'Escape') {
isEditing.value = false;
// Restaurar el contenido original de la tabla
editValue.value = props.element.content ?
JSON.parse(JSON.stringify(props.element.content)) :
getDefaultEditValue();
}
// Para tablas, Enter normal para nueva línea en celda, Ctrl+Enter para terminar
if (event.key === 'Enter' && event.ctrlKey) {
event.preventDefault();
finishEditing();
}
}
};
// Manejo de archivo de imagen
const handleFileSelect = (event) => {
const file = event.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
emit('update', {
id: props.element.id,
content: e.target.result,
fileName: file.name
});
};
reader.readAsDataURL(file);
}
// Limpiar el input
event.target.value = '';
};
// Funcionalidad de arrastre
const handleMouseDown = (event) => {
if (isEditing.value || isResizing.value) return;
isDragging.value = true;
dragStart.value = {
x: event.clientX - props.element.x,
y: event.clientY - props.element.y
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
event.preventDefault();
};
const handleMouseMove = (event) => {
if (isDragging.value && !isResizing.value) {
const newX = event.clientX - dragStart.value.x;
const newY = event.clientY - dragStart.value.y;
emit('move', {
id: props.element.id,
x: Math.max(0, newX),
y: Math.max(0, newY)
});
} else if (isResizing.value && !isDragging.value) {
handleResizeMove(event);
}
};
const handleMouseUp = () => {
isDragging.value = false;
isResizing.value = false;
resizeDirection.value = null;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
// Funcionalidad de redimensionamiento por esquina
const startResize = (event) => {
event.stopPropagation();
event.preventDefault();
isResizing.value = true;
resizeDirection.value = 'corner';
resizeStart.value = {
x: event.clientX,
y: event.clientY,
width: props.element.width || 200,
height: props.element.height || 40
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
// Funcionalidad de redimensionamiento por bordes
const startResizeEdge = (event, direction) => {
event.stopPropagation();
event.preventDefault();
isResizing.value = true;
resizeDirection.value = direction;
resizeStart.value = {
x: event.clientX,
y: event.clientY,
width: props.element.width || 200,
height: props.element.height || 40
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
};
const handleResizeMove = (event) => {
if (!isResizing.value) return;
const deltaX = event.clientX - resizeStart.value.x;
const deltaY = event.clientY - resizeStart.value.y;
let newWidth = resizeStart.value.width;
let newHeight = resizeStart.value.height;
// Calcular nuevas dimensiones según la dirección
if (resizeDirection.value === 'corner') {
newWidth = Math.max(getMinWidth(), Math.min(getMaxWidth(), resizeStart.value.width + deltaX));
newHeight = Math.max(getMinHeight(), Math.min(getMaxHeight(), resizeStart.value.height + deltaY));
} else if (resizeDirection.value === 'right') {
newWidth = Math.max(getMinWidth(), Math.min(getMaxWidth(), resizeStart.value.width + deltaX));
} else if (resizeDirection.value === 'bottom') {
newHeight = Math.max(getMinHeight(), Math.min(getMaxHeight(), resizeStart.value.height + deltaY));
}
emit('update', {
id: props.element.id,
width: newWidth,
height: newHeight
});
};
// Obtener tamaños mínimos según el tipo de elemento
const getMinWidth = () => {
switch (props.element.type) {
case 'text':
return 100;
case 'image':
return 100;
case 'table':
return 200;
default:
return 100;
}
};
const getMinHeight = () => {
switch (props.element.type) {
case 'text':
return 30;
case 'image':
return 80;
case 'table':
return 80;
default:
return 30;
}
};
// Obtener tamaños máximos según el tipo de elemento
const getMaxWidth = () => {
return 800; // Máximo general
};
const getMaxHeight = () => {
return 600; // Máximo general
};
</script>
<template>
<div
ref="elementRef"
:style="elementStyles"
@click="handleSelect"
@dblclick="startEditing"
@mousedown="handleMouseDown"
class="absolute group select-none"
:class="{
'ring-2 ring-blue-500 ring-opacity-50': isSelected,
'cursor-move': !isEditing && !isResizing,
'cursor-text': isEditing && (element.type === 'text' || element.type === 'code'),
'cursor-se-resize': isResizing && resizeDirection === 'corner',
'cursor-e-resize': isResizing && resizeDirection === 'right',
'cursor-s-resize': isResizing && resizeDirection === 'bottom'
}"
>
<!-- Input oculto para selección de archivos -->
<input
ref="fileInput"
type="file"
accept="image/*"
@change="handleFileSelect"
class="hidden"
/>
<!-- Elemento de Texto -->
<div
v-if="element.type === 'text'"
class="w-full h-full flex items-center px-3 py-2 bg-blue-100 rounded border border-blue-300 text-blue-800 text-sm font-medium dark:bg-blue-900/30 dark:border-blue-600 dark:text-blue-300"
>
<input
v-if="isEditing"
ref="editInput"
v-model="editValue"
@blur="finishEditing"
@keydown="handleKeydown"
class="w-full bg-transparent outline-none cursor-text"
@mousedown.stop
/>
<span v-else class="truncate pointer-events-none">
{{ element.content || 'Nuevo texto' }}
</span>
</div>
<!-- Elemento de Imagen -->
<div
v-else-if="element.type === 'image'"
class="w-full h-full flex items-center justify-center bg-gray-100 rounded border border-gray-300 dark:bg-primary/10 dark:border-primary/20 overflow-hidden"
>
<!-- Si hay imagen cargada -->
<img
v-if="element.content && element.content.startsWith('data:image')"
:src="element.content"
:alt="element.fileName || 'Imagen'"
class="w-full h-full object-cover pointer-events-none"
/>
<!-- Placeholder para imagen -->
<div v-else class="flex flex-col items-center justify-center text-gray-400 dark:text-primary-dt/50 p-4">
<GoogleIcon name="image" class="text-2xl mb-1" />
<span class="text-xs text-center">Haz doble clic para cargar imagen</span>
</div>
</div>
<!-- Elemento de Código -->
<div
v-else-if="element.type === 'code'"
class="w-full h-full bg-gray-900 rounded border overflow-hidden"
>
<div class="w-full h-6 bg-gray-800 flex items-center px-2 text-xs text-gray-400 border-b border-gray-700">
<div class="flex gap-1">
<div class="w-2 h-2 bg-red-500 rounded-full"></div>
<div class="w-2 h-2 bg-yellow-500 rounded-full"></div>
<div class="w-2 h-2 bg-green-500 rounded-full"></div>
</div>
<span class="ml-2">{{ element.fileName || 'script.js' }}</span>
</div>
<div class="p-2 h-[calc(100%-24px)]">
<textarea
v-if="isEditing"
ref="editTextarea"
v-model="editValue"
@blur="finishEditing"
@keydown="handleKeydown"
class="w-full h-full bg-transparent text-green-400 text-xs font-mono outline-none resize-none cursor-text"
@mousedown.stop
/>
<pre v-else class="text-green-400 text-xs font-mono overflow-auto h-full pointer-events-none whitespace-pre-wrap">{{ element.content || 'console.log("Hola mundo");' }}</pre>
</div>
</div>
<!-- Elemento de Tabla -->
<div
v-else-if="element.type === 'table'"
class="w-full h-full bg-white rounded border overflow-hidden"
>
<div v-if="element.content && element.content.data" class="w-full h-full">
<table class="w-full h-full text-xs border-collapse">
<thead v-if="element.content.data.length > 0">
<tr class="bg-blue-50 dark:bg-blue-900/20">
<th
v-for="(header, colIndex) in element.content.data[0]"
:key="colIndex"
class="border border-gray-300 dark:border-primary/20 px-1 py-1 text-left font-semibold text-blue-800 dark:text-blue-300"
>
<input
v-if="isEditing"
v-model="editValue.data[0][colIndex]"
class="w-full bg-transparent outline-none text-xs"
@mousedown.stop
@click.stop
@focus.stop
/>
<span v-else class="truncate">{{ header }}</span>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, rowIndex) in element.content.data.slice(1)"
:key="rowIndex"
class="hover:bg-gray-50 dark:hover:bg-primary/5"
>
<td
v-for="(cell, colIndex) in row"
:key="colIndex"
class="border border-gray-300 dark:border-primary/20 px-1 py-1"
>
<input
v-if="isEditing"
v-model="editValue.data[rowIndex + 1][colIndex]"
class="w-full bg-transparent outline-none text-xs"
@mousedown.stop
@click.stop
@focus.stop
/>
<span v-else class="truncate text-gray-700 dark:text-primary-dt">{{ cell }}</span>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Placeholder para tabla vacía -->
<div v-else class="flex flex-col items-center justify-center text-gray-400 dark:text-primary-dt/50 p-4">
<GoogleIcon name="table_chart" class="text-2xl mb-1" />
<span class="text-xs text-center">Doble clic para editar tabla</span>
</div>
</div>
<!-- Controles del elemento -->
<div
v-if="isSelected && !isEditing"
class="absolute -top-8 right-0 flex gap-1 opacity-100 transition-opacity z-10"
>
<!-- Indicador de tamaño -->
<div class="px-2 py-1 bg-gray-800 text-white text-xs rounded shadow-sm pointer-events-none">
{{ Math.round(element.width || 200) }} × {{ Math.round(element.height || 40) }}
</div>
<!-- Botón para cargar imagen (solo para elementos de imagen) -->
<button
v-if="element.type === 'image'"
@click.stop="() => fileInput.click()"
class="w-6 h-6 bg-blue-500 hover:bg-blue-600 text-white rounded text-xs flex items-center justify-center transition-colors shadow-sm"
title="Cargar imagen"
>
<GoogleIcon name="upload" class="text-xs" />
</button>
<!-- Botón eliminar -->
<button
@click.stop="handleDelete"
class="w-6 h-6 bg-red-500 hover:bg-red-600 text-white rounded text-xs flex items-center justify-center transition-colors shadow-sm"
title="Eliminar"
>
<GoogleIcon name="close" class="text-xs" />
</button>
</div>
<!-- Controles de redimensionamiento mejorados -->
<div v-if="isSelected && !isEditing" class="absolute inset-0 pointer-events-none">
<!-- Esquina inferior derecha -->
<div
@mousedown.stop="startResize"
class="absolute -bottom-1 -right-1 w-2 h-2 bg-blue-500 border border-white cursor-se-resize pointer-events-auto rounded-sm resize-handle-corner"
title="Redimensionar"
></div>
<!-- Lado derecho -->
<div
@mousedown.stop="(event) => startResizeEdge(event, 'right')"
class="absolute top-1 bottom-1 -right-0.5 w-1 bg-blue-500 opacity-0 cursor-e-resize pointer-events-auto resize-handle-edge"
title="Redimensionar ancho"
></div>
<!-- Lado inferior -->
<div
@mousedown.stop="(event) => startResizeEdge(event, 'bottom')"
class="absolute -bottom-0.5 left-1 right-1 h-1 bg-blue-500 opacity-0 cursor-s-resize pointer-events-auto resize-handle-edge"
title="Redimensionar alto"
></div>
<!-- Puntos de agarre visuales en los bordes (solo visuales) -->
<div class="absolute top-1/2 -right-0.5 w-1 h-6 -translate-y-1/2 bg-blue-500 opacity-30 rounded-full pointer-events-none resize-handle-visual"></div>
<div class="absolute -bottom-0.5 left-1/2 w-6 h-1 -translate-x-1/2 bg-blue-500 opacity-30 rounded-full pointer-events-none resize-handle-visual"></div>
</div>
<!-- Indicador de arrastre -->
<div
v-if="isDragging"
class="absolute inset-0 bg-blue-500 opacity-20 rounded pointer-events-none"
></div>
<!-- Indicador de redimensionamiento -->
<div
v-if="isResizing"
class="absolute inset-0 bg-green-500 opacity-20 rounded pointer-events-none"
></div>
<!-- Tooltip con instrucciones -->
<div
v-if="isSelected && !element.content && element.type !== 'image' && !isResizing"
class="absolute -bottom-8 left-0 bg-gray-900 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-10"
>
{{ element.type === 'text' ? 'Doble clic para editar texto' : 'Doble clic para editar código' }}
{{ element.type === 'code' ? ' (Ctrl+Enter para guardar)' : '' }}
</div>
<!-- Tooltip con instrucciones de redimensionamiento -->
<div
v-if="isSelected && !isEditing && element.type === 'image' && !element.content && !isResizing"
class="absolute -bottom-8 left-0 bg-gray-900 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-10"
>
Arrastra las esquinas para redimensionar
</div>
<!-- Botón para terminar edición de tabla -->
<div
v-if="isEditing && element.type === 'table'"
class="absolute -bottom-10 left-0 flex gap-2 z-20"
>
<button
@click="finishEditing"
class="px-3 py-1 bg-green-600 hover:bg-green-700 text-white text-xs rounded shadow-sm transition-colors"
>
Guardar (Ctrl+Enter)
</button>
<button
@click="() => { isEditing = false; editValue = JSON.parse(JSON.stringify(element.content)); }"
class="px-3 py-1 bg-gray-600 hover:bg-gray-700 text-white text-xs rounded shadow-sm transition-colors"
>
Cancelar (Esc)
</button>
</div>
</div>
</template>
<style scoped>
/* Estilos para los controles de redimensionamiento mejorados */
.resize-handle-corner {
transition: all 0.2s ease;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.resize-handle-corner:hover {
background-color: #2563eb;
transform: scale(1.1);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
.resize-handle-edge {
transition: all 0.2s ease;
}
.resize-handle-edge:hover {
opacity: 0.7 !important;
background-color: #2563eb;
}
.resize-handle-visual {
transition: all 0.2s ease;
}
/* Efecto hover para los indicadores visuales */
.group:hover .resize-handle-visual {
opacity: 0.6 !important;
}
.group:hover .resize-handle-edge {
opacity: 0.4 !important;
}
/* Prevenir selección de texto durante el redimensionamiento */
.select-none {
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
/* Animación suave para los controles */
@keyframes pulse-resize {
0%, 100% {
opacity: 0.3;
}
50% {
opacity: 0.7;
}
}
.group:hover .resize-handle-visual {
animation: pulse-resize 2s infinite;
}
</style>

View File

@ -1,64 +0,0 @@
<script setup>
import { ref } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
/** Propiedades */
const props = defineProps({
type: {
type: String,
required: true,
},
icon: String,
title: String,
description: String,
});
/** Eventos */
const emit = defineEmits(['dragstart']);
/** Referencias */
const isDragging = ref(false);
/** Métodos */
const handleDragStart = (event) => {
isDragging.value = true;
event.dataTransfer.setData('text/plain', JSON.stringify({
type: props.type,
title: props.title
}));
emit('dragstart', props.type);
};
const handleDragEnd = () => {
isDragging.value = false;
};
</script>
<template>
<div
draggable="true"
@dragstart="handleDragStart"
@dragend="handleDragEnd"
class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 bg-white cursor-grab hover:bg-gray-50 hover:border-blue-300 transition-colors dark:bg-primary-d dark:border-primary/20 dark:hover:bg-primary/10"
:class="{
'opacity-50 cursor-grabbing': isDragging,
'shadow-sm hover:shadow-md': !isDragging
}"
>
<div class="flex-shrink-0 w-8 h-8 rounded-md bg-blue-100 flex items-center justify-center dark:bg-blue-900/30">
<GoogleIcon
:name="icon"
class="text-blue-600 dark:text-blue-400 text-lg"
/>
</div>
<div class="flex-1 min-w-0">
<div class="text-sm font-medium text-gray-900 dark:text-primary-dt">
{{ title }}
</div>
<div class="text-xs text-gray-500 dark:text-primary-dt/70 truncate">
{{ description }}
</div>
</div>
</div>
</template>

View File

@ -1,366 +1,113 @@
<script setup>
import { ref, computed, nextTick, watch } from "vue";
import { ref, computed, watch } from "vue";
import GoogleIcon from "@Shared/GoogleIcon.vue";
import SimpleTable from "./TableEditor.vue";
import TiptapEditor from "./TiptapEditor.vue";
/** Propiedades */
const props = defineProps({
element: {
type: Object,
required: true,
},
isSelected: {
type: Boolean,
default: false,
},
element: { type: Object, required: true },
isSelected: { type: Boolean, default: false },
});
const emit = defineEmits([
"select",
"delete",
"update",
"move",
"editor-active",
"table-editing",
]);
/** Eventos */
const emit = defineEmits(["select", "delete", "update", "move"]);
/** Referencias */
const isEditing = ref(false);
const editValue = ref("");
const editInput = ref(null);
const editTextarea = ref(null);
const elementRef = ref(null);
const isDragging = ref(false);
const isResizing = ref(false);
const resizeDirection = ref(null); // 'corner', 'right', 'bottom'
const dragStart = ref({ x: 0, y: 0 });
const dragStart = ref({ mouseX: 0, mouseY: 0, elementX: 0, elementY: 0 });
const resizeStart = ref({ x: 0, y: 0, width: 0, height: 0 });
const fileInput = ref(null);
/** Referencias adicionales para auto-posicionamiento */
const controlsRef = ref(null);
/** Propiedades computadas */
const elementStyles = computed(() => {
const baseStyles = {
const elementStyles = computed(() => ({
left: `${props.element.x}px`,
top: `${props.element.y}px`,
width: `${props.element.width || 200}px`,
height: `${props.element.height || 40}px`,
// Asegurar que la fuente se renderice con la misma métrica que el PDF
fontFamily: "Helvetica, Arial, sans-serif",
lineHeight: "1.2",
letterSpacing: "normal",
};
height: `${props.element.height || 120}px`,
position: "absolute",
}));
// Aplicar estilos de formato para elementos de texto
if (props.element.type === "text" && props.element.formatting) {
const formatting = props.element.formatting;
// Aplicar tamaño de fuente con factor de corrección
if (formatting.fontSize) {
baseStyles.fontSize = `${formatting.fontSize}px`;
}
if (formatting.color) {
baseStyles.color = formatting.color;
}
// Alineación del contenedor en la página
if (formatting.containerAlign) {
const pageWidth = 794; // A4 width por defecto
const elementWidth = props.element.width || 200;
switch (formatting.containerAlign) {
case "center":
baseStyles.left = `${(pageWidth - elementWidth) / 2}px`;
break;
case "right":
baseStyles.left = `${pageWidth - elementWidth - 50}px`; // 50px margen
break;
case "left":
default:
baseStyles.left = `${props.element.x}px`;
watch(
() => props.isSelected,
(selected) => {
if (!selected && isEditing.value) {
isEditing.value = false;
emit("editor-active", null);
if (props.element.type === "table") {
emit("table-editing", false);
}
}
}
);
return baseStyles;
});
// Propiedades computadas para clases CSS dinámicas
const textContainerClasses = computed(() => {
if (props.element.type !== "text") return {};
const formatting = props.element.formatting || {};
return {
"font-bold": formatting.bold,
italic: formatting.italic,
underline: formatting.underline,
"text-left": !formatting.textAlign || formatting.textAlign === "left",
"text-center": formatting.textAlign === "center",
"text-right": formatting.textAlign === "right",
"justify-start": !formatting.textAlign || formatting.textAlign === "left",
"justify-center": formatting.textAlign === "center",
"justify-end": formatting.textAlign === "right",
};
});
const inputClasses = computed(() => {
if (props.element.type !== "text") return {};
const formatting = props.element.formatting || {};
return {
"font-bold": formatting.bold,
italic: formatting.italic,
underline: formatting.underline,
"text-left": !formatting.textAlign || formatting.textAlign === "left",
"text-center": formatting.textAlign === "center",
"text-right": formatting.textAlign === "right",
};
});
const inputStyles = computed(() => {
if (props.element.type !== "text") return {};
const formatting = props.element.formatting || {};
const styles = {};
if (formatting.fontSize) {
styles.fontSize = `${formatting.fontSize}px`;
}
if (formatting.color) {
styles.color = formatting.color;
}
return styles;
});
/** Propiedades computadas para posicionamiento dinámico */
const controlsPosition = computed(() => {
if (!props.isSelected || isEditing.value) return {};
// Si el elemento está muy cerca del borde superior
const isNearTop = props.element.y < 50;
return {
styles: isNearTop
? {
top: "100%",
marginTop: "8px",
}
: {
bottom: "100%",
marginBottom: "8px",
},
};
});
const tooltipPosition = computed(() => {
if (!props.isSelected || isEditing.value) return {};
const isNearTop = props.element.y < 50;
const hasControlButtons = props.element.type === "image";
const rightOffset = hasControlButtons ? "60px" : "0px";
return {
position: isNearTop ? "bottom" : "top",
styles: isNearTop
? {
top: "100%",
marginTop: "8px",
right: rightOffset,
}
: {
bottom: "100%",
marginBottom: "8px",
right: rightOffset,
},
};
});
const handleImageDoubleClick = (event) => {
event.stopPropagation();
if (props.element.type === "image") {
fileInput.value?.click();
}
};
/** Métodos */
const handleSelect = (event) => {
event.stopPropagation();
emit("select", props.element.id);
};
const handleDelete = () => {
emit("delete", props.element.id);
};
const startEditing = () => {
if (props.element.type === "table" && props.element.content) {
// Deep copy para evitar mutaciones directas
editValue.value = JSON.parse(JSON.stringify(props.element.content));
} else if (props.element.type === "code") {
editValue.value = props.element.content || 'console.log("Hola mundo");';
} else {
editValue.value = props.element.content || getDefaultEditValue();
}
if (!props.isSelected) emit("select", props.element.id);
if (props.element.type === "text" || props.element.type === "table") {
isEditing.value = true;
nextTick(() => {
if (editTextarea.value) editTextarea.value.focus();
if (editInput.value) editInput.value.focus();
});
if (props.element.type === "table") {
emit("table-editing", true);
}
}
if (props.element.type === "image") {
fileInput.value.click();
}
};
const finishEditing = () => {
if (isEditing.value) {
isEditing.value = false;
const handleContentUpdate = (newContent) => {
emit("update", { id: props.element.id, content: newContent });
};
// Para tablas, los datos ya se actualizaron en tiempo real
// Solo necesitamos confirmar que se guardaron
if (props.element.type === "table" && editValue.value) {
const handleCellUpdate = (rowIndex, colIndex, value) => {
const updatedData = JSON.parse(JSON.stringify(props.element.content.data));
updatedData[rowIndex][colIndex] = value;
emit("update", {
id: props.element.id,
content: editValue.value,
});
} else if (props.element.type !== "table") {
emit("update", {
id: props.element.id,
content: editValue.value,
});
}
}
};
const handleKeydown = (event) => {
if (props.element.type === "text") {
// Permitir Enter para salto de línea
if (event.key === "Enter") {
if (event.shiftKey || event.ctrlKey) {
event.preventDefault();
finishEditing();
}
// Si es solo Enter, permitir el salto de línea normal
} else if (event.key === "Escape") {
isEditing.value = false;
editValue.value = props.element.content || "Nuevo texto";
} else if (event.key === "Tab") {
event.preventDefault();
const start = editTextarea.value.selectionStart;
const end = editTextarea.value.selectionEnd;
const spaces = " ";
editValue.value =
editValue.value.substring(0, start) +
spaces +
editValue.value.substring(end);
// Restaurar posición del cursor
nextTick(() => {
editTextarea.value.selectionStart = editTextarea.value.selectionEnd =
start + spaces.length;
});
}
} else if (props.element.type === "code") {
if (event.key === "Escape") {
isEditing.value = false;
editValue.value = props.element.content || 'console.log("Hola mundo");';
}
// Para código, permitimos Enter normal y usamos Ctrl+Enter para terminar
if (event.key === "Enter" && event.ctrlKey) {
event.preventDefault();
finishEditing();
}
} else if (props.element.type === "table") {
if (event.key === "Escape") {
isEditing.value = false;
// Restaurar el contenido original de la tabla
editValue.value = props.element.content
? JSON.parse(JSON.stringify(props.element.content))
: getDefaultEditValue();
}
}
};
// Función para ajustar altura automáticamente del textarea
const adjustTextareaHeight = () => {
if (editTextarea.value) {
editTextarea.value.style.height = "auto";
editTextarea.value.style.height = editTextarea.value.scrollHeight + "px";
// Actualizar altura del elemento si es necesario
const newHeight = Math.max(40, editTextarea.value.scrollHeight + 20);
if (newHeight !== props.element.height) {
emit("update", {
id: props.element.id,
height: newHeight,
});
}
}
};
// Función para contar líneas y ajustar altura
const updateTextHeight = () => {
if (props.element.type === "text" && editValue.value) {
const lines = editValue.value.split("\n");
const fontSize = props.element.formatting?.fontSize || 14;
const lineHeight = fontSize * 1.4; // Factor de altura de línea
const padding = 20; // Padding vertical
const newHeight = Math.max(40, lines.length * lineHeight + padding);
if (newHeight !== props.element.height) {
emit("update", {
id: props.element.id,
height: newHeight,
});
}
}
};
// Manejo de archivo de imagen
const handleFileSelect = (event) => {
const file = event.target.files[0];
if (file && file.type.startsWith("image/")) {
const reader = new FileReader();
reader.onload = (e) => {
emit("update", {
id: props.element.id,
content: e.target.result,
fileName: file.name,
content: { data: updatedData },
});
};
reader.readAsDataURL(file);
}
// Limpiar el input
event.target.value = "";
const handleEditorFocus = (editor) => {
emit("editor-active", editor);
};
// Funcionalidad de arrastre
const handleMouseDown = (event) => {
if (isEditing.value || isResizing.value) return;
if (isEditing.value || event.target.closest(".resize-handle")) return;
event.preventDefault();
if (!props.isSelected) emit("select", props.element.id);
isDragging.value = true;
dragStart.value = {
x: event.clientX - props.element.x,
y: event.clientY - props.element.y,
mouseX: event.clientX,
mouseY: event.clientY,
elementX: props.element.x,
elementY: props.element.y,
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
event.preventDefault();
};
const handleMouseMove = (event) => {
if (isDragging.value && !isResizing.value) {
const newX = event.clientX - dragStart.value.x;
const newY = event.clientY - dragStart.value.y;
if (isDragging.value) {
const deltaX = event.clientX - dragStart.value.mouseX;
const deltaY = event.clientY - dragStart.value.mouseY;
const newX = dragStart.value.elementX + deltaX;
const newY = dragStart.value.elementY + deltaY;
emit("move", {
id: props.element.id,
x: Math.max(0, newX),
y: Math.max(0, newY),
});
} else if (isResizing.value && !isDragging.value) {
} else if (isResizing.value) {
handleResizeMove(event);
}
};
@ -368,214 +115,49 @@ const handleMouseMove = (event) => {
const handleMouseUp = () => {
isDragging.value = false;
isResizing.value = false;
resizeDirection.value = null;
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
};
// Funcionalidad de redimensionamiento por esquina
const startResize = (event) => {
event.stopPropagation();
event.preventDefault();
if (isEditing.value) return;
isResizing.value = true;
resizeDirection.value = "corner";
resizeStart.value = {
x: event.clientX,
y: event.clientY,
width: props.element.width || 200,
height: props.element.height || 40,
width: elementRef.value.offsetWidth,
height: elementRef.value.offsetHeight,
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
// Funcionalidad de redimensionamiento por bordes
const startResizeEdge = (event, direction) => {
event.stopPropagation();
event.preventDefault();
isResizing.value = true;
resizeDirection.value = direction;
resizeStart.value = {
x: event.clientX,
y: event.clientY,
width: props.element.width || 200,
height: props.element.height || 40,
};
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
};
const handleResizeMove = (event) => {
if (!isResizing.value) return;
const deltaX = event.clientX - resizeStart.value.x;
const deltaY = event.clientY - resizeStart.value.y;
const newWidth = Math.max(100, resizeStart.value.width + deltaX);
const newHeight = Math.max(40, resizeStart.value.height + deltaY);
emit("update", { id: props.element.id, width: newWidth, height: newHeight });
};
let newWidth = resizeStart.value.width;
let newHeight = resizeStart.value.height;
// Calcular nuevas dimensiones según la dirección
if (resizeDirection.value === "corner") {
newWidth = Math.max(
getMinWidth(),
Math.min(getMaxWidth(), resizeStart.value.width + deltaX)
);
newHeight = Math.max(
getMinHeight(),
Math.min(getMaxHeight(), resizeStart.value.height + deltaY)
);
} else if (resizeDirection.value === "right") {
newWidth = Math.max(
getMinWidth(),
Math.min(getMaxWidth(), resizeStart.value.width + deltaX)
);
} else if (resizeDirection.value === "bottom") {
newHeight = Math.max(
getMinHeight(),
Math.min(getMaxHeight(), resizeStart.value.height + deltaY)
);
}
const handleDelete = () => emit("delete", props.element.id);
const handleFileSelect = (event) => {
const file = event.target.files[0];
if (file && file.type.startsWith("image/")) {
const reader = new FileReader();
reader.onload = (e) =>
emit("update", {
id: props.element.id,
width: newWidth,
height: newHeight,
});
};
// Obtener tamaños mínimos según el tipo de elemento
const getMinWidth = () => {
switch (props.element.type) {
case "text":
return 100;
case "image":
return 100;
case "table":
return 200;
default:
return 100;
}
};
const getMinHeight = () => {
switch (props.element.type) {
case "text":
return 30;
case "image":
return 80;
case "table":
return 80;
default:
return 30;
}
};
// Obtener tamaños máximos según el tipo de elemento
const getMaxWidth = () => {
return 800; // Máximo general
};
const getMaxHeight = () => {
return 600; // Máximo general
};
/** Watchers */
watch(
() => props.isSelected,
(selected) => {
if (selected && isEditing.value) {
nextTick(() => {
if (props.element.type === "text" && editInput.value) {
editInput.value.focus();
editInput.value.select();
} else if (props.element.type === "code" && editTextarea.value) {
editTextarea.value.focus();
editTextarea.value.select();
}
});
}
}
);
// Watch para ajustar altura cuando cambie el texto
watch(editValue, () => {
if (isEditing.value && props.element.type === "text") {
nextTick(() => {
adjustTextareaHeight();
updateTextHeight();
});
}
});
const getDefaultEditValue = () => {
switch (props.element.type) {
case "text":
return "Nuevo texto";
case "table":
return {
data: [
["Columna 1", "Columna 2", "Columna 3"],
["Fila 1", "Fila 1", "Fila 1"],
["Fila 2", "Fila 2", "Fila 2"],
],
rows: 3,
cols: 3,
};
default:
return "";
}
};
// Nuevas variables reactivas para selección de texto
const selectedTextRange = ref(null);
const isSelectingText = ref(false);
// Método para capturar selección de texto
const handleTextSelection = () => {
if (props.element.type === 'text' && !isEditing.value) {
const selection = window.getSelection();
if (selection.rangeCount > 0 && selection.toString().length > 0) {
const range = selection.getRangeAt(0);
selectedTextRange.value = {
start: range.startOffset,
end: range.endOffset,
text: selection.toString()
};
isSelectingText.value = true;
// Emitir evento para activar TextFormatter
emit('text-selected', {
id: props.element.id,
selection: selectedTextRange.value,
element: props.element
});
} else {
selectedTextRange.value = null;
isSelectingText.value = false;
}
}
};
// Aplicar formato solo a texto seleccionado
const applyFormatToSelection = (formatting) => {
if (selectedTextRange.value && props.element.type === 'text') {
// Crear un nuevo contenido con formato aplicado solo a la selección
const content = props.element.content || '';
const beforeSelection = content.substring(0, selectedTextRange.value.start);
const selectedText = content.substring(selectedTextRange.value.start, selectedTextRange.value.end);
const afterSelection = content.substring(selectedTextRange.value.end);
// Aquí podrías implementar markdown o HTML para mantener formato
// Por ahora aplicamos formato a todo el elemento como antes
emit('update', {
id: props.element.id,
formatting: formatting
content: e.target.result,
fileName: file.name,
});
reader.readAsDataURL(file);
}
event.target.value = null;
};
</script>
@ -583,22 +165,96 @@ const applyFormatToSelection = (formatting) => {
<div
ref="elementRef"
:style="elementStyles"
class="group select-none bg-white border border-gray-300 rounded"
:class="{
'ring-2 ring-blue-500 border-blue-500 z-10': isSelected,
'z-20': isEditing,
'shadow-md': isSelected,
'overflow-hidden': element.type === 'image',
}"
@click="handleSelect"
@dblclick="startEditing"
@mousedown="handleMouseDown"
class="absolute group select-none"
:class="{
'ring-2 ring-blue-500 ring-opacity-50': isSelected,
'cursor-move': !isEditing && !isResizing,
'cursor-text': isEditing && element.type === 'text',
'cursor-se-resize': isResizing && resizeDirection === 'corner',
'cursor-e-resize': isResizing && resizeDirection === 'right',
'cursor-s-resize': isResizing && resizeDirection === 'bottom',
'z-50': isSelected,
'z-10': !isSelected,
}"
>
<!-- Input oculto para selección de archivos -->
<div
v-if="!isEditing"
@mousedown="handleMouseDown"
class="absolute inset-0 z-10 cursor-move"
/>
<TiptapEditor
v-if="element.type === 'text'"
:model-value="element.content"
:editable="isEditing"
@update:model-value="handleContentUpdate"
@focus="handleEditorFocus"
/>
<div
v-else-if="element.type === 'image'"
class="w-full h-full flex items-center justify-center bg-gray-50"
>
<img
v-if="element.content"
:src="element.content"
class="w-full h-full object-cover rounded"
:alt="element.fileName || 'Imagen'"
/>
<div v-else class="text-gray-400 text-center p-4">
<GoogleIcon name="image" class="text-3xl mb-2" />
<p class="text-xs">Doble clic para subir</p>
</div>
</div>
<div
v-else-if="element.type === 'table'"
class="w-full h-full overflow-auto"
@mousedown.stop
>
<table class="w-full h-full border-collapse">
<tbody>
<tr
v-for="(row, rowIndex) in element.content.data"
:key="rowIndex"
class="align-top"
>
<td
v-for="(cell, colIndex) in row"
:key="colIndex"
class="border p-0 text-sm relative"
>
<TiptapEditor
:key="`${element.id}-${rowIndex}-${colIndex}`"
:model-value="cell"
:editable="isEditing"
@update:model-value="
handleCellUpdate(rowIndex, colIndex, $event)
"
@focus="handleEditorFocus"
class="w-full h-full min-h-[2.5em]"
/>
</td>
</tr>
</tbody>
</table>
</div>
<div
v-if="isSelected && !isEditing"
class="absolute -top-8 right-0 flex items-center gap-1 z-20"
>
<button
@click.stop="handleDelete"
class="w-6 h-6 bg-red-500 hover:bg-red-600 text-white rounded flex items-center justify-center text-xs font-bold transition-colors"
title="Eliminar"
>
x
</button>
</div>
<div
v-if="isSelected && !isEditing"
@mousedown.stop="startResize"
class="resize-handle absolute -bottom-1 -right-1 w-3 h-3 bg-blue-500 border-2 border-white cursor-se-resize rounded-full z-20 hover:bg-blue-600 transition-colors"
/>
<input
ref="fileInput"
type="file"
@ -606,222 +262,5 @@ const applyFormatToSelection = (formatting) => {
@change="handleFileSelect"
class="hidden"
/>
<!-- Elemento de Texto MEJORADO -->
<div
v-if="element.type === 'text'"
class="w-full h-full flex items-start px-3 py-2 bg-white rounded border border-gray-300 shadow-sm"
:class="textContainerClasses"
:style="{
fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px',
color: element.formatting?.color || '#374151',
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.4',
letterSpacing: 'normal',
textRendering: 'geometricPrecision',
fontSmooth: 'always',
WebkitFontSmoothing: 'antialiased',
}"
>
<!-- Textarea para edición -->
<textarea
v-if="isEditing"
ref="editTextarea"
v-model="editValue"
@blur="finishEditing"
@keydown="handleKeydown"
@input="adjustTextareaHeight"
class="w-full bg-transparent outline-none resize-none cursor-text"
:class="inputClasses"
:style="{
...inputStyles,
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.4',
letterSpacing: 'normal',
minHeight: '20px',
height: 'auto',
}"
@mousedown.stop
placeholder="Escribe tu texto aquí... (Shift+Enter o Ctrl+Enter para terminar)"
></textarea>
<!-- Vista de solo lectura con selección de texto -->
<div
v-else
class="w-full h-full overflow-hidden cursor-text"
:class="textContainerClasses"
:style="{
fontSize: element.formatting?.fontSize ? `${element.formatting.fontSize}px` : '14px',
color: element.formatting?.color || '#374151',
fontFamily: 'Helvetica, Arial, sans-serif',
lineHeight: '1.4',
letterSpacing: 'normal',
whiteSpace: 'pre-wrap',
wordWrap: 'break-word',
}"
@mouseup="handleTextSelection"
@selectstart="() => isSelectingText = true"
>
{{ element.content || "Nuevo texto" }}
</div>
</div>
<!-- Elemento de Imagen -->
<div
v-else-if="element.type === 'image'"
class="w-full h-full flex items-center justify-center bg-gray-100 rounded border border-gray-300 dark:bg-primary/10 dark:border-primary/20 overflow-hidden"
@dblclick.stop="handleImageDoubleClick"
>
<!-- Si hay imagen cargada -->
<img
v-if="element.content && element.content.startsWith('data:image')"
:src="element.content"
:alt="element.fileName || 'Imagen'"
class="w-full h-full object-cover pointer-events-none"
/>
<!-- Placeholder para imagen -->
<div
v-else
class="flex flex-col items-center justify-center text-gray-400 dark:text-primary-dt/50 p-4"
>
<GoogleIcon name="image" class="text-2xl mb-1" />
<span class="text-xs text-center"
>Haz doble clic para cargar imagen</span
>
</div>
</div>
<!-- Elemento de Tabla SIMPLE -->
<SimpleTable
v-if="element.type === 'table'"
:element="element"
:is-editing="isEditing"
@update="(data) => emit('update', data)"
@finish-editing="() => { isEditing = false; }"
/>
<!-- Controles del elemento -->
<div
v-if="isSelected && !isEditing"
ref="controlsRef"
class="absolute right-0 flex gap-1 opacity-100 transition-opacity z-[60]"
:style="controlsPosition.styles"
>
<!-- Flecha indicadora cuando está abajo -->
<div
v-if="controlsPosition.position === 'bottom'"
class="absolute -top-2 right-2 w-0 h-0 border-l-4 border-r-4 border-b-4 border-l-transparent border-r-transparent border-b-gray-800"
></div>
<!-- Botón para cargar imagen -->
<button
v-if="element.type === 'image'"
@click.stop="() => fileInput.click()"
class="w-7 h-7 bg-blue-500 hover:bg-blue-600 text-white rounded-md text-xs flex items-center justify-center transition-colors shadow-md"
title="Cargar imagen"
>
<GoogleIcon name="upload" class="text-sm" />
</button>
<!-- Botón eliminar -->
<button
@click.stop="handleDelete"
class="w-7 h-7 bg-red-500 hover:bg-red-600 text-white rounded-md text-xs flex items-center justify-center transition-colors shadow-md"
title="Eliminar elemento"
>
<GoogleIcon name="close" class="text-sm" />
</button>
<!-- Flecha indicadora cuando está arriba -->
<div
v-if="controlsPosition.position === 'top'"
class="absolute -bottom-2 right-2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-gray-800"
></div>
</div>
<!-- Controles de redimensionamiento -->
<div
v-if="isSelected && !isEditing"
class="absolute inset-0 pointer-events-none z-[55]"
>
<!-- Esquina inferior derecha -->
<div
@mousedown.stop="startResize"
class="absolute -bottom-2 -right-2 w-5 h-5 bg-blue-500 border-2 border-white cursor-se-resize pointer-events-auto rounded-md shadow-lg hover:bg-blue-600 hover:scale-110 transition-all"
title="Redimensionar"
>
<div class="absolute inset-1 border border-white/40 rounded-sm"></div>
</div>
<!-- Lado derecho -->
<div
@mousedown.stop="(event) => startResizeEdge(event, 'right')"
class="absolute top-3 bottom-3 -right-1 w-2 bg-blue-500/80 cursor-e-resize pointer-events-auto rounded-full shadow-sm hover:bg-blue-600 hover:w-3 transition-all"
title="Redimensionar ancho"
>
<div
class="absolute top-1/2 left-1/2 w-0.5 h-6 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"
></div>
</div>
<!-- Lado inferior -->
<div
@mousedown.stop="(event) => startResizeEdge(event, 'bottom')"
class="absolute -bottom-1 left-3 right-3 h-2 bg-blue-500/80 cursor-s-resize pointer-events-auto rounded-full shadow-sm hover:bg-blue-600 hover:h-3 transition-all"
title="Redimensionar alto"
>
<div
class="absolute top-1/2 left-1/2 w-6 h-0.5 bg-white/60 -translate-x-1/2 -translate-y-1/2 rounded-full"
></div>
</div>
</div>
<!-- Tooltips adaptativos -->
<div
v-if="
isSelected && !element.content && element.type === 'text' && !isResizing
"
class="absolute right-0 bg-gray-900 text-white text-xs px-2 py-1 rounded whitespace-nowrap z-[60]"
:style="{
...tooltipPosition.styles,
[tooltipPosition.position === 'top' ? 'bottom' : 'top']: '100%',
[tooltipPosition.position === 'top' ? 'marginBottom' : 'marginTop']:
'8px',
}"
>
Doble clic para escribir párrafos
</div>
<!-- Indicador de arrastre -->
<div
v-if="isDragging"
class="absolute inset-0 bg-blue-500 opacity-20 rounded pointer-events-none"
></div>
<!-- Indicador de redimensionamiento -->
<div
v-if="isResizing"
class="absolute inset-0 bg-green-500 opacity-20 rounded pointer-events-none"
></div>
</div>
</template>
<style scoped>
.select-none {
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
/* Estilos para textarea */
textarea {
overflow: hidden;
scrollbar-width: none;
-ms-overflow-style: none;
}
textarea::-webkit-scrollbar {
display: none;
}
</style>

View File

@ -11,6 +11,7 @@ const props = defineProps({
icon: String,
title: String,
description: String,
tag: String
});
/** Eventos */
@ -24,7 +25,8 @@ const handleDragStart = (event) => {
isDragging.value = true;
event.dataTransfer.setData('text/plain', JSON.stringify({
type: props.type,
title: props.title
title: props.title,
tag: props.tag
}));
emit('dragstart', props.type);
};

View File

@ -5,348 +5,140 @@ import PageSizeSelector from '@Holos/PDF/PageSizeSelector.vue';
/** Propiedades */
const props = defineProps({
pages: {
type: Array,
default: () => [{ id: 1, elements: [] }]
},
selectedElementId: String,
isExporting: Boolean
pages: { type: Array, default: () => [] },
currentPage: { type: Number, default: 1 }
});
/** Eventos */
const emit = defineEmits(['drop', 'dragover', 'click', 'add-page', 'delete-page', 'page-change', 'page-size-change']);
const emit = defineEmits(['drop', 'add-page', 'delete-page', 'page-change', 'page-size-change', 'click']);
/** Referencias */
const viewportRef = ref(null);
const currentPage = ref(1);
const pageSize = ref('A4');
/** Tamaños de página */
const pageSizes = {
'A4': { width: 794, height: 1123, label: '210 × 297 mm' },
'A3': { width: 1123, height: 1587, label: '297 × 420 mm' },
'Letter': { width: 816, height: 1056, label: '216 × 279 mm' },
'Legal': { width: 816, height: 1344, label: '216 × 356 mm' },
'Tabloid': { width: 1056, height: 1632, label: '279 × 432 mm' }
'A4': { width: 794, height: 1123, label: 'A4 (210 x 297 mm)' },
'Letter': { width: 816, height: 1056, label: 'Carta (216 x 279 mm)' },
'A3': { width: 1123, height: 1587, label: 'A3 (297 x 420 mm)' },
'Legal': { width: 816, height: 1344, label: 'Oficio (216 x 356 mm)' },
'Tabloid': { width: 1056, height: 1632, label: 'Tabloide (279 x 432 mm)' }
};
/** Constantes de diseño ajustadas */
const PAGE_MARGIN = 50;
const ZOOM_LEVEL = 0.65;
/** Propiedades computadas */
const currentPageSize = computed(() => pageSizes[pageSize.value]);
const PAGE_WIDTH = computed(() => currentPageSize.value.width);
const PAGE_HEIGHT = computed(() => currentPageSize.value.height);
const scaledPageWidth = computed(() => PAGE_WIDTH.value * ZOOM_LEVEL);
const scaledPageHeight = computed(() => PAGE_HEIGHT.value * ZOOM_LEVEL);
const currentPageSize = computed(() => pageSizes[pageSize.value] || pageSizes['A4']);
const scaledPageWidth = computed(() => currentPageSize.value.width * ZOOM_LEVEL);
const scaledPageHeight = computed(() => currentPageSize.value.height * ZOOM_LEVEL);
const totalPages = computed(() => props.pages.length);
/** Watchers */
watch(pageSize, (newSize) => {
emit('page-size-change', {
size: newSize,
dimensions: pageSizes[newSize]
});
emit('page-size-change', { size: newSize, dimensions: pageSizes[newSize] });
});
/** Métodos */
const handleDrop = (event, pageIndex) => {
event.preventDefault();
const pageElement = event.currentTarget;
const rect = pageElement.getBoundingClientRect();
const relativeX = (event.clientX - rect.left) / ZOOM_LEVEL;
const relativeY = (event.clientY - rect.top) / ZOOM_LEVEL;
emit('drop', {
originalEvent: event,
pageIndex,
x: Math.max(0, Math.min(PAGE_WIDTH.value, relativeX)),
y: Math.max(0, Math.min(PAGE_HEIGHT.value, relativeY))
});
const rect = event.currentTarget.getBoundingClientRect();
const x = (event.clientX - rect.left) / ZOOM_LEVEL;
const y = (event.clientY - rect.top) / ZOOM_LEVEL;
emit('drop', { originalEvent: event, pageIndex, x, y });
};
const handleDragOver = (event) => {
event.preventDefault();
emit('dragover', event);
};
const handleClick = (event, pageIndex) => {
if (event.target.classList.contains('pdf-page')) {
emit('click', { originalEvent: event, pageIndex });
}
const setCurrentPage = (pageNumber) => {
emit('page-change', pageNumber);
};
const addPageAndNavigate = () => {
emit('add-page');
nextTick(() => {
setCurrentPage(totalPages.value);
});
};
const handleNextPage = () => {
if (currentPage.value >= totalPages.value) {
addPage();
if (props.currentPage >= totalPages.value) {
addPageAndNavigate();
} else {
setCurrentPage(currentPage.value + 1);
setCurrentPage(props.currentPage + 1);
}
};
const addPage = () => {
emit('add-page');
// Solo cambiar a la nueva página cuando se agrega una
nextTick(() => {
const newPageNumber = totalPages.value + 1;
setCurrentPage(newPageNumber);
});
};
const deletePage = (pageIndex) => {
if (totalPages.value > 1) {
emit('delete-page', pageIndex);
}
};
const scrollToPage = (pageNumber) => {
if (viewportRef.value) {
const pageElement = viewportRef.value.querySelector(`[data-page="${pageNumber}"]`);
if (pageElement) {
pageElement.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'center'
});
}
}
};
const setCurrentPage = (pageNumber) => {
currentPage.value = pageNumber;
emit('page-change', pageNumber);
// Mantener la página actual centrada
nextTick(() => {
scrollToPage(pageNumber);
});
};
/** Métodos expuestos */
defineExpose({
scrollToPage,
setCurrentPage,
PAGE_WIDTH,
PAGE_HEIGHT,
ZOOM_LEVEL
});
</script>
<template>
<div class="flex-1 flex flex-col bg-gray-100 dark:bg-primary-d/20">
<!-- Toolbar de páginas -->
<div class="flex items-center justify-between px-4 py-3 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20">
<div class="flex-1 flex flex-col bg-gray-100">
<div class="flex items-center justify-between px-4 py-3 bg-white border-b">
<div class="flex items-center gap-4">
<span class="text-sm font-medium text-gray-700 dark:text-primary-dt">
<span class="text-sm font-medium text-gray-700">
Página {{ currentPage }} de {{ totalPages }}
</span>
<div class="flex items-center gap-1 border-l border-gray-200 dark:border-primary/20 pl-4">
<div class="flex items-center gap-1 border-l pl-4">
<button
@click="setCurrentPage(Math.max(1, currentPage - 1))"
:disabled="currentPage <= 1"
class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded-md hover:bg-gray-100 dark:hover:bg-primary/10 transition-colors"
class="p-2 text-gray-500 hover:text-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
title="Página anterior"
>
<GoogleIcon name="keyboard_arrow_left" class="text-xl" />
</button>
<button
@click="handleNextPage"
:disabled="isExporting"
class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt rounded-md hover:bg-gray-100 dark:hover:bg-primary/10 relative transition-colors"
class="p-2 text-gray-500 hover:text-gray-700"
:title="currentPage >= totalPages ? 'Crear nueva página' : 'Página siguiente'"
>
<GoogleIcon name="keyboard_arrow_right" class="text-xl" />
<!-- Indicador mejorado -->
<div
v-if="currentPage >= totalPages"
class="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full flex items-center justify-center"
>
<GoogleIcon name="add" class="text-white text-xs" />
</div>
</button>
</div>
</div>
<div class="flex items-center gap-4">
<!-- Selector de tamaño de página -->
<div class="flex-shrink-0">
<PageSizeSelector v-model="pageSize" />
<!-- Info de página -->
<span class="text-xs text-gray-500 dark:text-primary-dt/70 bg-gray-50 dark:bg-primary/10 px-3 py-1.5 rounded-md border border-gray-200 dark:border-primary/20">
{{ currentPageSize.label }}
</span>
<button
@click="addPage"
:disabled="isExporting"
class="flex items-center gap-2 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors disabled:opacity-50 font-medium shadow-sm"
>
<GoogleIcon name="add" class="text-sm" />
Nueva Página
</button>
</div>
</div>
<!-- Resto del viewport -->
<div
ref="viewportRef"
class="flex-1 overflow-auto"
style="background-color: #f8fafc; background-image: radial-gradient(circle, #e2e8f0 1px, transparent 1px); background-size: 20px 20px;"
>
<!-- Contenedor horizontal centrado -->
<div class="flex items-center justify-center min-h-full p-8">
<div class="flex items-center gap-10">
<!-- Páginas MEJORADAS -->
<div
v-for="(page, pageIndex) in pages"
:key="page.id"
:data-page="pageIndex + 1"
class="relative group flex-shrink-0"
>
<!-- Header de página -->
<div class="flex flex-col items-center mb-4">
<div class="flex items-center gap-3 mb-1">
<span class="text-sm font-semibold text-gray-700 dark:text-primary-dt/90 bg-white dark:bg-primary-d px-3 py-1 rounded-full shadow-sm border border-gray-200 dark:border-primary/20">
<div class="flex-1 overflow-auto p-8" @click="$emit('click', $event)">
<div class="flex items-start justify-center gap-8 min-h-full">
<div v-for="(page, pageIndex) in pages" :key="page.id" class="relative group flex-shrink-0">
<div class="absolute -top-6 left-1/2 transform -translate-x-1/2 text-xs text-gray-500 whitespace-nowrap">
Página {{ pageIndex + 1 }}
</span>
</div>
<button
v-if="totalPages > 1"
@click="deletePage(pageIndex)"
:disabled="isExporting"
class="opacity-0 group-hover:opacity-100 w-7 h-7 text-red-500 hover:text-white hover:bg-red-500 disabled:opacity-50 rounded-full flex items-center justify-center transition-all duration-200"
class="absolute -top-6 right-0 w-6 h-6 bg-white rounded-full text-red-500 opacity-0 group-hover:opacity-100 flex items-center justify-center shadow-md hover:shadow-lg transition-all z-10"
title="Eliminar página"
>
<GoogleIcon name="delete" class="text-sm" />
</button>
</div>
<span class="text-xs text-gray-500 dark:text-primary-dt/60">
{{ currentPageSize.label }}
</span>
</div>
<!-- Contenedor de página -->
<div class="relative">
<!-- Sombra mejorada -->
<div class="absolute top-3 left-3 w-full h-full bg-gray-400/20 rounded-xl blur-sm"></div>
<!-- Página PDF -->
<div
class="pdf-page relative bg-white rounded-xl border border-gray-300 dark:border-primary/30 overflow-hidden transition-all duration-300"
class="pdf-page relative bg-white shadow-lg rounded-md border transition-all duration-200 overflow-hidden"
:class="{
'ring-3 ring-blue-500/50 shadow-2xl scale-105': currentPage === pageIndex + 1,
'shadow-lg hover:shadow-xl hover:scale-102': currentPage !== pageIndex + 1,
'opacity-60': isExporting
}"
:style="{
width: `${scaledPageWidth}px`,
height: `${scaledPageHeight}px`
'ring-2 ring-blue-500': currentPage === pageIndex + 1,
'hover:shadow-xl': currentPage !== pageIndex + 1
}"
:style="{ width: `${scaledPageWidth}px`, height: `${scaledPageHeight}px` }"
@drop="(e) => handleDrop(e, pageIndex)"
@dragover="handleDragOver"
@click="(e) => handleClick(e, pageIndex)"
@click="setCurrentPage(pageIndex + 1)"
>
<!-- Área de contenido -->
<div class="relative w-full h-full">
<!-- Guías de margen SUTILES -->
<div
class="absolute border border-dashed border-blue-300/30 pointer-events-none rounded-lg"
:style="{
top: `${PAGE_MARGIN * ZOOM_LEVEL}px`,
left: `${PAGE_MARGIN * ZOOM_LEVEL}px`,
width: `${(PAGE_WIDTH - (PAGE_MARGIN * 2)) * ZOOM_LEVEL}px`,
height: `${(PAGE_HEIGHT - (PAGE_MARGIN * 2)) * ZOOM_LEVEL}px`
}"
></div>
<!-- Elementos de la página -->
<div
class="absolute inset-0"
:style="{
transform: `scale(${ZOOM_LEVEL})`,
transformOrigin: 'top left',
width: `${PAGE_WIDTH}px`,
height: `${PAGE_HEIGHT}px`
}"
:style="{ transform: `scale(${ZOOM_LEVEL})`, transformOrigin: 'top left' }"
>
<slot
name="elements"
:page="page"
:pageIndex="pageIndex"
:pageWidth="PAGE_WIDTH"
:pageHeight="PAGE_HEIGHT"
:zoomLevel="ZOOM_LEVEL"
/>
<slot name="elements" :page="page" />
</div>
</div>
<!-- Indicador de página vacía -->
<div
v-if="page.elements.length === 0"
class="absolute inset-0 flex items-center justify-center pointer-events-none z-10"
:style="{ transform: `scale(${1/ZOOM_LEVEL})` }"
>
<div class="text-center text-gray-400 dark:text-primary-dt/50 p-6 bg-gray-50/80 dark:bg-primary/5 rounded-xl border-2 border-dashed border-gray-300/50 dark:border-primary/20">
<GoogleIcon name="description" class="text-5xl mb-3 opacity-60" />
<p class="text-base font-medium mb-1">Página {{ pageIndex + 1 }}</p>
<p class="text-sm opacity-75">Arrastra elementos aquí</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Overlay durante exportación -->
<div
v-if="isExporting"
class="absolute inset-0 bg-white/95 dark:bg-primary-d/95 flex items-center justify-center z-50 backdrop-blur-sm"
>
<div class="text-center bg-white dark:bg-primary-d rounded-2xl p-8 shadow-2xl border border-gray-200 dark:border-primary/20 max-w-sm w-full mx-4">
<div class="relative mb-4">
<GoogleIcon name="picture_as_pdf" class="text-6xl text-red-600 dark:text-red-400 animate-pulse" />
<div class="absolute inset-0 bg-red-100 dark:bg-red-900/20 rounded-full animate-ping opacity-20"></div>
</div>
<p class="text-xl font-semibold text-gray-900 dark:text-primary-dt mb-2">Generando PDF</p>
<p class="text-sm text-gray-600 dark:text-primary-dt/70 mb-4">Procesando {{ totalPages }} página{{ totalPages !== 1 ? 's' : '' }}</p>
<div class="w-full bg-gray-200 dark:bg-primary/20 rounded-full h-1">
<div class="bg-red-600 dark:bg-red-400 h-1 rounded-full animate-pulse" style="width: 100%"></div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.pdf-page {
transform-origin: center;
}
.scale-102 {
transform: scale(1.02);
}
.overflow-auto::-webkit-scrollbar {
height: 6px;
width: 6px;
}
.overflow-auto::-webkit-scrollbar-track {
background: transparent;
}
.overflow-auto::-webkit-scrollbar-thumb {
background: #cbd5e1;
border-radius: 3px;
}
.overflow-auto::-webkit-scrollbar-thumb:hover {
background: #94a3b8;
}
</style>

View File

@ -32,20 +32,6 @@ const pageSizes = [
height: 1587,
description: 'Doble de A4'
},
{
name: 'Letter',
label: 'Carta (216 x 279 mm)',
width: 816,
height: 1056,
description: 'Estándar US'
},
{
name: 'Legal',
label: 'Oficio (216 x 356 mm)',
width: 816,
height: 1344,
description: 'Legal US'
},
{
name: 'Tabloid',
label: 'Tabloide (279 x 432 mm)',
@ -65,20 +51,24 @@ const selectSize = (size) => {
emit('update:modelValue', size.name);
isOpen.value = false;
};
const closeDropdown = () => {
isOpen.value = false;
};
</script>
<template>
<div class="relative">
<!-- Selector principal MEJORADO -->
<!-- Selector principal -->
<button
@click="isOpen = !isOpen"
class="flex items-center gap-2 px-3 py-2 text-sm bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-lg hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors shadow-sm"
class="flex items-center gap-2 px-3 py-2 text-sm bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-lg hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors shadow-sm min-w-0"
>
<GoogleIcon name="aspect_ratio" class="text-gray-500 dark:text-primary-dt/70" />
<span class="text-gray-700 dark:text-primary-dt font-medium">{{ selectedSize.name }}</span>
<GoogleIcon name="aspect_ratio" class="text-gray-500 dark:text-primary-dt/70 flex-shrink-0 text-lg" />
<span class="text-gray-700 dark:text-primary-dt font-medium truncate">{{ selectedSize.name }}</span>
<GoogleIcon
name="expand_more"
class="text-gray-400 dark:text-primary-dt/50 transition-transform"
class="text-gray-400 dark:text-primary-dt/50 transition-transform flex-shrink-0 text-lg"
:class="{ 'rotate-180': isOpen }"
/>
</button>
@ -86,54 +76,56 @@ const selectSize = (size) => {
<!-- Dropdown -->
<div
v-if="isOpen"
@click.away="isOpen = false"
class="absolute top-full left-0 mt-2 w-80 bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-xl shadow-xl z-50 py-3"
v-click-away="closeDropdown"
class="absolute top-full right-0 mt-2 w-64 bg-white dark:bg-primary-d border border-gray-200 dark:border-primary/20 rounded-lg shadow-xl z-50 py-2"
>
<div class="px-4 py-2 text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider border-b border-gray-100 dark:border-primary/20 mb-2">
<div class="px-3 py-2 text-xs font-semibold text-gray-500 dark:text-primary-dt/70 uppercase tracking-wider border-b border-gray-100 dark:border-primary/20">
Tamaños de página
</div>
<div class="max-h-72 overflow-y-auto">
<div class="max-h-60 overflow-y-auto">
<button
v-for="size in pageSizes"
:key="size.name"
@click="selectSize(size)"
class="w-full flex items-center gap-4 px-4 py-3 hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors text-left"
class="w-full flex items-center gap-3 px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-primary/10 transition-colors text-left"
:class="{
'bg-blue-50 dark:bg-blue-900/20 border-l-4 border-blue-500': selectedSize.name === size.name
'bg-blue-50 dark:bg-blue-900/20 border-l-2 border-blue-500': selectedSize.name === size.name
}"
>
<!-- Miniatura del tamaño de página -->
<div class="flex-shrink-0">
<div
class="w-10 h-12 border-2 border-gray-300 dark:border-primary/30 rounded-md bg-white dark:bg-primary-d flex items-center justify-center shadow-sm"
class="w-6 h-8 border border-gray-300 dark:border-primary/30 rounded bg-white dark:bg-primary-d flex items-center justify-center"
:class="{
'border-blue-500 dark:border-blue-400 shadow-blue-200': selectedSize.name === size.name
'border-blue-500 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20': selectedSize.name === size.name
}"
>
<div
class="bg-gray-200 dark:bg-primary/20 rounded-sm"
class="bg-gray-300 dark:bg-primary/40 rounded-sm"
:style="{
width: `${Math.min(24, (size.width / size.height) * 36)}px`,
height: `${Math.min(36, (size.height / size.width) * 24)}px`
width: `${Math.min(16, (size.width / size.height) * 24)}px`,
height: `${Math.min(24, (size.height / size.width) * 16)}px`
}"
:class="{
'bg-blue-200 dark:bg-blue-800': selectedSize.name === size.name
'bg-blue-400 dark:bg-blue-600': selectedSize.name === size.name
}"
></div>
</div>
</div>
<!-- Información del tamaño -->
<div class="flex-1 min-w-0">
<div class="font-semibold text-gray-900 dark:text-primary-dt text-base">{{ size.name }}</div>
<div class="text-sm text-gray-600 dark:text-primary-dt/80">{{ size.label.split('(')[1]?.replace(')', '') || size.label }}</div>
<div class="text-xs text-gray-500 dark:text-primary-dt/60 mt-1">
<div class="font-medium text-gray-900 dark:text-primary-dt text-sm">{{ size.name }}</div>
<div class="text-xs text-gray-500 dark:text-primary-dt/70 truncate">
{{ size.description }}
</div>
</div>
<!-- Indicador de selección -->
<div v-if="selectedSize.name === size.name" class="flex-shrink-0">
<div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
<GoogleIcon name="check" class="text-white text-sm" />
<div class="w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center">
<GoogleIcon name="check" class="text-white text-xs" />
</div>
</div>
</button>

View File

@ -1,201 +0,0 @@
<script setup>
import { ref, computed, watch } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
const props = defineProps({
element: {
type: Object,
required: true
},
isEditing: {
type: Boolean,
default: false
}
});
const emit = defineEmits(['update', 'finish-editing']);
// Estructura simple: empezar con una celda
const tableData = ref([]);
// Watcher para sincronizar datos
watch(() => props.element.content, (newContent) => {
if (newContent && newContent.data && Array.isArray(newContent.data)) {
tableData.value = JSON.parse(JSON.stringify(newContent.data));
} else {
// Inicializar con una sola celda
tableData.value = [['']];
}
}, { immediate: true });
const rows = computed(() => tableData.value.length);
const cols = computed(() => tableData.value[0]?.length || 1);
// Agregar fila
const addRow = () => {
const newRow = new Array(cols.value).fill('');
tableData.value.push(newRow);
updateTable();
};
// Agregar columna
const addColumn = () => {
tableData.value.forEach(row => {
row.push('');
});
updateTable();
};
// Eliminar fila (no permitir si solo hay una)
const removeRow = (rowIndex) => {
if (tableData.value.length > 1) {
tableData.value.splice(rowIndex, 1);
updateTable();
}
};
// Eliminar columna (no permitir si solo hay una)
const removeColumn = (colIndex) => {
if (tableData.value[0]?.length > 1) {
tableData.value.forEach(row => {
row.splice(colIndex, 1);
});
updateTable();
}
};
// Actualizar celda
const updateCell = (rowIndex, colIndex, value) => {
if (tableData.value[rowIndex]) {
tableData.value[rowIndex][colIndex] = value;
updateTable();
}
};
// Actualizar tabla
const updateTable = () => {
const updatedContent = {
data: JSON.parse(JSON.stringify(tableData.value)),
rows: tableData.value.length,
cols: tableData.value[0]?.length || 1
};
// Calcular dimensiones dinámicas basadas en contenido
const cellWidth = 120;
const cellHeight = 35;
const newWidth = Math.max(120, updatedContent.cols * cellWidth);
const newHeight = Math.max(40, updatedContent.rows * cellHeight);
emit('update', {
id: props.element.id,
content: updatedContent,
width: newWidth,
height: newHeight
});
};
const finishEditing = () => {
emit('finish-editing');
};
</script>
<template>
<div class="w-full h-full bg-white rounded border border-gray-300 overflow-hidden">
<!-- Controles de tabla (solo cuando está editando) -->
<div
v-if="isEditing"
class="flex items-center gap-2 p-2 bg-gray-50 border-b"
>
<button
@click="addRow"
class="px-2 py-1 text-xs bg-green-500 hover:bg-green-600 text-white rounded flex items-center gap-1"
title="Agregar fila"
>
<GoogleIcon name="add" class="text-xs" />
+
</button>
<button
@click="addColumn"
class="px-2 py-1 text-xs bg-blue-500 hover:bg-blue-600 text-white rounded flex items-center gap-1"
title="Agregar columna"
>
<GoogleIcon name="add" class="text-xs" />
+
</button>
<div class="flex-1"></div>
<span class="text-xs text-gray-500">
{{ rows }}x{{ cols }}
</span>
<button
@click="finishEditing"
class="px-2 py-1 text-xs bg-gray-600 hover:bg-gray-700 text-white rounded"
>
Cerrar
</button>
</div>
<!-- Tabla -->
<div class="w-full h-full">
<table class="w-full h-full border-collapse text-sm">
<tbody>
<tr
v-for="(row, rowIndex) in tableData"
:key="`row-${rowIndex}`"
class="group"
:style="{ height: `${100/rows}%` }"
>
<td
v-for="(cell, colIndex) in row"
:key="`cell-${rowIndex}-${colIndex}`"
class="border border-gray-300 p-1 relative group/cell"
:style="{ width: `${100/cols}%` }"
>
<!-- Controles de celda (solo cuando está editando) -->
<div
v-if="isEditing && (rows > 1 || cols > 1)"
class="absolute -top-2 -right-2 opacity-0 group-hover/cell:opacity-100 transition-opacity z-10"
>
<!-- Eliminar fila -->
<button
v-if="rows > 1 && colIndex === 0"
@click="removeRow(rowIndex)"
class="w-4 h-4 bg-red-500 text-white rounded-full text-xs flex items-center justify-center mr-1"
title="Eliminar fila"
>
×
</button>
<!-- Eliminar columna -->
<button
v-if="cols > 1 && rowIndex === 0"
@click="removeColumn(colIndex)"
class="w-4 h-4 bg-red-500 text-white rounded-full text-xs flex items-center justify-center"
title="Eliminar columna"
>
×
</button>
</div>
<!-- Input de celda -->
<input
v-if="isEditing"
:value="cell"
@input="updateCell(rowIndex, colIndex, $event.target.value)"
class="w-full h-full bg-transparent outline-none text-center text-sm resize-none"
@click.stop
:placeholder="rowIndex === 0 && colIndex === 0 && !cell ? 'Escribe aquí...' : ''"
/>
<!-- Vista de solo lectura -->
<div v-else class="w-full h-full flex items-center justify-center text-center text-sm p-1">
{{ cell || (rowIndex === 0 && colIndex === 0 ? 'Tabla' : '') }}
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>

View File

@ -1,283 +1,221 @@
<script setup>
import { ref, computed, watch } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import { computed, ref } from "vue";
import GoogleIcon from "@Shared/GoogleIcon.vue";
const props = defineProps({
selectedElement: {
type: Object,
default: null
},
visible: {
type: Boolean,
default: false
},
activeTextElement: {
type: Object,
default: null
}
editor: { type: Object, default: null },
selectedElement: { type: Object, default: null },
isTableEditing: { type: Boolean, default: false },
});
const emit = defineEmits(["table-action"]);
const emit = defineEmits(['update', 'smart-align']);
const colorGrid = ref(null);
// Determinar si hay un elemento de texto activo (puede ser texto directo o celda de tabla)
const hasActiveText = computed(() => {
return props.visible && (
props.selectedElement?.type === 'text' ||
props.activeTextElement?.type === 'text' ||
(props.selectedElement?.type === 'table' && props.activeTextElement)
// CORRECCIÓN: Usar props.editor directamente para mantener la reactividad.
const isTextSelected = computed(
() => props.selectedElement?.type === "text" && props.editor
);
const isTableSelected = computed(
() => props.selectedElement?.type === "table" && props.isTableEditing
);
});
// Obtener formato del elemento activo
const formatting = computed(() => {
if (props.activeTextElement) {
return props.activeTextElement.formatting || {};
}
if (props.selectedElement?.type === 'text') {
return props.selectedElement.formatting || {};
}
return {};
});
// Obtener información del elemento activo
const activeElementInfo = computed(() => {
if (props.activeTextElement) {
return {
type: 'text',
context: props.selectedElement?.type === 'table' ? 'table-cell' : 'text-element'
};
}
if (props.selectedElement?.type === 'text') {
return {
type: 'text',
context: 'text-element'
};
}
return null;
});
/** Métodos de formato */
const toggleBold = () => {
if (!hasActiveText.value) return;
updateFormatting('bold', !formatting.value.bold);
};
const toggleItalic = () => {
if (!hasActiveText.value) return;
updateFormatting('italic', !formatting.value.italic);
};
const toggleUnderline = () => {
if (!hasActiveText.value) return;
updateFormatting('underline', !formatting.value.underline);
};
const updateFontSize = (size) => {
if (!hasActiveText.value) return;
updateFormatting('fontSize', size);
};
const updateTextAlign = (align) => {
if (!hasActiveText.value) return;
updateFormatting('textAlign', align);
};
const updateColor = (color) => {
if (!hasActiveText.value) return;
updateFormatting('color', color);
};
const updateFormatting = (key, value) => {
const newFormatting = { ...formatting.value, [key]: value };
// Determinar qué elemento actualizar
let targetId = null;
if (props.activeTextElement) {
targetId = props.activeTextElement.id;
} else if (props.selectedElement?.type === 'text') {
targetId = props.selectedElement.id;
}
if (targetId) {
emit('update', {
id: targetId,
formatting: newFormatting,
context: activeElementInfo.value?.context
});
}
};
/** Colores y tamaños predefinidos */
const predefinedColors = [
'#000000', '#333333', '#666666', '#999999',
'#FF0000', '#00FF00', '#0000FF', '#FFFF00',
'#FF00FF', '#00FFFF', '#FFA500', '#800080'
const FONT_SIZES = ["12", "14", "16", "20", "24", "30"];
const PRIMARY_COLORS = [
"#000000",
"#FF0000",
"#00FF00",
"#0000FF",
"#FFFF00",
"#FF00FF",
"#00FFFF",
"#FFFFFF",
"#800000",
"#008000",
"#000080",
"#808000",
"#800080",
"#008080",
"#C0C0C0",
"#808080",
];
const fontSizes = [8, 9, 10, 11, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72];
const currentFontSize = computed({
get() {
if (!props.editor) return "16";
const sz = props.editor.getAttributes("textStyle").fontSize;
return sz ? sz.replace("px", "") : "16";
},
set(value) {
if (props.editor) {
props.editor.chain().focus().setFontSize(`${value}px`).run();
}
},
});
const setColor = (color) => {
if (props.editor) {
props.editor.chain().focus().setColor(color).run();
if (colorGrid.value) {
colorGrid.value.classList.add("hidden");
}
}
};
const toggleColorGrid = () => {
if (colorGrid.value) {
colorGrid.value.classList.toggle("hidden");
}
};
const currentColour = computed(() => {
if (!props.editor) return "#000000";
return props.editor.getAttributes("textStyle").color || "#000000";
});
const textActions = [
{
action: () => {
if (props.editor) props.editor.chain().focus().toggleBold().run();
},
icon: "format_bold",
isActive: "bold",
},
{
action: () => {
if (props.editor) props.editor.chain().focus().toggleItalic().run();
},
icon: "format_italic",
isActive: "italic",
},
{
action: () => {
if (props.editor) props.editor.chain().focus().toggleUnderline().run();
},
icon: "format_underlined",
isActive: "underline",
},
{ type: "divider" },
{
action: () => {
if (props.editor) props.editor.chain().focus().setTextAlign("left").run();
},
icon: "format_align_left",
isActive: { textAlign: "left" },
},
{
action: () => {
if (props.editor)
props.editor.chain().focus().setTextAlign("center").run();
},
icon: "format_align_center",
isActive: { textAlign: "center" },
},
{
action: () => {
if (props.editor)
props.editor.chain().focus().setTextAlign("right").run();
},
icon: "format_align_right",
isActive: { textAlign: "right" },
},
];
</script>
<template>
<div
class="bg-gray-50 border-b border-gray-200 transition-all duration-300"
:class="{
'h-12 opacity-100': visible && hasActiveText,
'h-0 opacity-0 overflow-hidden': !visible || !hasActiveText
}"
class="w-full bg-white border-b px-4 py-2 shadow-sm h-14 flex items-center gap-2"
>
<div
v-if="hasActiveText"
class="flex items-center gap-4 px-4 py-2 h-full"
>
<!-- Información del elemento activo -->
<div class="flex items-center gap-2 text-xs text-gray-600 border-r border-gray-300 pr-4">
<GoogleIcon
:name="activeElementInfo?.context === 'table-cell' ? 'table_chart' : 'text_fields'"
class="text-sm"
/>
<span>
{{ activeElementInfo?.context === 'table-cell' ? 'Celda de tabla' : 'Texto' }}
</span>
</div>
<!-- Controles de estilo -->
<div class="flex items-center gap-1">
<template v-if="isTextSelected || isTableSelected">
<!-- Botones de formato de texto (disponibles para texto y tabla) -->
<template v-if="editor">
<button
@click="toggleBold"
:class="[
'w-8 h-8 rounded flex items-center justify-center text-sm font-bold transition-colors',
formatting.bold
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Negrita (Ctrl+B)"
v-for="item in textActions.filter((i) => !i.type)"
:key="item.icon"
@click="item.action"
@mousedown.prevent
:class="{ 'bg-gray-200': editor.isActive(item.isActive) }"
class="p-2 rounded hover:bg-gray-100"
>
B
<GoogleIcon :name="item.icon" />
</button>
<button
@click="toggleItalic"
:class="[
'w-8 h-8 rounded flex items-center justify-center text-sm italic transition-colors',
formatting.italic
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Cursiva (Ctrl+I)"
>
I
</button>
<div class="w-px h-6 bg-gray-200 mx-1"></div>
<button
@click="toggleUnderline"
:class="[
'w-8 h-8 rounded flex items-center justify-center text-sm underline transition-colors',
formatting.underline
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Subrayado (Ctrl+U)"
>
U
</button>
</div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Tamaño de fuente -->
<!-- Controles de tamaño y color para texto -->
<div class="flex items-center gap-2" @mousedown.stop>
<select
:value="formatting.fontSize || 12"
@change="updateFontSize(parseInt($event.target.value))"
class="px-2 py-1 text-sm border border-gray-200 rounded bg-white focus:ring-2 focus:ring-blue-500"
v-model="currentFontSize"
class="px-2 py-1 text-sm border border-gray-300 rounded"
>
<option v-for="size in fontSizes" :key="size" :value="size">
<option v-for="size in FONT_SIZES" :key="size" :value="size">
{{ size }}px
</option>
</select>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Alineación -->
<div class="flex gap-1">
<!-- Selector de colores -->
<div class="relative">
<button
@click="updateTextAlign('left')"
:class="[
'w-8 h-8 rounded flex items-center justify-center transition-colors',
(formatting.textAlign || 'left') === 'left'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Alinear izquierda"
type="button"
@click="toggleColorGrid"
class="w-8 h-6 border border-gray-300 rounded flex items-center justify-center"
:style="{ backgroundColor: currentColour }"
>
<GoogleIcon name="format_align_left" class="text-sm" />
<GoogleIcon name="palette" class="text-xs text-white mix-blend-difference" />
</button>
<button
@click="updateTextAlign('center')"
:class="[
'w-8 h-8 rounded flex items-center justify-center transition-colors',
formatting.textAlign === 'center'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Centrar"
>
<GoogleIcon name="format_align_center" class="text-sm" />
</button>
<button
@click="updateTextAlign('right')"
:class="[
'w-8 h-8 rounded flex items-center justify-center transition-colors',
formatting.textAlign === 'right'
? 'bg-blue-500 text-white shadow-sm'
: 'bg-white text-gray-700 hover:bg-blue-50 border border-gray-200'
]"
title="Alinear derecha"
>
<GoogleIcon name="format_align_right" class="text-sm" />
</button>
</div>
<!-- Separador -->
<div class="w-px h-6 bg-gray-300"></div>
<!-- Color -->
<div class="flex items-center gap-2">
<div
class="w-8 h-8 rounded border-2 border-gray-300 cursor-pointer relative overflow-hidden"
:style="{ backgroundColor: formatting.color || '#000000' }"
title="Color de texto"
ref="colorGrid"
class="absolute top-full left-0 mt-1 p-2 bg-white border rounded shadow-lg z-50 hidden"
>
<input
type="color"
:value="formatting.color || '#000000'"
@input="updateColor($event.target.value)"
class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
<div class="grid grid-cols-4 gap-1">
<button
v-for="color in PRIMARY_COLORS"
:key="color"
type="button"
@click="setColor(color)"
class="w-6 h-6 border rounded cursor-pointer hover:scale-110"
:style="{ backgroundColor: color }"
/>
</div>
<div class="flex gap-1">
<button
v-for="color in predefinedColors.slice(0, 4)"
:key="color"
@click="updateColor(color)"
class="w-6 h-6 rounded border border-gray-300 hover:scale-110 transition-transform"
:class="{
'ring-2 ring-blue-500': (formatting.color || '#000000') === color
}"
:style="{ backgroundColor: color }"
:title="color"
></button>
</div>
</div>
<!-- Información de estado -->
<div class="ml-auto text-xs text-gray-500">
{{ activeElementInfo?.context === 'table-cell' ? 'Formateando celda de tabla' : 'Formateando texto' }}
</div>
</div>
</div>
</template>
<!-- Controles específicos de tabla -->
<div v-if="isTableSelected" class="flex items-center gap-2 ml-auto" @mousedown.stop>
<button
type="button"
@click="emit('table-action', 'addRow')"
class="px-2 py-1 text-xs bg-green-500 text-white rounded hover:bg-green-600"
>
+ Fila
</button>
<button
type="button"
@click="emit('table-action', 'delRow')"
class="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600"
>
- Fila
</button>
<button
type="button"
@click="emit('table-action', 'addCol')"
class="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
>
+ Col
</button>
<button
type="button"
@click="emit('table-action', 'delCol')"
class="px-2 py-1 text-xs bg-red-600 text-white rounded hover:bg-red-700"
>
- Col
</button>
</div>
</template>
<div v-else class="text-sm text-gray-400">
Selecciona un elemento para ver sus opciones
</div>
</div>
</template>

View File

@ -0,0 +1,95 @@
<script setup>
import { useEditor, EditorContent } from "@tiptap/vue-3";
import { StarterKit } from "@tiptap/starter-kit";
import { Underline } from "@tiptap/extension-underline";
import { TextStyle } from "@tiptap/extension-text-style";
import { Color } from "@tiptap/extension-color";
import { FontSize } from "tiptap-extension-font-size";
import { TextAlign } from "@tiptap/extension-text-align";
import { watch } from "vue";
const props = defineProps({
modelValue: { type: String, default: "" },
editable: { type: Boolean, default: true },
});
const emit = defineEmits(["update:modelValue", "focus", "blur"]);
const editor = useEditor({
content: props.modelValue,
editable: props.editable,
extensions: [
StarterKit,
Underline,
TextStyle,
Color.configure({ types: ["textStyle"] }),
FontSize.configure({ types: ["textStyle"] }),
TextAlign.configure({ types: ["heading", "paragraph"] }),
],
onUpdate: ({ editor }) => emit("update:modelValue", editor.getHTML()),
onFocus: ({ editor }) => emit("focus", editor),
onBlur: ({ editor }) => emit("blur", editor),
});
// Observa cambios en el contenido desde fuera
watch(
() => props.modelValue,
(newValue) => {
if (editor.value && editor.value.getHTML() !== newValue) {
editor.value.commands.setContent(newValue, false);
}
}
);
// Observa cambios en el estado 'editable' desde fuera
watch(
() => props.editable,
(isEditable) => {
editor.value?.setEditable(isEditable);
}
);
defineExpose({ editor });
</script>
<template>
<EditorContent :editor="editor" />
</template>
<style scoped>
:deep(.ProseMirror) {
padding: 0.5rem;
outline: none;
width: 100%;
height: 100%;
word-wrap: break-word;
}
/* Estilos para cuando NO es editable */
:deep(.ProseMirror[contenteditable="false"]) {
cursor: default;
}
/* Estilos para cuando SÍ es editable */
:deep(.ProseMirror[contenteditable="true"]:focus) {
outline: none;
box-shadow: none;
}
/* Reglas generales que ya teníamos */
:deep(.ProseMirror span[style]) {
display: inline !important;
}
:deep(.ProseMirror p) {
margin: 0;
}
:deep(.ProseMirror ul),
:deep(.ProseMirror ol) {
padding-left: 1.5rem;
}
:deep(p[style*="text-align: center"]) {
text-align: center;
}
:deep(p[style*="text-align: right"]) {
text-align: right;
}
:deep(p[style*="text-align: left"]) {
text-align: left;
}
</style>

View File

@ -1,261 +0,0 @@
<script setup>
import { ref, computed, nextTick } from 'vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';
/** Propiedades */
const props = defineProps({
pages: {
type: Array,
default: () => [{ id: 1, elements: [] }]
},
selectedElementId: String,
isExporting: Boolean
});
/** Eventos */
const emit = defineEmits(['drop', 'dragover', 'click', 'add-page', 'delete-page', 'page-change']);
/** Referencias */
const viewportRef = ref(null);
const currentPage = ref(1);
/** Constantes de diseño */
const PAGE_WIDTH = 794; // A4 width in pixels (210mm @ 96dpi * 3.78)
const PAGE_HEIGHT = 1123; // A4 height in pixels (297mm @ 96dpi * 3.78)
const PAGE_MARGIN = 40;
const ZOOM_LEVEL = 0.8; // Factor de escala para visualización
/** Propiedades computadas */
const scaledPageWidth = computed(() => PAGE_WIDTH * ZOOM_LEVEL);
const scaledPageHeight = computed(() => PAGE_HEIGHT * ZOOM_LEVEL);
const totalPages = computed(() => props.pages.length);
/** Métodos */
const handleDrop = (event, pageIndex) => {
event.preventDefault();
const pageElement = event.currentTarget;
const rect = pageElement.getBoundingClientRect();
// Calcular posición relativa a la página específica
const relativeX = (event.clientX - rect.left) / ZOOM_LEVEL;
const relativeY = (event.clientY - rect.top) / ZOOM_LEVEL;
emit('drop', {
originalEvent: event,
pageIndex,
x: Math.max(PAGE_MARGIN, Math.min(PAGE_WIDTH - PAGE_MARGIN, relativeX)),
y: Math.max(PAGE_MARGIN, Math.min(PAGE_HEIGHT - PAGE_MARGIN, relativeY))
});
};
const handleDragOver = (event) => {
event.preventDefault();
emit('dragover', event);
};
const handleClick = (event, pageIndex) => {
if (event.target.classList.contains('pdf-page')) {
emit('click', { originalEvent: event, pageIndex });
}
};
const addPage = () => {
emit('add-page');
nextTick(() => {
scrollToPage(totalPages.value);
});
};
const deletePage = (pageIndex) => {
if (totalPages.value > 1) {
emit('delete-page', pageIndex);
}
};
const scrollToPage = (pageNumber) => {
if (viewportRef.value) {
const pageElement = viewportRef.value.querySelector(`[data-page="${pageNumber}"]`);
if (pageElement) {
pageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
};
const setCurrentPage = (pageNumber) => {
currentPage.value = pageNumber;
emit('page-change', pageNumber);
};
/** Métodos expuestos */
defineExpose({
scrollToPage,
setCurrentPage,
PAGE_WIDTH,
PAGE_HEIGHT,
ZOOM_LEVEL
});
</script>
<template>
<div class="flex-1 flex flex-col bg-gray-100 dark:bg-primary-d/20">
<!-- Toolbar de páginas -->
<div class="flex items-center justify-between px-4 py-2 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20">
<div class="flex items-center gap-3">
<span class="text-sm text-gray-600 dark:text-primary-dt">
Página {{ currentPage }} de {{ totalPages }}
</span>
<div class="flex items-center gap-1">
<button
@click="setCurrentPage(Math.max(1, currentPage - 1))"
:disabled="currentPage <= 1"
class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt"
>
<GoogleIcon name="keyboard_arrow_left" class="text-lg" />
</button>
<button
@click="setCurrentPage(Math.min(totalPages, currentPage + 1))"
:disabled="currentPage >= totalPages"
class="p-1 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed dark:text-primary-dt/70 dark:hover:text-primary-dt"
>
<GoogleIcon name="keyboard_arrow_right" class="text-lg" />
</button>
</div>
</div>
<div class="flex items-center gap-2">
<button
@click="addPage"
:disabled="isExporting"
class="flex items-center gap-1 px-2 py-1 text-xs bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors disabled:opacity-50"
>
<GoogleIcon name="add" class="text-sm" />
Nueva Página
</button>
</div>
</div>
<!-- Viewport de páginas -->
<div
ref="viewportRef"
class="flex-1 overflow-auto p-8"
style="background: linear-gradient(45deg, #f0f0f0 25%, transparent 25%), linear-gradient(-45deg, #f0f0f0 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #f0f0f0 75%), linear-gradient(-45deg, transparent 75%, #f0f0f0 75%); background-size: 20px 20px; background-position: 0 0, 0 10px, 10px -10px, -10px 0px;"
>
<div class="flex flex-col items-center gap-8">
<!-- Páginas -->
<div
v-for="(page, pageIndex) in pages"
:key="page.id"
:data-page="pageIndex + 1"
class="relative"
@mouseenter="setCurrentPage(pageIndex + 1)"
>
<!-- Número de página -->
<div class="absolute -top-6 left-0 flex items-center gap-2 text-xs text-gray-500 dark:text-primary-dt/70">
<span>Página {{ pageIndex + 1 }}</span>
<button
v-if="totalPages > 1"
@click="deletePage(pageIndex)"
:disabled="isExporting"
class="text-red-500 hover:text-red-700 disabled:opacity-50"
title="Eliminar página"
>
<GoogleIcon name="delete" class="text-sm" />
</button>
</div>
<!-- Página PDF -->
<div
class="pdf-page relative bg-white rounded-lg shadow-lg border border-gray-300 dark:border-primary/20"
:class="{
'ring-2 ring-blue-500': currentPage === pageIndex + 1,
'opacity-50': isExporting
}"
:style="{
width: `${scaledPageWidth}px`,
height: `${scaledPageHeight}px`,
transform: `scale(${ZOOM_LEVEL})`,
transformOrigin: 'top left'
}"
@drop="(e) => handleDrop(e, pageIndex)"
@dragover="handleDragOver"
@click="(e) => handleClick(e, pageIndex)"
>
<!-- Márgenes visuales -->
<div
class="absolute border border-dashed border-gray-300 dark:border-primary/30 pointer-events-none"
:style="{
top: `${PAGE_MARGIN}px`,
left: `${PAGE_MARGIN}px`,
width: `${PAGE_WIDTH - (PAGE_MARGIN * 2)}px`,
height: `${PAGE_HEIGHT - (PAGE_MARGIN * 2)}px`
}"
></div>
<!-- Elementos de la página -->
<slot
name="elements"
:page="page"
:pageIndex="pageIndex"
:pageWidth="PAGE_WIDTH"
:pageHeight="PAGE_HEIGHT"
/>
<!-- Indicador de página vacía -->
<div
v-if="page.elements.length === 0"
class="absolute inset-0 flex items-center justify-center pointer-events-none"
>
<div class="text-center text-gray-400 dark:text-primary-dt/50">
<GoogleIcon name="description" class="text-4xl mb-2" />
<p class="text-sm">Página {{ pageIndex + 1 }}</p>
<p class="text-xs">Arrastra elementos aquí</p>
</div>
</div>
</div>
<!-- Regla inferior (tamaño de referencia) -->
<div class="mt-2 text-xs text-gray-400 dark:text-primary-dt/50 text-center">
210 × 297 mm (A4)
</div>
</div>
<!-- Botón para agregar página al final -->
<button
@click="addPage"
:disabled="isExporting"
class="flex flex-col items-center justify-center w-40 h-20 border-2 border-dashed border-gray-300 dark:border-primary/30 rounded-lg hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-colors disabled:opacity-50"
>
<GoogleIcon name="add" class="text-2xl text-gray-400 dark:text-primary-dt/50" />
<span class="text-xs text-gray-500 dark:text-primary-dt/70 mt-1">Nueva Página</span>
</button>
</div>
</div>
<!-- Overlay durante exportación -->
<div
v-if="isExporting"
class="absolute inset-0 bg-white/80 dark:bg-primary-d/80 flex items-center justify-center z-50"
>
<div class="text-center">
<GoogleIcon name="picture_as_pdf" class="text-4xl text-red-600 dark:text-red-400 animate-pulse mb-2" />
<p class="text-sm font-medium text-gray-900 dark:text-primary-dt">Generando PDF...</p>
<p class="text-xs text-gray-500 dark:text-primary-dt/70">Procesando {{ totalPages }} página{{ totalPages !== 1 ? 's' : '' }}</p>
</div>
</div>
</div>
</template>
<style scoped>
.pdf-page {
transition: all 0.2s ease;
}
.pdf-page:hover {
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}
</style>

View File

@ -1,733 +1,327 @@
<script setup>
import { ref, onMounted, computed } from 'vue';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import Draggable from '@Holos/PDF/Draggable.vue';
import CanvasElement from '@Holos/PDF/Canvas.vue';
import PDFViewport from '@Holos/PDF/PDFViewport.vue';
import TextFormatter from '@Holos/PDF/TextFormatter.vue';
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import GoogleIcon from "@Shared/GoogleIcon.vue";
import Draggable from "@Holos/PDF/Draggable.vue";
import CanvasElement from "@Holos/PDF/Canvas.vue";
import PDFViewport from "@Holos/PDF/PDFViewport.vue";
import TextFormatter from "@Holos/PDF/TextFormatter.vue";
import htmlToPdfMake from "html-to-pdfmake";
/** Estado reactivo */
/** Estado Reactivo */
const pages = ref([{ id: 1, elements: [] }]);
const selectedElementId = ref(null);
const elementCounter = ref(0);
const documentTitle = ref('Documento sin título');
const isExporting = ref(false);
const documentTitle = ref("Documento sin título");
const currentPage = ref(1);
const pageIdCounter = ref(1); // <-- Agregar contador separado para páginas
const pageIdCounter = ref(1);
const isExporting = ref(false);
const currentPageSize = ref("A4");
/** Estado para tamaño de página */
const currentPageSize = ref({
width: 794, // A4 por defecto
height: 1123
});
const elementRefs = ref({});
const activeEditor = ref(null);
const isTableEditing = ref(false);
/** Manejar cambio de tamaño de página */
const handlePageSizeChange = (sizeData) => {
currentPageSize.value = sizeData.dimensions;
// Aquí podrías ajustar elementos existentes si es necesario
window.Notify.info(`Tamaño de página cambiado a ${sizeData.size}`);
};
const allElements = computed(() =>
pages.value.flatMap((page) => page.elements)
);
const totalElements = computed(() => allElements.value.length);
const selectedElement = computed(() =>
allElements.value.find((el) => el.id === selectedElementId.value)
);
// Actualizar el método moveElement para usar el tamaño dinámico
const moveElement = (moveData) => {
const element = allElements.value.find(el => el.id === moveData.id);
if (element) {
element.x = Math.max(0, Math.min(currentPageSize.value.width - (element.width || 200), moveData.x));
element.y = Math.max(0, Math.min(currentPageSize.value.height - (element.height || 40), moveData.y));
}
};
/** Referencias */
const viewportRef = ref(null);
/** Referencias adicionales para TextFormatter */
const selectedElement = ref(null);
const activeTextElement = ref(null);
const showTextFormatter = ref(false);
const selectElement = (elementId) => {
selectedElementId.value = elementId;
const selectedEl = allElements.value.find(el => el.id === elementId);
selectedElement.value = selectedEl;
// Mostrar TextFormatter si es texto o tabla
showTextFormatter.value = selectedEl?.type === 'text' || selectedEl?.type === 'table';
// Si es texto directo, activar como activeTextElement
if (selectedEl?.type === 'text') {
activeTextElement.value = selectedEl;
} else {
activeTextElement.value = null;
}
};
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
// Actualizar referencias si es necesario
if (selectedElement.value?.id === update.id) {
selectedElement.value = { ...element };
}
if (activeTextElement.value?.id === update.id) {
activeTextElement.value = { ...element };
}
}
};
// Manejar selección de texto dentro de celdas de tabla
const handleTextSelected = (data) => {
activeTextElement.value = data.element;
showTextFormatter.value = true;
};
/** Tipos de elementos disponibles */
const availableElements = [
{
type: 'text',
icon: 'text_fields',
title: 'Texto',
description: 'Texto enriquecido con formato'
},
{
type: 'image',
icon: 'image',
title: 'Imagen',
description: 'Subir y editar imágenes'
},
{
type: 'table',
icon: 'table_chart',
title: 'Tabla',
description: 'Tabla con filas y columnas'
}
];
/** Propiedades computadas */
const allElements = computed(() => {
return pages.value.flatMap(page => page.elements);
});
const totalElements = computed(() => {
return allElements.value.length;
});
/** Métodos del canvas */
const handleDrop = (dropData) => {
try {
const data = JSON.parse(dropData.originalEvent.dataTransfer.getData('text/plain'));
const newElement = {
id: `element-${++elementCounter.value}`,
type: data.type,
pageIndex: dropData.pageIndex,
x: dropData.x,
y: dropData.y,
width: data.type === 'table' ? 300 : data.type === 'image' ? 200 : 200,
height: data.type === 'table' ? 120 : data.type === 'image' ? 150 : 40,
content: getDefaultContent(data.type),
fileName: getDefaultFileName(data.type),
created_at: new Date().toISOString()
};
pages.value[dropData.pageIndex].elements.push(newElement);
selectedElementId.value = newElement.id;
} catch (error) {
console.error('Error al procesar elemento arrastrado:', error);
}
};
const getDefaultContent = (type) => {
switch(type) {
case 'text':
return 'Nuevo texto';
case 'table':
return {
rows: 3,
cols: 3,
data: [
['Encabezado 1', 'Encabezado 2', 'Encabezado 3'],
['Fila 1, Col 1', 'Fila 1, Col 2', 'Fila 1, Col 3'],
['Fila 2, Col 1', 'Fila 2, Col 2', 'Fila 2, Col 3']
]
};
case 'image':
return null;
default:
return null;
}
};
const getDefaultFileName = (type) => {
switch(type) {
case 'table':
return 'tabla.csv';
case 'image':
return null;
default:
return null;
}
};
const handleDragOver = (event) => {
event.preventDefault();
};
const deleteElement = (elementId) => {
const index = allElements.value.findIndex(el => el.id === elementId);
if (index !== -1) {
const pageIndex = Math.floor(index / 3); // Suponiendo 3 elementos por página
pages.value[pageIndex].elements.splice(index % 3, 1);
if (selectedElementId.value === elementId) {
selectedElementId.value = null;
}
}
};
/** Paginación */
const addPage = () => {
pageIdCounter.value++; // <-- Incrementar contador independiente
pages.value.push({
id: pageIdCounter.value,
elements: []
});
pages.value.push({ id: ++pageIdCounter.value, elements: [] });
};
const deletePage = (pageIndex) => {
if (pages.value.length > 1) {
// Mover elementos de la página eliminada a la página anterior
const elementsToMove = pages.value[pageIndex].elements;
if (pageIndex > 0 && elementsToMove.length > 0) {
elementsToMove.forEach(element => {
element.pageIndex = pageIndex - 1;
pages.value[pageIndex - 1].elements.push(element);
});
if (currentPage.value > pageIndex + 1) {
currentPage.value--;
} else if (currentPage.value === pageIndex + 1 && currentPage.value > 1) {
currentPage.value--;
}
pages.value.splice(pageIndex, 1);
// Actualizar índices de página de elementos restantes
pages.value.forEach((page, index) => {
page.elements.forEach(element => {
element.pageIndex = index;
});
});
// Ajustar página actual si es necesario
if (currentPage.value > pages.value.length) {
currentPage.value = pages.value.length;
}
}
};
/** Métodos de acciones rápidas */
const addQuickElement = (type) => {
const targetPageIndex = currentPage.value - 1;
const existingElements = pages.value[targetPageIndex].elements.length;
const handleDrop = (dropData) => {
const data = JSON.parse(
dropData.originalEvent.dataTransfer.getData("text/plain")
);
const newElement = createNewElement({ ...data, ...dropData });
pages.value[dropData.pageIndex].elements.push(newElement);
selectElement(newElement.id);
};
const newElement = {
const createNewElement = (data) => ({
id: `element-${++elementCounter.value}`,
type: type,
pageIndex: targetPageIndex,
x: 80 + (existingElements * 20),
y: 80 + (existingElements * 20),
width: type === 'table' ? 300 : type === 'image' ? 200 : 200,
height: type === 'table' ? 120 : type === 'image' ? 150 : 40,
content: getDefaultContent(type),
fileName: getDefaultFileName(type),
created_at: new Date().toISOString()
type: data.type,
pageIndex: data.pageIndex,
x: data.x,
y: data.y,
width: data.type === "table" ? 400 : 250,
height: data.type === "image" ? 150 : 120,
content: getDefaultContent(data.type),
});
const getDefaultContent = (type) => {
if (type === "text") return "<p>Escribe algo...</p>";
if (type === "table")
return {
data: [
["Encabezado 1", "Encabezado 2"],
["Celda 1", "Celda 2"],
],
};
return null;
};
pages.value[targetPageIndex].elements.push(newElement);
selectedElementId.value = newElement.id;
const selectElement = (elementId) => {
selectedElementId.value = elementId;
};
const exportPDF = async () => {
if (totalElements.value === 0) {
window.Notify.warning('No hay elementos para exportar');
return;
const deselectAll = (event) => {
if (event.target === event.currentTarget) {
selectedElementId.value = null;
activeEditor.value = null;
isTableEditing.value = false;
}
};
const moveElement = (moveData) => {
const el = allElements.value.find((e) => e.id === moveData.id);
if (el) Object.assign(el, moveData);
};
const updateElement = (update) => {
const el = allElements.value.find((e) => e.id === update.id);
if (el) Object.assign(el, update);
};
const deleteElement = (elementId) => {
pages.value.forEach((p) => {
p.elements = p.elements.filter((el) => el.id !== elementId);
});
if (selectedElementId.value === elementId) selectedElementId.value = null;
};
const clearCanvas = () => {
if (confirm("¿Seguro?")) {
pages.value = [{ id: 1, elements: [] }];
selectedElementId.value = null;
elementCounter.value = 0;
pageIdCounter.value = 1;
currentPage.value = 1;
}
};
try {
const handleTableEditing = (editing) => {
isTableEditing.value = editing;
};
const handlePageSizeChange = (sizeData) => {
currentPageSize.value = sizeData.size;
};
const handleKeydown = (event) => {
if (event.key === "Delete" && selectedElementId.value)
deleteElement(selectedElementId.value);
if (event.key === "Escape") selectedElementId.value = null;
};
onMounted(() => document.addEventListener("keydown", handleKeydown));
onBeforeUnmount(() => document.removeEventListener("keydown", handleKeydown));
const exportPDF = () => {
isExporting.value = true;
window.Notify.info('Generando PDF...');
// Crear un nuevo documento PDF con el tamaño de página seleccionado
const pdfDoc = await PDFDocument.create();
// Convertir dimensiones de pixels a puntos (1 px = 0.75 puntos)
const pageWidthPoints = currentPageSize.value.width * 0.75;
const pageHeightPoints = currentPageSize.value.height * 0.75;
// Obtener fuentes
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
const helveticaBoldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const courierFont = await pdfDoc.embedFont(StandardFonts.Courier);
// Procesar páginas del maquetador
for (let pageIndex = 0; pageIndex < pages.value.length; pageIndex++) {
const page = pages.value[pageIndex];
// Crear nueva página PDF
let currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]);
let currentPageHeight = pageHeightPoints;
// Ordenar elementos de esta página por posición
const sortedElements = [...page.elements].sort((a, b) => {
if (Math.abs(a.y - b.y) < 20) {
return a.x - b.x;
}
return a.y - b.y;
});
// Procesar elementos de la página
for (const element of sortedElements) {
// Calcular posición en el PDF manteniendo proporciones
const scaleX = pageWidthPoints / currentPageSize.value.width;
const scaleY = pageHeightPoints / currentPageSize.value.height;
const x = Math.max(50, element.x * scaleX);
const y = currentPageHeight - (element.y * scaleY) - 50;
switch (element.type) {
case 'text':
if (element.content && element.content.trim()) {
// Obtener formato del elemento
const formatting = element.formatting || {};
const fontSize = Math.max(8, Math.min(72, formatting.fontSize || 12));
const isBold = formatting.bold || false;
const textAlign = formatting.textAlign || 'left';
// Convertir color hexadecimal a RGB
let textColor = rgb(0, 0, 0);
if (formatting.color) {
const hex = formatting.color.replace('#', '');
const r = parseInt(hex.substr(0, 2), 16) / 255;
const g = parseInt(hex.substr(2, 2), 16) / 255;
const b = parseInt(hex.substr(4, 2), 16) / 255;
textColor = rgb(r, g, b);
}
// Seleccionar fuente
let font = isBold ? helveticaBoldFont : helveticaFont;
// NUEVO: Dividir por párrafos (saltos de línea)
const paragraphs = element.content.split('\n');
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
const lineHeight = fontSize * 1.4;
let currentY = y;
paragraphs.forEach((paragraph, paragraphIndex) => {
if (paragraph.trim() === '') {
// Párrafo vacío - solo agregar espacio
currentY -= lineHeight;
return;
}
// Dividir párrafo en líneas que caben en el ancho
const words = paragraph.split(' ');
const lines = [];
let currentLine = '';
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
const testWidth = font.widthOfTextAtSize(testLine, fontSize);
if (testWidth <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
}
if (currentLine) lines.push(currentLine);
// Dibujar cada línea del párrafo
lines.forEach((line, lineIndex) => {
let lineX = x;
const lineWidth = font.widthOfTextAtSize(line, fontSize);
// Calcular posición X según alineación
if (textAlign === 'center') {
lineX = x + (maxWidth - lineWidth) / 2;
} else if (textAlign === 'right') {
lineX = x + maxWidth - lineWidth;
}
currentPDFPage.drawText(line, {
x: Math.max(50, lineX),
y: currentY,
size: fontSize,
font: font,
color: textColor,
});
currentY -= lineHeight;
});
// Agregar espacio extra entre párrafos
if (paragraphIndex < paragraphs.length - 1) {
currentY -= lineHeight * 0.3;
}
});
}
break;
case 'image':
if (element.content && element.content.startsWith('data:image')) {
try {
const base64Data = element.content.split(',')[1];
const imageBytes = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
const content = [];
pages.value.forEach((page, pageIndex) => {
const pageContent = page.elements
.map((element) => {
const position = { x: element.x * 0.75, y: element.y * 0.75 };
let image;
if (element.content.includes('image/jpeg') || element.content.includes('image/jpg')) {
image = await pdfDoc.embedJpg(imageBytes);
} else if (element.content.includes('image/png')) {
image = await pdfDoc.embedPng(imageBytes);
if (element.type === "text" && element.content) {
return {
columns: [
{
stack: htmlToPdfMake(element.content),
width: (element.width || 250) * 0.75,
},
],
absolutePosition: position,
};
}
if (image) {
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
const maxHeight = Math.min(300, (element.height || 150) * scaleY);
const imageAspectRatio = image.width / image.height;
let displayWidth = maxWidth;
let displayHeight = maxWidth / imageAspectRatio;
if (displayHeight > maxHeight) {
displayHeight = maxHeight;
displayWidth = maxHeight * imageAspectRatio;
if (element.type === "image" && element.content) {
return {
image: element.content,
width: (element.width || 150) * 0.75,
absolutePosition: position,
};
}
if (element.type === "table" && element.content) {
const body = element.content.data.map((row) =>
row.map((cellContent) => {
return {
stack: htmlToPdfMake(cellContent || "<p></p>"),
border: [true, true, true, true],
};
})
);
const numCols = element.content.data[0]?.length || 1;
const colWidth = (element.width * 0.75) / numCols;
const widths = Array(numCols).fill(colWidth);
currentPDFPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
});
return {
columns: [
{
table: {
body: body,
widths: widths,
},
width: element.width * 0.75,
},
],
absolutePosition: position,
layout: {
hLineWidth: () => 0.5,
vLineWidth: () => 0.5,
hLineColor: () => "#000000",
vLineColor: () => "#000000",
paddingLeft: () => 4,
paddingRight: () => 4,
paddingTop: () => 2,
paddingBottom: () => 2,
},
};
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Placeholder para imagen con error
currentPDFPage.drawRectangle({
x: x,
y: y - 60,
width: 100 * scaleX,
height: 60 * scaleY,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
return null;
})
.filter(Boolean);
content.push(...pageContent);
if (pageIndex < pages.value.length - 1)
content.push({ text: "", pageBreak: "after" });
});
currentPDFPage.drawText('[Error al cargar imagen]', {
x: x + 5,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
}
}
break;
const docDefinition = {
content,
pageSize: currentPageSize.value.toUpperCase(),
pageMargins: [0, 0, 0, 0],
};
case 'table':
if (element.content && element.content.data && Array.isArray(element.content.data)) {
const tableData = element.content.data;
const totalCols = tableData[0]?.length || 0;
const totalRows = tableData.length;
if (totalCols > 0 && totalRows > 0) {
const availableWidth = Math.min(pageWidthPoints - 100, (element.width || 300) * scaleX);
const cellWidth = availableWidth / totalCols;
const cellHeight = 25;
const tableWidth = cellWidth * totalCols;
const tableHeight = cellHeight * totalRows;
// Dibujar borde exterior de la tabla
currentPDFPage.drawRectangle({
x: x,
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.2, 0.2, 0.2),
borderWidth: 1.5,
});
// Dibujar cada celda
tableData.forEach((row, rowIndex) => {
if (Array.isArray(row)) {
row.forEach((cell, colIndex) => {
const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight);
// Dibujar borde de celda
currentPDFPage.drawRectangle({
x: cellX,
y: cellY - cellHeight,
width: cellWidth,
height: cellHeight,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
// Fondo especial para headers
if (rowIndex === 0) {
currentPDFPage.drawRectangle({
x: cellX,
y: cellY - cellHeight,
width: cellWidth,
height: cellHeight,
color: rgb(0.95, 0.95, 1),
});
}
// Dibujar texto de la celda
if (cell && typeof cell === 'string' && cell.trim()) {
const maxChars = Math.max(1, Math.floor(cellWidth / 6));
let displayText = cell.trim();
if (displayText.length > maxChars) {
displayText = displayText.substring(0, maxChars - 3) + '...';
}
const fontSize = Math.max(8, Math.min(12, cellWidth / 8));
const font = rowIndex === 0 ? helveticaBoldFont : helveticaFont;
const textColor = rowIndex === 0 ? rgb(0.1, 0.1, 0.6) : rgb(0, 0, 0);
const textWidth = font.widthOfTextAtSize(displayText, fontSize);
const textX = cellX + (cellWidth - textWidth) / 2;
const textY = cellY - cellHeight/2 - fontSize/2;
currentPDFPage.drawText(displayText, {
x: Math.max(cellX + 2, textX),
y: Math.max(cellY - cellHeight + 5, textY),
size: fontSize,
font: font,
color: textColor,
});
}
});
}
});
}
}
break;
default:
console.warn(`Tipo de elemento no soportado: ${element.type}`);
break;
}
}
}
// Generar PDF
const pdfBytes = await pdfDoc.save();
// Descargar
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${documentTitle.value.replace(/\s+/g, '_')}.pdf`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
window.Notify.success('PDF generado correctamente');
} catch (error) {
console.error('Error al generar PDF:', error);
window.Notify.error('Error al generar el PDF: ' + error.message);
window.pdfMake
.createPdf(docDefinition)
.download(`${documentTitle.value || "documento"}.pdf`);
} catch (e) {
console.error("Error al exportar PDF:", e);
alert("Hubo un error al generar el PDF.");
} finally {
isExporting.value = false;
}
};
// Función auxiliar para calcular la altura aproximada de un elemento
const getElementHeight = (element) => {
switch (element.type) {
case 'text':
if (!element.content) return 20;
const lines = Math.ceil(element.content.length / 50);
return lines * 15 + 10;
case 'table':
if (!element.content || !element.content.data) return 60;
const tableRows = element.content.data.length;
return (tableRows * 20) + 20;
case 'image':
return Math.min(300, (element.height || 150) * 0.75) + 30;
default:
return 40;
}
};
const handleTableAction = (action) => {
if (!selectedElement.value || selectedElement.value.type !== "table") return;
const tableData = selectedElement.value.content.data;
const numCols = tableData[0]?.length || 1;
if (action === "addRow") tableData.push(Array(numCols).fill(""));
if (action === "addCol") tableData.forEach((row) => row.push(""));
if (action === "delRow" && tableData.length > 1) tableData.pop();
if (action === "delCol" && numCols > 1) tableData.forEach((row) => row.pop());
const clearCanvas = () => {
if (confirm('¿Estás seguro de que quieres limpiar el canvas? Se perderán todos los elementos.')) {
pages.value = [{ id: 1, elements: [] }];
selectedElementId.value = null;
elementCounter.value = 0;
pageIdCounter.value = 1; // <-- Resetear también el contador de páginas
currentPage.value = 1;
}
};
/** Atajos de teclado */
const handleKeydown = (event) => {
if (event.key === 'Delete' && selectedElementId.value) {
deleteElement(selectedElementId.value);
}
if (event.key === 'Escape') {
selectedElementId.value = null;
}
};
/** Ciclo de vida */
onMounted(() => {
document.addEventListener('keydown', handleKeydown);
// Actualizar tamaño de la tabla (opcional)
const newWidth = Math.max(200, tableData[0].length * 100);
const newHeight = Math.max(60, tableData.length * 30);
updateElement({
id: selectedElement.value.id,
content: { data: tableData },
width: newWidth,
height: newHeight,
});
};
const availableElements = [
{ type: "text", icon: "text_fields", title: "Texto" },
{ type: "image", icon: "image", title: "Imagen" },
{ type: "table", icon: "table_chart", title: "Tabla" },
];
</script>
<template>
<div class="flex flex-col lg:flex-row h-screen bg-gray-50">
<!-- Panel Izquierdo - Responsive -->
<div class="w-full lg:w-64 bg-white border-r border-gray-200 flex flex-col">
<!-- Header del panel -->
<div class="p-3 lg:p-4 border-b border-gray-200">
<div class="flex items-center gap-2 mb-3 lg:mb-4">
<GoogleIcon name="text_snippet" class="text-blue-600 text-lg lg:text-xl" />
<h2 class="font-semibold text-gray-900 text-sm">
Diseñador de Documentos
</h2>
<div class="p-3 lg:p-4 border-b">
<div class="flex items-center gap-2 mb-3">
<GoogleIcon name="text_snippet" class="text-blue-600 text-lg" />
<h2 class="font-semibold text-gray-900 text-sm">Diseñador</h2>
</div>
<!-- Título del documento -->
<input
v-model="documentTitle"
class="w-full px-2 py-1 text-xs border border-gray-200 rounded mb-3"
class="w-full px-2 py-1 text-xs border rounded mb-3"
placeholder="Título del documento"
/>
<!-- Botón de exportación PDF -->
<button
@click="exportPDF"
:disabled="isExporting"
class="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm rounded transition-colors"
:class="isExporting ? 'bg-gray-400 text-white cursor-not-allowed' : 'bg-red-600 hover:bg-red-700 text-white'"
class="w-full flex items-center justify-center gap-2 px-3 py-2 text-sm rounded transition-colors bg-red-600 hover:bg-red-700 text-white"
>
<GoogleIcon :name="isExporting ? 'hourglass_empty' : 'picture_as_pdf'" class="text-sm" />
{{ isExporting ? 'Generando PDF...' : 'Exportar PDF' }}
<GoogleIcon name="picture_as_pdf" class="text-sm" />{{
isExporting ? "Generando..." : "Exportar PDF"
}}
</button>
</div>
<!-- Sección Elementos -->
<div class="p-3 lg:p-4 flex-1 overflow-y-auto">
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">
<h3
class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3"
>
Elementos
</h3>
<p class="text-xs text-gray-400 mb-4 hidden lg:block">
Arrastra elementos al canvas para crear tu documento
</p>
<!-- Grid responsive de elementos -->
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-2 lg:gap-3">
<div class="grid grid-cols-1 gap-2">
<Draggable
v-for="element in availableElements"
:key="element.type"
:type="element.type"
:icon="element.icon"
:title="element.title"
:description="element.description"
v-for="el in availableElements"
:key="el.type"
v-bind="el"
/>
</div>
<!-- Agregar rápido - Solo en desktop -->
<div class="hidden lg:block">
<h3 class="text-xs font-semibold text-gray-500 uppercase tracking-wider mt-6 mb-3">
Agregar rápido
</h3>
<div class="space-y-2">
<button
v-for="element in availableElements"
:key="`quick-${element.type}`"
@click="addQuickElement(element.type)"
:disabled="isExporting"
class="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded transition-colors disabled:opacity-50"
>
<GoogleIcon name="add" class="text-gray-400 text-sm" />
{{ element.title }}
</button>
</div>
</div>
<!-- Limpiar todo -->
<div class="pt-4 mt-4 border-t border-gray-200">
<div class="pt-4 mt-4 border-t">
<button
v-if="totalElements > 0"
@click="clearCanvas"
:disabled="isExporting"
class="w-full flex items-center justify-center gap-1 px-2 py-1 text-xs text-red-600 hover:text-red-700 hover:bg-red-50 rounded transition-colors disabled:opacity-50"
class="w-full flex items-center justify-center gap-1 px-2 py-1 text-xs text-red-600 hover:bg-red-50 rounded"
>
<GoogleIcon name="delete" class="text-sm" />
Limpiar Todo
<GoogleIcon name="delete" class="text-sm" />Limpiar Todo
</button>
</div>
</div>
</div>
<!-- Área Principal con Viewport -->
<div class="flex-1 flex flex-col min-h-0">
<!-- Toolbar superior básico -->
<div class="h-12 lg:h-14 bg-white border-b border-gray-200 flex items-center justify-between px-3 lg:px-4">
<div class="flex items-center gap-2 lg:gap-4">
<h2 class="font-semibold text-gray-900 text-sm truncate max-w-32 lg:max-w-none">
{{ documentTitle }}
</h2>
</div>
<div class="flex items-center gap-2 lg:gap-4">
<span class="text-xs text-gray-500 hidden sm:block">
{{ totalElements }} elemento{{ totalElements !== 1 ? 's' : '' }} {{ pages.length }} página{{ pages.length !== 1 ? 's' : '' }}
</span>
</div>
</div>
<!-- TextFormatter estático y universal -->
<TextFormatter
:editor="activeEditor"
:selected-element="selectedElement"
:active-text-element="activeTextElement"
:visible="showTextFormatter"
@update="updateElement"
@smart-align="handleSmartAlign"
:is-table-editing="isTableEditing"
@table-action="handleTableAction"
/>
<!-- PDFViewport -->
<PDFViewport
ref="viewportRef"
:pages="pages"
:selected-element-id="selectedElementId"
:is-exporting="isExporting"
@drop="handleDrop"
@click="handleCanvasClick"
:current-page="currentPage"
@page-change="(p) => (currentPage = p)"
@add-page="addPage"
@delete-page="deletePage"
@page-change="(page) => currentPage = page"
@drop="handleDrop"
@click="deselectAll"
@page-size-change="handlePageSizeChange"
>
<template #elements="{ page, pageIndex }">
<template #elements="{ page }">
<CanvasElement
v-for="element in page.elements"
:key="element.id"
:ref="
(el) => {
if (el) elementRefs[element.id] = el;
}
"
:element="element"
:is-selected="selectedElementId === element.id && !isExporting"
:is-selected="selectedElementId === element.id"
@select="selectElement"
@delete="deleteElement"
@update="updateElement"
@move="moveElement"
@text-selected="handleTextSelected"
@editor-active="(editor) => (activeEditor = editor)"
@table-editing="handleTableEditing"
/>
</template>
</PDFViewport>