Maquetador de documentos (#2)

Co-authored-by: Juan Felipe Zapata Moreno <zapata_pipe@hotmail.com>
Reviewed-on: #2
This commit is contained in:
juan.zapata 2025-09-22 18:01:34 +00:00 committed by Juan Felipe Zapata Moreno
parent 703b39e052
commit 433994cda2
4 changed files with 1177 additions and 298 deletions

View File

@ -0,0 +1,606 @@
<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

@ -0,0 +1,64 @@
<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

@ -0,0 +1,261 @@
<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,11 +1,10 @@
<script setup>
import { ref, onMounted, computed } from 'vue';
import { ref, nextTick, 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 Draggable from '@Holos/Draggable.vue';
import CanvasElement from '@Holos/Canvas.vue';
import PDFViewport from '@Holos/PDFViewport.vue';
/** Estado reactivo */
const pages = ref([{ id: 1, elements: [] }]);
@ -14,85 +13,10 @@ const elementCounter = ref(0);
const documentTitle = ref('Documento sin título');
const isExporting = ref(false);
const currentPage = ref(1);
const pageIdCounter = ref(1); // <-- Agregar contador separado para páginas
/** Estado para tamaño de página */
const currentPageSize = ref({
width: 794, // A4 por defecto
height: 1123
});
/** 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}`);
};
// 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 */
const textFormatterElement = ref(null);
const showTextFormatter = ref(false);
const selectElement = (elementId) => {
selectedElementId.value = elementId;
const selectedEl = allElements.value.find(el => el.id === elementId);
showTextFormatter.value = selectedEl?.type === 'text';
textFormatterElement.value = selectedEl;
};
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
// Si se actualiza el formato, actualizar la referencia
if (update.formatting && textFormatterElement.value?.id === update.id) {
textFormatterElement.value = { ...element };
}
}
};
const handleSmartAlign = (alignData) => {
const element = allElements.value.find(el => el.id === alignData.id);
if (element && element.type === 'text') {
const pageWidth = currentPageSize.value.width;
const elementWidth = element.width || 200;
let newX = element.x;
switch (alignData.align) {
case 'center':
newX = (pageWidth - elementWidth) / 2;
break;
case 'right':
newX = pageWidth - elementWidth - 50;
break;
case 'left':
default:
newX = 50;
}
// Actualizar posición y formato
Object.assign(element, {
x: newX,
formatting: alignData.formatting
});
textFormatterElement.value = { ...element };
}
};
/** Tipos de elementos disponibles */
const availableElements = [
{
@ -185,6 +109,14 @@ const handleDragOver = (event) => {
event.preventDefault();
};
const handleCanvasClick = (clickData) => {
selectedElementId.value = null;
};
const selectElement = (elementId) => {
selectedElementId.value = elementId;
};
const deleteElement = (elementId) => {
const index = allElements.value.findIndex(el => el.id === elementId);
if (index !== -1) {
@ -196,11 +128,26 @@ const deleteElement = (elementId) => {
}
};
const updateElement = (update) => {
const element = allElements.value.find(el => el.id === update.id);
if (element) {
Object.assign(element, update);
}
};
const moveElement = (moveData) => {
const element = allElements.value.find(el => el.id === moveData.id);
if (element) {
element.x = moveData.x;
element.y = moveData.y;
}
};
/** Paginación */
const addPage = () => {
pageIdCounter.value++; // <-- Incrementar contador independiente
const newPageId = Math.max(...pages.value.map(p => p.id)) + 1;
pages.value.push({
id: pageIdCounter.value,
id: newPageId,
elements: []
});
};
@ -264,243 +211,249 @@ const exportPDF = async () => {
isExporting.value = true;
window.Notify.info('Generando PDF...');
// Crear un nuevo documento PDF con el tamaño de página seleccionado
// Crear un nuevo documento PDF
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;
let currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]);
let currentPageHeight = pageHeightPoints;
let currentPage = pdfDoc.addPage([595.28, 841.89]); // A4 size in points
let currentPageHeight = 841.89;
let yOffset = 50; // Margen superior
// 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 si no es la primera
if (pageIndex > 0) {
currentPDFPage = pdfDoc.addPage([pageWidthPoints, pageHeightPoints]);
currentPageHeight = pageHeightPoints;
// Ordenar elementos por posición (de arriba hacia abajo, de izquierda a derecha)
const sortedElements = [...allElements.value].sort((a, b) => {
if (Math.abs(a.y - b.y) < 20) {
return a.x - b.x; // Si están en la misma línea, ordenar por X
}
return a.y - b.y; // Ordenar por Y
});
// Procesar elementos
for (const element of sortedElements) {
// Calcular posición en el PDF
const x = Math.max(50, Math.min(500, (element.x * 0.75) + 50)); // Convertir y limitar X
let y = currentPageHeight - yOffset - (element.y * 0.75); // Convertir Y
// Verificar si necesitamos una nueva página
const elementHeight = getElementHeight(element);
if (y - elementHeight < 50) {
currentPage = pdfDoc.addPage([595.28, 841.89]);
currentPageHeight = 841.89;
yOffset = 50;
y = currentPageHeight - yOffset;
}
// 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;
});
switch (element.type) {
case 'text':
if (element.content) {
// Dividir texto largo en líneas
const words = element.content.split(' ');
const lines = [];
let currentLine = '';
const maxWidth = Math.min(400, (element.width || 200) * 0.75);
// 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) {
// Obtener formato del elemento
const formatting = element.formatting || {};
const fontSize = formatting.fontSize || 12;
const isBold = formatting.bold || false;
const isItalic = formatting.italic || false;
const textAlign = formatting.textAlign || 'left';
for (const word of words) {
const testLine = currentLine + (currentLine ? ' ' : '') + word;
const testWidth = helveticaFont.widthOfTextAtSize(testLine, 12);
// Convertir color hexadecimal a RGB
let textColor = rgb(0, 0, 0); // Negro por defecto
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);
if (testWidth <= maxWidth) {
currentLine = testLine;
} else {
if (currentLine) lines.push(currentLine);
currentLine = word;
}
// Seleccionar fuente
let font = helveticaFont;
if (isBold && !isItalic) {
font = helveticaBoldFont;
} else if (isBold && isItalic) {
// Para negrita + cursiva, usar negrita (limitación de PDF-lib)
font = helveticaBoldFont;
}
// Dividir texto largo en líneas
const words = element.content.split(' ');
const lines = [];
let currentLine = '';
const maxWidth = Math.min(pageWidthPoints - 100, (element.width || 200) * scaleX);
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);
// Calcular posición X según alineación
lines.forEach((line, index) => {
let lineX = x;
const lineWidth = font.widthOfTextAtSize(line, fontSize);
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: y - (index * (fontSize + 3)),
size: fontSize,
font: font,
color: textColor,
});
});
}
break;
if (currentLine) lines.push(currentLine);
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)
);
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);
}
// Dibujar cada línea
lines.forEach((line, index) => {
currentPage.drawText(line, {
x: x,
y: y - (index * 15),
size: 12,
font: helveticaFont,
color: rgb(0, 0, 0),
});
});
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;
}
yOffset += lines.length * 15 + 10;
}
break;
currentPDFPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
});
}
} 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,
});
case 'code':
if (element.content) {
// Dibujar fondo para el código
const codeLines = element.content.split('\n');
const codeWidth = Math.min(450, (element.width || 300) * 0.75);
const codeHeight = (codeLines.length * 12) + 20;
currentPDFPage.drawText('[Imagen no disponible]', {
x: x + 5,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
currentPage.drawRectangle({
x: x - 10,
y: y - codeHeight,
width: codeWidth,
height: codeHeight,
color: rgb(0.95, 0.95, 0.95),
});
// Dibujar código
codeLines.forEach((line, index) => {
// Truncar líneas muy largas
const maxChars = Math.floor(codeWidth / 6);
const displayLine = line.length > maxChars ?
line.substring(0, maxChars - 3) + '...' : line;
currentPage.drawText(displayLine, {
x: x - 5,
y: y - 15 - (index * 12),
size: 9,
font: courierFont,
color: rgb(0, 0, 0),
});
});
yOffset += codeHeight + 20;
}
break;
case 'image':
if (element.content && element.content.startsWith('data:image')) {
try {
// Convertir base64 a bytes
const base64Data = element.content.split(',')[1];
const imageBytes = Uint8Array.from(
atob(base64Data),
c => c.charCodeAt(0)
);
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);
}
} else {
// Placeholder para imagen vacía
currentPDFPage.drawRectangle({
if (image) {
// Calcular dimensiones manteniendo proporción
const maxWidth = Math.min(400, (element.width || 200) * 0.75);
const maxHeight = Math.min(300, (element.height || 150) * 0.75);
const imageAspectRatio = image.width / image.height;
let displayWidth = maxWidth;
let displayHeight = maxWidth / imageAspectRatio;
if (displayHeight > maxHeight) {
displayHeight = maxHeight;
displayWidth = maxHeight * imageAspectRatio;
}
currentPage.drawImage(image, {
x: x,
y: y - displayHeight,
width: displayWidth,
height: displayHeight,
});
yOffset += displayHeight + 20;
}
} catch (imageError) {
console.warn('Error al procesar imagen:', imageError);
// Dibujar placeholder para imagen
currentPage.drawRectangle({
x: x,
y: y - 60,
width: 100 * scaleX,
height: 60 * scaleY,
width: 100,
height: 60,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
borderDashArray: [3, 3],
});
currentPDFPage.drawText('[Imagen]', {
x: x + 25,
currentPage.drawText('[Imagen no disponible]', {
x: x + 5,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
yOffset += 80;
}
break;
} else {
// Placeholder para imagen vacía
currentPage.drawRectangle({
x: x,
y: y - 60,
width: 100,
height: 60,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
borderDashArray: [3, 3],
});
case 'table':
if (element.content && element.content.data) {
const tableData = element.content.data;
const cellWidth = 80 * scaleX;
const cellHeight = 20 * scaleY;
const tableWidth = tableData[0].length * cellWidth;
const tableHeight = tableData.length * cellHeight;
currentPage.drawText('[Imagen]', {
x: x + 25,
y: y - 35,
size: 10,
font: helveticaFont,
color: rgb(0.7, 0.7, 0.7),
});
currentPDFPage.drawRectangle({
x: x,
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.3, 0.3, 0.3),
borderWidth: 1,
});
yOffset += 80;
}
break;
tableData.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight) - 15;
case 'table':
if (element.content && element.content.data) {
const tableData = element.content.data;
const cellWidth = 80;
const cellHeight = 20;
const tableWidth = tableData[0].length * cellWidth;
const tableHeight = tableData.length * cellHeight;
currentPDFPage.drawRectangle({
x: cellX,
y: y - ((rowIndex + 1) * cellHeight),
width: cellWidth,
height: cellHeight,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
// Dibujar bordes de la tabla
currentPage.drawRectangle({
x: x,
y: y - tableHeight,
width: tableWidth,
height: tableHeight,
borderColor: rgb(0.3, 0.3, 0.3),
borderWidth: 1,
});
const maxChars = Math.floor(cellWidth / 8);
const displayText = cell.length > maxChars ?
cell.substring(0, maxChars - 3) + '...' : cell;
// Dibujar contenido de las celdas
tableData.forEach((row, rowIndex) => {
row.forEach((cell, colIndex) => {
const cellX = x + (colIndex * cellWidth);
const cellY = y - (rowIndex * cellHeight) - 15;
currentPDFPage.drawText(displayText, {
x: cellX + 5,
y: cellY,
size: 8,
font: helveticaFont,
color: rowIndex === 0 ? rgb(0.2, 0.2, 0.8) : rgb(0, 0, 0),
});
// Dibujar borde de celda
currentPage.drawRectangle({
x: cellX,
y: y - ((rowIndex + 1) * cellHeight),
width: cellWidth,
height: cellHeight,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 0.5,
});
// Dibujar texto de la celda (truncar si es muy largo)
const maxChars = 10;
const displayText = cell.length > maxChars ?
cell.substring(0, maxChars - 3) + '...' : cell;
currentPage.drawText(displayText, {
x: cellX + 5,
y: cellY,
size: 8,
font: helveticaFont,
color: rowIndex === 0 ? rgb(0.2, 0.2, 0.8) : rgb(0, 0, 0), // Encabezados en azul
});
});
}
break;
}
});
yOffset += tableHeight + 20;
}
break;
}
}
@ -551,8 +504,6 @@ const clearCanvas = () => {
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;
}
};
@ -575,7 +526,7 @@ onMounted(() => {
<template>
<div class="flex h-screen bg-gray-50 dark:bg-primary-d/50">
<!-- Panel Izquierdo - Elementos (sin cambios) -->
<!-- Panel Izquierdo - Elementos -->
<div class="w-64 bg-white dark:bg-primary-d border-r border-gray-200 dark:border-primary/20 flex flex-col">
<!-- Header del panel -->
<div class="p-4 border-b border-gray-200 dark:border-primary/20">
@ -651,12 +602,18 @@ onMounted(() => {
<!-- Área Principal con Viewport -->
<div class="flex-1 flex flex-col">
<!-- Toolbar superior básico -->
<!-- Toolbar superior -->
<div class="h-14 bg-white dark:bg-primary-d border-b border-gray-200 dark:border-primary/20 flex items-center justify-between px-4">
<div class="flex items-center gap-4">
<h2 class="font-semibold text-gray-900 dark:text-primary-dt text-sm">
{{ documentTitle }}
</h2>
<!-- Herramientas de formato (simuladas) -->
<div class="flex items-center gap-1 text-sm">
<button class="p-1 hover:bg-gray-100 dark:hover:bg-primary/10 rounded" :disabled="isExporting">
<GoogleIcon name="format_bold" class="text-gray-600 dark:text-primary-dt" />
</button>
<button class="p-1 hover:bg-gray-100 dark:hover:bg-primary/10 rounded" :disabled="isExporting">
<GoogleIcon name="format_italic" class="text-gray-600 dark:text-primary-dt" />
</button>
</div>
</div>
<div class="flex items-center gap-4">
@ -676,14 +633,6 @@ onMounted(() => {
</div>
</div>
<!-- TextFormatter como toolbar estático -->
<TextFormatter
:element="textFormatterElement"
:visible="showTextFormatter"
@update="updateElement"
@smart-align="handleSmartAlign"
/>
<!-- PDFViewport -->
<PDFViewport
ref="viewportRef"
@ -695,7 +644,6 @@ onMounted(() => {
@add-page="addPage"
@delete-page="deletePage"
@page-change="(page) => currentPage = page"
@page-size-change="handlePageSizeChange"
>
<template #elements="{ page, pageIndex }">
<CanvasElement