• function saveState() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(appState)); scheduleAutoDriveSync(); } catch (e) { console.error('Error guardando estado:', e); } } function renderTasksTable() { const thead = document.getElementById('tasks-table-header'); const tbody = document.getElementById('tasks-table-body'); const mobileList = document.getElementById('mobile-tasks-list'); const emptyState = document.getElementById('empty-state'); const visibleCols = appState.columns.filter(c => c.visible); // Renderizar Cabecera thead.innerHTML = ` Tarea / Subtareas ${visibleCols.map(col => `${col.label}`).join('')} Acciones `; const filtered = getFilteredTasks(); const filteredIds = new Set(filtered.map(t => t.id)); // Construir jerarquía: tareas padre + sus subtareas const topLevelTasks = sortTasksList( filtered.filter(t => !t.parentId || !filteredIds.has(t.parentId)) ); document.getElementById('current-view-count').textContent = filtered.length; if (topLevelTasks.length === 0) { tbody.innerHTML = ''; if (mobileList) mobileList.innerHTML = ''; emptyState.classList.remove('hidden'); return; } emptyState.classList.add('hidden'); let htmlRows = ''; let mobileCards = ''; topLevelTasks.forEach(task => { const children = sortTasksList( appState.tasks.filter(t => t.parentId === task.id && (showCompleted || !t.completed)) ); htmlRows += buildTaskRowHTML(task, false, children.length); mobileCards += buildMobileTaskCardHTML(task, false, children.length); if (children.length > 0 && task.expanded !== false) { children.forEach(sub => { htmlRows += buildTaskRowHTML(sub, true, 0); mobileCards += buildMobileTaskCardHTML(sub, true, 0); }); } }); tbody.innerHTML = htmlRows; if (mobileList) mobileList.innerHTML = mobileCards; } function buildMobileTaskCardHTML(task, isSubtask, childrenCount) { const today = getTodayISO(); const isOverdue = !task.completed && task.dueDate && task.dueDate < today; const isDueToday = !task.completed && task.dueDate === today; const folder = appState.folders.find(f => f.id === task.folderId); const histCount = Array.isArray(task.completionHistory) ? task.completionHistory.length : 0; const dateColor = isOverdue ? 'text-rose-600 dark:text-rose-400 font-semibold' : isDueToday ? 'text-emerald-600 dark:text-emerald-400 font-semibold' : 'text-slate-500 dark:text-slate-400'; return `

    ${escapeHTML(task.title)}

    ${task.priority >= 2 ? `${task.priority === 3 ? '🔥' : '🔴'}` : ''}
    ${task.notes ? `

    ${escapeHTML(task.notes)}

    ` : ''}
    ${folder ? `${escapeHTML(folder.name)}` : ''} ${task.context ? `${escapeHTML(task.context)}` : ''} ${task.dueDate ? `📅 ${formatHumanDate(task.dueDate)}${task.dueTime ? ' ' + task.dueTime : ''}` : ''} ${task.repeat && task.repeat.type !== 'none' ? ` 🔄 ${task.repeat.basis === 'completion' ? 'Realización' : 'Vencimiento'} ` : ''}
    ${!isSubtask ? ` ` : ''} ${histCount > 0 ? ` ` : ''} ${!isSubtask && childrenCount > 0 ? ` ` : ''}
    `; } function handleSearch(val) { searchQuery = val.trim(); const deskInput = document.getElementById('search-input'); const mobInput = document.getElementById('search-input-mobile'); if (deskInput && deskInput.value !== val) deskInput.value = val; if (mobInput && mobInput.value !== val) mobInput.value = val; updateClearFiltersVisibility(); renderTasksTable(); } function toggleMobileSearchBar() { const bar = document.getElementById('mobile-search-bar'); bar.classList.toggle('hidden'); if (!bar.classList.contains('hidden')) { document.getElementById('search-input-mobile').focus(); } } function clearAllFilters() { searchQuery = ''; document.getElementById('search-input').value = ''; const mobInput = document.getElementById('search-input-mobile'); if (mobInput) mobInput.value = ''; document.getElementById('filter-priority').value = ''; document.getElementById('filter-status').value = ''; document.getElementById('filter-recurrence').value = ''; updateClearFiltersVisibility(); renderTasksTable(); } // ========================================================================= // 13. SINCRONIZACIÓN CON GOOGLE DRIVE (taskflow-pro.json) Y PWA MANIFEST // ========================================================================= const DRIVE_CONFIG_KEY = 'taskflow_gdrive_config_v1'; const DRIVE_FILE_NAME = 'taskflow-pro.json'; const DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive.file'; let driveConfig = loadDriveConfig(); let driveAccessToken = null; let driveTokenClient = null; let driveSyncTimer = null; function loadDriveConfig() { try { const raw = localStorage.getItem(DRIVE_CONFIG_KEY); if (raw) return JSON.parse(raw); } catch (e) {} return { clientId: '', fileId: '', lastSync: '' }; } function saveDriveConfig() { localStorage.setItem(DRIVE_CONFIG_KEY, JSON.stringify(driveConfig)); updateDriveStatusUI(); } function openDriveSyncModal() { document.getElementById('drive-client-id').value = driveConfig.clientId || ''; updateDriveStatusUI(); const modal = document.getElementById('drive-sync-modal'); modal.classList.remove('hidden'); modal.classList.add('flex'); } function closeDriveSyncModal() { const modal = document.getElementById('drive-sync-modal'); modal.classList.add('hidden'); modal.classList.remove('flex'); } function updateDriveStatusUI() { const isConnected = Boolean(driveAccessToken); const badge = document.getElementById('drive-sync-badge'); const dot = document.getElementById('header-drive-dot'); const statusText = document.getElementById('drive-status-text'); const lastSyncText = document.getElementById('drive-last-sync-text'); const syncNowBtn = document.getElementById('btn-drive-sync-now'); const disconnectBtn = document.getElementById('btn-drive-disconnect'); if (isConnected) { badge.textContent = 'Drive OK'; badge.className = 'text-[10px] font-semibold px-1.5 py-0.5 rounded bg-emerald-100 dark:bg-emerald-500/20 text-emerald-700 dark:text-emerald-300'; dot.className = 'w-2 h-2 rounded-full bg-emerald-500'; statusText.textContent = 'Conectado a Google Drive (taskflow-pro.json)'; lastSyncText.textContent = driveConfig.lastSync ? `Última sincronización: ${driveConfig.lastSync}` : 'Sincronización automática activa.'; syncNowBtn.classList.remove('hidden'); disconnectBtn.classList.remove('hidden'); } else { badge.textContent = driveConfig.clientId ? 'Listo' : 'Local'; badge.className = 'text-[10px] font-semibold px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-800 text-slate-500'; dot.className = driveConfig.clientId ? 'w-2 h-2 rounded-full bg-amber-400' : 'w-2 h-2 rounded-full bg-slate-400'; statusText.textContent = driveConfig.clientId ? 'Client ID guardado — Pulsa Conectar para iniciar sesión' : 'Modo Local (sin vincular a Google Drive)'; lastSyncText.textContent = 'Los cambios se guardan en este navegador.'; syncNowBtn.classList.add('hidden'); disconnectBtn.classList.add('hidden'); } } function connectGoogleDrive() { const inputId = document.getElementById('drive-client-id').value.trim(); if (!inputId) { showToast('Introduce primero tu Google OAuth Client ID.', 'info'); return; } driveConfig.clientId = inputId; saveDriveConfig(); if (!window.google || !google.accounts || !google.accounts.oauth2) { showToast('La librería de Google aún está cargando. Inténtalo en 2 segundos.', 'info'); return; } driveTokenClient = google.accounts.oauth2.initTokenClient({ client_id: driveConfig.clientId, scope: DRIVE_SCOPE, callback: async (tokenResponse) => { if (tokenResponse && tokenResponse.access_token) { driveAccessToken = tokenResponse.access_token; updateDriveStatusUI(); showToast('☁️ Conectado con Google Drive. Sincronizando...', 'success'); await initialLoadOrCreateDriveFile(); } } }); driveTokenClient.requestAccessToken({ prompt: '' }); } function disconnectGoogleDrive() { driveAccessToken = null; driveConfig.fileId = ''; saveDriveConfig(); showToast('Desconectado de Google Drive.', 'info'); } async function findDriveFileId() { const query = encodeURIComponent(`name='${DRIVE_FILE_NAME}' and trashed=false`); const res = await fetch(`https://www.googleapis.com/drive/v3/files?q=${query}&fields=files(id,name,modifiedTime)`, { headers: { Authorization: `Bearer ${driveAccessToken}` } }); if (!res.ok) throw new Error('Error buscando archivo en Drive'); const data = await res.json(); return (data.files && data.files.length > 0) ? data.files[0].id : null; } async function initialLoadOrCreateDriveFile() { if (!driveAccessToken) return; try { let fileId = driveConfig.fileId || await findDriveFileId(); if (fileId) { driveConfig.fileId = fileId; const res = await fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`, { headers: { Authorization: `Bearer ${driveAccessToken}` } }); if (res.ok) { const remoteData = await res.json(); if (remoteData && Array.isArray(remoteData.tasks)) { appState = remoteData; localStorage.setItem(STORAGE_KEY, JSON.stringify(appState)); renderAll(); driveConfig.lastSync = `${getTodayISO()} ${getCurrentTimeHHMM()}`; saveDriveConfig(); showToast('📥 Datos cargados desde taskflow-pro.json en Drive.', 'success'); return; } } } // Si no existe en Drive, subir el estado actual await uploadStateToDrive(true); } catch (err) { console.error(err); showToast('No se pudo sincronizar con Drive. Revisa los orígenes autorizados en Google Cloud.', 'info'); } } async function uploadStateToDrive(notify = false) { if (!driveAccessToken) return; try { const fileContent = JSON.stringify(appState, null, 2); const metadata = { name: DRIVE_FILE_NAME, mimeType: 'application/json' }; if (!driveConfig.fileId) { driveConfig.fileId = await findDriveFileId(); } if (driveConfig.fileId) { // Actualizar archivo existente (PATCH media) const res = await fetch(`https://www.googleapis.com/upload/drive/v3/files/${driveConfig.fileId}?uploadType=media`, { method: 'PATCH', headers: { Authorization: `Bearer ${driveAccessToken}`, 'Content-Type': 'application/json' }, body: fileContent }); if (!res.ok) throw new Error('Error actualizando JSON en Drive'); } else { // Crear archivo nuevo (Multipart) const boundary = '-------taskflow_boundary_314159'; const body = `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n` + `${JSON.stringify(metadata)}\r\n` + `--${boundary}\r\nContent-Type: application/json\r\n\r\n` + `${fileContent}\r\n--${boundary}--`; const res = await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', { method: 'POST', headers: { Authorization: `Bearer ${driveAccessToken}`, 'Content-Type': `multipart/related; boundary=${boundary}` }, body }); if (!res.ok) throw new Error('Error creando JSON en Drive'); const created = await res.json(); driveConfig.fileId = created.id; } driveConfig.lastSync = `${getTodayISO()} ${getCurrentTimeHHMM()}`; saveDriveConfig(); if (notify) showToast('☁️ Archivo taskflow-pro.json guardado en Google Drive.', 'success'); } catch (err) { console.error(err); if (notify) showToast('Error al subir cambios a Drive. Tu sesión puede haber expirado.', 'info'); } } function scheduleAutoDriveSync() { if (!driveAccessToken) return; clearTimeout(driveSyncTimer); driveSyncTimer = setTimeout(() => { uploadStateToDrive(false); }, 1500); } async function syncWithGoogleDrive(notify = true) { if (!driveAccessToken) { connectGoogleDrive(); return; } await uploadStateToDrive(notify); } function exportDataToJSONFile() { const blob = new Blob([JSON.stringify(appState, null, 2)], { type: 'application/json' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = DRIVE_FILE_NAME; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showToast('⬇️ Descargado taskflow-pro.json', 'success'); } function importDataFromJSONFile(event) { const file = event.target.files && event.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = (e) => { try { const parsed = JSON.parse(e.target.result); if (parsed && Array.isArray(parsed.tasks)) { appState = parsed; saveState(); renderAll(); showToast('⬆️ Datos importados correctamente desde JSON.', 'success'); } else { showToast('El archivo JSON no tiene el formato válido de TaskFlow Pro.', 'info'); } } catch (err) { showToast('Error al leer el archivo JSON.', 'info'); } }; reader.readAsText(file); event.target.value = ''; } // Registrar Manifest PWA dinámico para instalación limpia en móvil function registerDynamicPWAManifest() { try { const svgIcon = ``; const iconUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgIcon); const manifest = { name: 'TaskFlow Pro', short_name: 'TaskFlow', start_url: '.', display: 'standalone', background_color: '#0f172a', theme_color: '#4f46e5', icons: [{ src: iconUrl, sizes: '192x192', type: 'image/svg+xml' }] }; const blob = new Blob([JSON.stringify(manifest)], { type: 'application/manifest+json' }); const link = document.createElement('link'); link.rel = 'manifest'; link.href = URL.createObjectURL(blob); document.head.appendChild(link); } catch (e) {} } // Inicialización al cargar window.addEventListener('DOMContentLoaded', () => { if (localStorage.getItem('taskflow_theme') === 'dark') { document.documentElement.classList.add('dark'); } registerDynamicPWAManifest(); updateDriveStatusUI(); renderAll(); });