Repository navigation
Expand file tree
/
Copy pathnavigation.ts
More file actions
224 lines (190 loc) · 6.39 KB
/
Copy pathnavigation.ts
File metadata and controls
224 lines (190 loc) · 6.39 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
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
import { gsap } from "gsap";
import { ScrollToPlugin } from "gsap/ScrollToPlugin";
import { initializeThemeToggle } from "./theme";
const TOP_OF_PAGE_THRESHOLD = 16;
const MIN_SCROLL_DURATION_SECONDS = 0.65;
const MAX_SCROLL_DURATION_SECONDS = 1;
const SCROLL_DURATION_PER_PIXEL = 0.00035;
gsap.registerPlugin(ScrollToPlugin);
export function initializeNavigation(): void {
const navigation = document.querySelector<HTMLElement>(".nav-shell");
if (!navigation) return;
const sectionLinks = Array.from(
document.querySelectorAll<HTMLAnchorElement>("[data-section-link]"),
);
initializeThemeToggle();
initializeMobileMenu(navigation);
initializeAnchorScrolling();
initializeSectionTracking(navigation, sectionLinks);
}
function initializeMobileMenu(navigation: HTMLElement): void {
const menu = navigation.querySelector<HTMLElement>(".nav__links");
const toggle =
navigation.querySelector<HTMLButtonElement>(".nav__menu-toggle");
if (!menu || !toggle) return;
const closeMenu = () => setMenuOpen(menu, toggle, false);
toggle.addEventListener("click", () =>
setMenuOpen(menu, toggle, !menu.classList.contains("is-open")),
);
menu
.querySelectorAll<HTMLAnchorElement>("a")
.forEach((link) => link.addEventListener("click", closeMenu));
document.addEventListener("click", (event) =>
closeMenuOnOutsideClick(event, navigation, closeMenu),
);
document.addEventListener("keydown", (event) =>
closeMenuOnEscape(event, toggle, closeMenu),
);
}
function setMenuOpen(
menu: HTMLElement,
toggle: HTMLButtonElement,
isOpen: boolean,
): void {
menu.classList.toggle("is-open", isOpen);
toggle.setAttribute("aria-expanded", String(isOpen));
toggle.setAttribute(
"aria-label",
isOpen ? "Close navigation menu" : "Open navigation menu",
);
}
function closeMenuOnOutsideClick(
event: MouseEvent,
navigation: HTMLElement,
closeMenu: () => void,
): void {
if (!navigation.contains(event.target as Node)) closeMenu();
}
function closeMenuOnEscape(
event: KeyboardEvent,
toggle: HTMLButtonElement,
closeMenu: () => void,
): void {
if (event.key !== "Escape" || toggle.getAttribute("aria-expanded") !== "true")
return;
closeMenu();
toggle.focus();
}
function initializeAnchorScrolling(): void {
const anchorLinks =
document.querySelectorAll<HTMLAnchorElement>('a[href^="#"]');
anchorLinks.forEach((link) => {
link.addEventListener("click", (event) => {
const target = getAnchorTarget(link.hash);
if (!target || isModifiedClick(event)) return;
event.preventDefault();
scrollToTarget(target, link.hash);
});
});
}
function getAnchorTarget(hash: string): HTMLElement | null {
if (!hash) return null;
return document.querySelector<HTMLElement>(hash);
}
function isModifiedClick(event: MouseEvent): boolean {
return (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
);
}
function scrollToTarget(target: HTMLElement, hash: string): void {
const destination = getScrollDestination(target);
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
window.scrollTo(0, destination);
updateLocationHash(hash);
return;
}
gsap.killTweensOf(window);
gsap.to(window, {
duration: getScrollDuration(destination - window.scrollY),
ease: "power2.inOut",
scrollTo: { y: destination, autoKill: true },
onComplete: () => updateLocationHash(hash),
});
}
function getScrollDestination(target: HTMLElement): number {
const scrollPadding =
Number.parseFloat(
getComputedStyle(document.documentElement).scrollPaddingTop,
) || 0;
const targetTop =
target.getBoundingClientRect().top + window.scrollY - scrollPadding;
const maximumScroll =
document.documentElement.scrollHeight - window.innerHeight;
return Math.max(0, Math.min(targetTop, maximumScroll));
}
function updateLocationHash(hash: string): void {
history.pushState(null, "", hash);
}
function getScrollDuration(distance: number): number {
return Math.min(
MAX_SCROLL_DURATION_SECONDS,
Math.max(
MIN_SCROLL_DURATION_SECONDS,
Math.abs(distance) * SCROLL_DURATION_PER_PIXEL,
),
);
}
function initializeSectionTracking(
navigation: HTMLElement,
sectionLinks: HTMLAnchorElement[],
): void {
const sections = getLinkedSections(sectionLinks);
let updatePending = false;
const requestUpdate = () => {
if (updatePending) return;
updatePending = true;
window.requestAnimationFrame(() => {
updateNavigationState(navigation, sectionLinks, sections);
updatePending = false;
});
};
if (document.readyState === "complete") requestUpdate();
else window.addEventListener("load", requestUpdate, { once: true });
window.addEventListener("scroll", requestUpdate, { passive: true });
window.addEventListener("resize", requestUpdate, { passive: true });
window.addEventListener("pageshow", requestUpdate);
}
function getLinkedSections(sectionLinks: HTMLAnchorElement[]): HTMLElement[] {
return sectionLinks
.map((link) =>
document.querySelector<HTMLElement>(`#${link.dataset.sectionLink}`),
)
.filter((section): section is HTMLElement => section !== null);
}
function updateNavigationState(
navigation: HTMLElement,
sectionLinks: HTMLAnchorElement[],
sections: HTMLElement[],
): void {
navigation.classList.toggle("is-scrolled", window.scrollY > 16);
setActiveSection(sectionLinks, findActiveSection(sections));
}
function findActiveSection(sections: HTMLElement[]): string | undefined {
if (window.scrollY <= TOP_OF_PAGE_THRESHOLD) return undefined;
const readingPosition = window.scrollY + window.innerHeight * 0.38;
const currentSection = sections.findLast(
(section) => getDocumentTop(section) <= readingPosition,
);
const isAtPageEnd =
window.innerHeight + window.scrollY >=
document.documentElement.scrollHeight - 8;
return isAtPageEnd ? sections.at(-1)?.id : currentSection?.id;
}
function getDocumentTop(element: HTMLElement): number {
return element.getBoundingClientRect().top + window.scrollY;
}
function setActiveSection(
sectionLinks: HTMLAnchorElement[],
activeSectionId?: string,
): void {
sectionLinks.forEach((link) => {
const isActive = link.dataset.sectionLink === activeSectionId;
link.classList.toggle("is-active", isActive);
if (isActive) link.setAttribute("aria-current", "location");
else link.removeAttribute("aria-current");
});
}