formforge-geostudio / script.js
mapolanski's picture
Onde esta tudo o que eu pedi? So apareceu um botao enviar dados e alguns textos. O sistemas que quero é um gerador de formularios e nao um formulario apenas
b2363b3 verified
Raw History Blame Contribute Delete
31.4 kB
// ============================================
// FormForge GeoStudio - Core JavaScript 🗺️
// ============================================
// Global State Management
const FormForge = {
currentForm: {
id: null,
name: '',
description: '',
fields: [],
theme: 'dark',
version: '2.0.0'
},
selectedElement: null,
currentDevice: 'mobile',
mapInstances: {},
undoStack: [],
redoStack: [],
maxUndoSteps: 50
};
// Initialize Application
document.addEventListener('DOMContentLoaded', () => {
console.log('🗺️ FormForge GeoStudio initializing...');
initTheme();
initKeyboardShortcuts();
loadForms();
animateEntry();
});
// ============================================
// Theme Management 🎨
// ============================================
function initTheme() {
const savedTheme = localStorage.getItem('geoforms-theme') || 'dark';
document.documentElement.classList.toggle('dark', savedTheme === 'dark');
updateThemeIcon(savedTheme === 'dark');
}
function toggleTheme() {
const isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('geoforms-theme', isDark ? 'dark' : 'light');
updateThemeIcon(isDark);
// Dispatch theme change event
window.dispatchEvent(new CustomEvent('themeChanged', { detail: { isDark } }));
}
function updateThemeIcon(isDark) {
// Update all theme toggle buttons
document.querySelectorAll('.theme-toggle, [onclick*="toggleTheme"]').forEach(btn => {
const sunIcon = btn.querySelector('.sun-icon, [data-feather="sun"]');
const moonIcon = btn.querySelector('.moon-icon, [data-feather="moon"]');
if (sunIcon) sunIcon.style.display = isDark ? 'none' : 'block';
if (moonIcon) moonIcon.style.display = isDark ? 'block' : 'none';
});
}
// ============================================
// Animation & Effects ✨
// ============================================
function animateEntry() {
const elements = document.querySelectorAll('.animate-on-load');
elements.forEach((el, i) => {
el.style.opacity = '0';
el.style.transform = 'translateY(20px)';
setTimeout(() => {
el.style.transition = 'all 0.5s ease';
el.style.opacity = '1';
el.style.transform = 'translateY(0)';
}, i * 100);
});
}
function showToast(message, type = 'success') {
const toast = document.createElement('div');
const colors = {
success: 'bg-green-500',
error: 'bg-red-500',
warning: 'bg-yellow-500',
info: 'bg-blue-500'
};
toast.className = `fixed bottom-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-2xl z-50 transform translate-y-full transition-transform duration-300 flex items-center gap-2`;
toast.innerHTML = `
<span>${type === 'success' ? '✅' : type === 'error' ? '❌' : type === 'warning' ? '⚠️' : 'ℹ️'}</span>
<span>${message}</span>
`;
document.body.appendChild(toast);
requestAnimationFrame(() => toast.classList.remove('translate-y-full'));
setTimeout(() => {
toast.classList.add('translate-y-full');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// ============================================
// Keyboard Shortcuts ⌨️
// ============================================
function initKeyboardShortcuts() {
document.addEventListener('keydown', (e) => {
// Ctrl/Cmd + S = Save
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
if (typeof saveCurrentForm === 'function') {
saveCurrentForm();
showToast('Formulário salvo! 💾');
}
}
// Ctrl/Cmd + Z = Undo
if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
e.preventDefault();
undo();
}
// Ctrl/Cmd + Shift + Z = Redo
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'z') {
e.preventDefault();
redo();
}
// Delete = Remove selected
if (e.key === 'Delete' && FormForge.selectedElement !== null) {
deleteElement(FormForge.selectedElement);
}
});
}
// ============================================
// Undo/Redo System ↩️
// ============================================
function saveState() {
const state = JSON.stringify(FormForge.currentForm.fields);
FormForge.undoStack.push(state);
if (FormForge.undoStack.length > FormForge.maxUndoSteps) {
FormForge.undoStack.shift();
}
FormForge.redoStack = [];
}
function undo() {
if (FormForge.undoStack.length === 0) return;
const current = JSON.stringify(FormForge.currentForm.fields);
FormForge.redoStack.push(current);
const previous = FormForge.undoStack.pop();
FormForge.currentForm.fields = JSON.parse(previous);
refreshBuilder();
showToast('Desfeito ↩️', 'info');
}
function redo() {
if (FormForge.redoStack.length === 0) return;
const current = JSON.stringify(FormForge.currentForm.fields);
FormForge.undoStack.push(current);
const next = FormForge.redoStack.pop();
FormForge.currentForm.fields = JSON.parse(next);
refreshBuilder();
showToast('Refeito ↪️', 'info');
}
function refreshBuilder() {
const preview = document.getElementById('devicePreview');
if (preview) {
// Clear and rebuild
const content = preview.shadowRoot?.getElementById('formContent');
if (content) {
content.innerHTML = '';
FormForge.currentForm.fields.forEach(field => {
preview.addField(field);
});
}
}
saveCurrentForm();
}
// Legacy compatibility
let currentForm = FormForge.currentForm;
let selectedElement = FormForge.selectedElement;
let currentDevice = FormForge.currentDevice;
let mapInstances = FormForge.mapInstances;
// Dashboard Functions
function loadForms() {
const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
const grid = document.getElementById('formsGrid');
const emptyState = document.getElementById('emptyState');
if (!grid) return;
if (forms.length === 0) {
grid.innerHTML = '';
emptyState.classList.remove('hidden');
return;
}
emptyState.classList.add('hidden');
grid.innerHTML = forms.map(form => `
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden group border border-gray-200 dark:border-gray-700">
<div class="h-32 bg-gradient-to-br from-primary-500 to-secondary-500 relative overflow-hidden">
<div class="absolute inset-0 opacity-20">
<svg class="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none">
<path d="M0 100 C 20 0 50 0 100 100 Z" fill="white"/>
</svg>
</div>
<div class="absolute top-4 right-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button onclick="editForm('${form.id}')" class="p-2 bg-white rounded-lg shadow-md hover:bg-gray-100 text-gray-700">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</button>
<button onclick="deleteForm('${form.id}')" class="p-2 bg-white rounded-lg shadow-md hover:bg-red-50 text-red-600">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
</button>
</div>
</div>
<div class="p-6">
<h3 class="text-lg font-bold text-gray-900 dark:text-white mb-2">${form.name}</h3>
<p class="text-gray-600 dark:text-gray-400 text-sm mb-4 line-clamp-2">${form.description || 'Sem descrição'}</p>
<div class="flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
<span class="flex items-center gap-1">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
${new Date(form.createdAt).toLocaleDateString('pt-BR')}
</span>
<span class="bg-primary-100 dark:bg-primary-900 text-primary-700 dark:text-primary-300 px-2 py-1 rounded-full text-xs font-medium">
${form.fields?.length || 0} campos
</span>
</div>
<div class="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700 flex gap-2">
<a href="preview.html?form=${form.id}" target="_blank" class="flex-1 text-center py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg text-sm font-medium text-gray-700 dark:text-gray-300 transition-colors">
Visualizar
</a>
<button onclick="exportSingleForm('${form.id}')" class="px-3 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-lg text-gray-700 dark:text-gray-300">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
</button>
</div>
</div>
</div>
`).join('');
}
function createNewForm() {
document.getElementById('newFormModal').classList.remove('hidden');
}
function closeModal() {
document.getElementById('newFormModal').classList.add('hidden');
document.getElementById('formName').value = '';
document.getElementById('formDescription').value = '';
}
function confirmNewForm() {
const name = document.getElementById('formName').value;
const description = document.getElementById('formDescription').value;
if (!name) {
alert('Por favor, insira um nome para o formulário');
return;
}
const form = {
id: 'form_' + Date.now(),
name,
description,
fields: [],
createdAt: new Date().toISOString(),
theme: 'dark'
};
const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
forms.push(form);
localStorage.setItem('geoforms_list', JSON.stringify(forms));
localStorage.setItem(`geoform_${form.id}`, JSON.stringify([]));
window.location.href = `builder.html?form=${form.id}`;
}
function editForm(formId) {
window.location.href = `builder.html?form=${formId}`;
}
function deleteForm(formId) {
if (!confirm('Tem certeza que deseja excluir este formulário?')) return;
let forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
forms = forms.filter(f => f.id !== formId);
localStorage.setItem('geoforms_list', JSON.stringify(forms));
localStorage.removeItem(`geoform_${formId}`);
loadForms();
}
function exportSingleForm(formId) {
const form = JSON.parse(localStorage.getItem(`geoform_${formId}`) || '[]');
const metadata = JSON.parse(localStorage.getItem('geoforms_list') || '[]').find(f => f.id === formId);
const exportData = {
metadata,
schema: form,
generatedAt: new Date().toISOString(),
version: '1.0'
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${metadata.name.replace(/\s+/g, '_')}_schema.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Builder Functions
function initBuilder() {
const urlParams = new URLSearchParams(window.location.search);
const formId = urlParams.get('form');
if (!formId) {
window.location.href = 'index.html';
return;
}
const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
const form = forms.find(f => f.id === formId);
if (!form) {
window.location.href = 'index.html';
return;
}
currentForm = {
...form,
fields: JSON.parse(localStorage.getItem(`geoform_${formId}`) || '[]')
};
renderBuilder();
setupDragAndDrop();
}
function renderBuilder() {
const preview = document.getElementById('devicePreview');
if (!preview) return;
preview.innerHTML = currentForm.fields.map((field, index) => `
<div class="form-element ${selectedElement === index ? 'selected' : ''}"
data-index="${index}"
onclick="selectElement(${index})">
<button class="delete-btn" onclick="event.stopPropagation(); deleteElement(${index})">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
${renderFieldPreview(field)}
</div>
`).join('');
if (currentForm.fields.length === 0) {
preview.innerHTML = `
<div class="text-center py-12 text-gray-400 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-3"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
<p>Arraste componentes aqui</p>
</div>
`;
}
}
function renderFieldPreview(field) {
const baseClass = "w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white";
switch(field.type) {
case 'text':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<input type="text" class="${baseClass} text-sm" placeholder="${field.placeholder || ''}" disabled>
`;
case 'textarea':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<textarea class="${baseClass} text-sm resize-none" rows="2" placeholder="${field.placeholder || ''}" disabled></textarea>
`;
case 'select':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<select class="${baseClass} text-sm" disabled>
<option>Selecione...</option>
</select>
`;
case 'number':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<input type="number" class="${baseClass} text-sm" disabled>
`;
case 'date':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<input type="date" class="${baseClass} text-sm" disabled>
`;
case 'photo':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<div class="${baseClass} text-center py-4 text-gray-400 text-sm">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
Área de foto
</div>
`;
case 'map':
return `
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">${field.label} ${field.required ? '<span class="text-red-500">*</span>' : ''}</label>
<div class="${baseClass} h-32 flex items-center justify-center text-gray-400 text-sm bg-gray-50 dark:bg-gray-800">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-2"><polygon points="1 6 1 22 8 18 16 22 21 18 21 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></svg>
Mapa (${field.geometryType === 'point' ? 'Ponto' : field.geometryType === 'line' ? 'Linha' : 'Polígono'})
</div>
`;
default:
return `<div>Unknown field type</div>`;
}
}
function setupDragAndDrop() {
const dropZone = document.getElementById('devicePreview');
document.querySelectorAll('.draggable-item').forEach(item => {
item.addEventListener('dragstart', (e) => {
e.dataTransfer.setData('fieldType', item.dataset.type);
item.classList.add('dragging');
});
item.addEventListener('dragend', () => {
item.classList.remove('dragging');
});
});
if (dropZone) {
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const fieldType = e.dataTransfer.getData('fieldType');
addField(fieldType);
});
}
}
function addField(type) {
const field = {
id: 'field_' + Date.now(),
type: type,
label: getDefaultLabel(type),
required: false,
placeholder: ''
};
if (type === 'select') {
field.options = 'Opção 1, Opção 2, Opção 3';
} else if (type === 'map') {
field.geometryType = 'point';
}
currentForm.fields.push(field);
saveCurrentForm();
renderBuilder();
selectElement(currentForm.fields.length - 1);
}
function getDefaultLabel(type) {
const labels = {
text: 'Texto',
textarea: 'Texto Longo',
select: 'Seleção',
number: 'Número',
date: 'Data',
photo: 'Foto',
map: 'Localização'
};
return labels[type] || 'Campo';
}
function selectElement(index) {
selectedElement = index;
renderBuilder();
updatePropertiesPanel();
}
function deleteElement(index) {
currentForm.fields.splice(index, 1);
selectedElement = null;
saveCurrentForm();
renderBuilder();
updatePropertiesPanel();
}
function updatePropertiesPanel() {
const panel = document.getElementById('propertiesContent');
if (!panel) return;
if (selectedElement === null) {
panel.innerHTML = `
<div class="text-center text-gray-500 mt-8">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="mx-auto mb-3 opacity-50"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
<p>Selecione um elemento para editar</p>
</div>
`;
return;
}
const field = currentForm.fields[selectedElement];
let extraFields = '';
if (field.type === 'select') {
extraFields = `
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Opções (separadas por vírgula)</label>
<textarea class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" rows="3" onchange="updateField(${selectedElement}, 'options', this.value)">${field.options || ''}</textarea>
</div>
`;
} else if (field.type === 'map') {
extraFields = `
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo de Geometria</label>
<select class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" onchange="updateField(${selectedElement}, 'geometryType', this.value)">
<option value="point" ${field.geometryType === 'point' ? 'selected' : ''}>Ponto</option>
<option value="line" ${field.geometryType === 'line' ? 'selected' : ''}>Linha</option>
<option value="polygon" ${field.geometryType === 'polygon' ? 'selected' : ''}>Polígono</option>
</select>
</div>
`;
} else if (['text', 'textarea'].includes(field.type)) {
extraFields = `
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Placeholder</label>
<input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" value="${field.placeholder || ''}" onchange="updateField(${selectedElement}, 'placeholder', this.value)">
</div>
`;
}
panel.innerHTML = `
<div class="space-y-4 animate-slide-in">
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Rótulo</label>
<input type="text" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm" value="${field.label}" onchange="updateField(${selectedElement}, 'label', this.value)">
</div>
${extraFields}
<div class="mb-4">
<label class="flex items-center cursor-pointer">
<div class="relative">
<input type="checkbox" class="sr-only" ${field.required ? 'checked' : ''} onchange="updateField(${selectedElement}, 'required', this.checked)">
<div class="w-10 h-6 bg-gray-200 dark:bg-gray-600 rounded-full shadow-inner"></div>
<div class="dot absolute w-4 h-4 bg-white rounded-full shadow -left-1 -top-1 transition transform ${field.required ? 'translate-x-6 bg-primary-500' : 'translate-x-1'} mt-1"></div>
</div>
<div class="ml-3 text-sm font-medium text-gray-700 dark:text-gray-300">Campo obrigatório</div>
</label>
</div>
<div class="pt-4 border-t border-gray-200 dark:border-gray-700">
<button onclick="deleteElement(${selectedElement})" class="w-full py-2 bg-red-100 dark:bg-red-900 text-red-600 dark:text-red-200 rounded-lg text-sm font-medium hover:bg-red-200 dark:hover:bg-red-800 transition-colors flex items-center justify-center gap-2">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
Remover Campo
</button>
</div>
</div>
`;
}
function updateField(index, property, value) {
currentForm.fields[index][property] = value;
saveCurrentForm();
renderBuilder();
}
function saveCurrentForm() {
localStorage.setItem(`geoform_${currentForm.id}`, JSON.stringify(currentForm.fields));
// Update metadata
const forms = JSON.parse(localStorage.getItem('geoforms_list') || '[]');
const formIndex = forms.findIndex(f => f.id === currentForm.id);
if (formIndex !== -1) {
forms[formIndex].fields = currentForm.fields;
forms[formIndex].updatedAt = new Date().toISOString();
localStorage.setItem('geoforms_list', JSON.stringify(forms));
}
}
function setDevice(device) {
currentDevice = device;
const preview = document.getElementById('devicePreview');
const buttons = document.querySelectorAll('.device-btn');
buttons.forEach(btn => {
btn.classList.toggle('bg-primary-100', btn.dataset.device === device);
btn.classList.toggle('dark:bg-primary-900', btn.dataset.device === device);
btn.classList.toggle('text-primary-600', btn.dataset.device === device);
});
preview.className = `device-${device} bg-white dark:bg-gray-800 p-4 overflow-y-auto`;
}
function exportForm() {
const exportData = {
metadata: {
id: currentForm.id,
name: currentForm.name,
description: currentForm.description,
createdAt: currentForm.createdAt,
updatedAt: new Date().toISOString()
},
schema: currentForm.fields,
config: {
theme: currentForm.theme,
version: '1.0.0'
}
};
// Create downloadable package
const jsonContent = JSON.stringify(exportData, null, 2);
const htmlContent = generateMobileHTML(exportData);
// Create a zip-like structure using data URLs
const manifest = {
name: currentForm.name,
files: {
'config.json': jsonContent,
'index.html': htmlContent,
'readme.txt': `geoForms Mobile Package\nFormulário: ${currentForm.name}\nGerado em: ${new Date().toLocaleString('pt-BR')}`
}
};
// Download as JSON for now (in real app, would be a zip)
const blob = new Blob([JSON.stringify(manifest, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${currentForm.name.replace(/\s+/g, '_')}_mobile_package.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
alert('Pacote exportado! Em uma aplicação real, isso geraria um arquivo .zip com HTML standalone para iOS/Android.');
}
function generateMobileHTML(data) {
// Generates a standalone HTML file for mobile deployment
return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>${data.metadata.name}</title>
<style>
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body { font-family: -apple-system, sans-serif; margin: 0; padding: 0; background: #f3f4f6; }
.header { background: #4f46e5; color: white; padding: 1rem; position: sticky; top: 0; z-index: 100; }
.form { padding: 1rem; max-width: 600px; margin: 0 auto; }
.field { margin-bottom: 1rem; background: white; padding: 1rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
label { display: block; margin-bottom: 0.5rem; font-weight: 500; color: #374151; }
input, select, textarea { width: 100%; padding: 0.75rem; border: 1px solid #d1d5db; border-radius: 6px; font-size: 16px; }
.required { color: #ef4444; }
button { width: 100%; padding: 1rem; background: #4f46e5; color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; margin-top: 1rem; }
.map { height: 200px; background: #e5e7eb; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #6b7280; }
</style>
</head>
<body>
<div class="header">
<h1>${data.metadata.name}</h1>
<small>${data.metadata.description || ''}</small>
</div>
<form class="form" onsubmit="event.preventDefault(); alert('Enviado!');">
${data.schema.map(field => {
let input = '';
if (field.type === 'text') input = `<input type="text" ${field.required ? 'required' : ''} placeholder="${field.placeholder || ''}">`;
else if (field.type === 'textarea') input = `<textarea rows="3" ${field.required ? 'required' : ''} placeholder="${field.placeholder || ''}"></textarea>`;
else if (field.type === 'number') input = `<input type="number" ${field.required ? 'required' : ''}>`;
else if (field.type === 'date') input = `<input type="date" ${field.required ? 'required' : ''}>`;
else if (field.type === 'select') input = `<select ${field.required ? 'required' : ''}><option value="">Selecione...</option>${(field.options || '').split(',').map(o => `<option value="${o.trim()}">${o.trim()}</option>`).join('')}</select>`;
else if (field.type === 'photo') input = `<div style="border: 2px dashed #d1d5db; padding: 2rem; text-align: center; color: #6b7280;">📷 Capturar Foto</div>`;
else if (field.type === 'map') input = `<div class="map">🗺️ Mapa ${field.geometryType || 'point'}</div>`;
return `<div class="field"><label>${field.label} ${field.required ? '<span class="required">*</span>' : ''}</label>${input}</div>`;
}).join('')}
<button type="submit">Enviar Dados</button>
</form>
</body>
</html>`;
}