Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions skills/tedi-angular/references/components.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -688,7 +679,7 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => {
</ng-template>

<!-- Desktop (lg and up): sticky sidebar next to the content. -->
<div *showAt="'lg'" #page class="scroll-page">
<div *showAt="'lg'" class="scroll-page">
<div class="scroll-page__grid">
<article>
<ng-container [ngTemplateOutlet]="articleTpl" />
Expand Down Expand Up @@ -726,7 +717,7 @@ const CHAPTERS: DemoSection[] = Array.from({ length: 30 }, (_, i) => {

<!-- Below lg: the sidebar collapses into a bottom bar + sheet. -->
<div *hideAt="'lg'" class="mobile-shell">
<div #page #scroller class="mobile-scroll">
<div #scroller class="mobile-scroll">
<article>
<ng-container [ngTemplateOutlet]="articleTpl" />
</article>
Expand Down Expand Up @@ -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<ElementRef<HTMLDivElement>>("page");
// Mobile scroll area; on desktop the window scrolls, so this is undefined.
private readonly scroller = viewChild<ElementRef<HTMLDivElement>>("scroller");
private readonly platformId = inject(PLATFORM_ID);
private seeking = false;
private seekTimeout?: ReturnType<typeof setTimeout>;
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<HTMLElement>(
`#${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<string, boolean>();

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 `<toc-sticky-demo />`.
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,
Expand All @@ -910,7 +831,7 @@ const STICKY_LAYOUT_SOURCE = `@Component({
template: \`
<!-- The page scrolls, the TOC sticks and (when the list is taller than the
viewport) scrolls on its own. -->
<div #page class="doc-page">
<div class="doc-page">
<article>
@for (chapter of chapters; track chapter.id) {
<section [id]="chapter.id">
Expand All @@ -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<ElementRef<HTMLDivElement>>("page");
private observer?: IntersectionObserver;
private seeking = false;
private seekTimeout?: ReturnType<typeof setTimeout>;
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<HTMLElement>("#" + 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`).
Expand Down
1 change: 1 addition & 0 deletions src/tedi/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Loading
Loading