/
toc.js
93 lines (80 loc) · 2.25 KB
/
toc.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
import {
customElement,
BoltElement,
html,
styleMap,
unsafeCSS,
} from '@bolt/element';
import classNames from 'classnames/dedupe';
import { withContext } from 'wc-context';
import tocStyles from './toc.scss';
import schema from '../toc.schema';
let cx = classNames.bind(tocStyles);
/*
* 1. @todo: remove SSR Hydration from this file, move to base
* 2. role="list": declares that an element is a list.
* 3. Aria lists reference: https://www.scottohara.me/blog/2018/05/26/aria-lists.html
*/
@customElement('bolt-toc')
class BoltToc extends withContext(BoltElement) {
static get properties() {
return {
header: String,
uuid: String,
};
}
constructor() {
super();
this.uuid = this.uuid || Math.floor(10000 + Math.random() * 90000);
}
/* [1] */
connectedCallback() {
super.connectedCallback && super.connectedCallback();
// Check if any `<ssr-keep>` elements have registered themselves here. If so, kick off the one-time hydration prep task.
if (this.ssrKeep && !this.ssrPrepped) {
this.ssrHydrationPrep();
}
}
/* [1] */
ssrHydrationPrep() {
// @todo: Move this to base-element, possibly as decorator
this.nodesToKeep = [];
this.ssrKeep.forEach(item => {
while (item.firstChild) {
this.nodesToKeep.push(item.firstChild); // track the nodes that will be preserved
this.appendChild(item.firstChild);
}
});
// Remove all children not in the "keep" array
Array.from(this.children)
.filter(item => !this.nodesToKeep.includes(item))
.forEach(node => {
node.parentElement.removeChild(node);
});
this.ssrPrepped = true;
}
static get styles() {
return [unsafeCSS(tocStyles)];
}
render() {
return html`
<nav
class="${cx(`c-bolt-toc`)}"
aria-labelledby="js-bolt-toc-${this.uuid}"
>
<h2
class="${cx(`c-bolt-toc__header`, {
[`c-bolt-toc__header--hidden`]: !this.header,
})}"
id="js-bolt-toc-${this.uuid}"
>
${this.header ? this.header : 'Table of Contents'}
</h2>
<div class="${cx(`c-bolt-toc__list`)}" role="list">
${this.slotify('default')}
</div>
</nav>
`;
}
}
export { BoltToc };