@plusguard/anchor 0.0.0-stage → 3.4.0

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