/
doc-viewer.ts
137 lines (115 loc) Β· 4.9 KB
/
doc-viewer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import { ComponentPortal, DomPortalOutlet } from '@angular/cdk/portal';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {
ApplicationRef,
Component,
ComponentFactoryResolver,
ElementRef,
EventEmitter,
Injector,
Input,
NgZone,
OnDestroy,
Output,
SecurityContext,
ViewContainerRef
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
import { ExampleViewer } from '../example-viewer/example-viewer';
@Component({
selector: 'doc-viewer',
template: 'Loading document...'
})
export class DocViewer implements OnDestroy {
/** The URL of the document to display. */
@Input()
set documentUrl(url: string) {
this.fetchDocument(url);
}
@Output() contentRendered = new EventEmitter<void>();
@Output() contentRenderFailed = new EventEmitter<void>();
/** The document text. It should not be HTML encoded. */
textContent = '';
private portalHosts: DomPortalOutlet[] = [];
private documentFetchSubscription: Subscription;
constructor(private _appRef: ApplicationRef,
private _componentFactoryResolver: ComponentFactoryResolver,
private _elementRef: ElementRef,
private _http: HttpClient,
private _injector: Injector,
private _viewContainerRef: ViewContainerRef,
private _ngZone: NgZone,
private _domSanitizer: DomSanitizer) {
}
ngOnDestroy() {
this.clearLiveExamples();
if (this.documentFetchSubscription) {
this.documentFetchSubscription.unsubscribe();
}
}
/** Fetch a document by URL. */
private fetchDocument(url: string) {
// Cancel previous pending request
if (this.documentFetchSubscription) {
this.documentFetchSubscription.unsubscribe();
}
this.documentFetchSubscription = this._http.get(url, {responseType: 'text'}).subscribe(
(document) => this.updateDocument(document),
(error) => this.showError(url, error)
);
}
/**
* Updates the displayed document.
* @param rawDocument The raw document content to show.
*/
private updateDocument(rawDocument: string) {
// Replace all relative fragment URLs with absolute fragment URLs. e.g. "#my-section" becomes
// "/components/button/api#my-section". This is necessary because otherwise these fragment
// links would redirect to "/#my-section".
// tslint:disable-next-line:no-parameter-reassignment
rawDocument = rawDocument.replace(/href="#([^"]*)"/g, (_m: string, fragmentUrl: string) => {
const absoluteUrl = `${location.pathname}#${fragmentUrl}`;
return `href="${this._domSanitizer.sanitize(SecurityContext.URL, absoluteUrl)}"`;
});
// tslint:disable-next-line:no-inner-html
this._elementRef.nativeElement.innerHTML = rawDocument;
this.textContent = this._elementRef.nativeElement.textContent;
this.loadComponents('mosaic-docs-example', ExampleViewer);
// Resolving and creating components dynamically in Angular happens synchronously, but since
// we want to emit the output if the components are actually rendered completely, we wait
// until the Angular zone becomes stable.
this._ngZone.onStable
.pipe(take(1))
.subscribe(() => this.contentRendered.next());
}
/** Show an error that occurred when fetching a document. */
private showError(url: string, error: HttpErrorResponse) {
// tslint:disable-next-line:no-console
console.error(error);
this._elementRef.nativeElement.innerText =
`Failed to load document: ${url}. Error: ${error.statusText}`;
this._ngZone.onStable
.pipe(take(1))
.subscribe(() => this.contentRenderFailed.next());
}
/** Instantiate a ExampleViewer for each example. */
private loadComponents(componentName: string, componentClass: any) {
const exampleElements =
this._elementRef.nativeElement.querySelectorAll(`[${componentName}]`);
Array.prototype.slice.call(exampleElements).forEach((element: Element) => {
const example = element.getAttribute(componentName);
const portalHost = new DomPortalOutlet(
element, this._componentFactoryResolver, this._appRef, this._injector);
const examplePortal = new ComponentPortal(componentClass, this._viewContainerRef);
const exampleViewer = portalHost.attach(examplePortal);
(exampleViewer.instance as ExampleViewer).example = example;
this.portalHosts.push(portalHost);
});
}
private clearLiveExamples() {
this.portalHosts.forEach((h) => h.dispose());
this.portalHosts = [];
}
}