forked from primer/view_components
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsub_header_element.ts
More file actions
79 lines (69 loc) · 2.21 KB
/
Copy pathsub_header_element.ts
File metadata and controls
79 lines (69 loc) · 2.21 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
78
79
import {controller, target, targets} from '@github/catalyst'
@controller('sub-header')
class SubHeaderElement extends HTMLElement {
@target filterInput: HTMLInputElement
@targets shownItemsOnExpandedFilter: HTMLElement[]
@targets filterExpandButton: HTMLElement[]
connectedCallback() {
this.setupFilterInputClearButton()
}
setupFilterInputClearButton() {
this.waitForCondition(
() => Boolean(this.filterInput),
() => {
this.toggleFilterInputClearButton()
},
)
}
toggleFilterInputClearButton() {
if (this.filterInput.value.length > 0) {
this.filterInput.classList.remove('SubHeader-filterInput_hiddenClearButton')
} else {
this.filterInput.classList.add('SubHeader-filterInput_hiddenClearButton')
}
}
expandFilterInput() {
for (const item of this.shownItemsOnExpandedFilter) {
item.classList.remove('d-none', 'd-sm-none')
}
for (const item of this.filterExpandButton) {
item.classList.remove('d-inline-flex', 'd-sm-inline-flex')
item.classList.add('d-none')
}
this.classList.add('SubHeader--expandedSearch')
this.filterInput.focus()
}
collapseFilterInput() {
for (const item of this.filterExpandButton) {
item.classList.remove('d-none')
}
for (const item of this.shownItemsOnExpandedFilter) {
item.classList.add('d-none', 'd-sm-none')
}
this.classList.remove('SubHeader--expandedSearch')
}
// Waits for condition to return true. If it returns false initially, this function creates a
// MutationObserver that calls body() whenever the contents of the component change.
private waitForCondition(condition: () => boolean, body: () => void) {
if (condition()) {
body()
} else {
const mutationObserver = new MutationObserver(() => {
if (condition()) {
body()
mutationObserver.disconnect()
}
})
mutationObserver.observe(this, {childList: true, subtree: true})
}
}
}
declare global {
interface Window {
SubHeaderElement: typeof SubHeaderElement
}
}
if (!window.customElements.get('sub-header')) {
window.SubHeaderElement = SubHeaderElement
window.customElements.define('sub-header', SubHeaderElement)
}