| 1 |
(() => { |
| 2 |
|
| 3 |
if (typeof navigation === 'undefined') return; |
| 4 |
|
| 5 |
let api; |
| 6 |
let activeCount = 0; |
| 7 |
let activeAborts = new Set(); |
| 8 |
let historyUpdating = false; |
| 9 |
let cleanupNavigation = null; |
| 10 |
|
| 11 |
function shouldShowIndicator(elt) { |
| 12 |
if (api.attributeValue(elt, 'hx-browser-indicator') === 'true') return true; |
| 13 |
if (htmx.config.boostBrowserIndicator && elt._htmx?.boosted) return true; |
| 14 |
return false; |
| 15 |
} |
| 16 |
|
| 17 |
function listenForNavigate() { |
| 18 |
navigation.addEventListener('navigate', (event) => { |
| 19 |
let hideBrowserIndicator; |
| 20 |
event.intercept({ |
| 21 |
handler: () => new Promise(r => { hideBrowserIndicator = r }), |
| 22 |
scroll: 'manual', |
| 23 |
focusReset: 'manual' |
| 24 |
}); |
| 25 |
let abortHandler = () => { |
| 26 |
if (historyUpdating) { |
| 27 |
|
| 28 |
listenForNavigate(); |
| 29 |
} else { |
| 30 |
|
| 31 |
activeAborts.forEach( abort => abort() ); |
| 32 |
activeAborts.clear(); |
| 33 |
activeCount = 0; |
| 34 |
cleanupNavigation = null; |
| 35 |
} |
| 36 |
}; |
| 37 |
event.signal.addEventListener('abort', abortHandler); |
| 38 |
cleanupNavigation = () => { |
| 39 |
event.signal.removeEventListener('abort', abortHandler); |
| 40 |
hideBrowserIndicator(); |
| 41 |
}; |
| 42 |
}, {once: true}); |
| 43 |
} |
| 44 |
|
| 45 |
function startIndicator() { |
| 46 |
listenForNavigate(); |
| 47 |
navigation.navigate(location.href, { history: 'replace' }); |
| 48 |
} |
| 49 |
|
| 50 |
function stopIndicator() { |
| 51 |
if (cleanupNavigation) { |
| 52 |
cleanupNavigation(); |
| 53 |
cleanupNavigation = null; |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
htmx.registerExtension('browser-indicator', { |
| 58 |
init: (internalAPI) => { |
| 59 |
api = internalAPI; |
| 60 |
}, |
| 61 |
|
| 62 |
htmx_before_history_update: () => { |
| 63 |
historyUpdating = true; |
| 64 |
}, |
| 65 |
|
| 66 |
htmx_after_history_update: () => { |
| 67 |
historyUpdating = false; |
| 68 |
}, |
| 69 |
|
| 70 |
htmx_before_request: (elt, detail) => { |
| 71 |
if (!shouldShowIndicator(elt)) return; |
| 72 |
detail.ctx._browserIndicator = true; |
| 73 |
if (detail.ctx.request?.abort) activeAborts.add(detail.ctx.request.abort); |
| 74 |
activeCount++; |
| 75 |
if (activeCount === 1) startIndicator(); |
| 76 |
}, |
| 77 |
|
| 78 |
htmx_finally_request: (elt, detail) => { |
| 79 |
if (!detail.ctx._browserIndicator) return; |
| 80 |
if (detail.ctx.request?.abort) activeAborts.delete(detail.ctx.request.abort); |
| 81 |
if (activeCount === 0) return; |
| 82 |
activeCount--; |
| 83 |
if (activeCount === 0) stopIndicator(); |
| 84 |
} |
| 85 |
}); |
| 86 |
})(); |