diff --git a/skills/tedi-angular/references/components.md b/skills/tedi-angular/references/components.md index 31cd1a398..9e7ea4f7a 100644 --- a/skills/tedi-angular/references/components.md +++ b/skills/tedi-angular/references/components.md @@ -422,6 +422,10 @@ Both entry points declare `[tedi-floating-button]`. The Community component is adds drag to close, snap points and a collapsed state, and with `showOverlay`, `trapFocus` and `lockScroll` off (plus `closeOnBackdropClick` off) it stays docked while the page behind remains usable. +- **`scrollSpy()` over a hand-written `IntersectionObserver` for `tedi-table-of-contents`.** The TOC + is controlled via `activeId`; `scrollSpy({ ids, scrollContainer, offset })` returns that id as a + signal plus `scrollToSection(id)` for the item links' click handlers. Sections are looked up when + `ids` changes, so when they render later (`@if`, `@defer`) pass `ids` as a signal that updates then. ### Responsive behaviour that isn't an input diff --git a/src/tedi/components/navigation/table-of-contents/table-of-contents.stories.ts b/src/tedi/components/navigation/table-of-contents/table-of-contents.stories.ts index dbb0b0a26..2f9d46f95 100644 --- a/src/tedi/components/navigation/table-of-contents/table-of-contents.stories.ts +++ b/src/tedi/components/navigation/table-of-contents/table-of-contents.stories.ts @@ -1,14 +1,5 @@ -import { isPlatformBrowser, NgTemplateOutlet } from "@angular/common"; -import { - Component, - effect, - ElementRef, - inject, - OnDestroy, - PLATFORM_ID, - signal, - viewChild, -} from "@angular/core"; +import { NgTemplateOutlet } from "@angular/common"; +import { Component, computed, ElementRef, viewChild } from "@angular/core"; import { Meta, StoryObj, moduleMetadata } from "@storybook/angular"; import { VISUAL_TEST_VIEWPORTS, @@ -20,6 +11,7 @@ import { IconComponent } from "../../base/icon/icon.component"; import { TextComponent } from "../../base/text/text.component"; import { HideAtDirective } from "../../../directives/hide-at/hide-at.directive"; import { ShowAtDirective } from "../../../directives/show-at/show-at.directive"; +import { scrollSpy } from "../../../utils/scroll-spy.util"; import { LinkComponent } from "../link/link.component"; import { TableOfContentsComponent } from "./table-of-contents.component"; import { TableOfContentsCollapsibleComponent } from "./table-of-contents-collapsible/table-of-contents-collapsible.component"; @@ -652,9 +644,8 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => { * Example for the StickyInLayout story: a documentation page with a sticky * table-of-contents sidebar. The window scrolls, the sticky TOC stays alongside * it and scrolls on its own when taller than the viewport. Below `lg` the - * sidebar collapses into `tedi-table-of-contents-collapsible`. The component is - * controlled via `activeId`: an `IntersectionObserver` highlights the section in - * view (scroll-spy) and clicking an item smooth-scrolls the page to it. + * sidebar collapses into `tedi-table-of-contents-collapsible`. `activeId` comes + * from `scrollSpy`. */ @Component({ selector: "toc-sticky-demo", @@ -688,7 +679,7 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => { -
+
@@ -726,7 +717,7 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => {
-
+
@@ -795,111 +786,41 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => { `, ], }) -class TocStickyDemoComponent implements OnDestroy { +class TocStickyDemoComponent { readonly chapters = CHAPTERS; readonly lorem = LOREM; - readonly activeId = signal(CHAPTERS[0].id); - // Resolves to whichever layout is rendered — the desktop grid or the mobile - // scroll area. - private readonly page = viewChild>("page"); // Mobile scroll area; on desktop the window scrolls, so this is undefined. private readonly scroller = viewChild>("scroller"); - private readonly platformId = inject(PLATFORM_ID); - private seeking = false; - private seekTimeout?: ReturnType; - private observer?: IntersectionObserver; - - constructor() { - // Re-attach the scroll-spy to the rendered sections whenever the layout - // swaps between the desktop sidebar and the mobile collapsible. - effect(() => { - const page = this.page()?.nativeElement; - const root = this.scroller()?.nativeElement ?? null; - this.observer?.disconnect(); - if (page && isPlatformBrowser(this.platformId)) { - this.observeSections(page, root); - } - }); - } - - ngOnDestroy(): void { - this.observer?.disconnect(); - clearTimeout(this.seekTimeout); - } - - // Smooth-scroll the window (desktop) or the scroll area (mobile) to the clicked - // section; guard the observer during the scroll so the marker doesn't flicker - // through sections. `scrollTo` rather than `scrollIntoView`, which would also - // scroll the Storybook docs page around the iframe. - selectSection(id: string, event: Event): void { - event.preventDefault(); - const target = this.page()?.nativeElement.querySelector( - `#${id}`, - ); - if (!target) return; - this.seeking = true; - this.activeId.set(id); - clearTimeout(this.seekTimeout); - this.seekTimeout = setTimeout(() => (this.seeking = false), 700); - const root = this.scroller()?.nativeElement; - const offset = target.getBoundingClientRect().top; - if (root) { - root.scrollTo({ - top: root.scrollTop + offset - root.getBoundingClientRect().top, - behavior: "smooth", - }); - } else { - window.scrollTo({ top: window.scrollY + offset, behavior: "smooth" }); - } - } - - // Scroll-spy: highlight the chapter currently in view within `root` (the - // viewport when null). - private observeSections(page: HTMLElement, root: HTMLElement | null): void { - const ids = this.chapters.flatMap((c) => [ + private readonly spy = scrollSpy({ + ids: CHAPTERS.flatMap((c) => [ c.id, ...(c.children ?? []).map((child) => child.id), - ]); - const visibility = new Map(); - - const pickActive = () => { - if (this.seeking) return; - const atBottom = root - ? root.scrollTop + root.clientHeight >= root.scrollHeight - 2 - : window.innerHeight + window.scrollY >= - document.documentElement.scrollHeight - 2; - if (atBottom) { - this.activeId.set(ids[ids.length - 1]); - return; - } - const active = ids.find((id) => visibility.get(id)); - if (active) this.activeId.set(active); - }; + ]), + scrollContainer: this.scroller, + // The scroll area's 2rem top padding keeps a clicked section off its top edge. + offset: computed(() => (this.scroller() ? 32 : 0)), + }); + readonly activeId = this.spy.activeId; - const observer = new IntersectionObserver( - (entries) => { - entries.forEach((entry) => - visibility.set( - (entry.target as HTMLElement).id, - entry.isIntersecting, - ), - ); - pickActive(); - }, - { root, rootMargin: "0px 0px -55% 0px" }, - ); - this.observer = observer; - ids.forEach((id) => { - const el = page.querySelector(`#${id}`); - if (el) observer.observe(el); - }); + selectSection(id: string, event: Event): void { + event.preventDefault(); + this.spy.scrollToSection(id); } } // The story renders a private demo component, so surface a representative, // copy-pasteable page as the "Show code" snippet instead of ``. -const STICKY_LAYOUT_SOURCE = `@Component({ +const STICKY_LAYOUT_SOURCE = `import { Component } from "@angular/core"; +import { + LinkComponent, + scrollSpy, + TableOfContentsComponent, + TableOfContentsItemComponent, + TextComponent, +} from "@tedi-design-system/angular/tedi"; + +@Component({ selector: "app-doc-page", imports: [ TableOfContentsComponent, @@ -910,7 +831,7 @@ const STICKY_LAYOUT_SOURCE = `@Component({ template: \` -
+
@for (chapter of chapters; track chapter.id) {
@@ -937,67 +858,29 @@ const STICKY_LAYOUT_SOURCE = `@Component({ } \`, }) -export class DocPageComponent implements OnDestroy { +export class DocPageComponent { readonly chapters = [ { id: "intro", label: "Sissejuhatus" }, { id: "methods", label: "Meetodid" }, // … ]; - readonly activeId = signal(this.chapters[0].id); - private readonly page = viewChild.required>("page"); - private observer?: IntersectionObserver; - private seeking = false; - private seekTimeout?: ReturnType; + private readonly spy = scrollSpy({ ids: this.chapters.map((c) => c.id) }); + readonly activeId = this.spy.activeId; - constructor() { - afterNextRender(() => this.trackActiveSection()); - } - - ngOnDestroy(): void { - this.observer?.disconnect(); - clearTimeout(this.seekTimeout); - } - - // Smooth-scroll the page to the clicked section; guard the observer during the - // scroll so the active marker doesn't flicker through the sections it passes. selectSection(id: string, event: Event): void { event.preventDefault(); - const target = this.page().nativeElement.querySelector("#" + id); - if (!target) return; - this.seeking = true; - this.activeId.set(id); - clearTimeout(this.seekTimeout); - this.seekTimeout = setTimeout(() => (this.seeking = false), 700); - target.scrollIntoView({ behavior: "smooth", block: "start" }); - } - - // Scroll-spy: highlight the section currently in view. - private trackActiveSection(): void { - const page = this.page().nativeElement; - const observer = new IntersectionObserver( - (entries) => { - if (this.seeking) return; - const visible = entries.find((entry) => entry.isIntersecting); - if (visible) this.activeId.set((visible.target as HTMLElement).id); - }, - { rootMargin: "0px 0px -55% 0px" }, - ); - this.observer = observer; - this.chapters.forEach((chapter) => { - const el = page.querySelector("#" + chapter.id); - if (el) observer.observe(el); - }); + this.spy.scrollToSection(id); } }`; /** * A documentation page with a sticky table-of-contents sidebar. The page scrolls, * and the sticky TOC stays alongside it, scrolling on its own when it is taller - * than the viewport. The component is controlled via `activeId`, so the consumer - * owns scroll behavior: this demo wires an `IntersectionObserver` to highlight the - * section in view (scroll-spy) and smooth-scrolls the page to a section when its - * item is clicked. + * than the viewport. + * + * `activeId` comes from `scrollSpy`, an opt-in helper exported from + * `@tedi-design-system/angular/tedi`. * * Tune the gap the sticky sidebar leaves above the viewport bottom with the * `--tedi-table-of-contents-sticky-bottom` CSS custom property (default `1.5rem`). diff --git a/src/tedi/utils/index.ts b/src/tedi/utils/index.ts index 0aa8eaf26..052aa8312 100644 --- a/src/tedi/utils/index.ts +++ b/src/tedi/utils/index.ts @@ -4,5 +4,6 @@ export * from "./deprecation.util"; export * from "./elements.util"; export * from "./file.util"; export * from "./matchers.util"; +export * from "./scroll-spy.util"; export * from "./tag-overflow.util"; export * from "./time.util"; diff --git a/src/tedi/utils/scroll-spy.util.spec.ts b/src/tedi/utils/scroll-spy.util.spec.ts new file mode 100644 index 000000000..55d1d06ca --- /dev/null +++ b/src/tedi/utils/scroll-spy.util.spec.ts @@ -0,0 +1,490 @@ +import { + Component, + computed, + ElementRef, + input, + PLATFORM_ID, + signal, + viewChild, +} from "@angular/core"; +import { ComponentFixture, TestBed } from "@angular/core/testing"; + +import { scrollSpy, ScrollSpyContainer } from "./scroll-spy.util"; + +type ObserverCallback = ( + entries: { target: Element; isIntersecting: boolean }[], +) => void; + +const observers: MockIntersectionObserver[] = []; + +class MockIntersectionObserver { + readonly observed: Element[] = []; + readonly disconnect = jest.fn(); + + constructor( + readonly callback: ObserverCallback, + readonly options: IntersectionObserverInit, + ) { + observers.push(this); + } + + observe(element: Element): void { + this.observed.push(element); + } + + fire(states: Record): void { + this.callback( + Object.entries(states).map(([id, isIntersecting]) => ({ + target: document.getElementById(id) as Element, + isIntersecting, + })), + ); + } +} + +const IDS = ["one", "two", "three"]; + +const rect = (top: number): DOMRect => ({ top }) as DOMRect; + +const lastObserver = () => observers[observers.length - 1]; + +const setDocumentScroll = (scrollY: number, scrollHeight: number): void => { + Object.defineProperty(window, "scrollY", { + value: scrollY, + configurable: true, + }); + Object.defineProperty(window, "innerHeight", { + value: 500, + configurable: true, + }); + Object.defineProperty(document.documentElement, "scrollHeight", { + value: scrollHeight, + configurable: true, + }); +}; + +const ids = signal(IDS); +const scrollContainer = signal(undefined); +const offset = signal(0); + +@Component({ + standalone: true, + template: ` +
+ @for (id of ids(); track id) { +
+ } + `, +}) +class HostComponent { + readonly ids = ids; + readonly area = viewChild.required>("area"); + readonly spy = scrollSpy({ ids, scrollContainer, offset }); +} + +@Component({ + standalone: true, + template: ` + @for (id of sections(); track id) { +
+ } + `, +}) +class RequiredInputHostComponent { + readonly sections = input.required(); + readonly spy = scrollSpy({ ids: computed(() => this.sections()) }); +} + +@Component({ + standalone: true, + template: `
+
`, +}) +class PlainValuesHostComponent { + readonly spy = scrollSpy({ ids: ["one", "two"], offset: 16 }); +} + +describe("scrollSpy", () => { + const originalObserver = window.IntersectionObserver; + const originalScrollTo = window.scrollTo; + let fixture: ComponentFixture; + + const render = () => { + fixture = TestBed.createComponent(HostComponent); + fixture.detectChanges(); + return fixture.componentInstance.spy; + }; + + beforeEach(() => { + observers.length = 0; + ids.set(IDS); + scrollContainer.set(undefined); + offset.set(0); + window.IntersectionObserver = + MockIntersectionObserver as unknown as typeof IntersectionObserver; + window.scrollTo = jest.fn(); + setDocumentScroll(0, 5000); + }); + + afterEach(() => { + window.IntersectionObserver = originalObserver; + window.scrollTo = originalScrollTo; + jest.useRealTimers(); + }); + + it("starts with the first id active", () => { + expect(render().activeId()).toBe("one"); + }); + + it("observes every rendered section against the window, inset by the offset", () => { + offset.set(64); + render(); + expect(lastObserver().observed.map((el) => el.id)).toEqual(IDS); + expect(lastObserver().options).toEqual({ + root: null, + rootMargin: "-64px 0px -55% 0px", + }); + }); + + it("accepts plain values instead of signals", () => { + const plain = TestBed.createComponent(PlainValuesHostComponent); + plain.detectChanges(); + expect(plain.componentInstance.spy.activeId()).toBe("one"); + expect(lastObserver().observed).toHaveLength(2); + expect(lastObserver().options.rootMargin).toBe("-16px 0px -55% 0px"); + }); + + it("accepts ids derived from a required input", () => { + const host = TestBed.createComponent(RequiredInputHostComponent); + host.componentRef.setInput("sections", ["one", "two"]); + host.detectChanges(); + expect(host.componentInstance.spy.activeId()).toBe("one"); + expect(lastObserver().observed).toHaveLength(2); + }); + + it("makes the first id active once ids that started empty are set", () => { + ids.set([]); + const spy = render(); + expect(spy.activeId()).toBeUndefined(); + + ids.set(IDS); + expect(spy.activeId()).toBe("one"); + }); + + it("falls back to the first id when the active one is removed", () => { + const spy = render(); + lastObserver().fire({ three: true }); + expect(spy.activeId()).toBe("three"); + + ids.set(["one", "two"]); + expect(spy.activeId()).toBe("one"); + }); + + it("keeps the first section active on a page too short to scroll", () => { + setDocumentScroll(0, 400); + const spy = render(); + lastObserver().fire({ one: true, two: true, three: true }); + window.dispatchEvent(new Event("scroll")); + expect(spy.activeId()).toBe("one"); + }); + + it("keeps the first section active in a container too short to scroll", () => { + const container = document.createElement("div"); + scrollContainer.set(container); + const spy = render(); + lastObserver().fire({ one: true, two: true }); + expect(spy.activeId()).toBe("one"); + }); + + it.each([-8, NaN])("treats an offset of %p as 0", (value) => { + offset.set(value); + render(); + expect(lastObserver().options.rootMargin).toBe("-0px 0px -55% 0px"); + }); + + it("re-observes when the offset changes", () => { + render(); + offset.set(48); + fixture.detectChanges(); + expect(observers[0].disconnect).toHaveBeenCalled(); + expect(lastObserver().options.rootMargin).toBe("-48px 0px -55% 0px"); + }); + + it("makes the first visible section active, in document order", () => { + const spy = render(); + lastObserver().fire({ two: true, three: true }); + expect(spy.activeId()).toBe("two"); + + lastObserver().fire({ two: false }); + expect(spy.activeId()).toBe("three"); + }); + + it("keeps the active id while no section is visible", () => { + const spy = render(); + lastObserver().fire({ two: true }); + lastObserver().fire({ two: false }); + expect(spy.activeId()).toBe("two"); + }); + + it("makes the last section active at the bottom of the page", () => { + const spy = render(); + setDocumentScroll(4500, 5000); + window.dispatchEvent(new Event("scroll")); + expect(spy.activeId()).toBe("three"); + }); + + it("follows a scroll container given as an ElementRef", () => { + const spy = render(); + const area = fixture.componentInstance.area(); + const el = area.nativeElement; + Object.defineProperty(el, "clientHeight", { value: 200 }); + Object.defineProperty(el, "scrollHeight", { value: 1000 }); + scrollContainer.set(area); + fixture.detectChanges(); + expect(lastObserver().options.root).toBe(el); + + el.scrollTop = 800; + el.dispatchEvent(new Event("scroll")); + expect(spy.activeId()).toBe("three"); + }); + + it("waits while the scroll container is null and re-observes when it changes", () => { + scrollContainer.set(null); + render(); + expect(observers).toHaveLength(0); + + scrollContainer.set(document.createElement("div")); + fixture.detectChanges(); + expect(observers).toHaveLength(1); + + scrollContainer.set(undefined); + fixture.detectChanges(); + expect(observers[0].disconnect).toHaveBeenCalled(); + expect(lastObserver().options.root).toBeNull(); + }); + + it("re-observes when the ids change", () => { + render(); + ids.set(["one", "two"]); + fixture.detectChanges(); + expect(observers).toHaveLength(2); + expect(lastObserver().observed.map((el) => el.id)).toEqual(["one", "two"]); + }); + + it("does nothing without IntersectionObserver", () => { + window.IntersectionObserver = + undefined as unknown as typeof IntersectionObserver; + expect(render().activeId()).toBe("one"); + expect(observers).toHaveLength(0); + }); + + it("does nothing on the server", () => { + TestBed.overrideProvider(PLATFORM_ID, { useValue: "server" }); + const spy = render(); + expect(spy.activeId()).toBe("one"); + expect(observers).toHaveLength(0); + + spy.scrollToSection("two"); + expect(spy.activeId()).toBe("one"); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + + it("disconnects and stops listening on destroy", () => { + const removeListener = jest.spyOn(window, "removeEventListener"); + render(); + const observer = lastObserver(); + fixture.destroy(); + expect(observer.disconnect).toHaveBeenCalled(); + expect(removeListener).toHaveBeenCalledWith("scroll", expect.any(Function)); + removeListener.mockRestore(); + }); + + describe("scrollToSection", () => { + it("makes the section active and smooth-scrolls the window to it, minus the offset", () => { + setDocumentScroll(100, 5000); + offset.set(40); + const spy = render(); + (document.getElementById("three") as HTMLElement).getBoundingClientRect = + () => rect(900); + + spy.scrollToSection("three"); + + expect(spy.activeId()).toBe("three"); + expect(window.scrollTo).toHaveBeenCalledWith({ + top: 960, + behavior: "smooth", + }); + }); + + it("scrolls the scroll container when one is given", () => { + const container = document.createElement("div"); + container.scrollTop = 50; + container.scrollTo = jest.fn(); + container.getBoundingClientRect = () => rect(100); + scrollContainer.set(container); + offset.set(32); + const spy = render(); + (document.getElementById("two") as HTMLElement).getBoundingClientRect = + () => rect(400); + + spy.scrollToSection("two"); + + expect(container.scrollTo).toHaveBeenCalledWith({ + top: 318, + behavior: "smooth", + }); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + + it("scrolls a container given as an ElementRef", () => { + const spy = render(); + const area = fixture.componentInstance.area(); + area.nativeElement.scrollTo = jest.fn(); + scrollContainer.set(area); + fixture.detectChanges(); + + spy.scrollToSection("two"); + + expect(area.nativeElement.scrollTo).toHaveBeenCalled(); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + + it("clears the pending hold on destroy", () => { + jest.useFakeTimers(); + render().scrollToSection("two"); + const pending = jest.getTimerCount(); + + fixture.destroy(); + expect(jest.getTimerCount()).toBe(pending - 1); + }); + + it("holds the clicked section until the scroll settles", () => { + jest.useFakeTimers(); + const spy = render(); + + spy.scrollToSection("three"); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("three"); + + // Each scroll event while smooth-scrolling extends the hold. + jest.advanceTimersByTime(80); + window.dispatchEvent(new Event("scroll")); + jest.advanceTimersByTime(80); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("three"); + + jest.advanceTimersByTime(100); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("two"); + }); + + it("rechecks the active section when the scroll is interrupted", () => { + jest.useFakeTimers(); + const spy = render(); + (document.getElementById("three") as HTMLElement).getBoundingClientRect = + () => rect(900); + + spy.scrollToSection("three"); + setDocumentScroll(300, 5000); + window.dispatchEvent(new Event("scroll")); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("three"); + + jest.advanceTimersByTime(100); + expect(spy.activeId()).toBe("two"); + }); + + it("keeps the clicked section when the scroll reaches it", () => { + jest.useFakeTimers(); + const spy = render(); + (document.getElementById("three") as HTMLElement).getBoundingClientRect = + () => rect(900); + + spy.scrollToSection("three"); + setDocumentScroll(900, 5000); + window.dispatchEvent(new Event("scroll")); + lastObserver().fire({ two: true }); + + jest.advanceTimersByTime(100); + expect(spy.activeId()).toBe("three"); + }); + + it("keeps the clicked section when the scroll area ends before it", () => { + jest.useFakeTimers(); + const spy = render(); + (document.getElementById("two") as HTMLElement).getBoundingClientRect = + () => rect(4800); + + spy.scrollToSection("two"); + setDocumentScroll(4500, 5000); + window.dispatchEvent(new Event("scroll")); + + jest.advanceTimersByTime(100); + expect(spy.activeId()).toBe("two"); + }); + + it("releases the hold when the scroll container changes", () => { + const spy = render(); + spy.scrollToSection("three"); + + scrollContainer.set(fixture.componentInstance.area()); + fixture.detectChanges(); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("two"); + }); + + it("keeps a hold made for a container that is not observed yet", () => { + const spy = render(); + const area = fixture.componentInstance.area(); + area.nativeElement.scrollTo = jest.fn(); + scrollContainer.set(area); + + spy.scrollToSection("three"); + fixture.detectChanges(); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("three"); + }); + + it("keeps the hold when the ids or offset change", () => { + const spy = render(); + spy.scrollToSection("three"); + + offset.set(16); + ids.set([...IDS]); + fixture.detectChanges(); + lastObserver().fire({ two: true }); + expect(spy.activeId()).toBe("three"); + }); + + it("jumps instantly with prefers-reduced-motion", () => { + const matchMedia = jest + .spyOn(window, "matchMedia") + .mockReturnValue({ matches: true } as MediaQueryList); + const spy = render(); + + spy.scrollToSection("two"); + + expect(window.scrollTo).toHaveBeenCalledWith( + expect.objectContaining({ behavior: "instant" }), + ); + matchMedia.mockRestore(); + }); + + it("does nothing while the scroll container is null", () => { + scrollContainer.set(null); + const spy = render(); + + spy.scrollToSection("two"); + + expect(spy.activeId()).toBe("one"); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + + it("ignores an unknown id", () => { + const spy = render(); + spy.scrollToSection("missing"); + expect(spy.activeId()).toBe("one"); + expect(window.scrollTo).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/tedi/utils/scroll-spy.util.ts b/src/tedi/utils/scroll-spy.util.ts new file mode 100644 index 000000000..2f28d112c --- /dev/null +++ b/src/tedi/utils/scroll-spy.util.ts @@ -0,0 +1,228 @@ +import { DOCUMENT, isPlatformBrowser } from "@angular/common"; +import { + afterRenderEffect, + computed, + DestroyRef, + ElementRef, + inject, + isSignal, + NgZone, + PLATFORM_ID, + Signal, + signal, + untracked, +} from "@angular/core"; + +type MaybeSignal = T | Signal; + +export type ScrollSpyContainer = + HTMLElement | ElementRef | null | undefined; + +export interface ScrollSpyOptions { + /** + * Ids of the observed sections, in document order. Sections are looked up when this changes, so + * pass a signal that updates once sections that render later are in the DOM. + */ + ids: MaybeSignal; + /** + * Element whose scroll drives the active id; `undefined` follows the window and `null` observes + * nothing. Pass a signal such as a `viewChild()` to re-observe when the container changes. + */ + scrollContainer?: MaybeSignal; + /** + * Height in px of anything covering the top of the scroll container, such as a sticky header. + * @default 0 + */ + offset?: MaybeSignal; +} + +export interface ScrollSpy { + /** Id of the section currently being read; the first id until another section is picked. */ + readonly activeId: Signal; + /** + * Makes the section active and scrolls it to the top of the scroll container. The active id is + * held until the scroll settles, so it doesn't pass through the sections in between. + */ + scrollToSection(id: string): void; +} + +/** How long scrolling must pause before a `scrollToSection` scroll counts as finished. */ +const SCROLL_IDLE_MS = 100; +/** Sub-pixel rounding tolerance (px) when comparing scroll positions. */ +const SCROLL_TOLERANCE = 2; + +const read = (value: MaybeSignal): T => + isSignal(value) ? value() : value; + +const toElement = (container: ScrollSpyContainer) => + container instanceof ElementRef ? container.nativeElement : container; + +// A negative or NaN offset would build an invalid `rootMargin`. +const toOffset = (offset: number | undefined) => Math.max(0, offset || 0); + +/** + * Tracks which page section is in view, e.g. for `activeId` of `tedi-table-of-contents` or any + * other in-page navigation. The first section in the top part of the scroll container is active; at + * the end of the scroll area the last one is. Must be called in an injection context; does nothing + * on the server. + */ +export function scrollSpy(options: ScrollSpyOptions): ScrollSpy { + const document = inject(DOCUMENT); + const zone = inject(NgZone); + const isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); + const picked = signal(undefined); + // Lazy, so `ids` may derive from a required input. + const activeId = computed(() => { + const ids = read(options.ids); + const id = picked(); + return id !== undefined && ids.includes(id) ? id : ids[0]; + }); + + let locked = false; + let unlockTimer: ReturnType | undefined; + let heldContainer: HTMLElement | null | undefined; + let heldTop = 0; + let pickActiveNow: (() => void) | undefined; + + const reachedHeldTop = (): boolean => { + const view = document.defaultView; + const top = heldContainer ? heldContainer.scrollTop : (view?.scrollY ?? 0); + const max = heldContainer + ? heldContainer.scrollHeight - heldContainer.clientHeight + : document.documentElement.scrollHeight - (view?.innerHeight ?? 0); + const target = Math.min(Math.max(0, heldTop), Math.max(0, max)); + return Math.abs(top - target) <= SCROLL_TOLERANCE; + }; + + const holdUntilScrollSettles = () => { + locked = true; + clearTimeout(unlockTimer); + zone.runOutsideAngular(() => { + unlockTimer = setTimeout(() => { + locked = false; + // An interrupted scroll stopped somewhere else, so the clicked section may not be in view. + if (!reachedHeldTop()) pickActiveNow?.(); + }, SCROLL_IDLE_MS); + }); + }; + + const isAtBottom = (container: HTMLElement | undefined): boolean => { + // `> 0`: an area too short to scroll is at its top, not its bottom. + if (container) { + return ( + container.scrollTop > 0 && + container.scrollTop + container.clientHeight >= + container.scrollHeight - SCROLL_TOLERANCE + ); + } + const view = document.defaultView; + return ( + !!view && + view.scrollY > 0 && + view.innerHeight + view.scrollY >= + document.documentElement.scrollHeight - SCROLL_TOLERANCE + ); + }; + + // After render, so the sections' `[id]` bindings are already in the DOM. + afterRenderEffect((onCleanup) => { + const ids = read(options.ids); + const container = toElement(read(options.scrollContainer)); + const offset = toOffset(read(options.offset)); + const view = document.defaultView; + + // A hold belongs to the container whose scroll it waits for. + if (locked && container !== heldContainer) { + locked = false; + clearTimeout(unlockTimer); + } + + if (!isBrowser || !view || container === null) return; + if (typeof IntersectionObserver === "undefined") return; + + const visibility = new Map(); + + const pickActive = () => { + if (locked) return; + if (isAtBottom(container)) { + picked.set(ids[ids.length - 1]); + return; + } + const visible = ids.find((id) => visibility.get(id)); + if (visible) picked.set(visible); + }; + + pickActiveNow = pickActive; + + const onScroll = () => { + if (locked) { + holdUntilScrollSettles(); + return; + } + pickActive(); + }; + + const scroller: HTMLElement | Window = container ?? view; + + const observer = zone.runOutsideAngular(() => { + const created = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => + visibility.set(entry.target.id, entry.isIntersecting), + ); + pickActive(); + }, + { root: container ?? null, rootMargin: `-${offset}px 0px -55% 0px` }, + ); + scroller.addEventListener("scroll", onScroll, { passive: true }); + return created; + }); + + ids.forEach((id) => { + const section = document.getElementById(id); + if (section) observer.observe(section); + }); + + onCleanup(() => { + observer.disconnect(); + scroller.removeEventListener("scroll", onScroll); + pickActiveNow = undefined; + }); + }); + + inject(DestroyRef).onDestroy(() => clearTimeout(unlockTimer)); + + const scrollToSection = (id: string): void => { + if (!isBrowser) return; + const view = document.defaultView; + const section = document.getElementById(id); + if (!view || !section) return; + + const container = toElement(untracked(() => read(options.scrollContainer))); + + if (container === null) return; + + const offset = toOffset(untracked(() => read(options.offset))); + const behavior: ScrollBehavior = view.matchMedia?.( + "(prefers-reduced-motion: reduce)", + ).matches + ? "instant" + : "smooth"; + const sectionTop = section.getBoundingClientRect().top; + const top = container + ? container.scrollTop + + sectionTop - + container.getBoundingClientRect().top - + offset + : view.scrollY + sectionTop - offset; + + picked.set(id); + heldContainer = container; + heldTop = top; + holdUntilScrollSettles(); + + (container ?? view).scrollTo({ top, behavior }); + }; + + return { activeId, scrollToSection }; +}