249 lines
7.8 KiB
JavaScript
249 lines
7.8 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);
|
|
};
|
|
}
|
|
|