/
code-editor.service.ts
180 lines (147 loc) · 6.08 KB
/
code-editor.service.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable, of, ReplaySubject, Subscription } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { CodeEditorConfig, NzConfigService } from 'ng-zorro-antd/core/config';
import { PREFIX, warn } from 'ng-zorro-antd/core/logger';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { JoinedEditorOptions, NzCodeEditorLoadingStatus } from './typings';
declare const monaco: NzSafeAny;
const NZ_CONFIG_MODULE_NAME = 'codeEditor';
function tryTriggerFunc(fn?: (...args: NzSafeAny[]) => NzSafeAny): (...args: NzSafeAny) => void {
return (...args: NzSafeAny[]) => {
if (fn) {
fn(...args);
}
};
}
// Caretaker note: previously, these were `NzCodeEditorService` properties.
// They're kept as static variables because this will allow loading Monaco only once.
// This applies to micro frontend apps with multiple Angular apps or a single Angular app
// that can be bootstrapped and destroyed multiple times (e.g. using Webpack module federation).
// Root providers are re-initialized each time the app is bootstrapped. Platform providers aren't.
// We can't make the `NzCodeEditorService` to be a platform provider (`@Injectable({ providedIn: 'platform' })`)
// since it depends on other root providers.
const loaded$ = new ReplaySubject<boolean>(1);
let loadingStatus = NzCodeEditorLoadingStatus.UNLOAD;
@Injectable({
providedIn: 'root'
})
export class NzCodeEditorService implements OnDestroy {
private document: Document;
private firstEditorInitialized = false;
private option: JoinedEditorOptions = {};
private config: CodeEditorConfig;
private subscription: Subscription | null;
option$ = new BehaviorSubject<JoinedEditorOptions>(this.option);
constructor(private readonly nzConfigService: NzConfigService, @Inject(DOCUMENT) _document: NzSafeAny) {
const globalConfig = this.nzConfigService.getConfigForComponent(NZ_CONFIG_MODULE_NAME);
this.document = _document;
this.config = { ...globalConfig };
if (this.config.monacoEnvironment) {
window.MonacoEnvironment = { ...this.config.monacoEnvironment };
}
this.option = this.config.defaultEditorOption || {};
this.subscription = this.nzConfigService.getConfigChangeEventForComponent(NZ_CONFIG_MODULE_NAME).subscribe(() => {
const newGlobalConfig: NzSafeAny = this.nzConfigService.getConfigForComponent(NZ_CONFIG_MODULE_NAME);
if (newGlobalConfig) {
this._updateDefaultOption(newGlobalConfig.defaultEditorOption);
}
});
}
ngOnDestroy(): void {
this.subscription!.unsubscribe();
this.subscription = null;
}
private _updateDefaultOption(option: JoinedEditorOptions): void {
this.option = { ...this.option, ...option };
this.option$.next(this.option);
if ('theme' in option && option.theme) {
monaco.editor.setTheme(option.theme);
}
}
requestToInit(): Observable<JoinedEditorOptions> {
if (loadingStatus === NzCodeEditorLoadingStatus.LOADED) {
this.onInit();
return of(this.getLatestOption());
}
if (loadingStatus === NzCodeEditorLoadingStatus.UNLOAD) {
if (this.config.useStaticLoading && typeof monaco === 'undefined') {
warn(
'You choose to use static loading but it seems that you forget ' +
'to config webpack plugin correctly. Please refer to our official website' +
'for more details about static loading.'
);
} else {
this.loadMonacoScript();
}
}
return loaded$.pipe(
tap(() => this.onInit()),
map(() => this.getLatestOption())
);
}
private loadMonacoScript(): void {
if (this.config.useStaticLoading) {
Promise.resolve().then(() => this.onLoad());
return;
}
if (loadingStatus === NzCodeEditorLoadingStatus.LOADING) {
return;
}
loadingStatus = NzCodeEditorLoadingStatus.LOADING;
const assetsRoot = this.config.assetsRoot;
const vs = assetsRoot ? `${assetsRoot}/vs` : 'assets/vs';
const windowAsAny = window as NzSafeAny;
const loadScript = this.document.createElement('script');
loadScript.type = 'text/javascript';
loadScript.src = `${vs}/loader.js`;
const onLoad = (): void => {
cleanup();
windowAsAny.require.config({
paths: { vs }
});
windowAsAny.require(['vs/editor/editor.main'], () => {
this.onLoad();
});
};
const onError = (): void => {
cleanup();
throw new Error(`${PREFIX} cannot load assets of monaco editor from source "${vs}".`);
};
const cleanup = (): void => {
// Caretaker note: we have to remove these listeners once the `<script>` is loaded successfully
// or not since the `onLoad` listener captures `this`, which will prevent the `NzCodeEditorService`
// from being garbage collected.
loadScript.removeEventListener('load', onLoad);
loadScript.removeEventListener('error', onError);
// We don't need to keep the `<script>` element within the `<body>` since JavaScript has
// been executed and Monaco is available globally. E.g. Webpack, always removes `<script>`
// elements after loading chunks (see its `LoadScriptRuntimeModule`).
this.document.documentElement.removeChild(loadScript);
};
loadScript.addEventListener('load', onLoad);
loadScript.addEventListener('error', onError);
this.document.documentElement.appendChild(loadScript);
}
private onLoad(): void {
loadingStatus = NzCodeEditorLoadingStatus.LOADED;
loaded$.next(true);
loaded$.complete();
tryTriggerFunc(this.config.onLoad)();
}
private onInit(): void {
if (!this.firstEditorInitialized) {
this.firstEditorInitialized = true;
tryTriggerFunc(this.config.onFirstEditorInit)();
}
tryTriggerFunc(this.config.onInit)();
}
private getLatestOption(): JoinedEditorOptions {
return { ...this.option };
}
}