(function() { 'use strict'; let socket; let reconnectTimer; let reconnectDelay = 1000; function connect() { const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = protocol + '//' + location.host + '/_ws'; try { socket = new WebSocket(wsUrl); socket.onopen = function() { console.log('[webook] Live reload connected'); reconnectDelay = 1000; }; socket.onmessage = function(event) { try { const msg = JSON.parse(event.data); if (msg.type === 'reload') { console.log('[webook] File changed, reloading...'); // If a markdown file changed and we're currently viewing it, reload via API if (msg.file && /\.(md|markdown)$/i.test(msg.file)) { const currentFile = getCurrentFile(); if (currentFile) { reloadCurrentFile(); } } else { // For CSS/js/images, do a full reload location.reload(); } } } catch (e) { location.reload(); } }; socket.onclose = function() { console.log('[webook] Live reload disconnected'); scheduleReconnect(); }; socket.onerror = function() { socket.close(); }; } catch (e) { scheduleReconnect(); } } function scheduleReconnect() { clearTimeout(reconnectTimer); reconnectTimer = setTimeout(function() { reconnectDelay = Math.min(reconnectDelay * 1.5, 30000); connect(); }, reconnectDelay); } function getCurrentFile() { const hash = decodeURIComponent(location.hash.slice(1)); if (hash) return hash; return window.__WEBOOK__ ? window.__WEBOOK__.defaultFile : null; } function reloadCurrentFile() { const hash = decodeURIComponent(location.hash.slice(1)); if (!hash) return location.reload(); // Dispatch hashchange to trigger reload window.dispatchEvent(new HashChangeEvent('hashchange')); } connect(); })();