Estiliza pagina de upload externo - responsiva (novo47)

This commit is contained in:
rodrigo committed 2025-02-08 23:24:04 -03:00
1 parent 05cd7b9c79
commit 631afa1c46
15 files changed
+1818 -24

No files matched your search

+694
View File
@@ -0,0 +1,694 @@
<!DOCTYPE html>
<html>
<head>
<title>Editor de Documentos</title>
<link href="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://unpkg.com/downloadjs@1.4.7/download.js"></script>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
body {
display: flex;
flex-direction: column;
font-family: Arial, sans-serif;
background: #f5f5f5;
}
/* Container principal com scroll */
.editor-container {
max-width: 1600px;
margin: 0 auto;
padding: 20px;
height: calc(100vh - 20px);
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 20px;
}
/* Container da imagem ajustado */
.img-container {
position: relative;
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
height: 70vh;
min-height: 500px;
max-height: 800px;
margin: 20px 0;
overflow: hidden;
}
/* Ajustes do Cropper */
.cropper-container {
position: relative !important;
width: 100% !important;
height: 100% !important;
}
.cropper-wrap-box {
background-color: #f8f8f8;
}
/* Pontos de redimensionamento maiores e mais visíveis */
.cropper-point {
width: 25px !important;
height: 25px !important;
background-color: #4CAF50 !important;
border: 3px solid white !important;
opacity: 1 !important;
border-radius: 50% !important;
}
.cropper-point.point-se {
width: 25px !important;
height: 25px !important;
opacity: 1 !important;
}
.cropper-view-box {
outline: 2px solid #4CAF50 !important;
outline-color: rgba(74, 175, 80, 0.75) !important;
}
.cropper-line {
width: 3px !important;
height: 3px !important;
background-color: #4CAF50 !important;
opacity: 0.8 !important;
}
/* Z-index ajustados */
.cropper-face {
z-index: 2 !important;
}
.cropper-line, .cropper-point {
z-index: 3 !important;
}
/* Área de controles sempre visível */
.controls-section {
position: sticky;
bottom: 70px;
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
z-index: 4;
}
.toolbar {
position: sticky;
bottom: 0;
background: #fff;
padding: 15px;
border-radius: 8px 8px 0 0;
box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
z-index: 5;
}
.controls {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
}
.range-control {
margin-bottom: 10px;
}
.range-control label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.range-control input[type="range"] {
width: 100%;
}
.toolbar {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 10px;
padding: 10px;
text-align: center;
background: #fff;
border-radius: 4px;
}
.toolbar button {
padding: 10px 20px;
margin: 0 8px;
font-weight: 500;
transition: all 0.3s ease;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.toolbar button:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
background: #45a049;
}
#preview {
display: block;
max-width: 100%;
max-height: 100%;
margin: auto;
}
.cropper-container {
width: 100% !important;
height: 100% !important;
}
.cropper-wrap-box {
background-color: #f8f8f8;
}
.cropper-view-box {
outline: 2px solid #4CAF50;
outline-color: rgba(74, 175, 80, 0.75);
}
.cropper-point {
width: 15px !important;
height: 15px !important;
background-color: #4CAF50;
opacity: 0.9;
border-radius: 50%;
}
.cropper-point.point-se {
width: 20px !important;
height: 20px !important;
background-color: #4CAF50;
}
.cropper-line {
background-color: #4CAF50;
opacity: 0.4;
}
.thumbnails {
height: 130px;
padding: 15px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: flex;
gap: 10px;
overflow-x: auto;
flex-shrink: 0; /* Impede encolhimento */
}
.thumbnail {
width: 110px;
height: 100px;
margin-right: 15px;
border-radius: 4px;
transition: all 0.3s ease;
object-fit: cover;
cursor: pointer;
border: 2px solid transparent;
}
.thumbnail:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}
.thumbnail.active {
border-color: #4CAF50;
}
#preview-container {
position: relative;
width: 100%;
height: 100%;
}
#preview-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.cropper-point {
width: 12px !important;
height: 12px !important;
background-color: #4CAF50 !important;
opacity: 0.8 !important;
}
/* Cursores específicos para cada ponto */
.cropper-point.point-e { cursor: e-resize !important; }
.cropper-point.point-n { cursor: n-resize !important; }
.cropper-point.point-w { cursor: w-resize !important; }
.cropper-point.point-s { cursor: s-resize !important; }
.cropper-point.point-ne { cursor: ne-resize !important; }
.cropper-point.point-nw { cursor: nw-resize !important; }
.cropper-point.point-sw { cursor: sw-resize !important; }
.cropper-point.point-se { cursor: se-resize !important; }
/* Linhas da caixa de recorte */
.cropper-line {
background-color: #4CAF50 !important;
opacity: 0.3 !important;
}
/* Área de recorte */
.cropper-view-box {
outline: 2px solid #4CAF50 !important;
outline-color: rgba(74, 175, 80, 0.75) !important;
}
/* Área fora do recorte */
.cropper-modal {
background-color: rgba(0, 0, 0, 0.5) !important;
}
/* Container do Cropper */
.cropper-container {
margin: auto;
max-height: calc(100vh - 350px) !important;
}
</style>
</head>
<body>
<div class="editor-container">
<div class="thumbnails" id="thumbnails">
<!-- Miniaturas serão inseridas aqui -->
</div>
<div class="img-container">
<div id="preview-container">
<img id="preview" src="">
<canvas id="preview-canvas"></canvas>
</div>
</div>
<div class="controls-section">
<div class="controls">
<div class="range-control">
<label>Brilho</label>
<input type="range" min="-100" max="100" value="0" id="brightness" oninput="adjustImage()">
<span id="brightnessValue">0</span>
</div>
<div class="range-control">
<label>Contraste</label>
<input type="range" min="-100" max="100" value="0" id="contrast" oninput="adjustImage()">
<span id="contrastValue">0</span>
</div>
<div class="range-control">
<label>Saturação</label>
<input type="range" min="-100" max="100" value="0" id="saturation" oninput="adjustImage()">
<span id="saturationValue">0</span>
</div>
<div class="range-control">
<label>Matiz</label>
<input type="range" min="-180" max="180" value="0" id="hue" oninput="adjustImage()">
<span id="hueValue">0</span>
</div>
</div>
</div>
<div class="toolbar">
<button onclick="resetImage()">Resetar</button>
<button onclick="rotateCCW()">Girar Esquerda</button>
<button onclick="rotateCW()">Girar Direita</button>
<button onclick="cropImage()">Recortar</button>
<button onclick="applyCrop()">Aplicar Recorte</button>
<button onclick="autoAdjust()">Otimização Automática</button>
<button onclick="combineImages()" style="background: #FF9800;">Unir Imagens</button>
<button onclick="saveImage()" style="background: #2196F3;">Salvar</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/cropperjs@1.5.12/dist/cropper.min.js"></script>
<script>
let cropper = null;
let currentImage = null;
function initCropper(url) {
return new Promise((resolve) => {
const preview = document.getElementById('preview');
preview.src = url;
if (cropper) {
cropper.destroy();
cropper = null;
}
preview.onload = function() {
cropper = new Cropper(preview, {
viewMode: 1,
dragMode: 'move',
aspectRatio: NaN,
autoCrop: true,
autoCropArea: 0.98,
cropBoxResizable: true,
cropBoxMovable: true,
zoomable: true,
rotatable: true,
scalable: true,
toggleDragModeOnDblclick: true,
ready: function() {
resolve();
}
});
};
});
}
function cropImage() {
if (!cropper) return;
if (cropper.getData().width === 0) {
// Se não houver área de recorte, criar uma
const containerData = cropper.getContainerData();
const minSize = Math.min(containerData.width, containerData.height);
cropper.setCropBoxData({
left: (containerData.width - minSize * 0.8) / 2,
top: (containerData.height - minSize * 0.8) / 2,
width: minSize * 0.8,
height: minSize * 0.8
});
}
// Alternar entre modos crop e move
if (cropper.options.dragMode === 'crop') {
cropper.setDragMode('move');
// Aplicar o recorte atual
const canvas = cropper.getCroppedCanvas();
if (canvas) {
const croppedImageUrl = canvas.toDataURL('image/jpeg');
cropper.replace(croppedImageUrl);
}
} else {
cropper.setDragMode('crop');
}
// Atualizar a UI
const cropBox = document.querySelector('.cropper-crop-box');
if (cropBox) {
cropBox.style.display = 'block';
}
// Forçar atualização do cropper
cropper.clear();
setTimeout(() => {
cropper.crop();
}, 50);
}
function applyCrop() {
if (!cropper) return;
const canvas = cropper.getCroppedCanvas({
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high'
});
if (canvas) {
const croppedImageUrl = canvas.toDataURL('image/jpeg');
cropper.destroy();
initCropper(croppedImageUrl);
}
}
async function rotateCW() {
if (!cropper) return;
try {
await cropper.rotate(90);
} catch (error) {
console.error('Erro ao rotacionar:', error);
}
}
async function rotateCCW() {
if (!cropper) return;
try {
await cropper.rotate(-90);
} catch (error) {
console.error('Erro ao rotacionar:', error);
}
}
function switchImage(index) {
currentImageIndex = index;
// Atualizar miniaturas
document.querySelectorAll('.thumbnail').forEach((thumb, i) => {
thumb.className = 'thumbnail' + (i === index ? ' active' : '');
});
// Carregar nova imagem
initCropper(images[index].url)
.then(() => {
// Restaurar filtros após inicialização
if (cropper) {
currentFilters = { ...images[index].filters };
updateFilterInputs();
applyCurrentFilters();
}
});
}
let images = [];
let currentImageIndex = 0;
let currentFilters = {
brightness: 100,
contrast: 100,
saturation: 100,
hue: 0
};
window.onload = function() {
try {
var allImages = JSON.parse(localStorage.getItem('allImages')) || [];
console.log('Imagens carregadas:', allImages);
if (allImages.length > 0) {
images = allImages.map(function(img) {
return {
url: img.url,
filters: { ...currentFilters }
};
});
} else {
var baseUrl = localStorage.getItem('tempImage');
if (!baseUrl) {
throw new Error('Nenhuma imagem encontrada');
}
images = [{
url: baseUrl,
filters: { ...currentFilters }
}];
}
// Criar miniaturas com verificação de URL
var thumbnailsContainer = document.getElementById('thumbnails');
thumbnailsContainer.innerHTML = '';
images.forEach(function(image, index) {
if (!image.url) {
console.error('URL da imagem inválida:', image);
return;
}
var thumb = document.createElement('img');
thumb.src = image.url;
thumb.className = 'thumbnail' + (index === 0 ? ' active' : '');
thumb.onerror = function() {
console.error('Erro ao carregar miniatura:', image.url);
this.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="110" height="100"><rect width="100%" height="100%" fill="%23ddd"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="%23666">Erro</text></svg>';
};
thumb.onclick = function() {
switchImage(index);
};
thumbnailsContainer.appendChild(thumb);
});
// Inicializar primeira imagem com verificação
if (images.length > 0 && images[0].url) {
console.log('Iniciando cropper com:', images[0].url);
initCropper(images[0].url).catch(function(error) {
console.error('Erro ao inicializar cropper:', error);
alert('Erro ao inicializar editor: ' + error.message);
});
} else {
throw new Error('Nenhuma imagem válida para inicializar');
}
} catch (error) {
console.error('Erro ao inicializar editor:', error);
alert('Erro ao carregar imagens: ' + error.message);
}
};
function updateFilterInputs() {
document.getElementById('brightness').value = currentFilters.brightness - 100;
document.getElementById('contrast').value = currentFilters.contrast - 100;
document.getElementById('saturation').value = currentFilters.saturation - 100;
document.getElementById('hue').value = currentFilters.hue;
document.getElementById('brightnessValue').textContent = currentFilters.brightness - 100;
document.getElementById('contrastValue').textContent = currentFilters.contrast - 100;
document.getElementById('saturationValue').textContent = currentFilters.saturation - 100;
document.getElementById('hueValue').textContent = currentFilters.hue;
}
function adjustImage() {
currentFilters = {
brightness: parseInt(document.getElementById('brightness').value) + 100,
contrast: parseInt(document.getElementById('contrast').value) + 100,
saturation: parseInt(document.getElementById('saturation').value) + 100,
hue: parseInt(document.getElementById('hue').value)
};
// Salvar filtros para a imagem atual
images[currentImageIndex].filters = { ...currentFilters };
applyCurrentFilters();
}
function applyCurrentFilters() {
if (!cropper) return;
const canvas = cropper.getCroppedCanvas();
if (!canvas || canvas.width === 0 || canvas.height === 0) return;
try {
const tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
const ctx = tempCanvas.getContext('2d');
ctx.filter = `brightness(${currentFilters.brightness}%)
contrast(${currentFilters.contrast}%)
saturate(${currentFilters.saturation}%)
hue-rotate(${currentFilters.hue}deg)`;
ctx.drawImage(canvas, 0, 0);
cropper.replace(tempCanvas.toDataURL('image/jpeg'));
} catch (error) {
console.error('Erro ao aplicar filtros:', error);
}
}
async function combineImages() {
try {
const { jsPDF } = window.jspdf;
const pdf = new jsPDF();
let currentY = 0;
for (let image of images) {
const img = await createImage(image.url);
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.filter = `brightness(${image.filters.brightness}%)
contrast(${image.filters.contrast}%)
saturate(${image.filters.saturation}%)
hue-rotate(${image.filters.hue}deg)`;
ctx.drawImage(img, 0, 0);
if (currentY > 0) {
pdf.addPage();
}
const imgData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(imgData, 'JPEG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height, '', 'FAST');
}
// Preview do PDF combinado
const pdfData = pdf.output('datauristring');
initCropper(pdfData);
} catch (error) {
console.error('Erro ao combinar imagens:', error);
alert('Erro ao combinar imagens: ' + error.message);
}
}
function createImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
function resetImage() {
if (cropper) {
cropper.reset();
currentFilters = {
brightness: 100,
contrast: 100,
saturation: 100,
hue: 0
};
images[currentImageIndex].filters = { ...currentFilters };
updateFilterInputs();
applyCurrentFilters();
}
}
function autoAdjust() {
// Implementar otimização automática aqui
alert('Função em desenvolvimento');
}
async function saveImage() {
if (!cropper) {
alert('Editor não inicializado corretamente');
return;
}
try {
// Obter canvas com filtros aplicados
const canvas = cropper.getCroppedCanvas({
maxWidth: 4096,
maxHeight: 4096,
fillColor: '#fff',
imageSmoothingEnabled: true,
imageSmoothingQuality: 'high'
});
if (!canvas) {
throw new Error('Não foi possível gerar a imagem');
}
// Criar PDF
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({
orientation: canvas.width > canvas.height ? 'l' : 'p',
unit: 'px',
format: [canvas.width, canvas.height]
});
// Adicionar imagem ao PDF
const imgData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(imgData, 'JPEG', 0, 0, canvas.width, canvas.height);
// Converter PDF para Blob
const pdfBlob = pdf.output('blob');
const formData = new FormData();
formData.append('image', pdfBlob, 'documento.pdf');
formData.append('client_id', localStorage.getItem('tempClientId'));
formData.append('doc_type', localStorage.getItem('tempDocType'));
const response = await fetch('index.php?page=save_edited', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
window.parent.postMessage({
type: 'documentSaved',
data: result
}, '*');
} else {
throw new Error(result.message || 'Erro ao salvar');
}
} catch (error) {
console.error('Erro:', error);
alert('Erro ao processar: ' + error.message);
}
}
</script>
</body>
</html>