| 1 | import { Controller } from "@hotwired/stimulus" |
| 2 | |
| 3 | export default class extends Controller { |
| 4 | static targets = ["tab", "panel"] |
| 5 | static values = { active: String } |
| 6 | |
| 7 | connect() { |
| 8 | const initial = this.activeValue || this.tabTargets[0]?.dataset.tabsKey |
| 9 | if (initial) this.#activate(initial, false) |
| 10 | } |
| 11 | |
| 12 | switch(event) { |
| 13 | event.preventDefault() |
| 14 | const key = event.currentTarget.dataset.tabsKey |
| 15 | if (key) this.#activate(key, true) |
| 16 | } |
| 17 | |
| 18 | #activate(key, push) { |
| 19 | this.activeValue = key |
| 20 | |
| 21 | this.tabTargets.forEach(tab => { |
| 22 | const active = tab.dataset.tabsKey === key |
| 23 | tab.classList.toggle("active", active) |
| 24 | }) |
| 25 | |
| 26 | this.panelTargets.forEach(panel => { |
| 27 | const active = panel.dataset.tabsKey === key |
| 28 | panel.classList.toggle("hidden", !active) |
| 29 | }) |
| 30 | |
| 31 | if (push && history.pushState) { |
| 32 | const url = new URL(window.location) |
| 33 | url.searchParams.set("tab", key) |
| 34 | history.replaceState({}, "", url) |
| 35 | } |
| 36 | } |
| 37 | } |