-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
dom.ts
491 lines (413 loc) · 14.7 KB
/
dom.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
import {
Constructable,
IContainer,
InjectArray,
IResolver,
PLATFORM,
Registration,
Reporter,
Writable
} from '@aurelia/kernel';
import {
CompiledTemplate,
DOM,
IDOM,
INode,
INodeSequence,
IRenderContext,
IRenderLocation,
ITemplate,
ITemplateFactory,
NodeSequence,
TemplateDefinition
} from '@aurelia/runtime';
export const enum NodeType {
Element = 1,
Attr = 2,
Text = 3,
CDATASection = 4,
EntityReference = 5,
Entity = 6,
ProcessingInstruction = 7,
Comment = 8,
Document = 9,
DocumentType = 10,
DocumentFragment = 11,
Notation = 12
}
function isRenderLocation(node: Node): node is Node & IRenderLocation {
return node.textContent === 'au-end';
}
export class HTMLDOM implements IDOM {
public readonly Node: typeof Node;
public readonly Element: typeof Element;
public readonly HTMLElement: typeof HTMLElement;
public readonly CustomEvent: typeof CustomEvent;
public readonly window: Window;
public readonly document: Document;
constructor(
window: Window,
document: Document,
TNode: typeof Node,
TElement: typeof Element,
THTMLElement: typeof HTMLElement,
TCustomEvent: typeof CustomEvent
) {
this.window = window;
this.document = document;
this.Node = TNode;
this.Element = TElement;
this.HTMLElement = THTMLElement;
this.CustomEvent = TCustomEvent;
if (DOM.isInitialized) {
Reporter.write(1001); // TODO: create reporters code // DOM already initialized (just info)
DOM.destroy();
}
DOM.initialize(this);
}
public static register(container: IContainer): IResolver<HTMLDOM> {
return Registration.alias(IDOM, this).register(container);
}
public addEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | AddEventListenerOptions): void {
(publisher || this.document).addEventListener(eventName, subscriber, options);
}
public appendChild(parent: Node, child: Node): void {
parent.appendChild(child);
}
public cloneNode<T>(node: T, deep?: boolean): T {
return (node as unknown as Node).cloneNode(deep !== false) as unknown as T;
}
public convertToRenderLocation(node: Node): IRenderLocation {
if (this.isRenderLocation(node)) {
return node; // it's already a IRenderLocation (converted by FragmentNodeSequence)
}
if (node.parentNode === null) {
throw Reporter.error(52);
}
const locationEnd = this.document.createComment('au-end');
const locationStart = this.document.createComment('au-start');
node.parentNode.replaceChild(locationEnd, node);
locationEnd.parentNode.insertBefore(locationStart, locationEnd);
(locationEnd as IRenderLocation).$start = locationStart as IRenderLocation;
(locationStart as IRenderLocation).$nodes = null;
return locationEnd as IRenderLocation;
}
public createDocumentFragment(markupOrNode?: string | Node): DocumentFragment {
if (markupOrNode === undefined || markupOrNode === null) {
return this.document.createDocumentFragment();
}
if (this.isNodeInstance(markupOrNode)) {
if ((markupOrNode as HTMLTemplateElement).content !== undefined) {
return (markupOrNode as HTMLTemplateElement).content;
}
const fragment = this.document.createDocumentFragment();
fragment.appendChild(markupOrNode);
return fragment;
}
return this.createTemplate(markupOrNode).content;
}
public createElement(name: string): HTMLElement {
return this.document.createElement(name);
}
public fetch(input: RequestInfo, init?: RequestInit): Promise<Response> {
return this.window.fetch(input, init);
}
// tslint:disable-next-line:no-any // this is how the DOM is typed
public createCustomEvent<T = any>(eventType: string, options?: CustomEventInit<T>): CustomEvent<T> {
return new this.CustomEvent(eventType, options);
}
public dispatchEvent(evt: Event): void {
this.document.dispatchEvent(evt);
}
public createNodeObserver(node: Node, cb: MutationCallback, init: MutationObserverInit): MutationObserver {
if (typeof MutationObserver === 'undefined') {
// TODO: find a proper response for this scenario
return {
disconnect(): void { /*empty*/ },
observe(): void { /*empty*/ },
takeRecords(): MutationRecord[] { return PLATFORM.emptyArray as MutationRecord[]; }
};
}
const observer = new MutationObserver(cb);
observer.observe(node, init);
return observer;
}
public createTemplate(markup?: unknown): HTMLTemplateElement {
if (markup === undefined || markup === null) {
return this.document.createElement('template');
}
const template = this.document.createElement('template');
template.innerHTML = (markup as string | object).toString();
return template;
}
public createTextNode(text: string): Text {
return this.document.createTextNode(text);
}
public insertBefore(nodeToInsert: Node, referenceNode: Node): void {
referenceNode.parentNode.insertBefore(nodeToInsert, referenceNode);
}
public isMarker(node: unknown): node is HTMLElement {
return (node as AuMarker).nodeName === 'AU-M';
}
public isNodeInstance(potentialNode: unknown): potentialNode is Node {
return potentialNode !== null && potentialNode !== undefined && (potentialNode as Node).nodeType > 0;
}
public isRenderLocation(node: unknown): node is IRenderLocation {
return (node as Comment).textContent === 'au-end';
}
public makeTarget(node: unknown): void {
(node as Element).className = 'au';
}
public registerElementResolver(container: IContainer, resolver: IResolver): void {
container.registerResolver(INode, resolver);
container.registerResolver(this.Node, resolver);
container.registerResolver(this.Element, resolver);
container.registerResolver(this.HTMLElement, resolver);
}
public remove(node: Node): void {
if ((node as ChildNode).remove) {
(node as ChildNode).remove();
} else {
node.parentNode.removeChild(node);
}
}
public removeEventListener(eventName: string, subscriber: EventListenerOrEventListenerObject, publisher?: Node, options?: boolean | EventListenerOptions): void {
(publisher || this.document).removeEventListener(eventName, subscriber, options);
}
public setAttribute(node: Element, name: string, value: unknown): void {
node.setAttribute(name, value as string);
}
}
const $DOM = DOM as unknown as HTMLDOM;
export { $DOM as DOM };
/**
* A specialized INodeSequence with optimizations for text (interpolation) bindings
* The contract of this INodeSequence is:
* - the previous element is an `au-m` node
* - text is the actual text node
*/
/** @internal */
export class TextNodeSequence implements INodeSequence {
public dom: HTMLDOM;
public firstChild: Text;
public lastChild: Text;
public childNodes: Text[];
private readonly targets: [Node];
constructor(dom: HTMLDOM, text: Text) {
this.dom = dom;
this.firstChild = text;
this.lastChild = text;
this.childNodes = [text];
this.targets = [new AuMarker(text) as unknown as Node];
}
public findTargets(): ArrayLike<Node> {
return this.targets;
}
public insertBefore(refNode: Node): void {
refNode.parentNode.insertBefore(this.firstChild, refNode);
}
public appendTo(parent: Node): void {
parent.appendChild(this.firstChild);
}
public remove(): void {
this.firstChild.remove();
}
}
// tslint:enable:no-any
// This is the most common form of INodeSequence.
// Every custom element or template controller whose node sequence is based on an HTML template
// has an instance of this under the hood. Anyone who wants to create a node sequence from
// a string of markup would also receive an instance of this.
// CompiledTemplates create instances of FragmentNodeSequence.
/** @internal */
export class FragmentNodeSequence implements INodeSequence {
public dom: IDOM;
public firstChild: Node;
public lastChild: Node;
public childNodes: Node[];
private end: IRenderLocation & Comment;
private start: IRenderLocation & Comment;
private readonly fragment: DocumentFragment;
private readonly targets: ArrayLike<Node>;
constructor(dom: IDOM, fragment: DocumentFragment) {
this.dom = dom;
this.fragment = fragment;
// tslint:disable-next-line:no-any
const targetNodeList = fragment.querySelectorAll('.au');
let i = 0;
let ii = targetNodeList.length;
const targets = this.targets = Array(ii);
while (i < ii) {
// eagerly convert all markers to RenderLocations (otherwise the renderer
// will do it anyway) and store them in the target list (since the comments
// can't be queried)
const target = targetNodeList[i];
if (target.nodeName === 'AU-M') {
// note the renderer will still call this method, but it will just return the
// location if it sees it's already a location
targets[i] = this.dom.convertToRenderLocation(target);
} else {
// also store non-markers for consistent ordering
targets[i] = target;
}
++i;
}
const childNodeList = fragment.childNodes;
i = 0;
ii = childNodeList.length;
const childNodes = this.childNodes = Array(ii);
while (i < ii) {
childNodes[i] = childNodeList[i] as Writable<Node>;
++i;
}
this.firstChild = fragment.firstChild;
this.lastChild = fragment.lastChild;
this.start = this.end = null;
}
public findTargets(): ArrayLike<Node> {
return this.targets;
}
public insertBefore(refNode: IRenderLocation & Comment): void {
refNode.parentNode.insertBefore(this.fragment, refNode);
// internally we could generally assume that this is an IRenderLocation,
// but since this is also public API we still need to double check
// (or horrible things might happen)
if (isRenderLocation(refNode)) {
this.end = refNode;
const start = this.start = refNode.$start as IRenderLocation & Comment;
if (start.$nodes === null) {
start.$nodes = this;
} else {
// if more than one INodeSequence uses the same IRenderLocation, it's an child
// of a repeater (or something similar) and we shouldn't remove all nodes between
// start - end since that would always remove all items from a repeater, even
// when only one is removed
// so we set $nodes to PLATFORM.emptyObject to 1) tell other sequences that it's
// occupied and 2) prevent start.$nodes === this from ever evaluating to true
// during remove()
start.$nodes = PLATFORM.emptyObject;
}
}
}
public appendTo(parent: Node): void {
// tslint:disable-next-line:no-any
parent.appendChild(this.fragment);
// this can never be a IRenderLocation, and if for whatever reason we moved
// from a IRenderLocation to a host, make sure "start" and "end" are null
this.start = this.end = null;
}
public remove(): void {
const fragment = this.fragment;
if (this.start !== null && this.start.$nodes === this) {
// if we're between a valid "start" and "end" (e.g. if/else, containerless, or a
// repeater with a single item) then simply remove everything in-between (but not
// the comments themselves as they belong to the parent)
const end = this.end;
let next: Node;
let current = this.start.nextSibling;
while (current !== end) {
next = current.nextSibling;
// tslint:disable-next-line:no-any
fragment.appendChild(current);
current = next;
}
this.start.$nodes = null;
this.start = this.end = null;
} else {
// otherwise just remove from first to last child in the regular way
let current = this.firstChild;
if (current.parentNode !== fragment) {
const end = this.lastChild;
let next: Node;
while (current !== null) {
next = current.nextSibling;
// tslint:disable-next-line:no-any
fragment.appendChild(current);
if (current === end) {
break;
}
current = next;
}
}
}
}
}
/** @internal */
export interface NodeSequenceFactory {
createNodeSequence(): INodeSequence;
}
/** @internal */
export class NodeSequenceFactory implements NodeSequenceFactory {
private readonly dom: IDOM;
private readonly deepClone: boolean;
private readonly node: Node;
private readonly Type: Constructable<INodeSequence>;
constructor(dom: IDOM, markupOrNode: string | Node) {
this.dom = dom;
const fragment = dom.createDocumentFragment(markupOrNode) as DocumentFragment;
const childNodes = fragment.childNodes;
switch (childNodes.length) {
case 0:
this.createNodeSequence = () => NodeSequence.empty;
return;
case 2:
const target = childNodes[0];
if (target.nodeName === 'AU-M' || target.nodeName === '#comment') {
const text = childNodes[1];
if (text.nodeType === NodeType.Text && text.textContent.length === 0) {
this.deepClone = false;
this.node = text;
this.Type = TextNodeSequence;
return;
}
}
// falls through if not returned
default:
this.deepClone = true;
this.node = fragment;
this.Type = FragmentNodeSequence;
}
}
public createNodeSequence(): INodeSequence {
return new this.Type(this.dom, this.node.cloneNode(this.deepClone));
}
}
export interface AuMarker extends INode { }
/** @internal */
export class AuMarker implements INode {
public get parentNode(): Node & ParentNode {
return this.nextSibling.parentNode;
}
public readonly nextSibling: Node;
public readonly previousSibling: Node;
public readonly content?: Node;
public readonly childNodes: ArrayLike<ChildNode>;
public readonly nodeName: 'AU-M';
public readonly nodeType: NodeType.Element;
public textContent: string;
constructor(next: Node) {
this.nextSibling = next;
this.textContent = '';
}
public remove(): void { /* do nothing */ }
}
(proto => {
proto.previousSibling = null;
proto.childNodes = PLATFORM.emptyArray;
proto.nodeName = 'AU-M';
proto.nodeType = NodeType.Element;
})(AuMarker.prototype as Writable<AuMarker>);
/** @internal */
export class HTMLTemplateFactory implements ITemplateFactory {
public static readonly inject: InjectArray = [IDOM];
private readonly dom: IDOM;
constructor(dom: IDOM) {
this.dom = dom;
}
public static register(container: IContainer): IResolver<ITemplateFactory> {
return Registration.singleton(ITemplateFactory, this).register(container);
}
public create(parentRenderContext: IRenderContext, definition: TemplateDefinition): ITemplate {
return new CompiledTemplate(this.dom, definition, new NodeSequenceFactory(this.dom, definition.template as string | Node), parentRenderContext);
}
}