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