-
Notifications
You must be signed in to change notification settings - Fork 3
/
Tabs.js
101 lines (80 loc) · 2.51 KB
/
Tabs.js
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
import _ from 'lodash'
import { el, createEl } from '../helpers/dom_utils'
import { createTab } from '../helpers/tabs'
const WRAPPER_ELEMENT = '.wrapper'
const TABS_CONTAINER = '#tabs'
const ACTIVE_TAB_CLASSNAME = 'active'
export const PRIORITY_TAB = createTab('procfile', true)
export const DEFAULT_TABS = [
createTab('npm'),
PRIORITY_TAB,
createTab('grunt'),
createTab('gulp'),
]
class Tabs {
wrapper = null
onChangeListeners = []
tabs = [...DEFAULT_TABS]
activeTab = _.find(this.tabs, { active: true })
constructor(wrapperElementQuery, tabsContainerQuery) {
this.tabsContainer = el(tabsContainerQuery)
this.wrapper = el(wrapperElementQuery)
}
createTabs = tabs => {
this.tabsContainer.innerHTML = ''
this.tabs = tabs
this.tabs.forEach(tab => {
createEl('button', {
className: 'tab' + (tab.active ? ` ${ACTIVE_TAB_CLASSNAME}` : ''),
id: tab.name,
innerText: tab.name,
onclick: () => this.setActive(tab.name),
parent: this.tabsContainer,
})
})
}
getAll = () => this.tabs
getTabBy = partialTabData => _.find(this.tabs, partialTabData)
getNotActiveTabs = () => this.getTabBy({ active: false })
getTab = name => this.getTabBy({ name })
getActive = () => this.activeTab
setActive = name => {
const prevTab = this.activeTab
// if (prevTab.name !== name) {
if (this.getTab(prevTab.name)) {
prevTab.active = false
el(`#${prevTab.name}`).classList.remove(ACTIVE_TAB_CLASSNAME)
}
this.activeTab = this.getTab(name)
this.activeTab.active = true
el(`#${this.activeTab.name}`).classList.add(ACTIVE_TAB_CLASSNAME)
if (this.onChangeListeners.length) {
this.onChangeListeners.forEach(listener =>
listener(this.activeTab.name, prevTab.name)
)
}
this.wrapper.className = `wrapper active-tab-${this.activeTab.name}`
return this.activeTab
}
setNextAsActive() {
const index = this.tabs.findIndex(tab => tab.name === this.activeTab.name)
if (_.isUndefined(this.tabs[index + 1])) {
this.setActive(this.tabs[0].name)
} else {
this.setActive(this.tabs[index + 1].name)
}
}
listenChanges = callback => {
this.onChangeListeners.push(callback)
}
removeTab = tab => {
const removingTabIndex = this.tabs.findIndex(
({ name }) => tab.name === name
)
if (removingTabIndex !== -1) {
this.tabs.splice(removingTabIndex, 1)
el(`#${tab.name}`).remove()
}
}
}
export default new Tabs(WRAPPER_ELEMENT, TABS_CONTAINER)