Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added routerLink support #506

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
17 changes: 15 additions & 2 deletions demo/src/app/cheat-sheet/cheat-sheet.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,20 @@ <h2 id="lists">Lists</h2>
<section>
<h2 id="links">Links</h2>
<pre class="language-none">{{ links$ | async }}</pre>
<markdown [data]="links$ | async"></markdown>
<markdown
[data]="links$ | async"
[routerLinkOptions]="{
paths: {
'/syntax-highlight': {
queryParams: {
utm_source: 'markdown-cheat-sheet',
utm_medium: 'link',
utm_campaign: 'markdown-cheat-sheet'
}
}
}
}"
></markdown>
</section>

<section>
Expand Down Expand Up @@ -61,4 +74,4 @@ <h2 id="horizontal-rule">Horizontal Rule</h2>
<pre class="language-none">{{ horizontalRule$ | async }}</pre>
<markdown [data]="horizontalRule$ | async"></markdown>
</section>
</app-scrollspy-nav-layout>
</app-scrollspy-nav-layout>
17 changes: 16 additions & 1 deletion demo/src/app/cheat-sheet/remote/links.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@ There are two ways to create links.

[You can use numbers for reference-style link definitions][1]

[I'm a router link](routerLink:/get-started)

```html
<markdown src="/path/to/markdown.md" [routerLinkOptions]="{
global: {
queryParams: { key: 'value' },
},
paths: {
'/path/to/page': {
queryParams: { key: 'value' },
}
}
}"></markdown>
```

Or leave it empty and use the [link text itself].

URLs and URLs in angle brackets will automatically get turned into links.
Expand All @@ -20,4 +35,4 @@ Some text to show that the reference links can follow later.

[arbitrary case-insensitive reference text]: https://www.mozilla.org
[1]: http://slashdot.org
[link text itself]: http://www.reddit.com
[link text itself]: http://www.reddit.com
66 changes: 63 additions & 3 deletions lib/src/markdown.component.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
import { CommonModule } from '@angular/common';
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
HostListener,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
TemplateRef,
Type,
ViewContainerRef,
} from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { NavigationExtras, Router } from '@angular/router';
import { from, merge, Subject } from 'rxjs';
import { filter, map, switchMap, takeUntil, tap } from 'rxjs/operators';
import { KatexOptions } from './katex-options';
import { MarkdownService, ParseOptions, RenderOptions } from './markdown.service';
import { MermaidAPI } from './mermaid-options';
import { PrismPlugin } from './prism-plugin';

export interface MarkdownRouterLinkOptions {
global?: NavigationExtras;
paths?: { [path: string]: NavigationExtras | undefined };
}

@Component({
// eslint-disable-next-line @angular-eslint/component-selector
selector: 'markdown, [markdown]',
template: '<ng-content></ng-content>',
template: `
<ng-container *ngIf="changed$ | async">
<ng-content></ng-content>
TheColorRed marked this conversation as resolved.
Show resolved Hide resolved
`,
imports: [CommonModule],
standalone: true,
})
export class MarkdownComponent implements OnChanges, AfterViewInit, OnDestroy {
Expand Down Expand Up @@ -97,12 +110,57 @@ export class MarkdownComponent implements OnChanges, AfterViewInit, OnDestroy {
@Input() prompt: string | undefined;
@Input() output: string | undefined;
@Input() user: string | undefined;
@Input() routerLinkOptions: MarkdownRouterLinkOptions | undefined;

// Event emitters
@Output() error = new EventEmitter<string | Error>();
@Output() load = new EventEmitter<string>();
@Output() ready = new EventEmitter<void>();

private changed = new Subject<void>();
/**
* When the markdown content is ready, or when the markdown content changes, this observable emits.
* - Get all the anchor tags in the markdown content.
* - Filter the anchor tags that have a `href` attribute that starts with `/routerLink:`.
* - Set the `data-routerLink` attribute to the `href` attribute without the `/routerLink:` prefix.
* - Remove the `/routerLink:` prefix from the `href` attribute.
*/
protected changed$ = merge(this.ready, this.changed).pipe(
map(() => this.element.nativeElement.querySelectorAll('a')),
switchMap(links => from(links)),
filter(link => link.getAttribute('href')?.startsWith('/routerLink:') === true),
tap(link => link.setAttribute('data-routerLink', link.getAttribute('href')!.replace('/routerLink:', ''))),
tap(link => link.setAttribute('href', link.getAttribute('href')!.replace('/routerLink:', ''))),
);

@HostListener('click', ['$event'])
onDocumentClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const anchor = target.nodeName.toLowerCase() === 'a' ? target : target.closest('a');
const path = anchor?.getAttribute('href');
if (path && anchor) {
// Stop the browser from navigating
event.preventDefault();
event.stopPropagation();

// Get the routerLink commands to navigate to
const commands = anchor.getAttribute('data-routerLink')!.split('/').filter(String);

let extras: NavigationExtras | undefined;
// Find the path in the routerLinkOptions
if (this.routerLinkOptions?.paths) {
extras = this.routerLinkOptions.paths[path];
}
// Get the global options if no path was found
if (!extras && this.routerLinkOptions?.global) {
extras = this.routerLinkOptions.global;
}

// Navigate to the path using the router service
this.router?.navigate(commands, extras);
}
}

private _clipboard = false;
private _commandLine = false;
private _disableSanitizer = false;
Expand All @@ -119,10 +177,12 @@ export class MarkdownComponent implements OnChanges, AfterViewInit, OnDestroy {
public element: ElementRef<HTMLElement>,
public markdownService: MarkdownService,
public viewContainerRef: ViewContainerRef,
@Optional() public router?: Router,
) { }

ngOnChanges(): void {
this.loadContent();
this.changed.next();
}

loadContent(): void {
Expand Down