Jake Vanderwerf
2026-05-12 16cb63b05910055c31dca821c86f2eb815da99e3
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
 * Handles the tabs functionality, given the html requirements are met
 */
class TabsContainer{
    constructor() {
        this.a11y = window.jvbA11y;
        this.error = window.jvbError;
 
        this.subscribers = new Set();
        this.tabs = new Map();
 
        this.hasHash = false;
        this.init();
    }
    init() {
        this.initElements();
        this.initListeners();
    }
 
    initElements() {
        this.selectors = {
            nav: '.tabs',
            tab: '[data-tab]',
            active: 'button.tab.active',
            section: '.tab-content',
            button: 'button.tab',
            select: 'select.tab-list',
        };
    }
    initListeners() {
        this.clickHandler = this.handleClick.bind(this);
        this.changeHandler = this.handleChange.bind(this);
    }
        handleClick(e) {
            let config = this.getConfig(e.target);
            if (!config) return;
 
            const tab = e.target.closest(this.selectors.tab);
            if (tab) {
                this.switchTab(tab.dataset.tab, config);
            }
        }
 
        handleChange(e) {
            let config = this.getConfig(e.target);
            if (!config) return;
            if (!config) return;
            this.switchTab(e.target.value, config);
        }
 
    /**
     *
     * @param {HTMLElement} container
     * @param {object} options
     */
    registerTab(container, options = {}) {
        if (!container) return false;
 
        let ui = window.uiFromSelectors(this.selectors, container);
        if (!ui.nav || !ui.section) {
            console.error('No tab navigation or section found');
            return false;
        }
        let tabsId = window.generateID('tab');
 
        container.dataset.tabsId = tabsId;
        ui.buttons = Array.from(container.querySelectorAll(this.selectors.button));
        ui.sections = Array.from(container.querySelectorAll(this.selectors.section));
        ui.sections.forEach(section => {
            if (section.querySelector('.tabs')) {
                options.hasChildren = true;
                this.registerTab(section, {parent: tabsId});
            }
        });
 
        if (ui.select) {
            ui.options = Array.from(ui.select.querySelectorAll('option'));
        }
 
        let config = {
            id: tabsId,
            ui: ui,
            updateURL: options.updateURL ?? true
        };
 
        //Add listeners
        ui.nav.addEventListener('click', this.clickHandler);
        ui.select?.addEventListener('change', this.changeHandler);
        this.tabs.set(tabsId, config);
        this.determineActiveTab(config);
 
        return config;
    }
 
    determineActiveTab(config) {
        if (this.getInitialTabFromHash()) {
            let updated = this.tabs.get(config.id);
            if (updated.activeTab && config.activeTab && updated.activeTab === config.activeTab) return;
        }
        let tab = config.ui.buttons[0].dataset.tab??false;
        if (tab) {
            this.switchTab(tab, config);
        }
    }
    getInitialTabFromHash() {
        if (this.hasHash || !window.location.search) return false;
        const params = new URLSearchParams(window.location.search);
        const hash = params.get('tab');
        if (!hash) return false;
 
        const parts = hash.split('|');
 
        parts.forEach(part => {
            // Find the config that has a button matching this part
            const conf = Array.from(this.tabs.values()).find(tab =>
                tab.ui.buttons.some(btn => btn.dataset.tab === part)
            );
 
            if (conf) {
                this.switchTab(part, conf);
            }
        });
 
        this.hasHash = true;
        return true;
    }
 
    /**
     *
     * @param {HTMLElement} container
     */
    removeTab(container) {
        if (!container || !container.dataset.tabsId) return;
        let config = this.tabs.get(container.dataset.tabsId);
        if (!config) return;
        config.ui.nav.removeEventListener('click', this.clickHandler);
        config.ui.select?.removeEventListener('change', this.changeHandler);
        this.tabs.delete(container.dataset.tabsId);
    }
 
    /**
     *
     * @param {string} tab
     * @param {string|Object} config Either the key of the tabs instance, or a tab config object
     */
    switchTab(tab, config) {
        config = (typeof config === 'string') ? this.tabs.get(config) : config;
        if (!config) return;
        let activeTab = config.ui.sections.filter(section => section.classList.contains('active'));
 
        if (Object.hasOwn(config, 'preCheck') && !config.preCheck(activeTab[0], config)) return;
        if (document.activeElement && this.isInTabs(document.activeElement, config)) document.activeElement.blur();
 
        config.ui.buttons.forEach((btn, index) => {
            btn.classList.remove('active', 'previous', 'next');
            let isActive = btn.dataset.tab === tab;
            btn.setAttribute('aria-selected', isActive);
            if (isActive) {
                btn.classList.add('active');
                let prv = Math.max(index - 1, 0);
                let next = Math.min(index+1, config.ui.buttons.length -1);
                if (prv !== index) {
                    config.ui.buttons[prv]?.classList.add('previous');
                }
                if (next !== index) {
                    config.ui.buttons[next]?.classList.add('next');
                }
            }
        });
 
        config.ui.sections.forEach((section, index) => {
            let isActive = section.dataset.tab === tab;
            section.classList.toggle('active', isActive);
            section.setAttribute('aria-hidden', !isActive);
            section.hidden = !isActive;
        });
 
        this.notify('tab-switched', {
            previous: config.activeTab,
            current: tab,
            config: config
        });
        config.activeTab = tab;
 
        this.tabs.set(config.id, config);
        if (config?.hasChildren) this.updateChildTabs(config.id);
        if (config?.updateURL) this.updateURL(config);
        if (config.ui.select) this.maybeUpdateSelect(tab, config);
 
        this.a11y.announce(`Switched to ${tab} tab`);
    }
    updateChildTabs(id) {
        Array.from(this.tabs.values()).filter(conf => conf.parent === id).forEach(inst => {
            let firstBtn = inst.ui.buttons[0].dataset.tab??false;
            if (firstBtn) {
                this.switchTab(firstBtn, inst);
            }
        });
    }
 
    updateURL(config) {
        if (!config.updateURL) return;
        let hash = this.checkAncestorsHash(config);
        if (hash) {
            window.history.pushState({tab:config.activeTab},'',`?tab=${hash}`);
        }
    }
    checkAncestorsHash(conf) {
        const parts = [];
        let current = conf;
 
        while (current) {
            parts.unshift(current.activeTab);
            current = current.parent ? this.tabs.get(current.parent) : null;
        }
 
        return parts.join('|');
    }
    maybeUpdateSelect(tab, config) {
        if (!config.ui.select || !Object.hasOwn(config, 'options')) return;
        config.options.forEach(option => {
            if (option.value === tab) {
                config.ui.select.value = tab;
                return;
            }
        });
 
    }
 
 
    /**
     * Event system
     */
    subscribe(callback) {
        this.subscribers.add(callback);
        return () => this.subscribers.delete(callback);
    }
 
    notify(event, data) {
        this.subscribers.forEach(cb => cb(event, data));
    }
 
    /**************************************************************
     UTILITY
    **************************************************************/
    /**
     *
     * @param {HTMLElement} target
     * @returns {object|boolean}
     */
    getConfig(target) {
        const instance = target.closest('[data-tabs-id]');
        if (!instance) return false;
        const config = this.tabs.get(instance.dataset.tabsId);
        if (!config) return false;
        return config;
    }
    isInTabs(target, config) {
        return config.ui.sections.some(section => section.contains(target));
    }
    /**************************************************************
     CLEANUP
    **************************************************************/
    destroy() {
        this.subscribers.clear();
 
        Array.from(this.tabs.values()).forEach(tab => {
            tab.ui.nav.removeEventListener('click', this.clickHandler);
            tab.ui.select?.removeEventListener('change', this.changeHandler);
        });
    }
}
 
document.addEventListener('DOMContentLoaded', function() {
    window.jvbTabs = new TabsContainer();
});