// 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 = `
`; } } // 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 = ' 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 => `${cell.trim()}`).join('') ).map(row => `${row}`).join(''); // Mostrar preview se houver elemento para isso const previewContainer = document.getElementById('csvPreview'); if (previewContainer) { previewContainer.innerHTML = ` Preview (primeiras 5 linhas): ${preview}
`; } } 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 = `
Imagem processada:
Preview
`; }; 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 = ' 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 = `
`; } } 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 = `
Preview
`; }; reader.readAsDataURL(file); } }); } }