From 161cb48d3a7dc82202ebe822a214a25c6c594bc7 Mon Sep 17 00:00:00 2001 From: Rhiannon Morris Date: Tue, 4 Aug 2020 02:20:57 +0200 Subject: [PATCH] use push/popstate for filters --- script/gallery.js | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/script/gallery.js b/script/gallery.js index a5a6f14..b2e5f81 100644 --- a/script/gallery.js +++ b/script/gallery.js @@ -17,7 +17,7 @@ function fillSets() { return [checkedValues(reqBoxes), checkedValues(excBoxes)]; } -function update() { +function updateItems() { let [reqTags, excTags] = fillSets(); let anyReq = reqTags.size > 0; @@ -33,6 +33,11 @@ function update() { } } +function update() { + updateItems(); + history.pushState(null, "", makeFragment()); +} + function converseId(id) { if (id.match(/^require/)) { return id.replace('require', 'exclude'); @@ -70,13 +75,41 @@ function reset(e) { } +function makeFragment() { + let ids = allBoxes.filter(b => b.checked).map(b => b.id); + if (ids.length == 0) { + return '#all'; + } else if (allBoxes.every(b => b.checked == b.defaultChecked)) { + return '#'; + } else { + return '#' + ids.join(';'); + } +} + +function useFragment() { + let frag = document.location.hash.replace(/^#/, ''); + + if (frag == 'all') { + clearForm(); + } else if (frag) { + let set = new Set(frag.split(';')); + allBoxes.forEach(b => b.checked = set.has(b.id)); + } else { + resetForm(); + } + + updateItems(); +} + + function setup() { allBoxes.forEach(b => b.addEventListener('change', () => toggle(b))); document.getElementById('clear').addEventListener('click', clear); document.getElementById('reset').addEventListener('click', reset); - update(); + window.addEventListener('popstate', useFragment); + useFragment(); } window.addEventListener('load', setup);