-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathscroll-spy-controller.ts
173 lines (148 loc) · 4.59 KB
/
scroll-spy-controller.ts
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
import type { ReactiveController, ReactiveControllerHost } from 'lit';
export interface ScrollSpyControllerOptions extends IntersectionObserverInit {
/**
* Tag names of legal link children.
* Legal children must have an `href` property/attribute pair, like `<a>`.
*/
tagNames: string[];
/**
* Attribute to set on the active link element.
* @default 'active'
*/
activeAttribute?: string;
/**
* The root node to query content for
* @default the host's root node
*/
rootNode?: Node;
/**
* function to call on link children to get their URL hash (i.e. id to scroll to)
* @default el => el.getAttribute('href');
*/
getHash?: (el: Element) => string | null;
}
export class ScrollSpyController implements ReactiveController {
#tagNames: string[];
#activeAttribute: string;
#io?: IntersectionObserver;
/** Which link's targets have already scrolled past? */
#passedLinks = new Set<Element>();
/** Ignore intersections? */
#force = false;
/** Has the intersection observer found an element? */
#intersected = false;
#root: ScrollSpyControllerOptions['root'];
#rootMargin?: string;
#threshold: number | number[];
#getRootNode: () => Node | null;
#getHash: (el: Element) => string | null;
get #linkChildren(): Element[] {
return Array.from(this.host.querySelectorAll(this.#tagNames.join(',')))
.filter(this.#getHash);
}
get root(): Element | Document | null | undefined {
return this.#root;
}
set root(v) {
this.#root = v;
this.#io?.disconnect();
this.#initIo();
}
get rootMargin(): string | undefined {
return this.#rootMargin;
}
set rootMargin(v) {
this.#rootMargin = v;
this.#io?.disconnect();
this.#initIo();
}
get threshold(): number | number[] {
return this.#threshold;
}
set threshold(v) {
this.#threshold = v;
this.#io?.disconnect();
this.#initIo();
}
constructor(
private host: ReactiveControllerHost & HTMLElement,
options: ScrollSpyControllerOptions,
) {
host.addController(this);
this.#tagNames = options.tagNames;
this.#root = options.root;
this.#rootMargin = options.rootMargin;
this.#activeAttribute = options.activeAttribute ?? 'active';
this.#threshold = options.threshold ?? 0.85;
this.#getRootNode = () => options.rootNode ?? host.getRootNode?.() ?? null;
this.#getHash = options?.getHash ?? ((el: Element) => el.getAttribute('href'));
}
hostConnected(): void {
this.#initIo();
}
#initIo() {
const rootNode = this.#getRootNode();
if (rootNode instanceof Document || rootNode instanceof ShadowRoot) {
const { rootMargin, threshold, root } = this;
this.#io = new IntersectionObserver(r => this.#onIo(r), { root, rootMargin, threshold });
this.#linkChildren
.map(x => this.#getHash(x))
.filter((x): x is string => !!x)
.map(x => rootNode.getElementById(x.replace('#', '')))
.filter((x): x is HTMLElement => !!x)
.forEach(target => this.#io?.observe(target));
}
}
#markPassed(link: Element, force: boolean) {
if (force) {
this.#passedLinks.add(link);
} else {
this.#passedLinks.delete(link);
}
}
#setActive(link?: EventTarget | null) {
for (const child of this.#linkChildren) {
child.toggleAttribute(this.#activeAttribute, child === link);
}
}
async #nextIntersection() {
this.#intersected = false;
// safeguard the loop
setTimeout(() => this.#intersected = false, 3000);
while (!this.#intersected) {
await new Promise(requestAnimationFrame);
}
}
async #onIo(entries: IntersectionObserverEntry[]) {
if (!this.#force) {
for (const { target, boundingClientRect, intersectionRect } of entries) {
const selector = `:is(${this.#tagNames.join(',')})[href="#${target.id}"]`;
const link = this.host.querySelector(selector);
if (link) {
this.#markPassed(link, boundingClientRect.top < intersectionRect.top);
}
}
const link = [...this.#passedLinks];
const last = link.at(-1);
this.#setActive(last ?? this.#linkChildren.at(0));
}
this.#intersected = true;
}
/**
* Explicitly set the active item
* @param link usually an `<a>`
*/
public async setActive(link: EventTarget | null): Promise<void> {
this.#force = true;
this.#setActive(link);
let sawActive = false;
for (const child of this.#linkChildren) {
this.#markPassed(child, !sawActive);
if (child === link) {
sawActive = true;
}
}
await this.#nextIntersection();
this.#force = false;
}
}