Skip to content

Isometric line figures that answer the pointer. For React and for anything with a DOM.

Docs sidebar: a black dot flies to the section in view and its text steps aside, in place of the grey pill

Lucas Marques3aa206562460
diff --git a/apps/site/app/globals.css b/apps/site/app/globals.css
index 3a58e7f..a9ba237 100644
--- a/apps/site/app/globals.css
+++ b/apps/site/app/globals.css
@@ -120,15 +120,23 @@ em { font-style: italic; }
.doc-more:hover { text-decoration-color: currentColor; }
/* The sidebar: the same links twice, grouped in a column from 1024px, one sideways strip under the top bar below it. */
-.doc-link { display: flex; align-items: center; height: 32px; padding: 0 10px; border-radius: 8px; font-size: 14px; color: var(--color-muted); white-space: nowrap; transition: background-color 150ms ease, color 150ms ease; }
-.doc-link:hover { color: var(--color-ink); }
-.doc-link[aria-current] { color: var(--color-ink); background: var(--color-stone); }
+.doc-link { display: flex; align-items: center; height: 32px; padding: 0 10px; border-radius: 8px; font-size: 14px; color: var(--color-muted); white-space: nowrap; transition: color 200ms ease; }
+.doc-link:hover, .doc-link[aria-current] { color: var(--color-ink); }
+/* The marked link's text steps aside for a dot that flies in from the link marked before. The old text steps back at
+ once and the new one steps aside as the dot lands, so the two never meet. Nothing moves until the first mark is
+ drawn: the page opens with it in place. */
+.doc-link > span { display: inline-block; }
+.doc-link[aria-current] > span { transform: translateX(12px); }
+[data-live] .doc-link > span { transition: transform 250ms var(--ease-out); }
+[data-live] .doc-link[aria-current] > span { transition-duration: 300ms; transition-delay: 160ms; }
+.doc-dot { position: absolute; top: 0; left: 0; width: 5px; height: 5px; border-radius: 50%; background: var(--color-ink); pointer-events: none; }
+[data-live] > .doc-dot { transition: translate 350ms var(--ease-out); }
.doc-sidebar { display: none; }
.doc-group-label { margin-bottom: 4px; padding: 0 10px; font-size: 12px; font-weight: 500; color: var(--color-muted); }
.doc-strip { position: sticky; top: var(--topbar); z-index: 9; margin: 0 calc(-1 * var(--gutter)); background: color-mix(in srgb, var(--color-canvas) 82%, transparent); backdrop-filter: blur(12px); }
-.doc-strip-scroll { overflow-x: auto; padding: 6px var(--gutter); scrollbar-width: none; }
+.doc-strip-scroll { position: relative; overflow-x: auto; padding: 6px var(--gutter); scrollbar-width: none; }
.doc-strip-scroll::-webkit-scrollbar { display: none; }
-.doc-strip-scroll ul { display: flex; gap: 2px; width: max-content; }
+.doc-strip-scroll ul { display: flex; gap: 8px; width: max-content; }
.doc-strip-scroll[data-start] { mask-image: linear-gradient(to right, transparent, #000 24px); }
.doc-strip-scroll[data-end] { mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent); }
.doc-strip-scroll[data-start][data-end] { mask-image: linear-gradient(to right, transparent, #000 24px, #000 calc(100% - 24px), transparent); }
@@ -136,7 +144,9 @@ em { font-style: italic; }
.docs { --doc-offset: calc(var(--topbar) + 24px); display: grid; grid-template-columns: 220px minmax(0, 1fr); column-gap: 56px; padding-top: 64px; }
.docs-main { padding-top: 0; }
.doc-strip { display: none; }
- .doc-sidebar { display: grid; gap: 24px; align-self: start; position: sticky; top: calc(var(--topbar) + 24px); }
+ /* short enough to fit the window from where it starts, 64px under the top bar, with 24px to spare; a shorter
+ window scrolls it */
+ .doc-sidebar { display: grid; gap: 24px; align-self: start; position: sticky; top: calc(var(--topbar) + 24px); max-height: calc(100vh - var(--topbar) - 88px); overflow-y: auto; scrollbar-width: thin; }
}
/* The hero: each block rises out of a blur, one after another. */
@@ -229,4 +239,5 @@ em { font-style: italic; }
.hero-rise > *, .enter, .enter-hint { animation-name: fade; }
.slide[data-ready] .slide-hl { transition: none; }
.icopy-b, .icopy[data-copied] .icopy-a { transform: none; filter: none; }
+ [data-live] > .doc-dot, [data-live] .doc-link > span { transition: none; }
}
diff --git a/apps/site/components/sidebar.tsx b/apps/site/components/sidebar.tsx
index 53e87f4..2f9f24c 100644
--- a/apps/site/components/sidebar.tsx
+++ b/apps/site/components/sidebar.tsx
@@ -1,55 +1,87 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { SECTIONS, type Group } from "@/lib/docs";
const GROUPS = [...new Set(SECTIONS.map((s) => s.group))] as Group[];
const LAST = SECTIONS[SECTIONS.length - 1].id;
/**
- * The docs' anchors: grouped in a column beside the page from 1024px, one
- * sideways strip under the top bar below it. Both are plain links, so they
- * work without JavaScript; the script only marks the section in view, which
- * is the first one, in page order, inside a band from under the sticky
- * chrome to 30% down the viewport.
+ * The section in view: the first one, in page order, inside a band from under the sticky chrome (a section's
+ * scroll-margin-top, read each time, as it differs on a phone) to 30% down the viewport. Null in a gap between two
+ * sections, where the mark stays put.
+ */
+function inView(sections: HTMLElement[]): string | null {
+ const top = parseFloat(getComputedStyle(sections[0]).scrollMarginTop) || 0;
+ const bottom = window.innerHeight * 0.3;
+ if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2) {
+ // the last section is too short to reach the band, so the end of the page marks it; unless the reader asked for
+ // a section the page could only bring into view, on a screen taller than what is left below it
+ const asked = sections.find((s) => `#${s.id}` === window.location.hash);
+ const at = asked?.getBoundingClientRect();
+ return asked && at && at.top >= 0 && at.top < window.innerHeight ? asked.id : LAST;
+ }
+ const hit = sections.find((s) => {
+ const at = s.getBoundingClientRect();
+ return at.bottom > top && at.top < bottom;
+ });
+ if (hit) return hit.id;
+ // above the first section nothing is in the band, so Install is marked, as at the top
+ return sections[0].getBoundingClientRect().top >= bottom ? SECTIONS[0].id : null;
+}
+
+/**
+ * Puts a list's dot by the marked link's text, on its centre line. The first time, the dot appears in place; after
+ * that it flies there, and in the column it swings out to the left on the way, like a thrown thing.
+ */
+function place(list: HTMLElement | null, active: string, swing: boolean) {
+ const dot = list?.querySelector<HTMLElement>(".doc-dot");
+ const link = list?.querySelector<HTMLElement>(`a[href="#${active}"]`);
+ if (!list || !dot || !link || !list.clientWidth) return;
+ const box = list.getBoundingClientRect();
+ const at = link.getBoundingClientRect();
+ const x = at.left - box.left + list.scrollLeft + parseFloat(getComputedStyle(link).paddingLeft);
+ const y = at.top - box.top + list.scrollTop + (at.height - dot.offsetHeight) / 2;
+ const to = `${x}px ${y}px`;
+ if (dot.style.translate === to) return;
+ if (!list.hasAttribute("data-live")) {
+ dot.style.translate = to;
+ // transitions start once the first mark has been drawn, so the page opens with it in place
+ requestAnimationFrame(() => requestAnimationFrame(() => list.setAttribute("data-live", "")));
+ return;
+ }
+ dot.style.translate = to;
+ if (swing && !matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ dot.animate([{ transform: "none" }, { transform: "translateX(-10px)", offset: 0.35 }, { transform: "none" }], { duration: 350, easing: "ease-in-out" });
+ }
+}
+
+/**
+ * The docs' anchors: grouped in a column beside the page from 1024px, one sideways strip under the top bar below it.
+ * Both are plain links, so they work without JavaScript; the script marks the section in view with a dot, and
+ * nothing is marked until it runs.
*/
export function Sidebar() {
- const [active, setActive] = useState(SECTIONS[0].id);
+ const [active, setActive] = useState<string | null>(null);
const [edges, setEdges] = useState({ start: false, end: false });
+ const column = useRef<HTMLElement>(null);
const strip = useRef<HTMLDivElement>(null);
useEffect(() => {
const sections = SECTIONS.map((s) => document.getElementById(s.id)).filter((el): el is HTMLElement => el !== null);
if (!sections.length) return;
- // the band starts where a section lands after a click: its scroll-margin-top, under the top bar and on a phone the strip
- const offset = parseFloat(getComputedStyle(sections[0]).scrollMarginTop) || 0;
- const inBand = new Set<string>();
const pick = () => {
- const end = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2;
- // the last section is too short to reach the band, so the end of the page marks it
- if (end) return setActive(LAST);
- const first = SECTIONS.find((s) => inBand.has(s.id));
- if (first) setActive(first.id);
- // above the first section nothing is in the band, so Install is active again, as on load
- else if (sections[0].getBoundingClientRect().top >= window.innerHeight * 0.3) setActive(SECTIONS[0].id);
+ const id = inView(sections);
+ if (id) setActive(id);
};
- const observer = new IntersectionObserver(
- (entries) => {
- for (const entry of entries) {
- if (entry.isIntersecting) inBand.add(entry.target.id);
- else inBand.delete(entry.target.id);
- }
- pick();
- },
- { rootMargin: `-${offset}px 0px -70% 0px` },
- );
- for (const el of sections) observer.observe(el);
+ pick();
window.addEventListener("scroll", pick, { passive: true });
+ window.addEventListener("resize", pick);
// the browser has already scrolled to a deep link's section, at once; the reader's own clicks from here on glide
document.documentElement.dataset.smooth = "";
return () => {
- observer.disconnect();
window.removeEventListener("scroll", pick);
+ window.removeEventListener("resize", pick);
delete document.documentElement.dataset.smooth;
};
}, []);
@@ -68,6 +100,20 @@ export function Sidebar() {
};
}, []);
+ // before paint, so the dot is never drawn by a link that is no longer marked
+ useLayoutEffect(() => {
+ if (!active) return;
+ const both = () => {
+ place(column.current, active, true);
+ place(strip.current, active, false);
+ };
+ both();
+ // a list that was hidden shows, or the window changes width: the dot keeps to its link
+ const resize = new ResizeObserver(both);
+ for (const el of [column.current, strip.current]) if (el) resize.observe(el);
+ return () => resize.disconnect();
+ }, [active]);
+
// Brings the marked item into the strip by scrolling the strip alone. scrollIntoView would also scroll the
// page, and would cut short the smooth scroll a click on the strip has just started.
useEffect(() => {
@@ -75,29 +121,36 @@ export function Sidebar() {
const item = el?.querySelector<HTMLElement>(`a[href="#${active}"]`);
if (!el || !item || !el.clientWidth) return;
const pad = 24;
- if (item.offsetLeft - pad < el.scrollLeft) el.scrollTo({ left: item.offsetLeft - pad });
- else if (item.offsetLeft + item.offsetWidth + pad > el.scrollLeft + el.clientWidth) el.scrollTo({ left: item.offsetLeft + item.offsetWidth + pad - el.clientWidth });
+ const box = el.getBoundingClientRect();
+ const at = item.getBoundingClientRect();
+ if (at.left - pad < box.left) el.scrollTo({ left: el.scrollLeft + at.left - pad - box.left });
+ else if (at.right + pad > box.right) el.scrollTo({ left: el.scrollLeft + at.right + pad - box.right });
}, [active]);
const link = (id: string, title: string) => (
<li key={id}>
- <a href={`#${id}`} className="doc-link" aria-current={id === active ? "location" : undefined}>{title}</a>
+ <a href={`#${id}`} className="doc-link" aria-current={id === active ? "location" : undefined}>
+ <span>{title}</span>
+ </a>
</li>
);
+ const dot = active && <span className="doc-dot" aria-hidden />;
return (
<>
- <nav aria-label="Docs" className="doc-sidebar">
+ <nav ref={column} aria-label="Docs" className="doc-sidebar">
{GROUPS.map((group) => (
<div key={group} className="doc-group">
<p className="doc-group-label">{group}</p>
<ul>{SECTIONS.filter((s) => s.group === group).map((s) => link(s.id, s.title))}</ul>
</div>
))}
+ {dot}
</nav>
<nav aria-label="Docs" className="doc-strip">
<div ref={strip} className="doc-strip-scroll" data-start={edges.start || undefined} data-end={edges.end || undefined}>
<ul>{SECTIONS.map((s) => link(s.id, s.title))}</ul>
+ {dot}
</div>
</nav>
</>
diff --git a/apps/site/test/site.spec.ts b/apps/site/test/site.spec.ts
index 8400480..3212e56 100644
--- a/apps/site/test/site.spec.ts
+++ b/apps/site/test/site.spec.ts
@@ -74,7 +74,8 @@ test("the docs prerender six empty boxes, then draw one figure per row with a cl
test("the docs' code is in greys: every token's colour has equal red, green and blue", async ({ page }) => {
await page.goto("/docs");
const colours = await page.locator("main pre span").evaluateAll((spans) => spans.map((s) => getComputedStyle(s).color));
- expect(colours.length).toBeGreaterThan(10);
+ // seven blocks of highlighted code, nearly two hundred spans: a page that lost its highlighting falls far short
+ expect(colours.length).toBeGreaterThan(150);
const tinted = colours.filter((c) => {
const [r, g, b] = c.match(/\d+(\.\d+)?/g)!.map(Number);
return !(r === g && g === b);
@@ -410,6 +411,143 @@ test("on a phone the sidebar is one strip under the top bar, and it follows the
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
});
+test("the sidebar marks its section with one black dot before its ink text, and no pill", async ({ page }) => {
+ await page.goto("/docs");
+ const nav = page.locator(".doc-sidebar");
+ await nav.getByRole("link", { name: "Theme" }).click();
+ await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("aria-current", "location");
+ const read = () => nav.evaluate((nav) => {
+ const ink = (el: Element) => {
+ const range = document.createRange();
+ range.selectNodeContents(el);
+ return range.getBoundingClientRect();
+ };
+ const on = nav.querySelector("a[aria-current]")!;
+ const off = nav.querySelector("a:not([aria-current])")!;
+ const dots = [...nav.querySelectorAll(".doc-dot")];
+ const dot = dots[0]?.getBoundingClientRect();
+ const box = on.getBoundingClientRect();
+ return {
+ dots: dots.length,
+ size: dot && [Math.round(dot.width), Math.round(dot.height)],
+ fill: dots[0] && getComputedStyle(dots[0]).backgroundColor,
+ round: dots[0] && getComputedStyle(dots[0]).borderRadius,
+ level: dot && Math.abs(dot.top + dot.height / 2 - (box.top + box.height / 2)),
+ clear: dot && ink(on).left - dot.right,
+ inside: dot && dot.left >= box.left,
+ // the text moves aside for the dot: its distance from the link's edge, against an unmarked link's
+ shift: Math.round(ink(on).left - box.left - (ink(off).left - off.getBoundingClientRect().left)),
+ on: [getComputedStyle(on).color, getComputedStyle(on).backgroundColor],
+ off: [getComputedStyle(off).color, getComputedStyle(off).backgroundColor],
+ };
+ });
+ await expect.poll(async () => (await read()).shift).toBe(12);
+ const r = await read();
+ expect(r.dots).toBe(1);
+ expect(r.size).toEqual([5, 5]);
+ expect(r.fill).toBe("rgb(10, 10, 10)");
+ expect(r.round).toBe("50%");
+ expect(r.level).toBeLessThan(1);
+ expect(r.clear).toBeGreaterThanOrEqual(4);
+ expect(r.inside).toBe(true);
+ expect(r.on).toEqual(["rgb(10, 10, 10)", "rgba(0, 0, 0, 0)"]);
+ expect(r.off).toEqual(["rgb(115, 115, 115)", "rgba(0, 0, 0, 0)"]);
+});
+
+test("the dot travels from section to section instead of jumping, and under reduced motion it jumps", async ({ page }) => {
+ await page.goto("/docs");
+ const nav = page.locator(".doc-sidebar");
+ await expect(nav.getByRole("link", { name: "Install" })).toHaveAttribute("aria-current", "location");
+ const flight = () => nav.evaluate((nav) => new Promise<number[]>((done) => {
+ const dot = nav.querySelector(".doc-dot")!;
+ const ys: number[] = [];
+ const t0 = performance.now();
+ const tick = () => {
+ // from the column's top: the column itself moves up as it sticks
+ const r = dot.getBoundingClientRect();
+ ys.push(r.top + r.height / 2 - nav.getBoundingClientRect().top);
+ if (performance.now() - t0 < 700) requestAnimationFrame(tick);
+ else done(ys);
+ };
+ requestAnimationFrame(tick);
+ // straight to Theme: no section passes through the band on the way, so the mark moves once
+ document.getElementById("theme")!.scrollIntoView({ behavior: "instant" });
+ }));
+ const centre = (name: string) => nav.getByRole("link", { name }).evaluate((a) => {
+ const r = a.getBoundingClientRect();
+ return r.top + r.height / 2 - a.closest("nav")!.getBoundingClientRect().top;
+ });
+ const from = await centre("Install");
+ const to = await centre("Theme");
+ const ys = await flight();
+ expect(ys.filter((y) => y > from + 2 && y < to - 2).length).toBeGreaterThanOrEqual(3);
+ expect(Math.abs(ys[ys.length - 1] - to)).toBeLessThan(1);
+
+ await page.emulateMedia({ reducedMotion: "reduce" });
+ await page.evaluate(() => window.scrollTo({ top: 0, behavior: "instant" }));
+ await expect(nav.getByRole("link", { name: "Install" })).toHaveAttribute("aria-current", "location");
+ await page.waitForTimeout(800);
+ const jump = await flight();
+ expect(jump.filter((y) => y > from + 2 && y < to - 2)).toEqual([]);
+});
+
+test("a deep link marks only its own section, with no other marked first", async ({ page }) => {
+ await page.addInitScript(() => {
+ const seen: string[] = [];
+ (window as unknown as { seen: string[] }).seen = seen;
+ const note = (el: Element) => el.matches(".doc-sidebar a[aria-current]") && seen.push(el.textContent!);
+ new MutationObserver((records) => {
+ for (const r of records) {
+ if (r.type === "attributes") note(r.target as Element);
+ for (const n of r.addedNodes) if (n instanceof Element) [n, ...n.querySelectorAll("*")].forEach(note);
+ }
+ }).observe(document, { subtree: true, childList: true, attributes: true, attributeFilter: ["aria-current"] });
+ });
+ await page.goto("/docs#theme");
+ const nav = page.locator(".doc-sidebar");
+ await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("aria-current", "location");
+ expect([...new Set(await page.evaluate(() => (window as unknown as { seen: string[] }).seen))]).toEqual(["Theme"]);
+});
+
+test("on a tall screen, a click on a section near the end marks that section, not the last", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1600 });
+ await page.goto("/docs");
+ const nav = page.locator(".doc-sidebar");
+ await nav.getByRole("link", { name: "Theme" }).click();
+ // the page cannot scroll Theme up to the top bar: it stops at its end, with Theme in view
+ await expect.poll(() => page.evaluate(() => innerHeight + scrollY >= document.documentElement.scrollHeight - 2)).toBe(true);
+ await page.waitForTimeout(300);
+ await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("aria-current", "location");
+});
+
+test("on a short screen the sidebar scrolls inside itself instead of running off the bottom", async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 420 });
+ await page.goto("/docs");
+ const side = await page.locator(".doc-sidebar").evaluate((el) => ({ bottom: el.getBoundingClientRect().bottom, scrolls: el.scrollHeight > el.clientHeight, overflow: getComputedStyle(el).overflowY }));
+ expect(side.bottom).toBeLessThanOrEqual(420);
+ expect(side.scrolls).toBe(true);
+ expect(side.overflow).toBe("auto");
+});
+
+// the band starts under the sticky chrome, which is taller on a phone, where the strip sits under the top bar
+for (const [from, to, nav] of [[1280, 390, ".doc-strip"], [390, 1280, ".doc-sidebar"]] as const) {
+ test(`after the window goes from ${from} to ${to}px wide, a click marks the section it lands on`, async ({ page }) => {
+ await page.setViewportSize({ width: from, height: 800 });
+ await page.goto("/docs");
+ await page.setViewportSize({ width: to, height: 800 });
+ const links = page.locator(nav);
+ for (const name of ["Theme", "Options", "CDN"]) {
+ await links.getByRole("link", { name }).click();
+ // the smooth scroll has stopped: two reads 150ms apart agree
+ await expect.poll(() => page.evaluate(() => new Promise<number>((r) => {
+ const y = scrollY;
+ setTimeout(() => r(scrollY - y), 150);
+ }))).toBe(0);
+ await expect(links.getByRole("link", { name })).toHaveAttribute("aria-current", "location");
+ }
+ });
+}
+
test.describe("on a 2x screen", () => {
test.use({ deviceScaleFactor: 2 });
@@ -445,6 +583,9 @@ test.describe("without JavaScript", () => {
await page.goto("/docs");
const nav = page.getByRole("navigation", { name: "Docs" });
await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("href", "#theme");
+ // the script marks the section in view; without it nothing is marked, rather than Install whatever the reader sees
+ await expect(page.locator("[aria-current]")).toHaveCount(0);
+ await expect(page.locator(".doc-dot")).toHaveCount(0);
await nav.getByRole("link", { name: "Theme" }).click();
await expect(page).toHaveURL(/\/docs#theme$/);
const quick = page.locator("#quick-start");