import { Controller } from '@hotwired/stimulus' export default class extends Controller { static classes = ['closed'] static targets = ['toggle', 'icon'] static values = { open: { type: Boolean, default: true, }, storageKey: { type: String, default: '' } } initialize() { this.target = this.hasToggleTarget ? this.toggleTarget : this.element // Restore state from storage if storageKey is provided if (this.hasStorageKey()) { this.restoreState() } } toggle() { this.openValue = !this.openValue } close() { this.openValue = false } open() { this.openValue = true } openValueChanged(open) { this.target.classList.toggle(this.closedClass, false === open) if (this.hasIconTarget) { this.iconTarget.classList.toggle('rotate-90', true === open) } // Save state to storage if storageKey is provided if (this.hasStorageKey()) { this.saveState() } } hasStorageKey() { return this.storageKeyValue && this.storageKeyValue.trim() !== '' } saveState() { sessionStorage.setItem(`toggle_${this.storageKeyValue}`, this.openValue.toString()) } restoreState() { const savedState = sessionStorage.getItem(`toggle_${this.storageKeyValue}`) if (savedState !== null) { this.openValue = savedState === 'true' } } }