@plusguard/anchor 0.0.0-stage → 3.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +625 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +692 -0
- package/index.css +156 -0
- package/index.ts +716 -0
- package/package.json +21 -5
package/index.ts
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* anchor — scrolling to a place on the page, from markup.
|
|
3
|
+
*
|
|
4
|
+
* <a href="#contact" data-pg-anchor>Contact</a>
|
|
5
|
+
* <div data-pg-anchor="#products">…a whole card…</div>
|
|
6
|
+
* <button data-pg-anchor="top" data-pg-anchor-visible="false">↑</button>
|
|
7
|
+
*
|
|
8
|
+
* data-pg-anchor is the target: "#id", "top" or "bottom". On a link it may
|
|
9
|
+
* be left empty — the target is then the link's own #hash, on this page.
|
|
10
|
+
*
|
|
11
|
+
* Options, on the element or anywhere above it (the nearest wins):
|
|
12
|
+
* data-pg-anchor-hash "true" writes #id to the address bar, a step
|
|
13
|
+
* in the history each time — Back goes back
|
|
14
|
+
* through them; "replace" writes it in place of
|
|
15
|
+
* the address — no step, Back leaves the page;
|
|
16
|
+
* "false", the default, leaves the address as
|
|
17
|
+
* it is
|
|
18
|
+
*
|
|
19
|
+
* The glide is CSS, so it changes per screen size (index.css):
|
|
20
|
+
* --pg-anchor-duration a time. Default 1200ms; 0s is a jump
|
|
21
|
+
* --pg-anchor-easing linear, ease…, cubic-bezier(…). Default: the
|
|
22
|
+
* curve below, Lenis's own
|
|
23
|
+
*
|
|
24
|
+
* When it scrolls: --pg-anchor-when on the element or above (index.css) —
|
|
25
|
+
* "always" (default); "passed", only back up to a section the reader has
|
|
26
|
+
* scrolled past — a tab bar's "start of the new tab" — never down; "never".
|
|
27
|
+
* A CSS variable, so it changes per screen size.
|
|
28
|
+
*
|
|
29
|
+
* Where a section lands: below the page's scroll-padding-top, its own
|
|
30
|
+
* scroll-margin-top and --pg-anchor-edge (index.css) — a fixed header is
|
|
31
|
+
* cleared with those, per screen size through media queries.
|
|
32
|
+
*
|
|
33
|
+
* The glide runs frame by frame, in both modes; the
|
|
34
|
+
* user's wheel, touch or keys stop it, and with reduced motion asked for it
|
|
35
|
+
* is a jump. On a page with Lenis, hand Lenis in with setAnchorScroller.
|
|
36
|
+
*
|
|
37
|
+
* Showing: an element with data-pg-anchor-visible (write "false" to start)
|
|
38
|
+
* turns "true" once the page has scrolled --pg-anchor-show-after. With
|
|
39
|
+
* data-pg-anchor-progress too, it gets --pg-anchor-progress, 0 to 1: how far
|
|
40
|
+
* the page has scrolled from where it showed to the end — index.css draws
|
|
41
|
+
* it as a ring round the element, filling as the page goes. It also
|
|
42
|
+
* keeps clear of data-pg-anchor-avoid areas, unless its --pg-anchor-avoid
|
|
43
|
+
* is "none" (per screen size, in a media query):
|
|
44
|
+
* data-pg-anchor-avoid it steps out of the way — up when it sits
|
|
45
|
+
* in the lower half of the screen, down in
|
|
46
|
+
* the upper — keeping --pg-anchor-avoid-space
|
|
47
|
+
* data-pg-anchor-avoid="hide" it passes under: the part the area covers
|
|
48
|
+
* is cut off; wholly under, it gets
|
|
49
|
+
* data-pg-anchor-covered="true"
|
|
50
|
+
*
|
|
51
|
+
* Spy: in a data-pg-anchor-spy menu, the links whose section has reached
|
|
52
|
+
* the landing line get data-pg-anchor-current="true" and
|
|
53
|
+
* aria-current="location"; the menu gets --pg-anchor-current-left / -top /
|
|
54
|
+
* -width / -height, for a marker that slides under the current link.
|
|
55
|
+
*
|
|
56
|
+
* Strip: a data-pg-anchor-strip row that scrolls sideways (tabs, chips, a
|
|
57
|
+
* spy menu) keeps its current item in view — the one marked aria-current,
|
|
58
|
+
* aria-selected="true" or aria-expanded="true" — and, if none is marked,
|
|
59
|
+
* the one clicked. --pg-anchor-strip: center (default; at the ends it
|
|
60
|
+
* simply stops), start, end or none; --pg-anchor-strip-duration and
|
|
61
|
+
* --pg-anchor-strip-easing for the slide. Only the row moves, never the
|
|
62
|
+
* page. On load the current item is put in view at once.
|
|
63
|
+
*
|
|
64
|
+
* Stay: inside a data-pg-anchor-stay box (an accordion), the item clicked
|
|
65
|
+
* keeps its place on the screen while the page above it changes — an
|
|
66
|
+
* answer closing above the question just opened, however it animates. The
|
|
67
|
+
* page scrolls by what the item would have moved, frame by frame, until it
|
|
68
|
+
* has been still a while; the user's wheel, touch or keys stop it.
|
|
69
|
+
* --pg-anchor-stay: none turns it off, per screen size.
|
|
70
|
+
*
|
|
71
|
+
* A <p> or <div> with data-pg-anchor is made reachable: tabindex="0",
|
|
72
|
+
* role="link", and Enter.
|
|
73
|
+
*/
|
|
74
|
+
|
|
75
|
+
const ATTR = "data-pg-anchor";
|
|
76
|
+
const HASH = "data-pg-anchor-hash";
|
|
77
|
+
const VISIBLE = "data-pg-anchor-visible";
|
|
78
|
+
const PROGRESS = "data-pg-anchor-progress";
|
|
79
|
+
const AVOID = "data-pg-anchor-avoid";
|
|
80
|
+
const SPY = "data-pg-anchor-spy";
|
|
81
|
+
const CURRENT = "data-pg-anchor-current";
|
|
82
|
+
const COVERED = "data-pg-anchor-covered";
|
|
83
|
+
const STRIP = "data-pg-anchor-strip";
|
|
84
|
+
const STAY = "data-pg-anchor-stay";
|
|
85
|
+
const LIFT = "--pg-anchor-lift";
|
|
86
|
+
const CLIP = "--pg-anchor-clip";
|
|
87
|
+
|
|
88
|
+
const DEFAULT_DURATION = 1200;
|
|
89
|
+
const DEFAULT_SHOW_AFTER = 400;
|
|
90
|
+
const DEFAULT_STRIP_DURATION = 500;
|
|
91
|
+
|
|
92
|
+
/* What a strip keeps in view: an item marked as the current one. */
|
|
93
|
+
const MARKED = '[aria-current]:not([aria-current="false"]), [aria-selected="true"], [aria-expanded="true"]';
|
|
94
|
+
/* What a click in a strip lands on, when nothing is marked. */
|
|
95
|
+
const ITEM = "a, button, [role='tab'], [tabindex], [data-pg-anchor]";
|
|
96
|
+
|
|
97
|
+
/* Lenis's own curve: off fast, then a long soft landing. */
|
|
98
|
+
export const anchorEasing = (t: number): number => Math.min(1, 1.001 - Math.pow(2, -10 * t));
|
|
99
|
+
|
|
100
|
+
/* What moves the page to `top` (px) over `duration` (ms; 0 is a jump), on
|
|
101
|
+
`easing` — the element's --pg-anchor-easing. */
|
|
102
|
+
export type AnchorScroller = (top: number, duration: number, easing: (t: number) => number) => void;
|
|
103
|
+
|
|
104
|
+
let scroller: AnchorScroller | null = null;
|
|
105
|
+
|
|
106
|
+
/*
|
|
107
|
+
* With Lenis, hand it in; null goes back to the built-in glide.
|
|
108
|
+
*
|
|
109
|
+
* setAnchorScroller((top, ms, easing) =>
|
|
110
|
+
* lenis.scrollTo(top, ms ? { duration: ms / 1000, easing } : { immediate: true }));
|
|
111
|
+
*/
|
|
112
|
+
export function setAnchorScroller(next: AnchorScroller | null): void {
|
|
113
|
+
stopGlide();
|
|
114
|
+
scroller = next;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function px(value: string): number {
|
|
118
|
+
const n = Number.parseFloat(value);
|
|
119
|
+
return Number.isFinite(n) ? n : 0;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function maxScroll(): number {
|
|
123
|
+
return Math.max(0, document.documentElement.scrollHeight - innerHeight);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function option(el: Element, attr: string): string | null {
|
|
127
|
+
return el.closest(`[${attr}]`)?.getAttribute(attr) ?? null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/* A keyword CSS variable: one of `values`, else the first of them. */
|
|
131
|
+
function keyword<T extends string>(el: Element, name: string, values: readonly T[]): T {
|
|
132
|
+
const raw = getComputedStyle(el).getPropertyValue(name).trim();
|
|
133
|
+
return (values as readonly string[]).includes(raw) ? (raw as T) : values[0];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function reducedMotion(): boolean {
|
|
137
|
+
return matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/* ---------- The glide ---------- */
|
|
141
|
+
|
|
142
|
+
let glide = 0;
|
|
143
|
+
const STOPPERS = ["wheel", "touchstart", "keydown", "pointerdown"] as const;
|
|
144
|
+
|
|
145
|
+
function stopGlide(): void {
|
|
146
|
+
if (!glide) return;
|
|
147
|
+
cancelAnimationFrame(glide);
|
|
148
|
+
glide = 0;
|
|
149
|
+
STOPPERS.forEach((type) => removeEventListener(type, stopGlide));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function glideTo(top: number, duration: number, easing: (t: number) => number): void {
|
|
153
|
+
stopGlide();
|
|
154
|
+
const from = scrollY;
|
|
155
|
+
// "instant" on every step: a page-wide scroll-behavior: smooth would
|
|
156
|
+
// otherwise turn each one into a smooth scroll of its own.
|
|
157
|
+
if (duration <= 0 || Math.abs(top - from) < 1) {
|
|
158
|
+
scrollTo({ top, behavior: "instant" });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const start = performance.now();
|
|
162
|
+
const step = (now: number): void => {
|
|
163
|
+
const t = Math.min(1, (now - start) / duration);
|
|
164
|
+
scrollTo({ top: from + (top - from) * easing(t), behavior: "instant" });
|
|
165
|
+
if (t < 1) glide = requestAnimationFrame(step);
|
|
166
|
+
else stopGlide();
|
|
167
|
+
};
|
|
168
|
+
STOPPERS.forEach((type) => addEventListener(type, stopGlide, { passive: true }));
|
|
169
|
+
glide = requestAnimationFrame(step);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/* ---------- Targets ---------- */
|
|
173
|
+
|
|
174
|
+
function isLink(el: Element): el is HTMLAnchorElement {
|
|
175
|
+
return el instanceof HTMLAnchorElement && el.hasAttribute("href");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function targetOf(el: Element): string {
|
|
179
|
+
const value = el.getAttribute(ATTR);
|
|
180
|
+
// JSX writes a bare data-pg-anchor as "true": same as empty.
|
|
181
|
+
if (value && value !== "true") return value;
|
|
182
|
+
// An empty value on a link: its #hash — but only for this page.
|
|
183
|
+
if (isLink(el) && el.host === location.host && el.pathname === location.pathname) return el.hash;
|
|
184
|
+
return "";
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function sectionOf(target: string): HTMLElement | null {
|
|
188
|
+
if (!target.startsWith("#") || target.length < 2) return null;
|
|
189
|
+
return document.getElementById(decodeURIComponent(target.slice(1)));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/* --pg-anchor-edge where `from` stands. */
|
|
193
|
+
const edgeOf = (from: Element): number => px(getComputedStyle(from).getPropertyValue("--pg-anchor-edge"));
|
|
194
|
+
|
|
195
|
+
/* How far below the screen's top a section lands — the spy's line too.
|
|
196
|
+
`edge`: --pg-anchor-edge of the link. */
|
|
197
|
+
function clearance(section: Element, edge: number): number {
|
|
198
|
+
return px(getComputedStyle(document.documentElement).scrollPaddingTop) + px(getComputedStyle(section).scrollMarginTop) + edge;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function destination(target: string, edge: number): number | null {
|
|
202
|
+
if (target === "top") return 0;
|
|
203
|
+
if (target === "bottom") return maxScroll();
|
|
204
|
+
const section = sectionOf(target);
|
|
205
|
+
if (!section) return null;
|
|
206
|
+
const top = section.getBoundingClientRect().top + scrollY - clearance(section, edge);
|
|
207
|
+
return Math.min(Math.max(0, Math.round(top)), maxScroll());
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/* A <time> variable, in ms. index.css registers them, so the browser hands
|
|
211
|
+
them back resolved — in seconds; ms is read too. Reduced motion: 0. */
|
|
212
|
+
function timeOf(el: Element, name: string, fallback: number): number {
|
|
213
|
+
if (reducedMotion()) return 0;
|
|
214
|
+
const raw = getComputedStyle(el).getPropertyValue(name).trim();
|
|
215
|
+
const n = Number.parseFloat(raw);
|
|
216
|
+
if (!Number.isFinite(n)) return fallback;
|
|
217
|
+
return Math.max(0, raw.endsWith("ms") ? n : n * 1000);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const WHEN = ["always", "passed", "never"] as const;
|
|
221
|
+
|
|
222
|
+
/* What a click asks for, read off the element clicked as it is clicked:
|
|
223
|
+
a frame later, when the page is measured, it may be gone — a copy in a
|
|
224
|
+
menu the same click closed or wrote again (fit-more-nav's "More"), and
|
|
225
|
+
a gone element has no CSS to read. */
|
|
226
|
+
type Ask = {
|
|
227
|
+
when: (typeof WHEN)[number];
|
|
228
|
+
write: string | null;
|
|
229
|
+
duration: number;
|
|
230
|
+
easing: (t: number) => number;
|
|
231
|
+
edge: number;
|
|
232
|
+
};
|
|
233
|
+
function askOf(el: Element): Ask {
|
|
234
|
+
return {
|
|
235
|
+
when: keyword(el, "--pg-anchor-when", WHEN),
|
|
236
|
+
write: option(el, HASH),
|
|
237
|
+
duration: timeOf(el, "--pg-anchor-duration", DEFAULT_DURATION),
|
|
238
|
+
easing: easingOf(el, "--pg-anchor-easing"),
|
|
239
|
+
edge: edgeOf(el),
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function go(ask: Ask, target: string, byKeyboard: boolean): void {
|
|
244
|
+
const top = destination(target, ask.edge);
|
|
245
|
+
if (top === null) return;
|
|
246
|
+
|
|
247
|
+
// A section writes its #id; top and bottom clear the hash — whether or
|
|
248
|
+
// not the page then moves. "true" adds a step to the history, "replace"
|
|
249
|
+
// writes over the address — keeping the history's state, which a
|
|
250
|
+
// router (Next) keeps there.
|
|
251
|
+
const write = ask.write;
|
|
252
|
+
if (write === "true" || write === "replace") {
|
|
253
|
+
const hash = target.startsWith("#") ? target : "";
|
|
254
|
+
const url = hash || location.pathname + location.search;
|
|
255
|
+
if (location.hash !== hash) {
|
|
256
|
+
if (write === "replace") history.replaceState(history.state, "", url);
|
|
257
|
+
else history.pushState(null, "", url);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// "passed": back up to a section scrolled past, never down to one ahead.
|
|
262
|
+
const when = ask.when;
|
|
263
|
+
if (when === "never" || (when === "passed" && top >= scrollY - 1)) return;
|
|
264
|
+
|
|
265
|
+
(scroller ?? glideTo)(top, ask.duration, ask.easing);
|
|
266
|
+
|
|
267
|
+
// From the keyboard, Tab carries on from the section, as a real jump
|
|
268
|
+
// would; focus without a scroll of its own, the glide is doing that.
|
|
269
|
+
// Not for "passed": that brings the reader back to the start of what
|
|
270
|
+
// they are reading, it is no jump — focus stays on the tab pressed.
|
|
271
|
+
const section = sectionOf(target);
|
|
272
|
+
if (byKeyboard && section && when === "always") {
|
|
273
|
+
if (!section.hasAttribute("tabindex")) section.setAttribute("tabindex", "-1");
|
|
274
|
+
section.focus({ preventScroll: true });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/* ---------- Reachable from the keyboard ---------- */
|
|
279
|
+
|
|
280
|
+
function isNative(el: Element): boolean {
|
|
281
|
+
return isLink(el) || el instanceof HTMLButtonElement;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function reachable(el: Element): void {
|
|
285
|
+
if (isNative(el)) return;
|
|
286
|
+
if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "0");
|
|
287
|
+
if (!el.hasAttribute("role")) el.setAttribute("role", "link");
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/* ---------- Showing, stepping aside, spying ---------- */
|
|
291
|
+
|
|
292
|
+
function write(el: Element, attr: string, value: string | null): void {
|
|
293
|
+
if (el.getAttribute(attr) === value) return;
|
|
294
|
+
if (value === null) el.removeAttribute(attr);
|
|
295
|
+
else el.setAttribute(attr, value);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function writeVar(el: HTMLElement, name: string, value: string): void {
|
|
299
|
+
if (el.style.getPropertyValue(name) !== value) el.style.setProperty(name, value);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function show(el: HTMLElement): void {
|
|
303
|
+
const raw = getComputedStyle(el).getPropertyValue("--pg-anchor-show-after");
|
|
304
|
+
const after = raw.trim() ? px(raw) : DEFAULT_SHOW_AFTER;
|
|
305
|
+
write(el, VISIBLE, String(scrollY >= after));
|
|
306
|
+
// The ring: from where it showed (0) to the end of the page (1).
|
|
307
|
+
if (el.hasAttribute(PROGRESS)) {
|
|
308
|
+
const end = maxScroll();
|
|
309
|
+
const done = end > after ? Math.min(1, Math.max(0, (scrollY - after) / (end - after))) : 1;
|
|
310
|
+
writeVar(el, "--pg-anchor-progress", done.toFixed(4));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function stepAside(el: HTMLElement, all: Element[]): void {
|
|
315
|
+
// "none", for this screen size: no stepping aside, no passing under.
|
|
316
|
+
const avoids = keyword(el, "--pg-anchor-avoid", ["auto", "none"] as const) === "auto";
|
|
317
|
+
const areas = all.filter((area) => area.getAttribute(AVOID) !== "hide");
|
|
318
|
+
const under = all.filter((area) => area.getAttribute(AVOID) === "hide");
|
|
319
|
+
const rect = el.getBoundingClientRect();
|
|
320
|
+
let lift = 0;
|
|
321
|
+
let clipTop = 0;
|
|
322
|
+
let clipBottom = 0;
|
|
323
|
+
|
|
324
|
+
if (all.length && avoids) {
|
|
325
|
+
// Where it sits without the lift it has now.
|
|
326
|
+
const now = px(el.style.getPropertyValue(LIFT));
|
|
327
|
+
const top = rect.top + now;
|
|
328
|
+
const bottom = rect.bottom + now;
|
|
329
|
+
const space = px(getComputedStyle(el).getPropertyValue("--pg-anchor-avoid-space"));
|
|
330
|
+
const up = (top + bottom) / 2 > innerHeight / 2;
|
|
331
|
+
|
|
332
|
+
// Areas can sit back to back: keep stepping until clear of all.
|
|
333
|
+
for (let pass = 0; pass <= areas.length; pass++) {
|
|
334
|
+
let moved = false;
|
|
335
|
+
for (const area of areas) {
|
|
336
|
+
const a = area.getBoundingClientRect();
|
|
337
|
+
if (!a.width || !a.height || a.right <= rect.left || a.left >= rect.right) continue;
|
|
338
|
+
if (bottom - lift <= a.top - space || top - lift >= a.bottom + space) continue;
|
|
339
|
+
lift = up ? Math.max(lift, bottom - (a.top - space)) : Math.min(lift, top - (a.bottom + space));
|
|
340
|
+
moved = true;
|
|
341
|
+
}
|
|
342
|
+
if (!moved) break;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// An area taller than the screen cannot be stepped around: stay on
|
|
346
|
+
// screen, over it, rather than leave the screen.
|
|
347
|
+
if (top - lift < 0 || bottom - lift > innerHeight) lift = 0;
|
|
348
|
+
|
|
349
|
+
// "hide" areas: pass under them — the part they cover is cut off,
|
|
350
|
+
// so the element goes in at one edge and comes out at the other.
|
|
351
|
+
const at = { top: top - lift, bottom: bottom - lift };
|
|
352
|
+
for (const area of under) {
|
|
353
|
+
const a = area.getBoundingClientRect();
|
|
354
|
+
if (!a.width || !a.height || a.right <= rect.left || a.left >= rect.right) continue;
|
|
355
|
+
if (a.bottom <= at.top || a.top >= at.bottom) continue;
|
|
356
|
+
if (a.top <= at.top) clipTop = Math.max(clipTop, Math.min(a.bottom, at.bottom) - at.top);
|
|
357
|
+
if (a.bottom >= at.bottom) clipBottom = Math.max(clipBottom, at.bottom - Math.max(a.top, at.top));
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
writeVar(el, LIFT, lift ? `${Math.round(lift)}px` : "0px");
|
|
362
|
+
|
|
363
|
+
// Wide side insets keep the shadow on the sides that are not covered.
|
|
364
|
+
const cutTop = Math.round(clipTop);
|
|
365
|
+
const cutBottom = Math.round(clipBottom);
|
|
366
|
+
const covered = cutTop + cutBottom >= Math.round(rect.height);
|
|
367
|
+
writeVar(el, CLIP, cutTop || cutBottom ? `inset(${cutTop}px -100vmax ${cutBottom}px -100vmax)` : "none");
|
|
368
|
+
write(el, COVERED, String(covered));
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function spy(menu: HTMLElement): void {
|
|
372
|
+
const links = [...menu.querySelectorAll(`[${ATTR}]`)];
|
|
373
|
+
const atBottom = scrollY >= maxScroll() - 1;
|
|
374
|
+
let current: HTMLElement | null = null;
|
|
375
|
+
let best = -Infinity;
|
|
376
|
+
|
|
377
|
+
for (const link of links) {
|
|
378
|
+
const section = sectionOf(targetOf(link));
|
|
379
|
+
if (!section) continue;
|
|
380
|
+
const top = section.getBoundingClientRect().top - clearance(section, edgeOf(link));
|
|
381
|
+
// Reached the landing line (a pixel's slack for rounding) — or, at
|
|
382
|
+
// the very bottom, simply on screen: the last sections can never
|
|
383
|
+
// climb that far.
|
|
384
|
+
const reached = top <= 1 || (atBottom && top < innerHeight);
|
|
385
|
+
if (reached && top > best) {
|
|
386
|
+
best = top;
|
|
387
|
+
current = section;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
let marker: Element | null = null;
|
|
392
|
+
for (const link of links) {
|
|
393
|
+
const on = current !== null && sectionOf(targetOf(link)) === current;
|
|
394
|
+
write(link, CURRENT, String(on));
|
|
395
|
+
write(link, "aria-current", on ? "location" : null);
|
|
396
|
+
if (on && !marker) marker = link;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Where the current link sits inside the menu, for a sliding marker.
|
|
400
|
+
if (marker) {
|
|
401
|
+
const m = menu.getBoundingClientRect();
|
|
402
|
+
const r = marker.getBoundingClientRect();
|
|
403
|
+
writeVar(menu, "--pg-anchor-current-left", `${Math.round(r.left - m.left - menu.clientLeft + menu.scrollLeft)}px`);
|
|
404
|
+
writeVar(menu, "--pg-anchor-current-top", `${Math.round(r.top - m.top - menu.clientTop + menu.scrollTop)}px`);
|
|
405
|
+
writeVar(menu, "--pg-anchor-current-width", `${Math.round(r.width)}px`);
|
|
406
|
+
writeVar(menu, "--pg-anchor-current-height", `${Math.round(r.height)}px`);
|
|
407
|
+
} else {
|
|
408
|
+
writeVar(menu, "--pg-anchor-current-width", "0px");
|
|
409
|
+
writeVar(menu, "--pg-anchor-current-height", "0px");
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/* ---------- Staying in place ---------- */
|
|
414
|
+
|
|
415
|
+
/* Still this many frames in a row: whatever moved it has settled. Long
|
|
416
|
+
enough to outlast a short transition-delay before anything moves. */
|
|
417
|
+
const STILL_FRAMES = 20;
|
|
418
|
+
const STAY_LIMIT = 3000;
|
|
419
|
+
|
|
420
|
+
let stopStay = (): void => {};
|
|
421
|
+
|
|
422
|
+
/* Keep `el` where it is on screen: scroll by whatever it drifts. */
|
|
423
|
+
function stay(el: Element): void {
|
|
424
|
+
stopStay();
|
|
425
|
+
const at = el.getBoundingClientRect().top;
|
|
426
|
+
const start = performance.now();
|
|
427
|
+
let still = 0;
|
|
428
|
+
let frame = 0;
|
|
429
|
+
const user = ["wheel", "touchstart", "keydown"] as const;
|
|
430
|
+
const stop = (): void => {
|
|
431
|
+
cancelAnimationFrame(frame);
|
|
432
|
+
user.forEach((type) => removeEventListener(type, stop));
|
|
433
|
+
stopStay = () => {};
|
|
434
|
+
};
|
|
435
|
+
const step = (now: number): void => {
|
|
436
|
+
if (!el.isConnected) return stop();
|
|
437
|
+
const drift = el.getBoundingClientRect().top - at;
|
|
438
|
+
if (Math.abs(drift) >= 0.5) {
|
|
439
|
+
still = 0;
|
|
440
|
+
const top = Math.min(Math.max(0, scrollY + drift), maxScroll());
|
|
441
|
+
(scroller ?? glideTo)(top, 0, anchorEasing);
|
|
442
|
+
} else {
|
|
443
|
+
still++;
|
|
444
|
+
}
|
|
445
|
+
if (still >= STILL_FRAMES || now - start > STAY_LIMIT) stop();
|
|
446
|
+
else frame = requestAnimationFrame(step);
|
|
447
|
+
};
|
|
448
|
+
user.forEach((type) => addEventListener(type, stop, { passive: true }));
|
|
449
|
+
stopStay = stop;
|
|
450
|
+
frame = requestAnimationFrame(step);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/* ---------- Strips ---------- */
|
|
454
|
+
|
|
455
|
+
/* CSS easing keywords and cubic-bezier(), as the browser reads them. */
|
|
456
|
+
const KEYWORDS: Record<string, [number, number, number, number]> = {
|
|
457
|
+
ease: [0.25, 0.1, 0.25, 1],
|
|
458
|
+
"ease-in": [0.42, 0, 1, 1],
|
|
459
|
+
"ease-out": [0, 0, 0.58, 1],
|
|
460
|
+
"ease-in-out": [0.42, 0, 0.58, 1],
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
function bezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {
|
|
464
|
+
const at = (a: number, b: number, t: number): number => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
|
|
465
|
+
return (x) => {
|
|
466
|
+
if (x <= 0) return 0;
|
|
467
|
+
if (x >= 1) return 1;
|
|
468
|
+
// The curve's t for this x, by halving: monotonic in x for 0 ≤ x1, x2 ≤ 1.
|
|
469
|
+
let lo = 0;
|
|
470
|
+
let hi = 1;
|
|
471
|
+
for (let i = 0; i < 24; i++) {
|
|
472
|
+
const mid = (lo + hi) / 2;
|
|
473
|
+
if (at(x1, x2, mid) < x) lo = mid;
|
|
474
|
+
else hi = mid;
|
|
475
|
+
}
|
|
476
|
+
return at(y1, y2, (lo + hi) / 2);
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/* --pg-anchor-easing, --pg-anchor-strip-easing: linear, ease, ease-in,
|
|
481
|
+
ease-out, ease-in-out or cubic-bezier(…). Anything else, or nothing:
|
|
482
|
+
anchorEasing, Lenis's curve. */
|
|
483
|
+
function easingOf(el: Element, name: string): (t: number) => number {
|
|
484
|
+
const raw = getComputedStyle(el).getPropertyValue(name).trim().toLowerCase();
|
|
485
|
+
if (raw === "linear") return (t) => t;
|
|
486
|
+
if (KEYWORDS[raw]) return bezier(...KEYWORDS[raw]);
|
|
487
|
+
const m = raw.match(/^cubic-bezier\(([^)]+)\)$/);
|
|
488
|
+
const n = m ? m[1].split(",").map(Number) : [];
|
|
489
|
+
if (n.length === 4 && n.every(Number.isFinite) && n[0] >= 0 && n[0] <= 1 && n[2] >= 0 && n[2] <= 1) {
|
|
490
|
+
return bezier(n[0], n[1], n[2], n[3]);
|
|
491
|
+
}
|
|
492
|
+
return anchorEasing;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
type Strip = { item: Element | null | undefined; width: number; frame: number; stop: () => void };
|
|
497
|
+
const strips = new WeakMap<HTMLElement, Strip>();
|
|
498
|
+
|
|
499
|
+
function stripOf(el: HTMLElement): Strip {
|
|
500
|
+
let s = strips.get(el);
|
|
501
|
+
if (!s) {
|
|
502
|
+
s = { item: undefined, width: 0, frame: 0, stop: () => {} };
|
|
503
|
+
strips.set(el, s);
|
|
504
|
+
}
|
|
505
|
+
return s;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/* Where the row's scroll would put `item` as --pg-anchor-strip asks. */
|
|
509
|
+
function stripLeft(strip: HTMLElement, item: Element): number | null {
|
|
510
|
+
const align = keyword(strip, "--pg-anchor-strip", ["center", "start", "end", "none"] as const);
|
|
511
|
+
if (align === "none") return null;
|
|
512
|
+
const css = getComputedStyle(strip);
|
|
513
|
+
const rtl = css.direction === "rtl";
|
|
514
|
+
const box = strip.getBoundingClientRect();
|
|
515
|
+
const r = item.getBoundingClientRect();
|
|
516
|
+
const left = box.left + strip.clientLeft;
|
|
517
|
+
const right = left + strip.clientWidth;
|
|
518
|
+
const padLeft = px(css.scrollPaddingLeft);
|
|
519
|
+
const padRight = px(css.scrollPaddingRight);
|
|
520
|
+
const atLeft = (align === "start") !== rtl;
|
|
521
|
+
|
|
522
|
+
let delta: number;
|
|
523
|
+
if (align === "center") delta = r.left + r.width / 2 - (left + strip.clientWidth / 2);
|
|
524
|
+
else if (atLeft) delta = r.left - (left + padLeft);
|
|
525
|
+
else delta = r.right - (right - padRight);
|
|
526
|
+
|
|
527
|
+
// The ends: it can go no further — so the first items stay at the
|
|
528
|
+
// start and the last at the end, and only those between are centred.
|
|
529
|
+
const max = Math.max(0, strip.scrollWidth - strip.clientWidth);
|
|
530
|
+
const [min, top] = rtl ? [-max, 0] : [0, max];
|
|
531
|
+
return Math.min(top, Math.max(min, Math.round(strip.scrollLeft + delta)));
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function slide(strip: HTMLElement, item: Element, animate: boolean): void {
|
|
535
|
+
const state = stripOf(strip);
|
|
536
|
+
state.stop();
|
|
537
|
+
const to = stripLeft(strip, item);
|
|
538
|
+
if (to === null) return;
|
|
539
|
+
const from = strip.scrollLeft;
|
|
540
|
+
const duration = animate ? timeOf(strip, "--pg-anchor-strip-duration", DEFAULT_STRIP_DURATION) : 0;
|
|
541
|
+
if (duration <= 0 || Math.abs(to - from) < 1) {
|
|
542
|
+
strip.scrollTo({ left: to, behavior: "instant" });
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const ease = easingOf(strip, "--pg-anchor-strip-easing");
|
|
546
|
+
const start = performance.now();
|
|
547
|
+
// The user's own wheel, touch or press on the row stops it.
|
|
548
|
+
const stoppers = ["wheel", "touchstart", "pointerdown"] as const;
|
|
549
|
+
const stop = (): void => {
|
|
550
|
+
cancelAnimationFrame(state.frame);
|
|
551
|
+
state.frame = 0;
|
|
552
|
+
stoppers.forEach((type) => strip.removeEventListener(type, stop));
|
|
553
|
+
state.stop = () => {};
|
|
554
|
+
};
|
|
555
|
+
const step = (now: number): void => {
|
|
556
|
+
const t = Math.min(1, (now - start) / duration);
|
|
557
|
+
strip.scrollTo({ left: from + (to - from) * ease(t), behavior: "instant" });
|
|
558
|
+
if (t < 1) state.frame = requestAnimationFrame(step);
|
|
559
|
+
else stop();
|
|
560
|
+
};
|
|
561
|
+
stoppers.forEach((type) => strip.addEventListener(type, stop, { passive: true }));
|
|
562
|
+
state.stop = stop;
|
|
563
|
+
state.frame = requestAnimationFrame(step);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/* Keep the marked item in view; the first time, at once. When the row
|
|
567
|
+
changes width with the same item marked — a phone turned, a panel
|
|
568
|
+
beside it opened — the item is put back in place at once too: the old
|
|
569
|
+
scroll no longer shows it where it was, or at all. */
|
|
570
|
+
function follow(strip: HTMLElement): void {
|
|
571
|
+
const state = stripOf(strip);
|
|
572
|
+
const item = strip.querySelector(MARKED);
|
|
573
|
+
const width = strip.clientWidth;
|
|
574
|
+
const resized = width !== state.width;
|
|
575
|
+
state.width = width;
|
|
576
|
+
if (item === state.item) {
|
|
577
|
+
if (item && resized) slide(strip, item, false);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
const first = state.item === undefined;
|
|
581
|
+
state.item = item;
|
|
582
|
+
if (item) slide(strip, item, !first);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/* Only the newest call answers events — a late cleanup from an older one
|
|
586
|
+
(React remounting) cannot switch it off. Same rule as the other packages. */
|
|
587
|
+
let live: object | null = null;
|
|
588
|
+
|
|
589
|
+
/* Start listening; returns the cleanup for a React effect. */
|
|
590
|
+
export function initAnchor(): () => void {
|
|
591
|
+
if (typeof document === "undefined") return () => {};
|
|
592
|
+
|
|
593
|
+
const self = {};
|
|
594
|
+
live = self;
|
|
595
|
+
|
|
596
|
+
let floats: HTMLElement[] = [];
|
|
597
|
+
let areas: Element[] = [];
|
|
598
|
+
let menus: HTMLElement[] = [];
|
|
599
|
+
let rows: HTMLElement[] = [];
|
|
600
|
+
let dirty = true;
|
|
601
|
+
let frame = 0;
|
|
602
|
+
|
|
603
|
+
const update = (): void => {
|
|
604
|
+
frame = 0;
|
|
605
|
+
if (live !== self) return;
|
|
606
|
+
if (dirty) {
|
|
607
|
+
dirty = false;
|
|
608
|
+
floats = [...document.querySelectorAll<HTMLElement>(`[${VISIBLE}]`)];
|
|
609
|
+
areas = [...document.querySelectorAll(`[${AVOID}]`)];
|
|
610
|
+
menus = [...document.querySelectorAll<HTMLElement>(`[${SPY}]`)];
|
|
611
|
+
rows = [...document.querySelectorAll<HTMLElement>(`[${STRIP}]`)];
|
|
612
|
+
rowSizes?.disconnect();
|
|
613
|
+
rows.forEach((row) => rowSizes?.observe(row));
|
|
614
|
+
document.querySelectorAll(`[${ATTR}]`).forEach(reachable);
|
|
615
|
+
}
|
|
616
|
+
floats.forEach((el) => {
|
|
617
|
+
show(el);
|
|
618
|
+
stepAside(el, areas);
|
|
619
|
+
});
|
|
620
|
+
menus.forEach(spy);
|
|
621
|
+
// After the spy: a spy menu that is a strip follows its own mark.
|
|
622
|
+
rows.forEach(follow);
|
|
623
|
+
};
|
|
624
|
+
const schedule = (): void => {
|
|
625
|
+
if (!frame) frame = requestAnimationFrame(update);
|
|
626
|
+
};
|
|
627
|
+
// A strip's own width, not the window's: a row can narrow while the
|
|
628
|
+
// window stays — a panel beside it opens.
|
|
629
|
+
const rowSizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
|
|
630
|
+
|
|
631
|
+
const onClick = (event: MouseEvent): void => {
|
|
632
|
+
if (live !== self || event.button !== 0 || !(event.target instanceof Element)) return;
|
|
633
|
+
|
|
634
|
+
// In a strip with nothing marked, the item clicked comes into view.
|
|
635
|
+
// A marked one is followed by update(), once the click has marked it.
|
|
636
|
+
const row = event.target.closest<HTMLElement>(`[${STRIP}]`);
|
|
637
|
+
const item = row && event.target.closest(ITEM);
|
|
638
|
+
if (row && item && item !== row && row.contains(item)) {
|
|
639
|
+
requestAnimationFrame(() => {
|
|
640
|
+
if (live === self && !row.querySelector(MARKED)) slide(row, item, true);
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
const el = event.target.closest(`[${ATTR}]`);
|
|
645
|
+
if (!el) return;
|
|
646
|
+
// A link opened in a new tab or window stays the browser's.
|
|
647
|
+
if (isLink(el) && (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) return;
|
|
648
|
+
const target = targetOf(el);
|
|
649
|
+
if (target !== "top" && target !== "bottom" && !sectionOf(target)) return;
|
|
650
|
+
event.preventDefault();
|
|
651
|
+
// detail is 0 for a click that came from the keyboard.
|
|
652
|
+
const byKeyboard = event.detail === 0;
|
|
653
|
+
// What it asks for now, while it is there; the page a frame later:
|
|
654
|
+
// a menu closed by this same click unlocks the page first, and the
|
|
655
|
+
// section is measured where it has settled.
|
|
656
|
+
const ask = askOf(el);
|
|
657
|
+
requestAnimationFrame(() => go(ask, target, byKeyboard));
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
// Before any other click handler — targetFunctions closing the answer
|
|
661
|
+
// above — so the place is noted while nothing has moved yet.
|
|
662
|
+
const onClickFirst = (event: MouseEvent): void => {
|
|
663
|
+
if (live !== self || !(event.target instanceof Element)) return;
|
|
664
|
+
const box = event.target.closest(`[${STAY}]`);
|
|
665
|
+
const item = box && event.target.closest(ITEM);
|
|
666
|
+
// An item that scrolls the page itself is left to do that.
|
|
667
|
+
if (!box || !item || !box.contains(item) || item.hasAttribute(ATTR)) return;
|
|
668
|
+
if (keyword(item, "--pg-anchor-stay", ["auto", "none"] as const) === "none") return;
|
|
669
|
+
stay(item);
|
|
670
|
+
};
|
|
671
|
+
|
|
672
|
+
const onKeydown = (event: KeyboardEvent): void => {
|
|
673
|
+
if (live !== self || event.key !== "Enter" || !(event.target instanceof Element)) return;
|
|
674
|
+
const el = event.target.closest(`[${ATTR}]`);
|
|
675
|
+
if (!el || isNative(el) || el !== event.target) return;
|
|
676
|
+
event.preventDefault();
|
|
677
|
+
(el as HTMLElement).click();
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// The marks a strip follows change often — the spy's, a tab's — and
|
|
681
|
+
// need no new look round the page; anything else does.
|
|
682
|
+
const MARKS = ["aria-current", "aria-selected", "aria-expanded"];
|
|
683
|
+
const mo = new MutationObserver((records) => {
|
|
684
|
+
if (records.some((r) => !r.attributeName || !MARKS.includes(r.attributeName))) dirty = true;
|
|
685
|
+
schedule();
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
document.addEventListener("click", onClickFirst, true);
|
|
689
|
+
document.addEventListener("click", onClick);
|
|
690
|
+
document.addEventListener("keydown", onKeydown);
|
|
691
|
+
addEventListener("scroll", schedule, { passive: true });
|
|
692
|
+
addEventListener("resize", schedule);
|
|
693
|
+
addEventListener("load", schedule);
|
|
694
|
+
mo.observe(document.body, {
|
|
695
|
+
childList: true,
|
|
696
|
+
subtree: true,
|
|
697
|
+
attributes: true,
|
|
698
|
+
attributeFilter: [ATTR, VISIBLE, PROGRESS, AVOID, SPY, STRIP, ...MARKS],
|
|
699
|
+
});
|
|
700
|
+
// Now, not a frame later: a strip shows its current item from the start.
|
|
701
|
+
update();
|
|
702
|
+
|
|
703
|
+
return () => {
|
|
704
|
+
document.removeEventListener("click", onClickFirst, true);
|
|
705
|
+
document.removeEventListener("click", onClick);
|
|
706
|
+
stopStay();
|
|
707
|
+
document.removeEventListener("keydown", onKeydown);
|
|
708
|
+
removeEventListener("scroll", schedule);
|
|
709
|
+
removeEventListener("resize", schedule);
|
|
710
|
+
removeEventListener("load", schedule);
|
|
711
|
+
mo.disconnect();
|
|
712
|
+
rowSizes?.disconnect();
|
|
713
|
+
if (frame) cancelAnimationFrame(frame);
|
|
714
|
+
if (live === self) live = null;
|
|
715
|
+
};
|
|
716
|
+
}
|