Skip to content
This repository was archived by the owner on Dec 18, 2024. It is now read-only.

fix: create proper fragment urls #329

Merged
merged 1 commit into from
Nov 28, 2017
Merged
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
22 changes: 21 additions & 1 deletion src/app/shared/doc-viewer/doc-viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {Subscription} from 'rxjs/Subscription';
import {ExampleViewer} from '../example-viewer/example-viewer';
import {HeaderLink} from './header-link';
import {ComponentPortal, DomPortalHost} from '@angular/cdk/portal';
import {Router} from '@angular/router';

@Component({
selector: 'doc-viewer',
Expand All @@ -40,7 +41,8 @@ export class DocViewer implements OnDestroy {
private _elementRef: ElementRef,
private _http: Http,
private _injector: Injector,
private _viewContainerRef: ViewContainerRef) {}
private _viewContainerRef: ViewContainerRef,
private _router: Router) {}

/** Fetch a document by URL. */
private _fetchDocument(url: string) {
Expand All @@ -57,6 +59,7 @@ export class DocViewer implements OnDestroy {
this.textContent = this._elementRef.nativeElement.textContent;
this._loadComponents('material-docs-example', ExampleViewer);
this._loadComponents('header-link', HeaderLink);
this._fixFragmentUrls();
this.contentLoaded.next();
} else {
this._elementRef.nativeElement.innerText =
Expand Down Expand Up @@ -100,6 +103,23 @@ export class DocViewer implements OnDestroy {
this._portalHosts = [];
}

/**
* A fragment link is a link that references a specific element on the page that should be
* scrolled into the viewport on page load or click.
*
* By default those links refer to the root page of the documentation and the fragment links
* won't work properly. Those links need to be updated to be relative to the current base URL.
*/
private _fixFragmentUrls() {
const baseUrl = this._router.url.split('#')[0];
const anchorElements =
[].slice.call(this._elementRef.nativeElement.querySelectorAll('a')) as HTMLAnchorElement[];

anchorElements
.filter(anchorEl => anchorEl.hash)
.forEach(anchorEl => anchorEl.href = `${baseUrl}${anchorEl.hash}`);
}

ngOnDestroy() {
this._clearLiveExamples();

Expand Down