forked from denoland/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabs.client.ts
55 lines (48 loc) · 1.61 KB
/
tabs.client.ts
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
class GroupSelectEvent extends Event {
groupId: string;
tabId: string;
constructor(groupId: string, tabId: string) {
super("deno-tab-select");
this.groupId = groupId;
this.tabId = tabId;
}
}
for (const tabGroup of document.querySelectorAll<HTMLElement>(".deno-tabs")) {
const buttons = tabGroup.querySelectorAll<HTMLElement>(
".deno-tabs-buttons button",
)!;
const tabs = tabGroup.querySelectorAll<HTMLElement>(
".deno-tabs-content div",
)!;
const groupId = tabGroup.dataset.id!;
document.addEventListener("deno-tab-select", (event: Event) => {
if (!(event instanceof GroupSelectEvent)) return;
if (event.groupId !== groupId) return;
for (const button of buttons) {
const active = button.dataset.tab === event.tabId;
button.dataset.active = String(active);
}
for (const tab of tabs) {
const active = tab.dataset.tab === event.tabId;
tab.dataset.active = String(active);
}
});
for (const button of buttons) {
button.addEventListener("click", () => {
const tabId = button.dataset.tab!;
localStorage.setItem(`deno-tab-${groupId}`, tabId);
document.dispatchEvent(new GroupSelectEvent(groupId, tabId));
});
}
const storedTabId = localStorage.getItem(`deno-tab-${groupId}`);
if (storedTabId) {
document.dispatchEvent(new GroupSelectEvent(groupId, storedTabId));
}
const anyTabActive = Array.from(tabs).some((tab) =>
tab.dataset.active === "true"
);
if (!anyTabActive && tabs.length > 0) {
const firstTabId = tabs[0].dataset.tab!;
document.dispatchEvent(new GroupSelectEvent(groupId, firstTabId));
}
}