From 78b92abcb39e8ca311bf7185932f7313f4626fbf Mon Sep 17 00:00:00 2001 From: ccmelvin Date: Mon, 4 Aug 2025 11:42:57 -0400 Subject: [PATCH] fix(docs): enable fragment navigation and anchor linking (#3291) --- src/app/app.component.ts | 19 +++++++++++++++++++ .../shared/components/toc/toc.component.ts | 6 ++++++ 2 files changed, 25 insertions(+) diff --git a/src/app/app.component.ts b/src/app/app.component.ts index 9cbba081b7..7496e7ab58 100644 --- a/src/app/app.component.ts +++ b/src/app/app.component.ts @@ -1,6 +1,7 @@ import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; import { Meta, Title } from '@angular/platform-browser'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; +import { ViewportScroller } from '@angular/common'; import { filter } from 'rxjs/operators'; import { HOMEPAGE_TITLE, TITLE_SUFFIX } from './constants'; @@ -17,6 +18,7 @@ export class AppComponent implements OnInit { private readonly metaService: Meta, private readonly router: Router, private readonly activatedRoute: ActivatedRoute, + private readonly viewportScroller: ViewportScroller, ) {} async ngOnInit() { @@ -25,6 +27,7 @@ export class AppComponent implements OnInit { .subscribe((ev: NavigationEnd) => { this.updateTitle(); this.updateMeta(ev); + this.handleFragmentScroll(ev); }); } @@ -58,4 +61,20 @@ export class AppComponent implements OnInit { this.robotsElement = undefined; } } + + private handleFragmentScroll(event: NavigationEnd) { + const fragment = event.url.split('#')[1]; + if (fragment) { + setTimeout(() => { + const element = document.getElementById(fragment); + if (element) { + const offsetTop = element.offsetTop - 100; + window.scrollTo({ + top: offsetTop, + behavior: 'smooth' + }); + } + }, 100); + } + } } diff --git a/src/app/shared/components/toc/toc.component.ts b/src/app/shared/components/toc/toc.component.ts index 14768db4c1..97be5b076d 100644 --- a/src/app/shared/components/toc/toc.component.ts +++ b/src/app/shared/components/toc/toc.component.ts @@ -103,7 +103,13 @@ export class TocComponent implements OnInit, OnDestroy, OnChanges { } navigateToAnchor($event: MouseEvent, elementRef: HTMLElement) { + $event.preventDefault(); if (elementRef) { + const offsetTop = elementRef.offsetTop - this.scrollTopOffset; + window.scrollTo({ + top: offsetTop, + behavior: 'smooth' + }); this.findCurrentHeading(); } }