-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathElement.ts
587 lines (530 loc) · 23.2 KB
/
Element.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import { Node, NodeName, NamespaceURI } from './Node';
import { ParentNode } from './ParentNode';
import { DOMTokenList, synchronizedAccessor } from './DOMTokenList';
import { Attr, toString as attrsToString, matchPredicate as matchAttrPredicate } from './Attr';
import { mutate } from '../MutationObserver';
import { MutationRecordType } from '../MutationRecord';
import { toLower, toUpper } from '../../utils';
import { CSSStyleDeclaration } from '../css/CSSStyleDeclaration';
import { matchChildrenElements } from './matchElements';
import { reflectProperties } from './enhanceElement';
import { store as storeString } from '../strings';
import { Document } from './Document';
import { transfer } from '../MutationTransfer';
import { TransferrableKeys } from '../../transfer/TransferrableKeys';
import { NodeType, HTML_NAMESPACE } from '../../transfer/TransferrableNodes';
import { TransferrableBoundingClientRect } from '../../transfer/TransferrableBoundClientRect';
import { TransferrableMutationType } from '../../transfer/TransferrableMutation';
import { MessageToWorker, MessageType, BoundingClientRectToWorker } from '../../transfer/Messages';
import { parse } from '../../third_party/html-parser/html-parser';
import { propagate } from './Node';
import { Event } from '../Event';
import { getNextElementSibling, getPreviousElementSibling } from './elementSibling';
export const NS_NAME_TO_CLASS: { [key: string]: typeof Element } = {};
export const registerSubclass = (localName: string, subclass: typeof Element, namespace: string = HTML_NAMESPACE): any =>
(NS_NAME_TO_CLASS[`${namespace}:${localName}`] = subclass);
interface PropertyBackedAttributes {
[key: string]: [(el: Element) => string | null, (el: Element, value: string) => string | boolean];
}
export function definePropertyBackedAttributes(defineOn: typeof Element, attributes: PropertyBackedAttributes) {
const sub = Object.create(defineOn[TransferrableKeys.propertyBackedAttributes]);
defineOn[TransferrableKeys.propertyBackedAttributes] = Object.assign(sub, attributes);
}
interface ClientRect {
left: number;
top: number;
right: number;
bottom: number;
x: number;
y: number;
width: number;
height: number;
}
/**
* There are six kinds of elements, each having different start/close tag semantics.
* @see https://html.spec.whatwg.org/multipage/syntax.html#elements-2
*/
enum ElementKind {
NORMAL,
VOID,
// The following element kinds have no special handling in worker-dom yet
// and are lumped into the NORMAL kind.
/*
FOREIGN,
TEMPLATE,
RAW_TEXT,
ESCAPABLE_RAW,
*/
}
/**
* @see https://html.spec.whatwg.org/multipage/syntax.html#void-elements
*/
const VOID_ELEMENTS: string[] = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR'];
export class Element extends ParentNode {
private _classList: DOMTokenList;
public static [TransferrableKeys.propertyBackedAttributes]: PropertyBackedAttributes = {
class: [(el): string | null => el.classList.value, (el, value: string) => (el.classList.value = value)],
style: [(el): string | null => el.cssText, (el, value: string) => (el.cssText = value)],
};
public localName: NodeName;
public attributes: Attr[] = [];
public namespaceURI: NamespaceURI;
private style_: CSSStyleDeclaration | undefined;
/**
* Element "kind" dictates certain behaviors e.g. start/end tag semantics.
* @see https://html.spec.whatwg.org/multipage/syntax.html#elements-2
*/
private kind: ElementKind;
constructor(nodeType: NodeType, localName: NodeName, namespaceURI: NamespaceURI, ownerDocument: Node | null, overrideIndex?: number) {
super(nodeType, toUpper(localName), ownerDocument, overrideIndex);
this.namespaceURI = namespaceURI || HTML_NAMESPACE;
this.localName = localName;
this.kind = VOID_ELEMENTS.includes(this.tagName) ? ElementKind.VOID : ElementKind.NORMAL;
this[TransferrableKeys.creationFormat] = [
this[TransferrableKeys.index],
this.nodeType,
storeString(this.localName),
0,
this.namespaceURI === null ? 0 : storeString(this.namespaceURI),
];
}
// We lazily instantiate the CSSStyleDeclaration to keep element creation cheap
// See https://github.com/ampproject/worker-dom/pull/1096 for context.
get style(): CSSStyleDeclaration {
if (!this.style_) {
this.style_ = new CSSStyleDeclaration(this);
}
return this.style_;
}
// Unimplemented properties
// Element.clientHeight – https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight
// Element.clientLeft – https://developer.mozilla.org/en-US/docs/Web/API/Element/clientLeft
// Element.clientTop – https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
// Element.clientWidth – https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth
// set Element.innerHTML – https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
// Element.prefix – https://developer.mozilla.org/en-US/docs/Web/API/Element/prefix
// Element.scrollHeight – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight
// Element.scrollLeft – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft
// Element.scrollLeftMax – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeftMax
// Element.scrollTop – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
// Element.scrollTopMax – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTopMax
// Element.scrollWidth – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth
// Element.shadowRoot – !! CustomElements – https://developer.mozilla.org/en-US/docs/Web/API/Element/shadowRoot
// Element.slot – !! CustomElements – https://developer.mozilla.org/en-US/docs/Web/API/Element/slot
// Element.tabStop – https://developer.mozilla.org/en-US/docs/Web/API/Element/tabStop
// Element.undoManager – https://developer.mozilla.org/en-US/docs/Web/API/Element/undoManager
// Element.undoScope – https://developer.mozilla.org/en-US/docs/Web/API/Element/undoScope
// Unimplemented Methods
// Element.attachShadow() – !! CustomElements – https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow
// Element.animate() – https://developer.mozilla.org/en-US/docs/Web/API/Element/animate
// Element.closest() – https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
// Element.getAttributeNames() – https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
// Element.getBoundingClientRect() – https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
// Element.getClientRects() – https://developer.mozilla.org/en-US/docs/Web/API/Element/getClientRects
// Element.getElementsByTagNameNS() – https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagNameNS
// Element.insertAdjacentElement() – https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
// Element.insertAdjacentHTML() – https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
// Element.insertAdjacentText() – https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText
// Element.matches() – https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
// Element.releasePointerCapture() – https://developer.mozilla.org/en-US/docs/Web/API/Element/releasePointerCapture
// Element.requestFullscreen() – https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen
// Element.requestPointerLock() – https://developer.mozilla.org/en-US/docs/Web/API/Element/requestPointerLock
// Element.scrollIntoView() – https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
// Element.setCapture() – https://developer.mozilla.org/en-US/docs/Web/API/Element/setCapture
// Element.setPointerCapture() – https://developer.mozilla.org/en-US/docs/Web/API/Element/setPointerCapture
// Partially implemented Mixin Methods
// Both Element.querySelector() and Element.querySelector() are only implemented for the following simple selectors:
// - Element selectors
// - ID selectors
// - Class selectors
// - Attribute selectors
// Element.querySelector() – https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
// Element.querySelectorAll() – https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
// Mixins not implemented
// Slotable.assignedSlot – https://developer.mozilla.org/en-US/docs/Web/API/Slotable/assignedSlot
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/previousElementSibling
* Returns the Element immediately prior to the specified one in its parent's children list,
* or null if the specified element is the first one in the list.
*/
get previousElementSibling(): Node | null {
return getPreviousElementSibling(this);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/nextElementSibling
* Returns the Element immediately following the specified one in its parent's children list,
* or null if the specified element is the last one in the list.
*/
get nextElementSibling(): Node | null {
return getNextElementSibling(this);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
* @return string representation of serialized HTML describing the Element and its descendants.
*/
get outerHTML(): string {
const tag = this.localName || this.tagName;
const start = `<${[tag, attrsToString(this.attributes)].join(' ').trim()}>`;
const contents = this.innerHTML;
if (!contents) {
if (this.kind === ElementKind.VOID) {
// Void elements e.g. <input> only have a start tag (unless children are added programmatically).
// https://html.spec.whatwg.org/multipage/syntax.html#void-elements
return start;
}
}
return start + contents + `</${tag}>`;
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
* @return string representation of serialized HTML describing the Element's descendants.
*/
get innerHTML(): string {
const childNodes = this.childNodes;
if (childNodes.length) {
return childNodes
.map((child) => {
switch (child.nodeType) {
case NodeType.TEXT_NODE:
return child.textContent;
case NodeType.COMMENT_NODE:
return `<!--${child.textContent}-->`;
default:
return child.outerHTML;
}
})
.join('');
}
return '';
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
* @param html The raw html string to parse.
*/
set innerHTML(html: string) {
const root = parse(html, this);
// remove previous children
this.childNodes.forEach((n) => {
propagate(n, 'isConnected', false);
propagate(n, TransferrableKeys.scopingRoot, n);
});
mutate(
this.ownerDocument as Document,
{
removedNodes: this.childNodes,
type: MutationRecordType.CHILD_LIST,
target: this,
},
[
TransferrableMutationType.CHILD_LIST,
this[TransferrableKeys.index],
0,
0,
0,
this.childNodes.length,
...this.childNodes.map((node) => node[TransferrableKeys.index]),
],
);
this.childNodes = [];
// add new children
root.childNodes.forEach((child: Node) => this.appendChild(child));
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
* @param text new text replacing all childNodes content.
*/
set textContent(text: string) {
// TODO(KB): Investigate removing all children in a single .splice to childNodes.
this.childNodes.slice().forEach((child: Node) => child.remove());
this.appendChild(this.ownerDocument.createTextNode(text));
}
/**
* Getter returning the text representation of Element.childNodes.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
* @return text from all childNodes.
*/
get textContent(): string {
return this.getTextContent();
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName
* @return string tag name (i.e 'div')
*/
get tagName(): string {
return this.nodeName;
}
/**
* Sets the value of an attribute on this element using a null namespace.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
* @param name attribute name
* @param value attribute value
*/
public setAttribute(name: string, value: unknown): void {
this.setAttributeNS(HTML_NAMESPACE, name, value);
}
/**
* Get the value of an attribute on this Element with the null namespace.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
* @param name attribute name
* @return value of a specified attribute on the element, or null if the attribute doesn't exist.
*/
public getAttribute(name: string): string | null {
return this.getAttributeNS(HTML_NAMESPACE, name);
}
/**
* Remove an attribute from this element in the null namespace.
*
* Method returns void, so it is not chainable.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
* @param name attribute name
*/
public removeAttribute(name: string): void {
this.removeAttributeNS(HTML_NAMESPACE, name);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
* @param name attribute name
* @return Boolean indicating if the element has the specified attribute.
*/
public hasAttribute(name: string): boolean {
return this.hasAttributeNS(HTML_NAMESPACE, name);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
* @return Boolean indicating if the element has any attributes.
*/
public hasAttributes(): boolean {
return this.attributes.length > 0;
}
/**
* Sets the value of an attribute on this Element with the provided namespace.
*
* If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS
* @param namespaceURI
* @param name attribute name
* @param value attribute value
*/
public setAttributeNS(namespaceURI: NamespaceURI, name: string, value: unknown): void {
const valueAsString = String(value);
const propertyBacked = (this.constructor as typeof Element)[TransferrableKeys.propertyBackedAttributes][name];
if (propertyBacked !== undefined) {
if (!this.attributes.find(matchAttrPredicate(namespaceURI, name))) {
this.attributes.push({
namespaceURI,
name,
value: valueAsString,
});
}
propertyBacked[1](this, valueAsString);
return;
}
const oldValue = this[TransferrableKeys.storeAttribute](namespaceURI, name, valueAsString);
mutate(
this.ownerDocument as Document,
{
type: MutationRecordType.ATTRIBUTES,
target: this,
attributeName: name,
attributeNamespace: namespaceURI,
value: valueAsString,
oldValue,
},
[
TransferrableMutationType.ATTRIBUTES,
this[TransferrableKeys.index],
storeString(name),
storeString(namespaceURI),
value !== null ? storeString(valueAsString) + 1 : 0,
],
);
}
public [TransferrableKeys.storeAttribute](namespaceURI: NamespaceURI, name: string, value: string): string {
const attr = this.attributes.find(matchAttrPredicate(namespaceURI, name));
const oldValue = (attr && attr.value) || '';
if (attr) {
attr.value = value;
} else {
this.attributes.push({
namespaceURI,
name,
value,
});
}
return oldValue;
}
/**
* Get the value of an attribute on this Element with the specified namespace.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNS
* @param namespaceURI attribute namespace
* @param name attribute name
* @return value of a specified attribute on the element, or null if the attribute doesn't exist.
*/
public getAttributeNS(namespaceURI: NamespaceURI, name: string): string | null {
const attr = this.attributes.find(matchAttrPredicate(namespaceURI, name));
if (attr) {
const propertyBacked = (this.constructor as typeof Element)[TransferrableKeys.propertyBackedAttributes][name];
return propertyBacked !== undefined ? propertyBacked[0](this) : attr.value;
}
return null;
}
/**
* Remove an attribute from this element in the specified namespace.
*
* Method returns void, so it is not chainable.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
* @param namespaceURI attribute namespace
* @param name attribute name
*/
public removeAttributeNS(namespaceURI: NamespaceURI, name: string): void {
const index = this.attributes.findIndex(matchAttrPredicate(namespaceURI, name));
if (index >= 0) {
const oldValue = this.attributes[index].value;
this.attributes.splice(index, 1);
mutate(
this.ownerDocument as Document,
{
type: MutationRecordType.ATTRIBUTES,
target: this,
attributeName: name,
attributeNamespace: namespaceURI,
oldValue,
},
[
TransferrableMutationType.ATTRIBUTES,
this[TransferrableKeys.index],
storeString(name),
storeString(namespaceURI),
0, // 0 means no value
],
);
}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributeNS
* @param namespaceURI attribute namespace
* @param name attribute name
* @return Boolean indicating if the element has the specified attribute.
*/
public hasAttributeNS(namespaceURI: NamespaceURI, name: string): boolean {
return this.attributes.some(matchAttrPredicate(namespaceURI, name));
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
* @param names contains one more more classnames to match on. Multiples are space seperated, indicating an AND operation.
* @return Element array with matching classnames
*/
public getElementsByClassName(names: string): Array<Element> {
const inputClassList = names.split(' ');
// TODO(KB) – Compare performance of [].some(value => DOMTokenList.contains(value)) and regex.
// const classRegex = new RegExp(classNames.split(' ').map(name => `(?=.*${name})`).join(''));
return matchChildrenElements(this, (element) => inputClassList.some((inputClassName) => element.classList.contains(inputClassName)));
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
* @param tagName the qualified name to look for. The special string "*" represents all elements.
* @return Element array with matching tagnames
*/
public getElementsByTagName(tagName: string): Array<Element> {
const lowerTagName = toLower(tagName);
return matchChildrenElements(
this,
tagName === '*'
? (_) => true
: (element) => (element.namespaceURI === HTML_NAMESPACE ? element.localName === lowerTagName : element.tagName === tagName),
);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
* @param name value of name attribute elements must have to be returned
* @return Element array with matching name attributes
*/
public getElementsByName(name: any): Array<Element> {
const stringName = '' + name;
return matchChildrenElements(this, (element) => element.getAttribute('name') === stringName);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
* @param deep boolean determines if the clone should include a recursive copy of all childNodes.
* @return Element containing all current attributes and potentially childNode clones of the Element requested to be cloned.
*/
public cloneNode(deep: boolean = false): Element {
const clone: Element = this.ownerDocument.createElementNS(
this.namespaceURI,
this.namespaceURI === HTML_NAMESPACE ? toLower(this.tagName) : this.tagName,
);
this.attributes.forEach((attr) => clone.setAttribute(attr.name, attr.value));
if (deep) {
this.childNodes.forEach((child: Node) => clone.appendChild(child.cloneNode(deep)));
}
return clone;
}
/**
* Return the ClientRect for an Element once determined by the main thread.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
* @return Promise<ClientRect>
*
* Note: Edge and IE11 do not return the x/y value, but top/left are equivalent. Normalize the values here.
*/
public getBoundingClientRectAsync(): Promise<ClientRect> {
const defaultValue = {
left: 0,
top: 0,
right: 0,
bottom: 0,
x: 0,
y: 0,
width: 0,
height: 0,
};
return new Promise((resolve) => {
const messageHandler = ({ data }: { data: MessageToWorker }) => {
if (
data[TransferrableKeys.type] === MessageType.GET_BOUNDING_CLIENT_RECT &&
(data as BoundingClientRectToWorker)[TransferrableKeys.target][0] === this[TransferrableKeys.index]
) {
this.ownerDocument.removeGlobalEventListener('message', messageHandler);
const transferredBoundingClientRect: TransferrableBoundingClientRect = (data as BoundingClientRectToWorker)[TransferrableKeys.data];
resolve({
top: transferredBoundingClientRect[0],
right: transferredBoundingClientRect[1],
bottom: transferredBoundingClientRect[2],
left: transferredBoundingClientRect[3],
width: transferredBoundingClientRect[4],
height: transferredBoundingClientRect[5],
x: transferredBoundingClientRect[0],
y: transferredBoundingClientRect[3],
});
}
};
if (!this.ownerDocument.addGlobalEventListener || !this.isConnected) {
// Elements run within Node runtimes are missing addEventListener as a global.
// In this case, treat the return value the same as a disconnected node.
resolve(defaultValue);
} else {
this.ownerDocument.addGlobalEventListener('message', messageHandler);
transfer(this.ownerDocument as Document, [TransferrableMutationType.GET_BOUNDING_CLIENT_RECT, this[TransferrableKeys.index]]);
setTimeout(resolve, 500, defaultValue); // TODO: Why a magical constant, define and explain.
}
});
}
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
click() {
const event = new Event('click', {});
event.target = this;
this.dispatchEvent(event);
}
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
scrollIntoView() {
if (this.isConnected) {
transfer(this.ownerDocument as Document, [TransferrableMutationType.SCROLL_INTO_VIEW, this[TransferrableKeys.index]]);
}
}
public get classList(): DOMTokenList {
return this._classList || (this._classList = new DOMTokenList(this, 'class'));
}
}
synchronizedAccessor(Element, 'classList', 'className');
reflectProperties([{ id: [''] }], Element);