-
-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathbuild-html.js
327 lines (293 loc) · 9.92 KB
/
build-html.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
/**
* This file is responsible for building the DOM and updating DOM state.
*
* @author Tim Scanlin
*/
export default function (options) {
const forEach = [].forEach
const some = [].some
const body = typeof window !== 'undefined' && document.body
const SPACE_CHAR = ' '
let tocElement
let currentlyHighlighting = true
/**
* Create link and list elements.
* @param {Object} d
* @param {HTMLElement} container
* @return {HTMLElement}
*/
function createEl (d, container) {
const link = container.appendChild(createLink(d))
if (d.children.length) {
const list = createList(d.isCollapsed)
d.children.forEach((child) => {
createEl(child, list)
})
link.appendChild(list)
}
}
/**
* Render nested heading array data into a given element.
* @param {HTMLElement} parent Optional. If provided updates the {@see tocElement} to match.
* @param {Array} data
* @return {HTMLElement}
*/
function render (parent, data) {
const collapsed = false
const container = createList(collapsed)
data.forEach((d) => {
createEl(d, container)
})
// Return if no TOC element is provided or known.
tocElement = parent || tocElement
if (tocElement === null) {
return
}
// Remove existing child if it exists.
if (tocElement.firstChild) {
tocElement.removeChild(tocElement.firstChild)
}
// Just return the parent and don't append the list if no links are found.
if (data.length === 0) {
return tocElement
}
// Append the Elements that have been created
return tocElement.appendChild(container)
}
/**
* Create link element.
* @param {Object} data
* @return {HTMLElement}
*/
function createLink (data) {
const item = document.createElement('li')
const a = document.createElement('a')
if (options.listItemClass) {
item.setAttribute('class', options.listItemClass)
}
if (options.onClick) {
a.onclick = options.onClick
}
if (options.includeTitleTags) {
a.setAttribute('title', data.textContent)
}
if (options.includeHtml && data.childNodes.length) {
forEach.call(data.childNodes, (node) => {
a.appendChild(node.cloneNode(true))
})
} else {
// Default behavior. Set to textContent to keep tests happy.
a.textContent = data.textContent
}
a.setAttribute('href', `${options.basePath}#${data.id}`)
a.setAttribute('class', `${options.linkClass +
SPACE_CHAR}node-name--${data.nodeName}${SPACE_CHAR}${options.extraLinkClasses}`)
item.appendChild(a)
return item
}
/**
* Create list element.
* @param {Boolean} isCollapsed
* @return {HTMLElement}
*/
function createList (isCollapsed) {
const listElement = (options.orderedList) ? 'ol' : 'ul'
const list = document.createElement(listElement)
let classes = options.listClass + SPACE_CHAR + options.extraListClasses
if (isCollapsed) {
// No plus/equals here fixes compilation issue.
classes = classes + SPACE_CHAR + options.collapsibleClass
classes = classes + SPACE_CHAR + options.isCollapsedClass
}
list.setAttribute('class', classes)
return list
}
/**
* Update fixed sidebar class.
* @return {HTMLElement}
*/
function updateFixedSidebarClass () {
const scrollTop = getScrollTop()
const posFixedEl = document.querySelector(options.positionFixedSelector)
if (options.fixedSidebarOffset === 'auto') {
options.fixedSidebarOffset = tocElement.offsetTop
}
if (scrollTop > options.fixedSidebarOffset) {
if (posFixedEl.className.indexOf(options.positionFixedClass) === -1) {
posFixedEl.className += SPACE_CHAR + options.positionFixedClass
}
} else {
posFixedEl.className = posFixedEl.className.replace(SPACE_CHAR + options.positionFixedClass, '')
}
}
/**
* Get top position of heading
* @param {HTMLElement} obj
* @return {int} position
*/
function getHeadingTopPos (obj) {
let position = 0
if (obj !== null) {
position = obj.offsetTop
if (options.hasInnerContainers) { position += getHeadingTopPos(obj.offsetParent) }
}
return position
}
/**
* Update className only when changed.
* @param {HTMLElement} obj
* @param {string} className
* @return {HTMLElement} obj
*/
function updateClassname (obj, className) {
if (obj && obj.className !== className) {
obj.className = className
}
return obj
}
/**
* Update TOC highlighting and collapsed groupings.
*/
function updateToc (headingsArray) {
// Add fixed class at offset
if (options.positionFixedSelector) {
updateFixedSidebarClass()
}
// Get the top most heading currently visible on the page so we know what to highlight.
const headings = headingsArray
// Using some instead of each so that we can escape early.
if (currentlyHighlighting &&
!!tocElement &&
headings.length > 0) {
const topHeader = getTopHeader(headings)
const oldActiveTocLink = tocElement.querySelector(`.${options.activeLinkClass}`)
const activeTocLink = tocElement
.querySelector(`.${options.linkClass}.node-name--${topHeader.nodeName}[href="${options.basePath}#${topHeader.id.replace(/([ #;&,.+*~':"!^$[\]()=>|/\\@])/g, '\\$1')}"]`)
// Performance improvement to only change the classes
// for the toc if a new link should be highlighted.
if (oldActiveTocLink === activeTocLink) {
return
}
// Remove the active class from the other tocLinks.
const tocLinks = tocElement
.querySelectorAll(`.${options.linkClass}`)
forEach.call(tocLinks, (tocLink) => {
updateClassname(tocLink, tocLink.className.replace(SPACE_CHAR + options.activeLinkClass, ''))
})
const tocLis = tocElement
.querySelectorAll(`.${options.listItemClass}`)
forEach.call(tocLis, (tocLi) => {
updateClassname(tocLi, tocLi.className.replace(SPACE_CHAR + options.activeListItemClass, ''))
})
// Add the active class to the active tocLink.
if (activeTocLink && activeTocLink.className.indexOf(options.activeLinkClass) === -1) {
activeTocLink.className += SPACE_CHAR + options.activeLinkClass
}
const li = activeTocLink?.parentNode
if (li && li.className.indexOf(options.activeListItemClass) === -1) {
li.className += SPACE_CHAR + options.activeListItemClass
}
const tocLists = tocElement
.querySelectorAll(`.${options.listClass}.${options.collapsibleClass}`)
// Collapse the other collapsible lists.
forEach.call(tocLists, (list) => {
if (list.className.indexOf(options.isCollapsedClass) === -1) {
list.className += SPACE_CHAR + options.isCollapsedClass
}
})
// Expand the active link's collapsible list and its sibling if applicable.
if (activeTocLink?.nextSibling && activeTocLink.nextSibling.className.indexOf(options.isCollapsedClass) !== -1) {
updateClassname(activeTocLink.nextSibling, activeTocLink.nextSibling.className.replace(SPACE_CHAR + options.isCollapsedClass, ''))
}
removeCollapsedFromParents(activeTocLink?.parentNode.parentNode)
}
}
/**
* Remove collapsed class from parent elements.
* @param {HTMLElement} element
* @return {HTMLElement}
*/
function removeCollapsedFromParents (element) {
if (element && element.className.indexOf(options.collapsibleClass) !== -1 && element.className.indexOf(options.isCollapsedClass) !== -1) {
updateClassname(element, element.className.replace(SPACE_CHAR + options.isCollapsedClass, ''))
return removeCollapsedFromParents(element.parentNode.parentNode)
}
return element
}
/**
* Disable TOC Animation when a link is clicked.
* @param {Event} event
*/
function disableTocAnimation (event) {
const target = event.target || event.srcElement
if (typeof target.className !== 'string' || target.className.indexOf(options.linkClass) === -1) {
return
}
// Bind to tocLink clicks to temporarily disable highlighting
// while smoothScroll is animating.
currentlyHighlighting = false
}
/**
* Enable TOC Animation.
*/
function enableTocAnimation () {
currentlyHighlighting = true
}
/**
* Return currently highlighting status.
*/
function getCurrentlyHighlighting () {
return currentlyHighlighting
}
function getScrollTop () {
// If a fixed content container was set
let top
if (options.scrollContainer && document.querySelector(options.scrollContainer)) {
top = document.querySelector(options.scrollContainer).scrollTop
} else {
top = document.documentElement.scrollTop || body.scrollTop
}
return top
}
function getTopHeader (headings, scrollTop = getScrollTop()) {
let topHeader
some.call(headings, (heading, i) => {
if (getHeadingTopPos(heading) > scrollTop + options.headingsOffset + 10) {
// Don't allow negative index value.
const index = (i === 0) ? i : i - 1
topHeader = headings[index]
return true
}
if (i === headings.length - 1) {
// This allows scrolling for the last heading on the page.
topHeader = headings[headings.length - 1]
return true
}
})
return topHeader
}
function updateUrlHashForHeader (headingsArray) {
const scrollTop = getScrollTop()
const topHeader = getTopHeader(headingsArray, scrollTop)
if (!topHeader || scrollTop < 5) {
if (!(window.location.hash === '#' || window.location.hash === '')) {
window.history.pushState(null, null, '#')
}
} else if (topHeader) {
const newHash = `#${topHeader.id}`
if (window.location.hash !== newHash) {
window.history.pushState(null, null, newHash)
}
}
}
return {
enableTocAnimation,
disableTocAnimation,
render,
updateToc,
getCurrentlyHighlighting,
getTopHeader,
getScrollTop,
updateUrlHashForHeader
}
}