-
Notifications
You must be signed in to change notification settings - Fork 341
/
Copy pathsidebar-list.js
260 lines (216 loc) · 7.45 KB
/
sidebar-list.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
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
import { el, getCurrentPageSidebarType, qs, qsAll } from '../helpers'
import { getSidebarNodes } from '../globals'
// Sidebar list is only rendered when needed.
// Mobile users may never see the sidebar.
let init = false
export function initialize () {
if (init) return
init = true
const sidebarList = document.getElementById('sidebar-list-nav')
if (!sidebarList) return
const defaultTab = getCurrentPageSidebarType()
const tabs = {
extras: sidebarList.dataset.extras || 'Pages',
modules: 'Modules',
tasks: '<span translate="no">Mix</span> Tasks'
}
Object.entries(tabs).forEach(([type, titleHtml]) => {
const nodes = getSidebarNodes()[type]
if (!nodes?.length) return
const tabId = `${type}-list-tab-button`
const tabpanelId = `${type}-tab-panel`
const selected = type === defaultTab
const tab = el('button', {
id: tabId,
role: 'tab',
tabindex: selected ? 0 : -1,
'aria-selected': selected || undefined,
'aria-controls': tabpanelId
})
tab.innerHTML = titleHtml
tab.addEventListener('keydown', handleTabKeydown)
tab.addEventListener('click', handleTabClick)
sidebarList.appendChild(el('li', {}, [tab]))
const nodeList = el('ul', {class: 'full-list'})
nodeList.addEventListener('click', handleNodeListClick)
const tabpanel = el('div', {
id: tabpanelId,
class: 'sidebar-tabpanel',
role: 'tabpanel',
'aria-labelledby': tabId,
hidden: selected ? undefined : ''
}, [nodeList])
document.getElementById('sidebar').appendChild(tabpanel)
let group = ''
let nestedContext
let lastModule
nodeList.replaceChildren(...nodes.flatMap(node => {
const items = []
const hasHeaders = Array.isArray(node.headers)
const translate = hasHeaders ? undefined : 'no'
const href = node?.url || `${node.id}.html`
// Group header.
if (node.group !== group) {
items.push(el('li', {class: 'group', translate}, [node.group]))
group = node.group
nestedContext = undefined
}
// Nesting context.
if (node.nested_context && node.nested_context !== nestedContext) {
nestedContext = node.nested_context
if (lastModule !== nestedContext) {
items.push(el('li', {class: 'nesting-context', translate: 'no', 'aria-hidden': true}, [nestedContext]))
}
} else {
lastModule = node.title
}
items.push(el('li', {}, [
el('a', {href: href, translate}, [node.nested_title || node.title]),
...childList(`node-${node.id}-headers`,
hasHeaders
? renderHeaders(node)
: renderSectionsAndGroups(node)
)
]))
return items
}))
})
// Update new sidebar list with current hash.
markCurrentHashInSidebar()
// Triggers layout, defer.
requestAnimationFrame(scrollNodeListToCurrentCategory)
// Keep updated with future changes.
window.addEventListener('hashchange', markCurrentHashInSidebar)
window.addEventListener('exdoc:loaded', markCurrentHashInSidebar)
}
/**
* @param {string} id
* @param {HTMLElement[]} childItems
*/
function childList (id, childItems) {
if (!childItems.length) return []
return [
el('button', {'aria-label': 'expand', 'aria-expanded': false, 'aria-controls': id}),
el('ul', {id}, childItems)
]
}
function renderHeaders (node) {
return node.headers
.map(({id, anchor}) =>
el('li', {}, [
el('a', {href: `${node.id}.html#${anchor}`}, [id])
])
)
}
function renderSectionsAndGroups (node) {
const items = []
if (node.sections?.length) {
items.push(el('li', {}, [
el('a', {href: `${node.id}.html#content`}, ['Sections']),
...childList(`${node.id}-sections-list`,
node.sections
.map(({id, anchor}) =>
el('li', {}, [
el('a', {href: `${node.id}.html#${anchor}`}, [id])
])
)
)
]))
}
if (node.nodeGroups) {
items.push(el('li', {}, [
el('a', {href: `${node.id}.html#summary`}, ['Summary'])
]))
items.push(...node.nodeGroups.map(({key, name, nodes}) =>
el('li', {}, [
el('a', {href: `${node.id}.html#${key}`}, [name]),
...childList(`node-${node.id}-group-${key}-list`,
nodes
.map(({anchor, title, id}) =>
el('li', {}, [
el('a', {href: `${node.id}.html#${anchor}`, title, translate: 'no'}, [id])
])
)
)
])
))
}
return items
}
/** @param {HTMLButtonElement} */
function activateTab (next) {
const prev = document.getElementById('sidebar-list-nav').querySelector('[aria-selected]')
if (prev === next) return
if (prev) {
prev.removeAttribute('aria-selected')
prev.setAttribute('tabindex', '-1')
document.getElementById(prev.getAttribute('aria-controls')).setAttribute('hidden', 'hidden')
}
next.setAttribute('aria-selected', 'true')
next.setAttribute('tabindex', '0')
document.getElementById(next.getAttribute('aria-controls')).removeAttribute('hidden')
}
function scrollNodeListToCurrentCategory () {
qs('#sidebar [role=tabpanel]:not([hidden]) a[aria-selected]')?.scrollIntoView()
}
function markCurrentHashInSidebar () {
const sidebar = document.getElementById('sidebar')
const {pathname, hash} = window.location
// All sidebar links are relative and end in .html.
const page = pathname.split('/').pop().replace(/\.html$/, '') + '.html'
// Try find exact link with hash, fall back to page.
const current = sidebar.querySelector(`li a[href="${page + hash}"]`) || sidebar.querySelector(`li a[href="${page}"]`)
if (!current) return
// Unset previous.
sidebar.querySelectorAll('.full-list a[aria-selected]').forEach(element => {
element.removeAttribute('aria-selected')
})
// Close open menus.
sidebar.querySelectorAll('.full-list button[aria-expanded=true]').forEach(element => {
element.setAttribute('aria-expanded', false)
})
// Walk up parents, updating link, button and tab attributes.
let element = current.parentElement
while (element) {
if (element.tagName === 'LI') {
const link = element.firstChild
link.setAttribute('aria-selected', link.getAttribute('href') === page ? 'page' : 'true')
const button = link.nextSibling
if (button?.tagName === 'BUTTON') {
button.setAttribute('aria-expanded', true)
}
} else if (element.role === 'tabpanel') {
if (element.hasAttribute('hidden')) {
activateTab(document.getElementById(element.getAttribute('aria-labelledby')))
}
break
}
element = element.parentElement
}
}
/**
* Provide left/right arrow navigation for tablist, as required by ARIA authoring practices guide.
*
* @param {KeyboardEvent}
**/
function handleTabKeydown (event) {
if (!['ArrowRight', 'ArrowLeft'].includes(event.key)) { return }
const tabs = Array.from(qsAll('#sidebar-list-nav [role="tab"]'))
const currentIndex = tabs.indexOf(event.currentTarget)
const nextIndex = currentIndex + (event.key === 'ArrowRight' ? 1 : -1)
const nextTab = tabs.at(nextIndex % tabs.length)
activateTab(nextTab)
nextTab.focus()
}
/** @param {MouseEvent} */
function handleTabClick (event) {
activateTab(event.currentTarget)
scrollNodeListToCurrentCategory()
}
/** @param {MouseEvent} */
function handleNodeListClick (event) {
const target = event.target
if (target.tagName === 'BUTTON') {
target.setAttribute('aria-expanded', target.getAttribute('aria-expanded') === 'false')
}
}