-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtabs_controller.js
More file actions
77 lines (64 loc) · 2.03 KB
/
tabs_controller.js
File metadata and controls
77 lines (64 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["tab", "panel"]
connect() {
this.activeTabClasses = (this.data.get("activeTab") || "active").split(" ")
this.inactiveTabClasses = (
this.data.get("inactiveTab") || "inactive"
).split(" ")
if (this.anchor) {
const index = this.tabTargets.findIndex((tab) => tab.id === this.anchor)
if (index >= 0) {
this.index = index
this.showTab()
}
}
}
change(event) {
event.preventDefault()
// If target specifies an index, use that
if (event.currentTarget.dataset.index) {
this.index = event.currentTarget.dataset.index
// If target specifies an index, use that
} else if (event.currentTarget.dataset.id) {
this.index = this.tabTargets.findIndex(
(tab) => tab.id == event.currentTarget.dataset.id,
)
// Otherwise, use the index of the current target
} else {
this.index = this.tabTargets.indexOf(event.currentTarget)
}
window.dispatchEvent(new CustomEvent("tsc:tab-change"))
}
showTab() {
this.tabTargets.forEach((tab, index) => {
const panel = this.panelTargets[index]
if (index === this.index) {
panel.classList.remove("hidden")
tab.classList.remove(...this.inactiveTabClasses)
tab.classList.add(...this.activeTabClasses)
// Update URL with the tab ID if it has one
// This will be automatically selected on page load
if (tab.id) {
history.replaceState({}, "", "#" + tab.id)
}
} else {
panel.classList.add("hidden")
tab.classList.remove(...this.activeTabClasses)
tab.classList.add(...this.inactiveTabClasses)
}
})
}
get index() {
return parseInt(this.data.get("index") || 0)
}
set index(value) {
this.data.set("index", value >= 0 ? value : 0)
this.showTab()
}
get anchor() {
return document.URL.split("#").length > 1
? document.URL.split("#")[1]
: null
}
}