document.addEventListener('click', async (e) => { const link = e.target.closest('a'); if (!link) return; const url = link.getAttribute('href'); if (!url || url.startsWith('#') || url.startsWith('javascript:')) return; // Only intercept same-origin links if (link.origin !== window.location.origin) return; // Ignore links that open in a new tab, download, or modifier keys if (link.target === '_blank' || link.hasAttribute('download')) return; if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey) return; // Optional: add a "data-turbo='false'" attribute check to disable it on specific links if (link.getAttribute('data-turbo') === 'false') return; e.preventDefault(); document.body.style.cursor = 'wait'; try { const response = await fetch(url); if (!response.ok) throw new Error('Fetch failed'); const html = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); document.title = doc.title; document.body.innerHTML = doc.body.innerHTML; // Carry over classes on the body if they changed document.body.className = doc.body.className; document.body.style.cursor = 'default'; window.history.pushState({}, '', url); window.scrollTo(0, 0); // Dispatch a custom event so other scripts can re-initialize if necessary document.dispatchEvent(new Event('diy-turbo:load')); } catch (error) { console.error('DIY Turbo navigation error:', error); window.location.href = url; // fallback } }); window.addEventListener('popstate', async () => { document.body.style.cursor = 'wait'; try { const response = await fetch(window.location.href); if (!response.ok) throw new Error('Fetch failed'); const html = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html'); document.title = doc.title; document.body.innerHTML = doc.body.innerHTML; document.body.className = doc.body.className; document.body.style.cursor = 'default'; document.dispatchEvent(new Event('diy-turbo:load')); } catch (error) { console.error('DIY Turbo popstate error:', error); window.location.reload(); // fallback } });