@plusguard/anchor 3.3.2 → 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/README.md CHANGED
@@ -38,16 +38,16 @@ Load both halves straight from jsDelivr — no install, and the page works
38
38
  when opened by double-clicking:
39
39
 
40
40
  ```html
41
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@plusguard/anchor@3.3.2/index.css" />
41
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@plusguard/anchor@3.4.0/index.css" />
42
42
 
43
43
  <script type="module">
44
- import { initAnchor } from "https://cdn.jsdelivr.net/npm/@plusguard/anchor@3.3.2/dist/index.js";
44
+ import { initAnchor } from "https://cdn.jsdelivr.net/npm/@plusguard/anchor@3.4.0/dist/index.js";
45
45
 
46
46
  initAnchor();
47
47
  </script>
48
48
  ```
49
49
 
50
- Pin the version (`@3.3.2`) on a live site. A pinned URL never changes;
50
+ Pin the version (`@3.4.0`) on a live site. A pinned URL never changes;
51
51
  `@3` follows the newest 3.x release.
52
52
 
53
53
  ## Who does what
@@ -79,6 +79,7 @@ enough; this package is for the rest.
79
79
  | `index.css` | The CSS half: the lengths, hiding, stepping aside, passing under |
80
80
  | `dist/index.js` | Compiled ES module — plain HTML, no build step |
81
81
  | `dist/index.d.ts` | Types for `dist/index.js` |
82
+ | `early.js` | A small classic script for `<head>`: on a reload, the back-to-top button from the first frame (see Back to top) |
82
83
 
83
84
  Importing `dist/index.js` from your own files? Serve the page over HTTP —
84
85
  browsers block module imports on `file://`.
@@ -291,6 +292,27 @@ in step with what is open.
291
292
  - **Showing.** `data-pg-anchor-visible` turns `"true"` once the page has
292
293
  scrolled `--pg-anchor-show-after`. `index.css` hides the `"false"` state
293
294
  at zero weight — add your own transition to fade it.
295
+ - **On a reload — `early.js`.** The browser puts a reloaded page back
296
+ where it was at once, but the button would come a moment later, once the
297
+ module has measured the scroll. As the page is left, `initAnchor()`
298
+ notes whether its floating elements are showing (and how far round the
299
+ ring is) in `sessionStorage`; `early.js`, a small classic script in
300
+ `<head>`, reads that before anything is drawn and marks `<html>` with
301
+ `data-pg-anchor-early="shown"` — `index.css` then shows them from the
302
+ first frame, the ring where it was, with no fade. Once the page has
303
+ loaded, `initAnchor()` measures again and takes over. Only on a reload
304
+ or Back/Forward, where the browser restores the scroll — a fresh visit
305
+ starts at the top, and so does the button; and only when every floating
306
+ element was showing, so none ever shows that should not.
307
+
308
+ ```html
309
+ <head>
310
+ …
311
+ <script src="https://cdn.jsdelivr.net/npm/@plusguard/anchor@3.4.0/early.js"></script>
312
+ </head>
313
+ ```
314
+
315
+ Not deferred, not a module — or its text written inline there.
294
316
  - **A ring that fills — `data-pg-anchor-progress`.** Round the button, on
295
317
  its edge: empty where it first shows, full at the end of the page,
296
318
  filling from the top, clockwise, as the page scrolls — and emptying as it
@@ -617,6 +639,25 @@ useEffect(() => {
617
639
  If `initAnchor` is called again before the first cleanup runs (React
618
640
  remounting in development), only the newest call answers.
619
641
 
642
+ `early.js` goes in the root layout's `<head>` — inline, so the page waits
643
+ for no extra file. It marks `<html>` only, never the button, so only
644
+ `<html>` needs `suppressHydrationWarning` (a theme script usually has it
645
+ there already). In Next, a server component can read the file's text:
646
+
647
+ ```tsx
648
+ import { readFileSync } from "node:fs";
649
+ import path from "node:path";
650
+
651
+ // From the app's folder, where next runs.
652
+ const early = readFileSync(path.join(process.cwd(), "node_modules/@plusguard/anchor/early.js"), "utf8");
653
+
654
+ // in the root layout:
655
+ <html suppressHydrationWarning>
656
+ <head>
657
+ <script dangerouslySetInnerHTML={{ __html: early }} />
658
+ </head>
659
+ ```
660
+
620
661
  See [`examples/react/Example.tsx`](examples/react/Example.tsx). A plain HTML
621
662
  version, with every case above and a `?lenis` switch, is in
622
663
  [`examples/static/index.html`](examples/static/index.html) — an accordion
package/dist/index.js CHANGED
@@ -48,6 +48,10 @@
48
48
  * is cut off; wholly under, it gets
49
49
  * data-pg-anchor-covered="true"
50
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
+ *
51
55
  * Spy: in a data-pg-anchor-spy menu, the links whose section has reached
52
56
  * the landing line get data-pg-anchor-current="true" and
53
57
  * aria-current="location"; the menu gets --pg-anchor-current-left / -top /
@@ -81,6 +85,11 @@ const CURRENT = "data-pg-anchor-current";
81
85
  const COVERED = "data-pg-anchor-covered";
82
86
  const STRIP = "data-pg-anchor-strip";
83
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";
84
93
  const LIFT = "--pg-anchor-lift";
85
94
  const CLIP = "--pg-anchor-clip";
86
95
  const DEFAULT_DURATION = 1200;
@@ -270,16 +279,25 @@ function writeVar(el, name, value) {
270
279
  if (el.style.getPropertyValue(name) !== value)
271
280
  el.style.setProperty(name, value);
272
281
  }
273
- function show(el) {
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) {
274
288
  const raw = getComputedStyle(el).getPropertyValue("--pg-anchor-show-after");
275
289
  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;
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))
281
300
  writeVar(el, "--pg-anchor-progress", done.toFixed(4));
282
- }
283
301
  }
284
302
  function stepAside(el, all) {
285
303
  // "none", for this screen size: no stepping aside, no passing under.
@@ -569,6 +587,8 @@ export function initAnchor() {
569
587
  let rows = [];
570
588
  let dirty = true;
571
589
  let frame = 0;
590
+ const root = document.documentElement;
591
+ let holding = root.getAttribute(EARLY) === "shown";
572
592
  const update = () => {
573
593
  frame = 0;
574
594
  if (live !== self)
@@ -584,7 +604,7 @@ export function initAnchor() {
584
604
  document.querySelectorAll(`[${ATTR}]`).forEach(reachable);
585
605
  }
586
606
  floats.forEach((el) => {
587
- show(el);
607
+ show(el, holding);
588
608
  stepAside(el, areas);
589
609
  });
590
610
  menus.forEach(spy);
@@ -595,6 +615,51 @@ export function initAnchor() {
595
615
  if (!frame)
596
616
  frame = requestAnimationFrame(update);
597
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
+ };
598
663
  // A strip's own width, not the window's: a row can narrow while the
599
664
  // window stays — a panel beside it opens.
600
665
  const rowSizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
@@ -665,7 +730,8 @@ export function initAnchor() {
665
730
  document.addEventListener("keydown", onKeydown);
666
731
  addEventListener("scroll", schedule, { passive: true });
667
732
  addEventListener("resize", schedule);
668
- addEventListener("load", schedule);
733
+ addEventListener("load", onLoad);
734
+ addEventListener("pagehide", onPagehide);
669
735
  mo.observe(document.body, {
670
736
  childList: true,
671
737
  subtree: true,
@@ -674,6 +740,8 @@ export function initAnchor() {
674
740
  });
675
741
  // Now, not a frame later: a strip shows its current item from the start.
676
742
  update();
743
+ if (holding && document.readyState === "complete")
744
+ setTimeout(settle);
677
745
  return () => {
678
746
  document.removeEventListener("click", onClickFirst, true);
679
747
  document.removeEventListener("click", onClick);
@@ -681,7 +749,8 @@ export function initAnchor() {
681
749
  document.removeEventListener("keydown", onKeydown);
682
750
  removeEventListener("scroll", schedule);
683
751
  removeEventListener("resize", schedule);
684
- removeEventListener("load", schedule);
752
+ removeEventListener("load", onLoad);
753
+ removeEventListener("pagehide", onPagehide);
685
754
  mo.disconnect();
686
755
  rowSizes?.disconnect();
687
756
  if (frame)
package/early.js ADDED
@@ -0,0 +1,37 @@
1
+ /*
2
+ * anchor — early.js: on a reload, the back-to-top button where it was.
3
+ *
4
+ * A data-pg-anchor-visible element shows once initAnchor() has measured
5
+ * the scroll — a moment after the page is drawn. On a reload halfway down,
6
+ * the browser puts the page back where it was at once, but the button
7
+ * comes a moment later. initAnchor() notes, as the page is left, whether
8
+ * its floating elements were showing; this little script reads that before
9
+ * anything is drawn and marks <html> with data-pg-anchor-early="shown" —
10
+ * index.css shows them from the first frame, and initAnchor() takes over
11
+ * once the page has loaded.
12
+ *
13
+ * Only on a reload or Back/Forward to the same address, where the browser
14
+ * restores the scroll; a fresh visit starts at the top, as the button does.
15
+ *
16
+ * A classic script in <head> — not deferred, not a module: this file from
17
+ * the CDN as its src, or its text written inline there (README). No
18
+ * dependencies; nothing to call. Nothing here may spell the tag that ends
19
+ * a script, so that the text can be inlined as it is.
20
+ */
21
+ (function () {
22
+ var nav = performance.getEntriesByType && performance.getEntriesByType("navigation")[0];
23
+ var type = nav ? nav.type : "";
24
+ if (type !== "reload" && type !== "back_forward") return;
25
+ if (history.scrollRestoration === "manual") return;
26
+ var saved;
27
+ try {
28
+ saved = JSON.parse(sessionStorage.getItem("pg-anchor-early") || "{}")[location.pathname + location.search];
29
+ } catch (e) {
30
+ return;
31
+ }
32
+ if (!saved || saved.shown !== true) return;
33
+ var root = document.documentElement;
34
+ root.setAttribute("data-pg-anchor-early", "shown");
35
+ // The ring, as far round as it was.
36
+ if (typeof saved.progress === "number") root.style.setProperty("--pg-anchor-early-progress", String(saved.progress));
37
+ })();
package/index.css CHANGED
@@ -120,6 +120,16 @@
120
120
  visibility: hidden;
121
121
  opacity: 0;
122
122
  }
123
+ /* A reload halfway down: early.js marked <html> before the first frame,
124
+ so it shows from that frame, its ring as far round as it was —
125
+ until initAnchor() has the real scroll (index.ts). */
126
+ :where(html[data-pg-anchor-early="shown"]) :where([data-pg-anchor-visible="false"]) {
127
+ visibility: visible;
128
+ opacity: 1;
129
+ }
130
+ :where(html[data-pg-anchor-early="shown"]) :where([data-pg-anchor-progress]) {
131
+ --pg-anchor-progress: var(--pg-anchor-early-progress, 0);
132
+ }
123
133
  }
124
134
 
125
135
  /* Out of the way of an avoided area, by as much as index.ts measured. The
package/index.ts CHANGED
@@ -48,6 +48,10 @@
48
48
  * is cut off; wholly under, it gets
49
49
  * data-pg-anchor-covered="true"
50
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
+ *
51
55
  * Spy: in a data-pg-anchor-spy menu, the links whose section has reached
52
56
  * the landing line get data-pg-anchor-current="true" and
53
57
  * aria-current="location"; the menu gets --pg-anchor-current-left / -top /
@@ -82,6 +86,11 @@ const CURRENT = "data-pg-anchor-current";
82
86
  const COVERED = "data-pg-anchor-covered";
83
87
  const STRIP = "data-pg-anchor-strip";
84
88
  const STAY = "data-pg-anchor-stay";
89
+ const EARLY = "data-pg-anchor-early";
90
+ const EARLY_PROGRESS = "--pg-anchor-early-progress";
91
+ /* What early.js reads on a reload: per address, whether the floating
92
+ elements were showing as the page was left. */
93
+ const EARLY_STORE = "pg-anchor-early";
85
94
  const LIFT = "--pg-anchor-lift";
86
95
  const CLIP = "--pg-anchor-clip";
87
96
 
@@ -299,16 +308,24 @@ function writeVar(el: HTMLElement, name: string, value: string): void {
299
308
  if (el.style.getPropertyValue(name) !== value) el.style.setProperty(name, value);
300
309
  }
301
310
 
302
- function show(el: HTMLElement): void {
311
+ /* holding: early.js showed it on a reload and the page has not loaded yet —
312
+ the browser may not have put the scroll back, so a "not yet" is not
313
+ believed; it stays as early.js drew it. */
314
+ /* Where it stands now: showing or not, and how far round its ring is —
315
+ from where it showed (0) to the end of the page (1). */
316
+ function measure(el: HTMLElement): { shown: boolean; done: number } {
303
317
  const raw = getComputedStyle(el).getPropertyValue("--pg-anchor-show-after");
304
318
  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
- }
319
+ const end = maxScroll();
320
+ const done = end > after ? Math.min(1, Math.max(0, (scrollY - after) / (end - after))) : 1;
321
+ return { shown: scrollY >= after, done };
322
+ }
323
+
324
+ function show(el: HTMLElement, holding = false): void {
325
+ const { shown, done } = measure(el);
326
+ if (holding && !shown) return;
327
+ write(el, VISIBLE, String(shown));
328
+ if (el.hasAttribute(PROGRESS)) writeVar(el, "--pg-anchor-progress", done.toFixed(4));
312
329
  }
313
330
 
314
331
  function stepAside(el: HTMLElement, all: Element[]): void {
@@ -599,6 +616,8 @@ export function initAnchor(): () => void {
599
616
  let rows: HTMLElement[] = [];
600
617
  let dirty = true;
601
618
  let frame = 0;
619
+ const root = document.documentElement;
620
+ let holding = root.getAttribute(EARLY) === "shown";
602
621
 
603
622
  const update = (): void => {
604
623
  frame = 0;
@@ -614,7 +633,7 @@ export function initAnchor(): () => void {
614
633
  document.querySelectorAll(`[${ATTR}]`).forEach(reachable);
615
634
  }
616
635
  floats.forEach((el) => {
617
- show(el);
636
+ show(el, holding);
618
637
  stepAside(el, areas);
619
638
  });
620
639
  menus.forEach(spy);
@@ -624,6 +643,48 @@ export function initAnchor(): () => void {
624
643
  const schedule = (): void => {
625
644
  if (!frame) frame = requestAnimationFrame(update);
626
645
  };
646
+ // Loaded, and a task on: the scroll is back where it was, so the
647
+ // floating elements are measured from now on, not held. A timer, not a
648
+ // frame — a tab opened in the background draws no frames.
649
+ const settle = (): void => {
650
+ if (!holding || live !== self) return;
651
+ holding = false;
652
+ root.removeAttribute(EARLY);
653
+ root.style.removeProperty(EARLY_PROGRESS);
654
+ if (!root.getAttribute("style")) root.removeAttribute("style");
655
+ schedule();
656
+ };
657
+ const onLoad = (): void => {
658
+ schedule();
659
+ setTimeout(settle);
660
+ };
661
+
662
+ // Leaving the page (a reload too): note for early.js whether the
663
+ // floating elements are showing, and how far round the first ring is —
664
+ // measured now, not read from what was last drawn, which may lag.
665
+ const onPagehide = (): void => {
666
+ if (live !== self) return;
667
+ const all = [...document.querySelectorAll<HTMLElement>(`[${VISIBLE}]`)];
668
+ if (!all.length) return;
669
+ const ring = all.find((el) => el.hasAttribute(PROGRESS));
670
+ const note = {
671
+ shown: all.every((el) => measure(el).shown),
672
+ progress: ring ? Number(measure(ring).done.toFixed(4)) : undefined,
673
+ };
674
+ try {
675
+ const notes = JSON.parse(sessionStorage.getItem(EARLY_STORE) || "{}");
676
+ const key = location.pathname + location.search;
677
+ delete notes[key];
678
+ notes[key] = note;
679
+ // The newest 20 addresses are enough for Back and reloads.
680
+ const keys = Object.keys(notes);
681
+ keys.slice(0, Math.max(0, keys.length - 20)).forEach((k) => delete notes[k]);
682
+ sessionStorage.setItem(EARLY_STORE, JSON.stringify(notes));
683
+ } catch {
684
+ // Storage full or blocked: the button comes a moment later, as before.
685
+ }
686
+ };
687
+
627
688
  // A strip's own width, not the window's: a row can narrow while the
628
689
  // window stays — a panel beside it opens.
629
690
  const rowSizes = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(schedule);
@@ -690,7 +751,8 @@ export function initAnchor(): () => void {
690
751
  document.addEventListener("keydown", onKeydown);
691
752
  addEventListener("scroll", schedule, { passive: true });
692
753
  addEventListener("resize", schedule);
693
- addEventListener("load", schedule);
754
+ addEventListener("load", onLoad);
755
+ addEventListener("pagehide", onPagehide);
694
756
  mo.observe(document.body, {
695
757
  childList: true,
696
758
  subtree: true,
@@ -699,6 +761,7 @@ export function initAnchor(): () => void {
699
761
  });
700
762
  // Now, not a frame later: a strip shows its current item from the start.
701
763
  update();
764
+ if (holding && document.readyState === "complete") setTimeout(settle);
702
765
 
703
766
  return () => {
704
767
  document.removeEventListener("click", onClickFirst, true);
@@ -707,7 +770,8 @@ export function initAnchor(): () => void {
707
770
  document.removeEventListener("keydown", onKeydown);
708
771
  removeEventListener("scroll", schedule);
709
772
  removeEventListener("resize", schedule);
710
- removeEventListener("load", schedule);
773
+ removeEventListener("load", onLoad);
774
+ removeEventListener("pagehide", onPagehide);
711
775
  mo.disconnect();
712
776
  rowSizes?.disconnect();
713
777
  if (frame) cancelAnimationFrame(frame);
package/package.json CHANGED
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@plusguard/anchor",
3
- "version": "3.3.2",
3
+ "version": "3.4.0",
4
4
  "description": "In-page scrolling from HTML attributes: to a section, the top or the bottom, with a set duration — with or without Lenis. A back-to-top button that shows after a set scroll and steps out of the way of marked elements. Zero dependencies, framework-agnostic. CSS included.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "exports": {
9
9
  ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
10
- "./index.css": "./index.css"
10
+ "./index.css": "./index.css",
11
+ "./early.js": "./early.js"
11
12
  },
12
- "files": ["dist", "index.ts", "index.css", "README.md", "LICENSE"],
13
+ "files": ["dist", "index.ts", "index.css", "early.js", "README.md", "LICENSE"],
13
14
  "sideEffects": ["*.css"],
14
15
  "scripts": {
15
16
  "build": "npx -p typescript tsc index.ts --outDir dist --declaration --target es2020 --module es2020 --lib dom,es2020 --strict"