Remember localStorage state after filtering

This commit is contained in:
Andy Smith
2025-09-16 14:46:21 -05:00
parent 3cad86411f
commit ec0433d721
4 changed files with 28 additions and 53 deletions
@@ -1,60 +1,47 @@
import { Controller } from "@hotwired/stimulus"
// TODO: roll up this controller to one level; remove from sections
// This will involve using events to select the sections when they're clicked
export default class extends Controller {
static values = { key: String }
static targets = [ "input" ]
static targets = [ "input", "section" ]
connect() {
this.#restoreToggle()
sectionTargetConnected() {
this.#restoreToggles()
}
toggle() {
console.log(this.element)
if (this.element.hasAttribute("data-ignore")) {
// console.log("Don't save it!")
} else {
// console.log("Save it!")
if (this.element.open) {
localStorage.removeItem(this.#localStorageKey)
// When toggling, save the state to localStorage as long as it's not
// temporarily expanded during a filter
toggle(event) {
const section = event.target
if (!section.hasAttribute("data-temp-expand")) {
if (section.open) {
localStorage.removeItem(this.#localStorageKey(section))
} else {
localStorage.setItem(this.#localStorageKey, this.keyValue)
localStorage.setItem(this.#localStorageKey(section), true)
}
}
}
// OK, here's the behavior we want:
// Open the dialog, and the sections are in various states of collapsed/open.
// When you filter, we open them all.
// When the filter is empty, we need to go back to the saved state.
showAll() {
console.log(this.element)
// When filtering, we open everything and don't save to local storage.
// When the filter is cleared, we restore toggles
showWhileFiltering() {
if (this.inputTarget.value) {
for (const section of this.#sections) {
section.setAttribute("data-ignore", true)
section.setAttribute("open", true)
for (const section of this.sectionTargets) {
section.setAttribute("data-temp-expand", true)
section.open = true
}
} else {
// UGH! This works in the context of the controller on the section, not from the birds-eye view of the details el.
this.#restoreToggle()
this.#restoreToggles()
}
}
#restoreToggle() {
// console.log("RESTORE TOGGLE")
const isCollapsed = localStorage.getItem(this.#localStorageKey) != null
if (isCollapsed) this.element.open = false
#restoreToggles() {
for (const section of this.sectionTargets) {
const isCollapsed = localStorage.getItem(this.#localStorageKey(section)) != null
if (isCollapsed) section.open = false
section.removeAttribute("data-temp-expand")
}
}
get #localStorageKey() {
return this.keyValue
}
get #sections() {
return this.element.querySelectorAll(":scope details:not([open])")
#localStorageKey(section) {
return section.getAttribute("data-nav-section-expander-key-value")
}
}