From eb9ea0cbcab418628966b003f74e7b4f2e63fb67 Mon Sep 17 00:00:00 2001 From: carson Date: Tue, 5 May 2020 02:59:48 -0700 Subject: [PATCH] load content from server on history cache miss --- TODO.md | 11 ++++++----- src/htmx.js | 27 ++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/TODO.md b/TODO.md index 24b45771..38aa6d37 100644 --- a/TODO.md +++ b/TODO.md @@ -12,10 +12,12 @@ ## TODOS -* history support - * Implement LRU - * Issue GET to restore content if there isn't a copy locally -* polling cancellation API +* settle formalization + * focus recapture +* polling cancellation API 205 code +* meta config tag +* simple logging API + * Testing * polling * merge @@ -23,7 +25,6 @@ * history * hx-boost * transition model for content swaps -* distribute on https://unpkg.com/ * build website with 11ty * landing page * docs page diff --git a/src/htmx.js b/src/htmx.js index d8cecea9..39d9b791 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -584,8 +584,8 @@ var HTMx = HTMx || (function () { // History Support //==================================================================== function getHistoryElement() { - var historyElt = getDocument().getElementsByClassName('hx-history-element'); - return historyElt.length > 0 ? historyElt[0] : getDocument().body; + var historyElt = getDocument().querySelector('.hx-history-element'); + return historyElt || getDocument().body; } function purgeOldestPaths(paths, historyTimestamps) { @@ -628,13 +628,30 @@ var HTMx = HTMx || (function () { } } + function loadHistoryFromServer(pathAndSearch) { + triggerEvent(getDocument().body, "historyCacheMiss.hx", {path: pathAndSearch}); + var request = new XMLHttpRequest(); + request.open('GET', pathAndSearch, true); + request.onload = function () { + triggerEvent(getDocument().body, "historyCacheMissLoad.hx", {path: pathAndSearch}); + if (this.status >= 200 && this.status < 400) { + var fragment = makeFragment(this.response); + fragment = fragment.querySelector('.hx-history-element') || fragment; + swapInnerHTML(getHistoryElement(), fragment); + } + }; + } + function restoreHistory() { var pathAndSearch = location.pathname+location.search; triggerEvent(getDocument().body, "historyUpdate.hx", {path:pathAndSearch}); - bumpHistoryAccessDate(pathAndSearch); var content = localStorage.getItem('hx-history-content-' + pathAndSearch); - var elt = getHistoryElement(); - swapInnerHTML(elt, makeFragment(content)); + if (content) { + bumpHistoryAccessDate(pathAndSearch); + swapInnerHTML(getHistoryElement(), makeFragment(content)); + } else { + loadHistoryFromServer(pathAndSearch); + } } function shouldPush(elt) {