413 lines
14 KiB
JavaScript
413 lines
14 KiB
JavaScript
// wwwroot/js/converters/text-case-converter.js
|
|
// Implementação específica para conversor de maiúsculas/minúsculas
|
|
|
|
let converterConfig = null;
|
|
|
|
// Função principal chamada pelo widget base
|
|
async function performConversion(formData) {
|
|
const textInput = formData.get('inputText');
|
|
const caseType = formData.get('caseType') || 'upper';
|
|
|
|
if (!textInput || textInput.trim() === '') {
|
|
throw new Error('Por favor, insira algum texto para converter');
|
|
}
|
|
|
|
// Fazer requisição para o backend
|
|
const requestData = new FormData();
|
|
requestData.append('inputType', 'text');
|
|
requestData.append('textInput', textInput);
|
|
requestData.append('language', document.documentElement.lang || 'pt');
|
|
|
|
// Adicionar opções
|
|
const options = { caseType: caseType };
|
|
requestData.append('options', JSON.stringify(options));
|
|
|
|
const response = await fetch('/converter/api/convert/text-case', {
|
|
method: 'POST',
|
|
body: requestData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json();
|
|
throw new Error(error.message || 'Erro na conversão');
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
// Mostrar resultado
|
|
showConversionResult(result.outputText);
|
|
}
|
|
|
|
// Função para mostrar o resultado
|
|
function showConversionResult(outputText) {
|
|
const outputArea = document.getElementById('outputArea');
|
|
const outputTextElement = document.getElementById('outputText');
|
|
const successActions = document.getElementById('successActions');
|
|
|
|
if (outputTextElement) {
|
|
outputTextElement.value = outputText;
|
|
outputArea.style.display = 'block';
|
|
successActions.style.display = 'block';
|
|
}
|
|
}
|
|
|
|
// Inicialização específica do conversor
|
|
function initializeConverter() {
|
|
loadConverterConfig();
|
|
setupAdvancedOptions();
|
|
}
|
|
|
|
// Carregar configuração do conversor
|
|
async function loadConverterConfig() {
|
|
try {
|
|
const response = await fetch('/converter/config/text-case');
|
|
if (response.ok) {
|
|
converterConfig = await response.json();
|
|
updateUIWithConfig(converterConfig.config);
|
|
}
|
|
} catch (error) {
|
|
console.error('Erro ao carregar configuração:', error);
|
|
}
|
|
}
|
|
|
|
// Atualizar UI com configuração
|
|
function updateUIWithConfig(config) {
|
|
const texts = config.localizedTexts;
|
|
|
|
// Atualizar textos localizados
|
|
Object.keys(texts).forEach(key => {
|
|
const elements = document.querySelectorAll(`[data-text="${key}"]`);
|
|
elements.forEach(el => {
|
|
if (el.tagName === 'INPUT' && (el.type === 'button' || el.type === 'submit')) {
|
|
el.value = texts[key];
|
|
} else {
|
|
el.textContent = texts[key];
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Configurar opções avançadas
|
|
function setupAdvancedOptions() {
|
|
const advancedContainer = document.getElementById('advancedSettings');
|
|
if (advancedContainer) {
|
|
advancedContainer.innerHTML = `
|
|
<div class="row">
|
|
<div class="col-md-6">
|
|
<label class="form-label">Tipo de Conversão</label>
|
|
<select name="caseType" class="form-select">
|
|
<option value="upper">MAIÚSCULAS</option>
|
|
<option value="lower">minúsculas</option>
|
|
<option value="title">Primeira Maiúscula Em Cada Palavra</option>
|
|
<option value="sentence">Primeira maiúscula apenas</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
}
|
|
|
|
// wwwroot/js/converters/csv-json-converter.js
|
|
// Implementação específica para conversor CSV para JSON
|
|
|
|
async function performConversion(formData) {
|
|
const textInput = formData.get('inputText');
|
|
const fileInput = formData.get('file');
|
|
|
|
if (!textInput && !fileInput) {
|
|
throw new Error('Por favor, forneça conteúdo CSV ou faça upload de um arquivo');
|
|
}
|
|
|
|
const requestData = new FormData();
|
|
|
|
if (fileInput && fileInput.size > 0) {
|
|
requestData.append('inputType', 'file');
|
|
requestData.append('fileInput', fileInput);
|
|
} else {
|
|
requestData.append('inputType', 'text');
|
|
requestData.append('textInput', textInput);
|
|
}
|
|
|
|
requestData.append('language', document.documentElement.lang || 'pt');
|
|
|
|
const response = await fetch('/converter/api/convert/csv-json', {
|
|
method: 'POST',
|
|
body: requestData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json();
|
|
throw new Error(error.message || 'Erro na conversão');
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
// Mostrar resultado formatado
|
|
showJsonResult(result.outputText);
|
|
}
|
|
|
|
function showJsonResult(jsonText) {
|
|
const outputTextElement = document.getElementById('outputText');
|
|
const successActions = document.getElementById('successActions');
|
|
|
|
if (outputTextElement) {
|
|
// Formatar JSON para melhor visualização
|
|
try {
|
|
const parsed = JSON.parse(jsonText);
|
|
outputTextElement.value = JSON.stringify(parsed, null, 2);
|
|
} catch {
|
|
outputTextElement.value = jsonText;
|
|
}
|
|
|
|
document.getElementById('outputArea').style.display = 'block';
|
|
successActions.style.display = 'block';
|
|
|
|
// Adicionar botão de download
|
|
addDownloadButton(jsonText);
|
|
}
|
|
}
|
|
|
|
function addDownloadButton(content) {
|
|
const successActions = document.getElementById('successActions');
|
|
|
|
// Verificar se já existe botão de download
|
|
if (document.getElementById('downloadJsonBtn')) return;
|
|
|
|
const downloadBtn = document.createElement('button');
|
|
downloadBtn.id = 'downloadJsonBtn';
|
|
downloadBtn.type = 'button';
|
|
downloadBtn.className = 'btn btn-sm btn-outline-success';
|
|
downloadBtn.innerHTML = '<i class="fas fa-download me-1"></i> Baixar JSON';
|
|
|
|
downloadBtn.addEventListener('click', () => {
|
|
const blob = new Blob([content], { type: 'application/json' });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = 'converted.json';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
});
|
|
|
|
successActions.appendChild(downloadBtn);
|
|
}
|
|
|
|
function initializeConverter() {
|
|
// CSV específico: permitir preview dos dados
|
|
setupCsvPreview();
|
|
}
|
|
|
|
function setupCsvPreview() {
|
|
const textInput = document.getElementById('inputText');
|
|
if (textInput) {
|
|
textInput.addEventListener('input', debounce(showCsvPreview, 500));
|
|
}
|
|
}
|
|
|
|
function showCsvPreview() {
|
|
const textInput = document.getElementById('inputText');
|
|
const csvContent = textInput.value.trim();
|
|
|
|
if (csvContent.length > 0) {
|
|
try {
|
|
const lines = csvContent.split('\n').slice(0, 5); // Mostrar só 5 linhas
|
|
const preview = lines.map(line =>
|
|
line.split(',').map(cell => `<td>${cell.trim()}</td>`).join('')
|
|
).map(row => `<tr>${row}</tr>`).join('');
|
|
|
|
// Mostrar preview se houver elemento para isso
|
|
const previewContainer = document.getElementById('csvPreview');
|
|
if (previewContainer) {
|
|
previewContainer.innerHTML = `
|
|
<small class="text-muted">Preview (primeiras 5 linhas):</small>
|
|
<table class="table table-sm table-bordered mt-1">
|
|
${preview}
|
|
</table>
|
|
`;
|
|
}
|
|
} catch (error) {
|
|
// Ignorar erros de preview
|
|
}
|
|
}
|
|
}
|
|
|
|
// Utility function
|
|
function debounce(func, wait) {
|
|
let timeout;
|
|
return function executedFunction(...args) {
|
|
const later = () => {
|
|
clearTimeout(timeout);
|
|
func(...args);
|
|
};
|
|
clearTimeout(timeout);
|
|
timeout = setTimeout(later, wait);
|
|
};
|
|
}
|
|
|
|
// wwwroot/js/converters/image-ocr-converter.js
|
|
// Implementação específica para conversor de imagem para texto (OCR)
|
|
|
|
async function performConversion(formData) {
|
|
const fileInput = formData.get('file');
|
|
|
|
if (!fileInput || fileInput.size === 0) {
|
|
throw new Error('Por favor, selecione uma imagem');
|
|
}
|
|
|
|
// Validar tipo de arquivo
|
|
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'application/pdf'];
|
|
if (!allowedTypes.includes(fileInput.type)) {
|
|
throw new Error('Formato de arquivo não suportado. Use JPG, PNG, GIF, BMP ou PDF.');
|
|
}
|
|
|
|
// Validar tamanho (15MB)
|
|
if (fileInput.size > 15 * 1024 * 1024) {
|
|
throw new Error('Arquivo muito grande. Tamanho máximo: 15MB');
|
|
}
|
|
|
|
const requestData = new FormData();
|
|
requestData.append('inputType', 'file');
|
|
requestData.append('fileInput', fileInput);
|
|
requestData.append('language', document.documentElement.lang || 'pt');
|
|
|
|
// Adicionar opções de OCR se houver
|
|
const ocrLanguage = formData.get('ocrLanguage') || 'por';
|
|
const options = { ocrLanguage: ocrLanguage };
|
|
requestData.append('options', JSON.stringify(options));
|
|
|
|
const response = await fetch('/converter/api/convert/image-ocr', {
|
|
method: 'POST',
|
|
body: requestData
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json();
|
|
throw new Error(error.message || 'Erro no processamento da imagem');
|
|
}
|
|
|
|
const result = await response.json();
|
|
|
|
// Mostrar resultado do OCR
|
|
showOcrResult(result.outputText, fileInput);
|
|
}
|
|
|
|
function showOcrResult(extractedText, originalFile) {
|
|
const outputTextElement = document.getElementById('outputText');
|
|
const successActions = document.getElementById('successActions');
|
|
|
|
if (outputTextElement) {
|
|
outputTextElement.value = extractedText;
|
|
document.getElementById('outputArea').style.display = 'block';
|
|
successActions.style.display = 'block';
|
|
|
|
// Mostrar preview da imagem
|
|
showImagePreview(originalFile);
|
|
|
|
// Adicionar botão para salvar texto
|
|
addSaveTextButton(extractedText);
|
|
}
|
|
}
|
|
|
|
function showImagePreview(file) {
|
|
const previewContainer = document.getElementById('imagePreview');
|
|
if (previewContainer && file.type.startsWith('image/')) {
|
|
const reader = new FileReader();
|
|
reader.onload = function (e) {
|
|
previewContainer.innerHTML = `
|
|
<div class="mt-3">
|
|
<small class="text-muted">Imagem processada:</small><br>
|
|
<img src="${e.target.result}" alt="Preview" class="img-thumbnail mt-1" style="max-height: 200px;">
|
|
</div>
|
|
`;
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
}
|
|
|
|
function addSaveTextButton(text) {
|
|
const successActions = document.getElementById('successActions');
|
|
|
|
if (document.getElementById('saveTextBtn')) return;
|
|
|
|
const saveBtn = document.createElement('button');
|
|
saveBtn.id = 'saveTextBtn';
|
|
saveBtn.type = 'button';
|
|
saveBtn.className = 'btn btn-sm btn-outline-success';
|
|
saveBtn.innerHTML = '<i class="fas fa-save me-1"></i> Salvar Texto';
|
|
|
|
saveBtn.addEventListener('click', () => {
|
|
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = 'texto-extraido.txt';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
});
|
|
|
|
successActions.appendChild(saveBtn);
|
|
}
|
|
|
|
function initializeConverter() {
|
|
setupAdvancedOcrOptions();
|
|
setupImagePreview();
|
|
}
|
|
|
|
function setupAdvancedOcrOptions() {
|
|
const advancedContainer = document.getElementById('advancedSettings');
|
|
if (advancedContainer) {
|
|
advancedContainer.innerHTML = `
|
|
<div class="row">
|
|
<div class="col-md-6">
|
|
<label class="form-label">Idioma do OCR</label>
|
|
<select name="ocrLanguage" class="form-select">
|
|
<option value="por">Português</option>
|
|
<option value="eng">English</option>
|
|
<option value="spa">Español</option>
|
|
<option value="fra">Français</option>
|
|
<option value="deu">Deutsch</option>
|
|
</select>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<label class="form-label">Qualidade</label>
|
|
<select name="quality" class="form-select">
|
|
<option value="balanced">Balanceada</option>
|
|
<option value="fast">Rápida</option>
|
|
<option value="accurate">Precisa</option>
|
|
</select>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
}
|
|
|
|
function setupImagePreview() {
|
|
const fileInput = document.getElementById('fileInput');
|
|
if (fileInput) {
|
|
fileInput.addEventListener('change', function (e) {
|
|
const file = e.target.files[0];
|
|
if (file && file.type.startsWith('image/')) {
|
|
const reader = new FileReader();
|
|
reader.onload = function (event) {
|
|
let previewContainer = document.getElementById('imagePreview');
|
|
if (!previewContainer) {
|
|
previewContainer = document.createElement('div');
|
|
previewContainer.id = 'imagePreview';
|
|
fileInput.parentNode.appendChild(previewContainer);
|
|
}
|
|
|
|
previewContainer.innerHTML = `
|
|
<div class="mt-2">
|
|
<img src="${event.target.result}" alt="Preview" class="img-thumbnail" style="max-height: 150px;">
|
|
</div>
|
|
`;
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
});
|
|
}
|
|
} |