-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
dom_renderer.ts
532 lines (460 loc) Β· 15.8 KB
/
dom_renderer.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DOCUMENT, isPlatformServer, Ι΅getDOM as getDOM} from '@angular/common';
import {
APP_ID,
CSP_NONCE,
Inject,
Injectable,
InjectionToken,
NgZone,
OnDestroy,
PLATFORM_ID,
Renderer2,
RendererFactory2,
RendererStyleFlags2,
RendererType2,
ViewEncapsulation,
Ι΅RuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {EventManager} from './events/event_manager';
import {SharedStylesHost} from './shared_styles_host';
export const NAMESPACE_URIS: {[ns: string]: string} = {
'svg': 'http://www.w3.org/2000/svg',
'xhtml': 'http://www.w3.org/1999/xhtml',
'xlink': 'http://www.w3.org/1999/xlink',
'xml': 'http://www.w3.org/XML/1998/namespace',
'xmlns': 'http://www.w3.org/2000/xmlns/',
'math': 'http://www.w3.org/1998/MathML/',
};
const COMPONENT_REGEX = /%COMP%/g;
export const COMPONENT_VARIABLE = '%COMP%';
export const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
export const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
/**
* The default value for the `REMOVE_STYLES_ON_COMPONENT_DESTROY` DI token.
*/
const REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT = true;
/**
* A DI token that indicates whether styles
* of destroyed components should be removed from DOM.
*
* By default, the value is set to `true`.
* @publicApi
*/
export const REMOVE_STYLES_ON_COMPONENT_DESTROY = new InjectionToken<boolean>(
ngDevMode ? 'RemoveStylesOnCompDestroy' : '',
{
providedIn: 'root',
factory: () => REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT,
},
);
export function shimContentAttribute(componentShortId: string): string {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
export function shimHostAttribute(componentShortId: string): string {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
export function shimStylesContent(compId: string, styles: string[]): string[] {
return styles.map((s) => s.replace(COMPONENT_REGEX, compId));
}
@Injectable()
export class DomRendererFactory2 implements RendererFactory2, OnDestroy {
private readonly rendererByCompId = new Map<
string,
EmulatedEncapsulationDomRenderer2 | NoneEncapsulationDomRenderer
>();
private readonly defaultRenderer: Renderer2;
private readonly platformIsServer: boolean;
constructor(
private readonly eventManager: EventManager,
private readonly sharedStylesHost: SharedStylesHost,
@Inject(APP_ID) private readonly appId: string,
@Inject(REMOVE_STYLES_ON_COMPONENT_DESTROY) private removeStylesOnCompDestroy: boolean,
@Inject(DOCUMENT) private readonly doc: Document,
@Inject(PLATFORM_ID) readonly platformId: Object,
readonly ngZone: NgZone,
@Inject(CSP_NONCE) private readonly nonce: string | null = null,
) {
this.platformIsServer = isPlatformServer(platformId);
this.defaultRenderer = new DefaultDomRenderer2(
eventManager,
doc,
ngZone,
this.platformIsServer,
);
}
createRenderer(element: any, type: RendererType2 | null): Renderer2 {
if (!element || !type) {
return this.defaultRenderer;
}
if (this.platformIsServer && type.encapsulation === ViewEncapsulation.ShadowDom) {
// Domino does not support shadow DOM.
type = {...type, encapsulation: ViewEncapsulation.Emulated};
}
const renderer = this.getOrCreateRenderer(element, type);
// Renderers have different logic due to different encapsulation behaviours.
// Ex: for emulated, an attribute is added to the element.
if (renderer instanceof EmulatedEncapsulationDomRenderer2) {
renderer.applyToHost(element);
} else if (renderer instanceof NoneEncapsulationDomRenderer) {
renderer.applyStyles();
}
return renderer;
}
private getOrCreateRenderer(element: any, type: RendererType2): Renderer2 {
const rendererByCompId = this.rendererByCompId;
let renderer = rendererByCompId.get(type.id);
if (!renderer) {
const doc = this.doc;
const ngZone = this.ngZone;
const eventManager = this.eventManager;
const sharedStylesHost = this.sharedStylesHost;
const removeStylesOnCompDestroy = this.removeStylesOnCompDestroy;
const platformIsServer = this.platformIsServer;
switch (type.encapsulation) {
case ViewEncapsulation.Emulated:
renderer = new EmulatedEncapsulationDomRenderer2(
eventManager,
sharedStylesHost,
type,
this.appId,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
);
break;
case ViewEncapsulation.ShadowDom:
return new ShadowDomRenderer(
eventManager,
sharedStylesHost,
element,
type,
doc,
ngZone,
this.nonce,
platformIsServer,
);
default:
renderer = new NoneEncapsulationDomRenderer(
eventManager,
sharedStylesHost,
type,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
);
break;
}
rendererByCompId.set(type.id, renderer);
}
return renderer;
}
ngOnDestroy() {
this.rendererByCompId.clear();
}
}
class DefaultDomRenderer2 implements Renderer2 {
data: {[key: string]: any} = Object.create(null);
/**
* By default this renderer throws when encountering synthetic properties
* This can be disabled for example by the AsyncAnimationRendererFactory
*/
throwOnSyntheticProps = true;
constructor(
private readonly eventManager: EventManager,
private readonly doc: Document,
private readonly ngZone: NgZone,
private readonly platformIsServer: boolean,
) {}
destroy(): void {}
destroyNode = null;
createElement(name: string, namespace?: string): any {
if (namespace) {
// TODO: `|| namespace` was added in
// https://github.com/angular/angular/commit/2b9cc8503d48173492c29f5a271b61126104fbdb to
// support how Ivy passed around the namespace URI rather than short name at the time. It did
// not, however extend the support to other parts of the system (setAttribute, setAttribute,
// and the ServerRenderer). We should decide what exactly the semantics for dealing with
// namespaces should be and make it consistent.
// Related issues:
// https://github.com/angular/angular/issues/44028
// https://github.com/angular/angular/issues/44883
return this.doc.createElementNS(NAMESPACE_URIS[namespace] || namespace, name);
}
return this.doc.createElement(name);
}
createComment(value: string): any {
return this.doc.createComment(value);
}
createText(value: string): any {
return this.doc.createTextNode(value);
}
appendChild(parent: any, newChild: any): void {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.appendChild(newChild);
}
insertBefore(parent: any, newChild: any, refChild: any): void {
if (parent) {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.insertBefore(newChild, refChild);
}
}
removeChild(parent: any, oldChild: any): void {
if (parent) {
parent.removeChild(oldChild);
}
}
selectRootElement(selectorOrNode: string | any, preserveContent?: boolean): any {
let el: any =
typeof selectorOrNode === 'string' ? this.doc.querySelector(selectorOrNode) : selectorOrNode;
if (!el) {
throw new RuntimeError(
RuntimeErrorCode.ROOT_NODE_NOT_FOUND,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`The selector "${selectorOrNode}" did not match any elements`,
);
}
if (!preserveContent) {
el.textContent = '';
}
return el;
}
parentNode(node: any): any {
return node.parentNode;
}
nextSibling(node: any): any {
return node.nextSibling;
}
setAttribute(el: any, name: string, value: string, namespace?: string): void {
if (namespace) {
name = namespace + ':' + name;
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
} else {
el.setAttribute(name, value);
}
} else {
el.setAttribute(name, value);
}
}
removeAttribute(el: any, name: string, namespace?: string): void {
if (namespace) {
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
} else {
el.removeAttribute(`${namespace}:${name}`);
}
} else {
el.removeAttribute(name);
}
}
addClass(el: any, name: string): void {
el.classList.add(name);
}
removeClass(el: any, name: string): void {
el.classList.remove(name);
}
setStyle(el: any, style: string, value: any, flags: RendererStyleFlags2): void {
if (flags & (RendererStyleFlags2.DashCase | RendererStyleFlags2.Important)) {
el.style.setProperty(style, value, flags & RendererStyleFlags2.Important ? 'important' : '');
} else {
el.style[style] = value;
}
}
removeStyle(el: any, style: string, flags: RendererStyleFlags2): void {
if (flags & RendererStyleFlags2.DashCase) {
// removeProperty has no effect when used on camelCased properties.
el.style.removeProperty(style);
} else {
el.style[style] = '';
}
}
setProperty(el: any, name: string, value: any): void {
if (el == null) {
return;
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
this.throwOnSyntheticProps &&
checkNoSyntheticProp(name, 'property');
el[name] = value;
}
setValue(node: any, value: string): void {
node.nodeValue = value;
}
listen(
target: 'window' | 'document' | 'body' | any,
event: string,
callback: (event: any) => boolean,
): () => void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
this.throwOnSyntheticProps &&
checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
target = getDOM().getGlobalEventTarget(this.doc, target);
if (!target) {
throw new Error(`Unsupported event target ${target} for event ${event}`);
}
}
return this.eventManager.addEventListener(
target,
event,
this.decoratePreventDefault(callback),
) as VoidFunction;
}
private decoratePreventDefault(eventHandler: Function): Function {
// `DebugNode.triggerEventHandler` needs to know if the listener was created with
// decoratePreventDefault or is a listener added outside the Angular context so it can handle
// the two differently. In the first case, the special '__ngUnwrap__' token is passed to the
// unwrap the listener (see below).
return (event: any) => {
// Ivy uses '__ngUnwrap__' as a special token that allows us to unwrap the function
// so that it can be invoked programmatically by `DebugNode.triggerEventHandler`. The
// debug_node can inspect the listener toString contents for the existence of this special
// token. Because the token is a string literal, it is ensured to not be modified by compiled
// code.
if (event === '__ngUnwrap__') {
return eventHandler;
}
// Run the event handler inside the ngZone because event handlers are not patched
// by Zone on the server. This is required only for tests.
const allowDefaultBehavior = this.platformIsServer
? this.ngZone.runGuarded(() => eventHandler(event))
: eventHandler(event);
if (allowDefaultBehavior === false) {
event.preventDefault();
}
return undefined;
};
}
}
const AT_CHARCODE = (() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name: string, nameKind: string) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_SYNTHETIC_PROPERTY,
`Unexpected synthetic ${nameKind} ${name} found. Please make sure that:
- Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application.
- There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`,
);
}
}
function isTemplateNode(node: any): node is HTMLTemplateElement {
return node.tagName === 'TEMPLATE' && node.content !== undefined;
}
class ShadowDomRenderer extends DefaultDomRenderer2 {
private shadowRoot: any;
constructor(
eventManager: EventManager,
private sharedStylesHost: SharedStylesHost,
private hostEl: any,
component: RendererType2,
doc: Document,
ngZone: NgZone,
nonce: string | null,
platformIsServer: boolean,
) {
super(eventManager, doc, ngZone, platformIsServer);
this.shadowRoot = (hostEl as any).attachShadow({mode: 'open'});
this.sharedStylesHost.addHost(this.shadowRoot);
const styles = shimStylesContent(component.id, component.styles);
for (const style of styles) {
const styleEl = document.createElement('style');
if (nonce) {
styleEl.setAttribute('nonce', nonce);
}
styleEl.textContent = style;
this.shadowRoot.appendChild(styleEl);
}
}
private nodeOrShadowRoot(node: any): any {
return node === this.hostEl ? this.shadowRoot : node;
}
override appendChild(parent: any, newChild: any): void {
return super.appendChild(this.nodeOrShadowRoot(parent), newChild);
}
override insertBefore(parent: any, newChild: any, refChild: any): void {
return super.insertBefore(this.nodeOrShadowRoot(parent), newChild, refChild);
}
override removeChild(parent: any, oldChild: any): void {
return super.removeChild(this.nodeOrShadowRoot(parent), oldChild);
}
override parentNode(node: any): any {
return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(node)));
}
override destroy() {
this.sharedStylesHost.removeHost(this.shadowRoot);
}
}
class NoneEncapsulationDomRenderer extends DefaultDomRenderer2 {
private readonly styles: string[];
constructor(
eventManager: EventManager,
private readonly sharedStylesHost: SharedStylesHost,
component: RendererType2,
private removeStylesOnCompDestroy: boolean,
doc: Document,
ngZone: NgZone,
platformIsServer: boolean,
compId?: string,
) {
super(eventManager, doc, ngZone, platformIsServer);
this.styles = compId ? shimStylesContent(compId, component.styles) : component.styles;
}
applyStyles(): void {
this.sharedStylesHost.addStyles(this.styles);
}
override destroy(): void {
if (!this.removeStylesOnCompDestroy) {
return;
}
this.sharedStylesHost.removeStyles(this.styles);
}
}
class EmulatedEncapsulationDomRenderer2 extends NoneEncapsulationDomRenderer {
private contentAttr: string;
private hostAttr: string;
constructor(
eventManager: EventManager,
sharedStylesHost: SharedStylesHost,
component: RendererType2,
appId: string,
removeStylesOnCompDestroy: boolean,
doc: Document,
ngZone: NgZone,
platformIsServer: boolean,
) {
const compId = appId + '-' + component.id;
super(
eventManager,
sharedStylesHost,
component,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
compId,
);
this.contentAttr = shimContentAttribute(compId);
this.hostAttr = shimHostAttribute(compId);
}
applyToHost(element: any): void {
this.applyStyles();
this.setAttribute(element, this.hostAttr, '');
}
override createElement(parent: any, name: string): Element {
const el = super.createElement(parent, name);
super.setAttribute(el, this.contentAttr, '');
return el;
}
}