/** * YAZ Platform - Offline-First HTMX Integration * Version: 1.0.0 * * Bridges HTMX form submissions with the offline sync queue. * When online: normal HTMX flow. * When offline: intercepts submission, saves to IndexedDB, shows pending UI. * On reconnect: flushes queue to /api/v1/sync/push, updates indicators. * * Depends on: pwa.js (window.PWA), htmx */ const _log = (typeof window !== "undefined" && window.YAZ_DEBUG) ? console.log.bind(console) : function(){}; 'use strict'; (function () { // Wait for PWA to initialize const pwa = window.PWA; if (!pwa) { console.warn('[Offline] PWA module not available'); return; } // ========================================================================= // SYNC STATUS INDICATOR // ========================================================================= const STATUS_ICONS = { online: '🟢', offline: '🔴', syncing: '🔄', pending: '⏳', conflict: '⚠️' }; function updateStatusBadge() { const badge = document.getElementById('sync-status'); if (!badge) return; const online = pwa.isOnline(); pwa.getSyncStatus().then(status => { if (status.pending > 0) { badge.innerHTML = `${STATUS_ICONS.pending} ${status.pending} pending`; badge.className = 'sync-badge sync-pending'; } else if (online) { badge.innerHTML = `${STATUS_ICONS.online} Synced`; badge.className = 'sync-badge sync-online'; } else { badge.innerHTML = `${STATUS_ICONS.offline} Offline`; badge.className = 'sync-badge sync-offline'; } }); } // ========================================================================= // HTMX OFFLINE INTERCEPTOR // ========================================================================= /** * Intercept HTMX mutations when offline. * Non-GET requests that fail due to network are queued. */ document.body.addEventListener('htmx:beforeRequest', function (event) { const elt = event.detail.elt; const method = (event.detail.requestConfig.verb || 'GET').toUpperCase(); // Only intercept mutations if (method === 'GET') return; // If online, let HTMX proceed normally if (pwa.isOnline()) return; // Offline: cancel the request and queue it event.preventDefault(); const path = event.detail.requestConfig.path; const params = event.detail.requestConfig.parameters; // Build payload from form parameters const payload = {}; if (params) { if (typeof params === 'string') { new URLSearchParams(params).forEach((v, k) => { payload[k] = v; }); } else { Object.assign(payload, params); } } const draftId = crypto.randomUUID(); // Queue to sync pwa.queueMutation({ type: 'offline_form', method: method, endpoint: path, data: payload }); // Save draft to IndexedDB pwa.db.save('drafts', { id: draftId, type: 'form_submission', case_id: payload.case_id || null, tenant_id: null, // Will be added by server data: payload, endpoint: path, method: method, sync_status: 'pending', updated_at: Date.now() }); // Show optimistic UI feedback const target = elt.closest('[hx-target]'); if (target) { const targetId = target.getAttribute('hx-target'); const targetEl = document.querySelector(targetId); if (targetEl) { const notice = document.createElement('div'); notice.className = 'offline-notice'; notice.innerHTML = `${STATUS_ICONS.pending} Saved offline — will sync when connected`; targetEl.prepend(notice); setTimeout(() => notice.remove(), 5000); } } updateStatusBadge(); }); // ========================================================================= // SERVER SYNC FLUSH // ========================================================================= /** * Flush queued operations to the server-side sync API. * Called when connectivity is restored. */ async function flushToServer() { if (!pwa.isOnline()) return; const queue = await pwa.db.getAll('syncQueue'); if (queue.length === 0) return; _log(`[Offline] Flushing ${queue.length} queued operations`); updateSyncingState(true); // Build batch for /api/v1/sync/push const operations = queue.map(item => ({ id: String(item.id), method: item.method || 'POST', path: item.endpoint, payload: item.data, client_ts: new Date(item.timestamp).toISOString(), })); try { const response = await fetch('/api/v1/sync/push', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ operations }) }); if (response.ok || response.status === 207) { const result = await response.json(); for (const res of result.results) { if (res.status === 'applied') { // Remove from queue const queueId = parseInt(res.client_id, 10) || null; if (queueId) { await pwa.db.delete('syncQueue', queueId); } // Update draft status try { const drafts = await pwa.db.getAll('drafts'); for (const d of drafts) { if (d.sync_status === 'pending') { d.sync_status = 'synced'; await pwa.db.save('drafts', d); } } } catch (_) { /* best effort */ } } else if (res.status === 'conflict') { // Save conflict for user resolution await pwa.db.save('conflicts', { id: crypto.randomUUID(), sync_op_id: res.id, case_id: null, local_data: res.client_data || {}, server_data: res.server_data || {}, detected_at: Date.now(), resolved: false }); } } _log('[Offline] Sync complete:', result.results.length, 'operations'); // Refresh page data if (typeof htmx !== 'undefined') { htmx.trigger(document.body, 'yaz:synced'); } } } catch (error) { console.error('[Offline] Sync flush failed:', error); } finally { updateSyncingState(false); updateStatusBadge(); } } function updateSyncingState(syncing) { const badge = document.getElementById('sync-status'); if (!badge) return; if (syncing) { badge.innerHTML = `${STATUS_ICONS.syncing} Syncing...`; badge.className = 'sync-badge sync-syncing'; } } // ========================================================================= // NETWORK CHANGE LISTENER // ========================================================================= pwa.network.onChange(async (status) => { if (status === 'online') { // Flush queue to server await flushToServer(); } updateStatusBadge(); }); // ========================================================================= // CACHE CASE DATA FOR OFFLINE READS // ========================================================================= /** * After HTMX loads case data, cache the response HTML for offline reads. */ document.body.addEventListener('htmx:afterSwap', function (event) { const path = event.detail.pathInfo?.requestPath || ''; // Cache case detail pages if (path.match(/\/apps\/traces\/[A-Z]+-\d+-\d+/)) { const html = event.detail.target.innerHTML; const caseId = path.split('/').pop(); pwa.db.save('cachedCases', { id: caseId, tenant_id: null, path: path, html: html, cached_at: Date.now() }).catch(() => {}); } }); // ========================================================================= // INIT // ========================================================================= // Initial badge update if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', updateStatusBadge); } else { updateStatusBadge(); } // Expose for manual use window.yazOffline = { flush: flushToServer, updateBadge: updateStatusBadge, STATUS_ICONS }; _log('[Offline] HTMX offline integration loaded'); })();