| 1 |
(() => { |
| 2 |
let api; |
| 3 |
let _currentId = null; |
| 4 |
|
| 5 |
const INDEX_KEY = 'htmx-history-index'; |
| 6 |
|
| 7 |
function cfg() { |
| 8 |
return htmx.config.historyCache; |
| 9 |
} |
| 10 |
|
| 11 |
function prefixSelector(s) { |
| 12 |
let result = [s]; |
| 13 |
if (htmx.config.prefix) result.push(s.replaceAll('hx-', htmx.config.prefix)); |
| 14 |
return result.join(','); |
| 15 |
} |
| 16 |
|
| 17 |
function canUseStorage() { |
| 18 |
try { |
| 19 |
sessionStorage.setItem('__htmx_test__', '1'); |
| 20 |
sessionStorage.removeItem('__htmx_test__'); |
| 21 |
return true; |
| 22 |
} catch (_) { return false; } |
| 23 |
} |
| 24 |
|
| 25 |
function genId() { |
| 26 |
return crypto.randomUUID?.() ?? Math.random().toString(36).slice(2); |
| 27 |
} |
| 28 |
|
| 29 |
function getHistoryTarget() { |
| 30 |
return htmx.find(prefixSelector('[hx-history-elt]')) || document.body; |
| 31 |
} |
| 32 |
|
| 33 |
const ATTR_VALUE = 'data-htmx-history-value'; |
| 34 |
const ATTR_CHECKED = 'data-htmx-history-checked'; |
| 35 |
const ATTR_SCROLL = 'data-htmx-history-scroll'; |
| 36 |
|
| 37 |
function annotateState(root) { |
| 38 |
root.querySelectorAll('input, textarea, select').forEach(el => { |
| 39 |
let type = el.type?.toLowerCase(); |
| 40 |
if (type === 'file' || type === 'password') return; |
| 41 |
if (type === 'checkbox' || type === 'radio') { |
| 42 |
if (el.checked) el.setAttribute(ATTR_CHECKED, '1'); |
| 43 |
} else if (el.tagName === 'SELECT' && el.multiple) { |
| 44 |
let selected = Array.from(el.options).filter(o => o.selected).map(o => o.value); |
| 45 |
if (selected.length) el.setAttribute(ATTR_VALUE, JSON.stringify(selected)); |
| 46 |
} else if (el.value) { |
| 47 |
el.setAttribute(ATTR_VALUE, el.value); |
| 48 |
} |
| 49 |
}); |
| 50 |
root.querySelectorAll('*').forEach(el => { |
| 51 |
if (el.scrollTop > 0 || el.scrollLeft > 0) |
| 52 |
el.setAttribute(ATTR_SCROLL, `${el.scrollTop},${el.scrollLeft}`); |
| 53 |
}); |
| 54 |
} |
| 55 |
|
| 56 |
function restoreAnnotations(root) { |
| 57 |
root.querySelectorAll(`[${ATTR_CHECKED}]`).forEach(el => { |
| 58 |
el.checked = true; |
| 59 |
el.removeAttribute(ATTR_CHECKED); |
| 60 |
}); |
| 61 |
root.querySelectorAll(`[${ATTR_VALUE}]`).forEach(el => { |
| 62 |
let raw = el.getAttribute(ATTR_VALUE); |
| 63 |
if (el.tagName === 'SELECT' && el.multiple) { |
| 64 |
let values = JSON.parse(raw); |
| 65 |
Array.from(el.options).forEach(o => { o.selected = values.includes(o.value); }); |
| 66 |
} else { |
| 67 |
el.value = raw; |
| 68 |
} |
| 69 |
el.removeAttribute(ATTR_VALUE); |
| 70 |
}); |
| 71 |
root.querySelectorAll(`[${ATTR_SCROLL}]`).forEach(el => { |
| 72 |
let [top, left] = el.getAttribute(ATTR_SCROLL).split(',').map(Number); |
| 73 |
el.scrollTop = top; |
| 74 |
el.scrollLeft = left; |
| 75 |
el.removeAttribute(ATTR_SCROLL); |
| 76 |
}); |
| 77 |
} |
| 78 |
|
| 79 |
function cleanContent(elt) { |
| 80 |
let clone = elt.cloneNode(true); |
| 81 |
clone.querySelectorAll('.htmx-request').forEach(el => el.classList.remove('htmx-request')); |
| 82 |
clone.querySelectorAll('[disabled][data-disabled-by-htmx]').forEach(el => { |
| 83 |
el.removeAttribute('disabled'); |
| 84 |
el.removeAttribute('data-disabled-by-htmx'); |
| 85 |
}); |
| 86 |
return clone.outerHTML; |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
function stampCurrentEntry() { |
| 92 |
let state = history.state || { htmx: true }; |
| 93 |
let id = state.htmxId; |
| 94 |
if (!id) { |
| 95 |
id = genId(); |
| 96 |
history.replaceState({ ...state, htmxId: id }, '', location.href); |
| 97 |
} |
| 98 |
_currentId = id; |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
function readIndex() { |
| 104 |
try { return JSON.parse(sessionStorage.getItem(INDEX_KEY)) || []; } catch { return []; } |
| 105 |
} |
| 106 |
|
| 107 |
function writeIndex(index) { |
| 108 |
sessionStorage.setItem(INDEX_KEY, JSON.stringify(index)); |
| 109 |
} |
| 110 |
|
| 111 |
function saveToStorage(htmxId, entry) { |
| 112 |
if (!canUseStorage() || cfg().size <= 0) return false; |
| 113 |
let index = readIndex().filter(id => id !== htmxId); |
| 114 |
while (index.length >= cfg().size) { |
| 115 |
sessionStorage.removeItem('htmx-history-' + index.shift()); |
| 116 |
} |
| 117 |
let data = JSON.stringify(entry); |
| 118 |
while (true) { |
| 119 |
try { |
| 120 |
sessionStorage.setItem('htmx-history-' + htmxId, data); |
| 121 |
index.push(htmxId); |
| 122 |
writeIndex(index); |
| 123 |
return true; |
| 124 |
} catch (e) { |
| 125 |
if (index.length === 0) return false; |
| 126 |
sessionStorage.removeItem('htmx-history-' + index.shift()); |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
function getFromStorage(htmxId) { |
| 132 |
try { return JSON.parse(sessionStorage.getItem('htmx-history-' + htmxId)); } catch { return null; } |
| 133 |
} |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
function saveCurrentPage(targetId) { |
| 139 |
targetId = targetId || _currentId; |
| 140 |
if (!targetId) return; |
| 141 |
if (htmx.find(prefixSelector('[hx-history="false"]'))) return; |
| 142 |
|
| 143 |
let target = getHistoryTarget(); |
| 144 |
annotateState(target); |
| 145 |
let head = document.head.outerHTML; |
| 146 |
let scroll = window.scrollY; |
| 147 |
let title = document.title; |
| 148 |
|
| 149 |
let detail = { target, head }; |
| 150 |
if (api.triggerHtmxEvent(document, 'htmx:history:cache:before:save', detail) === false) return; |
| 151 |
let content = cleanContent(target); |
| 152 |
head = detail.head; |
| 153 |
|
| 154 |
saveToStorage(targetId, { content, head, scroll, title }); |
| 155 |
api.triggerHtmxEvent(document, 'htmx:history:cache:after:save', { content, head, scroll, title }); |
| 156 |
} |
| 157 |
|
| 158 |
function getCachedContent() { |
| 159 |
let id = history.state?.htmxId; |
| 160 |
if (!id) return null; |
| 161 |
return canUseStorage() ? getFromStorage(id) : null; |
| 162 |
} |
| 163 |
|
| 164 |
async function restoreFromCache(item) { |
| 165 |
let detail = { head: item.head, ready: null }; |
| 166 |
api.triggerHtmxEvent(document, 'htmx:history:cache:before:restore', detail); |
| 167 |
if (detail.ready) await detail.ready; |
| 168 |
|
| 169 |
let ctx = { |
| 170 |
sourceElement: document.body, |
| 171 |
target: getHistoryTarget(), |
| 172 |
swap: cfg().swapStyle, |
| 173 |
text: item.content, |
| 174 |
transition: false, |
| 175 |
_deferredHeadScripts: detail._deferredHeadScripts |
| 176 |
}; |
| 177 |
await htmx.swap(ctx); |
| 178 |
|
| 179 |
document.title = item.title || document.title; |
| 180 |
requestAnimationFrame(() => { |
| 181 |
window.scrollTo(0, item.scroll || 0); |
| 182 |
restoreAnnotations(getHistoryTarget()); |
| 183 |
api.triggerHtmxEvent(document, 'htmx:history:cache:after:restore', { item }); |
| 184 |
}); |
| 185 |
} |
| 186 |
|
| 187 |
htmx.registerExtension('history-cache', { |
| 188 |
init: (internalAPI) => { |
| 189 |
api = internalAPI; |
| 190 |
htmx.config.historyCache ??= {}; |
| 191 |
htmx.config.historyCache.size ??= 10; |
| 192 |
htmx.config.historyCache.refreshOnMiss ??= false; |
| 193 |
htmx.config.historyCache.disable ??= false; |
| 194 |
htmx.config.historyCache.swapStyle ??= 'outerSync'; |
| 195 |
stampCurrentEntry(); |
| 196 |
}, |
| 197 |
|
| 198 |
|
| 199 |
htmx_before_history_update: (elt, detail) => { |
| 200 |
if (cfg().disable) return; |
| 201 |
if (!_currentId) stampCurrentEntry(); |
| 202 |
saveCurrentPage(); |
| 203 |
}, |
| 204 |
|
| 205 |
|
| 206 |
htmx_after_history_update: () => { |
| 207 |
if (cfg().disable) return; |
| 208 |
stampCurrentEntry(); |
| 209 |
}, |
| 210 |
|
| 211 |
htmx_before_history_restore: (elt, detail) => { |
| 212 |
if (cfg().disable) return; |
| 213 |
|
| 214 |
let outgoingId = _currentId; |
| 215 |
let destinationId = history.state?.htmxId; |
| 216 |
|
| 217 |
if (outgoingId && outgoingId !== destinationId) { |
| 218 |
saveCurrentPage(outgoingId); |
| 219 |
} |
| 220 |
|
| 221 |
if (!destinationId) { |
| 222 |
stampCurrentEntry(); |
| 223 |
} else { |
| 224 |
_currentId = destinationId; |
| 225 |
} |
| 226 |
|
| 227 |
let item = getCachedContent(); |
| 228 |
if (!item) { |
| 229 |
let missDetail = { path: detail.path, refreshOnMiss: cfg().refreshOnMiss }; |
| 230 |
api.triggerHtmxEvent(document, 'htmx:history:cache:miss', missDetail); |
| 231 |
if (missDetail.refreshOnMiss) { location.reload(); return false; } |
| 232 |
return; |
| 233 |
} |
| 234 |
|
| 235 |
let hitDetail = { path: detail.path, item }; |
| 236 |
if (api.triggerHtmxEvent(document, 'htmx:history:cache:hit', hitDetail) === false) return; |
| 237 |
|
| 238 |
detail.cancelled = true; |
| 239 |
restoreFromCache(hitDetail.item); |
| 240 |
return false; |
| 241 |
} |
| 242 |
}); |
| 243 |
})(); |