Debian Codegraph @

mixmark-io-domino/lib/Element.js

raw symbols SCIP
1 "use strict";
2 module.exports = Element;
3
4 var xml = require('./xmlnames');
5 var utils = require('./utils');
6 var NAMESPACE = utils.NAMESPACE;
7 var attributes = require('./attributes');
8 var Node = require('./Node');
9 var NodeList = require('./NodeList');
10 var NodeUtils = require('./NodeUtils');
11 var FilteredElementList = require('./FilteredElementList');
12 var DOMException = require('./DOMException');
13 var DOMTokenList = require('./DOMTokenList');
14 var select = require('./select');
15 var ContainerNode = require('./ContainerNode');
16 var ChildNode = require('./ChildNode');
17 var NonDocumentTypeChildNode = require('./NonDocumentTypeChildNode');
18 var NamedNodeMap = require('./NamedNodeMap');
19
20 var uppercaseCache = Object.create(null);
21
22 function Element(doc, localName, namespaceURI, prefix) {
23 ContainerNode.call(this);
24 this.nodeType = Node.ELEMENT_NODE;
25 this.ownerDocument = doc;
26 this.localName = localName;
27 this.namespaceURI = namespaceURI;
28 this.prefix = prefix;
29 this._tagName = undefined;
30
31 // These properties maintain the set of attributes
32 this._attrsByQName = Object.create(null); // The qname->Attr map
33 this._attrsByLName = Object.create(null); // The ns|lname->Attr map
34 this._attrKeys = []; // attr index -> ns|lname
35 }
36
37 function recursiveGetText(node, a) {
38 if (node.nodeType === Node.TEXT_NODE) {
39 a.push(node._data);
40 }
41 else {
42 for(var i = 0, n = node.childNodes.length; i < n; i++)
43 recursiveGetText(node.childNodes[i], a);
44 }
45 }
46
47 Element.prototype = Object.create(ContainerNode.prototype, {
48 isHTML: { get: function isHTML() {
49 return this.namespaceURI === NAMESPACE.HTML && this.ownerDocument.isHTML;
50 }},
51 tagName: { get: function tagName() {
52 if (this._tagName === undefined) {
53 var tn;
54 if (this.prefix === null) {
55 tn = this.localName;
56 } else {
57 tn = this.prefix + ':' + this.localName;
58 }
59 if (this.isHTML) {
60 var up = uppercaseCache[tn];
61 if (!up) {
62 // Converting to uppercase can be slow, so cache the conversion.
63 uppercaseCache[tn] = up = utils.toASCIIUpperCase(tn);
64 }
65 tn = up;
66 }
67 this._tagName = tn;
68 }
69 return this._tagName;
70 }},
71 nodeName: { get: function() { return this.tagName; }},
72 nodeValue: {
73 get: function() {
74 return null;
75 },
76 set: function() {}
77 },
78 textContent: {
79 get: function() {
80 var strings = [];
81 recursiveGetText(this, strings);
82 return strings.join('');
83 },
84 set: function(newtext) {
85 this.removeChildren();
86 if (newtext !== null && newtext !== undefined && newtext !== '') {
87 this._appendChild(this.ownerDocument.createTextNode(newtext));
88 }
89 }
90 },
91 innerText: {
92 get: function() {
93 var strings = [];
94 recursiveGetText(this, strings);
95 // Strip and collapse whitespace
96 // This doesn't 100% match the browser behavior,
97 // but should cover most of the cases. This is also similar to
98 // how Angular's renderer used to work: the `textContent` and `innerText`
99 // were almost equivalent from the renderer perspective.
100 // See: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext
101 return strings.join('').replace(/[ \t\n\f\r]+/g, ' ').trim();
102 },
103 set: function(newtext) {
104 this.removeChildren();
105 if (newtext !== null && newtext !== undefined && newtext !== '') {
106 this._appendChild(this.ownerDocument.createTextNode(newtext));
107 }
108 }
109 },
110 innerHTML: {
111 get: function() {
112 return this.serialize();
113 },
114 set: utils.nyi
115 },
116 outerHTML: {
117 get: function() {
118 // "the attribute must return the result of running the HTML fragment
119 // serialization algorithm on a fictional node whose only child is
120 // the context object"
121 //
122 // The serialization logic is intentionally implemented in a separate
123 // `NodeUtils` helper instead of the more obvious choice of a private
124 // `_serializeOne()` method on the `Node.prototype` in order to avoid
125 // the megamorphic `this._serializeOne` property access, which reduces
126 // performance unnecessarily. If you need specialized behavior for a
127 // certain subclass, you'll need to implement that in `NodeUtils`.
128 // See https://github.com/fgnass/domino/pull/142 for more information.
129 return NodeUtils.serializeOne(this, { nodeType: 0 });
130 },
131 set: function(v) {
132 var document = this.ownerDocument;
133 var parent = this.parentNode;
134 if (parent === null) { return; }
135 if (parent.nodeType === Node.DOCUMENT_NODE) {
136 utils.NoModificationAllowedError();
137 }
138 if (parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
139 parent = parent.ownerDocument.createElement("body");
140 }
141 var parser = document.implementation.mozHTMLParser(
142 document._address,
143 parent
144 );
145 parser.parse(v===null?'':String(v), true);
146 this.replaceWith(parser._asDocumentFragment());
147 },
148 },
149
150 _insertAdjacent: { value: function _insertAdjacent(position, node) {
151 var first = false;
152 switch(position) {
153 case 'beforebegin':
154 first = true;
155 /* falls through */
156 case 'afterend':
157 var parent = this.parentNode;
158 if (parent === null) { return null; }
159 return parent.insertBefore(node, first ? this : this.nextSibling);
160 case 'afterbegin':
161 first = true;
162 /* falls through */
163 case 'beforeend':
164 return this.insertBefore(node, first ? this.firstChild : null);
165 default:
166 return utils.SyntaxError();
167 }
168 }},
169
170 insertAdjacentElement: { value: function insertAdjacentElement(position, element) {
171 if (element.nodeType !== Node.ELEMENT_NODE) {
172 throw new TypeError('not an element');
173 }
174 position = utils.toASCIILowerCase(String(position));
175 return this._insertAdjacent(position, element);
176 }},
177
178 insertAdjacentText: { value: function insertAdjacentText(position, data) {
179 var textNode = this.ownerDocument.createTextNode(data);
180 position = utils.toASCIILowerCase(String(position));
181 this._insertAdjacent(position, textNode);
182 // "This method returns nothing because it existed before we had a chance
183 // to design it."
184 }},
185
186 insertAdjacentHTML: { value: function insertAdjacentHTML(position, text) {
187 position = utils.toASCIILowerCase(String(position));
188 text = String(text);
189 var context;
190 switch(position) {
191 case 'beforebegin':
192 case 'afterend':
193 context = this.parentNode;
194 if (context === null || context.nodeType === Node.DOCUMENT_NODE) {
195 utils.NoModificationAllowedError();
196 }
197 break;
198 case 'afterbegin':
199 case 'beforeend':
200 context = this;
201 break;
202 default:
203 utils.SyntaxError();
204 }
205 if ( (!(context instanceof Element)) || (
206 context.ownerDocument.isHTML &&
207 context.localName === 'html' &&
208 context.namespaceURI === NAMESPACE.HTML
209 ) ) {
210 context = context.ownerDocument.createElementNS(NAMESPACE.HTML, 'body');
211 }
212 var parser = this.ownerDocument.implementation.mozHTMLParser(
213 this.ownerDocument._address, context
214 );
215 parser.parse(text, true);
216 this._insertAdjacent(position, parser._asDocumentFragment());
217 }},
218
219 children: { get: function() {
220 if (!this._children) {
221 this._children = new ChildrenCollection(this);
222 }
223 return this._children;
224 }},
225
226 attributes: { get: function() {
227 if (!this._attributes) {
228 this._attributes = new AttributesArray(this);
229 }
230 return this._attributes;
231 }},
232
233
234 firstElementChild: { get: function() {
235 for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) {
236 if (kid.nodeType === Node.ELEMENT_NODE) return kid;
237 }
238 return null;
239 }},
240
241 lastElementChild: { get: function() {
242 for (var kid = this.lastChild; kid !== null; kid = kid.previousSibling) {
243 if (kid.nodeType === Node.ELEMENT_NODE) return kid;
244 }
245 return null;
246 }},
247
248 childElementCount: { get: function() {
249 return this.children.length;
250 }},
251
252
253 // Return the next element, in source order, after this one or
254 // null if there are no more. If root element is specified,
255 // then don't traverse beyond its subtree.
256 //
257 // This is not a DOM method, but is convenient for
258 // lazy traversals of the tree.
259 nextElement: { value: function(root) {
260 if (!root) root = this.ownerDocument.documentElement;
261 var next = this.firstElementChild;
262 if (!next) {
263 // don't use sibling if we're at root
264 if (this===root) return null;
265 next = this.nextElementSibling;
266 }
267 if (next) return next;
268
269 // If we can't go down or across, then we have to go up
270 // and across to the parent sibling or another ancestor's
271 // sibling. Be careful, though: if we reach the root
272 // element, or if we reach the documentElement, then
273 // the traversal ends.
274 for(var parent = this.parentElement;
275 parent && parent !== root;
276 parent = parent.parentElement) {
277
278 next = parent.nextElementSibling;
279 if (next) return next;
280 }
281
282 return null;
283 }},
284
285 // XXX:
286 // Tests are currently failing for this function.
287 // Awaiting resolution of:
288 // http://lists.w3.org/Archives/Public/www-dom/2011JulSep/0016.html
289 getElementsByTagName: { value: function getElementsByTagName(lname) {
290 var filter;
291 if (!lname) return new NodeList();
292 if (lname === '*')
293 filter = function() { return true; };
294 else if (this.isHTML)
295 filter = htmlLocalNameElementFilter(lname);
296 else
297 filter = localNameElementFilter(lname);
298
299 return new FilteredElementList(this, filter);
300 }},
301
302 getElementsByTagNameNS: { value: function getElementsByTagNameNS(ns, lname){
303 var filter;
304 if (ns === '*' && lname === '*')
305 filter = function() { return true; };
306 else if (ns === '*')
307 filter = localNameElementFilter(lname);
308 else if (lname === '*')
309 filter = namespaceElementFilter(ns);
310 else
311 filter = namespaceLocalNameElementFilter(ns, lname);
312
313 return new FilteredElementList(this, filter);
314 }},
315
316 getElementsByClassName: { value: function getElementsByClassName(names){
317 names = String(names).trim();
318 if (names === '') {
319 var result = new NodeList(); // Empty node list
320 return result;
321 }
322 names = names.split(/[ \t\r\n\f]+/); // Split on ASCII whitespace
323 return new FilteredElementList(this, classNamesElementFilter(names));
324 }},
325
326 getElementsByName: { value: function getElementsByName(name) {
327 return new FilteredElementList(this, elementNameFilter(String(name)));
328 }},
329
330 // Utility methods used by the public API methods above
331 clone: { value: function clone() {
332 var e;
333
334 // XXX:
335 // Modify this to use the constructor directly or
336 // avoid error checking in some other way. In case we try
337 // to clone an invalid node that the parser inserted.
338 //
339 if (this.namespaceURI !== NAMESPACE.HTML || this.prefix || !this.ownerDocument.isHTML) {
340 e = this.ownerDocument.createElementNS(
341 this.namespaceURI, (this.prefix !== null) ?
342 (this.prefix + ':' + this.localName) : this.localName
343 );
344 } else {
345 e = this.ownerDocument.createElement(this.localName);
346 }
347
348 for(var i = 0, n = this._attrKeys.length; i < n; i++) {
349 var lname = this._attrKeys[i];
350 var a = this._attrsByLName[lname];
351 var b = a.cloneNode();
352 b._setOwnerElement(e);
353 e._attrsByLName[lname] = b;
354 e._addQName(b);
355 }
356 e._attrKeys = this._attrKeys.concat();
357
358 return e;
359 }},
360
361 isEqual: { value: function isEqual(that) {
362 if (this.localName !== that.localName ||
363 this.namespaceURI !== that.namespaceURI ||
364 this.prefix !== that.prefix ||
365 this._numattrs !== that._numattrs)
366 return false;
367
368 // Compare the sets of attributes, ignoring order
369 // and ignoring attribute prefixes.
370 for(var i = 0, n = this._numattrs; i < n; i++) {
371 var a = this._attr(i);
372 if (!that.hasAttributeNS(a.namespaceURI, a.localName))
373 return false;
374 if (that.getAttributeNS(a.namespaceURI,a.localName) !== a.value)
375 return false;
376 }
377
378 return true;
379 }},
380
381 // This is the 'locate a namespace prefix' algorithm from the
382 // DOM specification. It is used by Node.lookupPrefix()
383 // (Be sure to compare DOM3 and DOM4 versions of spec.)
384 _lookupNamespacePrefix: { value: function _lookupNamespacePrefix(ns, originalElement) {
385 if (
386 this.namespaceURI &&
387 this.namespaceURI === ns &&
388 this.prefix !== null &&
389 originalElement.lookupNamespaceURI(this.prefix) === ns
390 ) {
391 return this.prefix;
392 }
393
394 for(var i = 0, n = this._numattrs; i < n; i++) {
395 var a = this._attr(i);
396 if (
397 a.prefix === 'xmlns' &&
398 a.value === ns &&
399 originalElement.lookupNamespaceURI(a.localName) === ns
400 ) {
401 return a.localName;
402 }
403 }
404
405 var parent = this.parentElement;
406 return parent ? parent._lookupNamespacePrefix(ns, originalElement) : null;
407 }},
408
409 // This is the 'locate a namespace' algorithm for Element nodes
410 // from the DOM Core spec. It is used by Node#lookupNamespaceURI()
411 lookupNamespaceURI: { value: function lookupNamespaceURI(prefix) {
412 if (prefix === '' || prefix === undefined) { prefix = null; }
413 if (this.namespaceURI !== null && this.prefix === prefix)
414 return this.namespaceURI;
415
416 for(var i = 0, n = this._numattrs; i < n; i++) {
417 var a = this._attr(i);
418 if (a.namespaceURI === NAMESPACE.XMLNS) {
419 if (
420 (a.prefix === 'xmlns' && a.localName === prefix) ||
421 (prefix === null && a.prefix === null && a.localName === 'xmlns')
422 ) {
423 return a.value || null;
424 }
425 }
426 }
427
428 var parent = this.parentElement;
429 return parent ? parent.lookupNamespaceURI(prefix) : null;
430 }},
431
432 //
433 // Attribute handling methods and utilities
434 //
435
436 /*
437 * Attributes in the DOM are tricky:
438 *
439 * - there are the 8 basic get/set/has/removeAttribute{NS} methods
440 *
441 * - but many HTML attributes are also 'reflected' through IDL
442 * attributes which means that they can be queried and set through
443 * regular properties of the element. There is just one attribute
444 * value, but two ways to get and set it.
445 *
446 * - Different HTML element types have different sets of reflected
447 attributes.
448 *
449 * - attributes can also be queried and set through the .attributes
450 * property of an element. This property behaves like an array of
451 * Attr objects. The value property of each Attr is writeable, so
452 * this is a third way to read and write attributes.
453 *
454 * - for efficiency, we really want to store attributes in some kind
455 * of name->attr map. But the attributes[] array is an array, not a
456 * map, which is kind of unnatural.
457 *
458 * - When using namespaces and prefixes, and mixing the NS methods
459 * with the non-NS methods, it is apparently actually possible for
460 * an attributes[] array to have more than one attribute with the
461 * same qualified name. And certain methods must operate on only
462 * the first attribute with such a name. So for these methods, an
463 * inefficient array-like data structure would be easier to
464 * implement.
465 *
466 * - The attributes[] array is live, not a snapshot, so changes to the
467 * attributes must be immediately visible through existing arrays.
468 *
469 * - When attributes are queried and set through IDL properties
470 * (instead of the get/setAttributes() method or the attributes[]
471 * array) they may be subject to type conversions, URL
472 * normalization, etc., so some extra processing is required in that
473 * case.
474 *
475 * - But access through IDL properties is probably the most common
476 * case, so we'd like that to be as fast as possible.
477 *
478 * - We can't just store attribute values in their parsed idl form,
479 * because setAttribute() has to return whatever string is passed to
480 * getAttribute even if it is not a legal, parseable value. So
481 * attribute values must be stored in unparsed string form.
482 *
483 * - We need to be able to send change notifications or mutation
484 * events of some sort to the renderer whenever an attribute value
485 * changes, regardless of the way in which it changes.
486 *
487 * - Some attributes, such as id and class affect other parts of the
488 * DOM API, like getElementById and getElementsByClassName and so
489 * for efficiency, we need to specially track changes to these
490 * special attributes.
491 *
492 * - Some attributes like class have different names (className) when
493 * reflected.
494 *
495 * - Attributes whose names begin with the string 'data-' are treated
496 specially.
497 *
498 * - Reflected attributes that have a boolean type in IDL have special
499 * behavior: setting them to false (in IDL) is the same as removing
500 * them with removeAttribute()
501 *
502 * - numeric attributes (like HTMLElement.tabIndex) can have default
503 * values that must be returned by the idl getter even if the
504 * content attribute does not exist. (The default tabIndex value
505 * actually varies based on the type of the element, so that is a
506 * tricky one).
507 *
508 * See
509 * http://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#reflect
510 * for rules on how attributes are reflected.
511 *
512 */
513
514 getAttribute: { value: function getAttribute(qname) {
515 var attr = this.getAttributeNode(qname);
516 return attr ? attr.value : null;
517 }},
518
519 getAttributeNS: { value: function getAttributeNS(ns, lname) {
520 var attr = this.getAttributeNodeNS(ns, lname);
521 return attr ? attr.value : null;
522 }},
523
524 getAttributeNode: { value: function getAttributeNode(qname) {
525 qname = String(qname);
526 if (/[A-Z]/.test(qname) && this.isHTML)
527 qname = utils.toASCIILowerCase(qname);
528 var attr = this._attrsByQName[qname];
529 if (!attr) return null;
530
531 if (Array.isArray(attr)) // If there is more than one
532 attr = attr[0]; // use the first
533
534 return attr;
535 }},
536
537 getAttributeNodeNS: { value: function getAttributeNodeNS(ns, lname) {
538 ns = (ns === undefined || ns === null) ? '' : String(ns);
539 lname = String(lname);
540 var attr = this._attrsByLName[ns + '|' + lname];
541 return attr ? attr : null;
542 }},
543
544 hasAttribute: { value: function hasAttribute(qname) {
545 qname = String(qname);
546 if (/[A-Z]/.test(qname) && this.isHTML)
547 qname = utils.toASCIILowerCase(qname);
548 return this._attrsByQName[qname] !== undefined;
549 }},
550
551 hasAttributeNS: { value: function hasAttributeNS(ns, lname) {
552 ns = (ns === undefined || ns === null) ? '' : String(ns);
553 lname = String(lname);
554 var key = ns + '|' + lname;
555 return this._attrsByLName[key] !== undefined;
556 }},
557
558 hasAttributes: { value: function hasAttributes() {
559 return this._numattrs > 0;
560 }},
561
562 toggleAttribute: { value: function toggleAttribute(qname, force) {
563 qname = String(qname);
564 if (!xml.isValidName(qname)) utils.InvalidCharacterError();
565 if (/[A-Z]/.test(qname) && this.isHTML)
566 qname = utils.toASCIILowerCase(qname);
567 var a = this._attrsByQName[qname];
568 if (a === undefined) {
569 if (force === undefined || force === true) {
570 this._setAttribute(qname, '');
571 return true;
572 }
573 return false;
574 } else {
575 if (force === undefined || force === false) {
576 this.removeAttribute(qname);
577 return false;
578 }
579 return true;
580 }
581 }},
582
583 // Set the attribute without error checking. The parser uses this.
584 _setAttribute: { value: function _setAttribute(qname, value) {
585 // XXX: the spec says that this next search should be done
586 // on the local name, but I think that is an error.
587 // email pending on www-dom about it.
588 var attr = this._attrsByQName[qname];
589 var isnew;
590 if (!attr) {
591 attr = this._newattr(qname);
592 isnew = true;
593 }
594 else {
595 if (Array.isArray(attr)) attr = attr[0];
596 }
597
598 // Now set the attribute value on the new or existing Attr object.
599 // The Attr.value setter method handles mutation events, etc.
600 attr.value = value;
601 if (this._attributes) this._attributes[qname] = attr;
602 if (isnew && this._newattrhook) this._newattrhook(qname, value);
603 }},
604
605 // Check for errors, and then set the attribute
606 setAttribute: { value: function setAttribute(qname, value) {
607 qname = String(qname);
608 if (!xml.isValidName(qname)) utils.InvalidCharacterError();
609 if (/[A-Z]/.test(qname) && this.isHTML)
610 qname = utils.toASCIILowerCase(qname);
611 this._setAttribute(qname, String(value));
612 }},
613
614
615 // The version with no error checking used by the parser
616 _setAttributeNS: { value: function _setAttributeNS(ns, qname, value) {
617 var pos = qname.indexOf(':'), prefix, lname;
618 if (pos < 0) {
619 prefix = null;
620 lname = qname;
621 }
622 else {
623 prefix = qname.substring(0, pos);
624 lname = qname.substring(pos+1);
625 }
626
627 if (ns === '' || ns === undefined) ns = null;
628 var key = (ns === null ? '' : ns) + '|' + lname;
629
630 var attr = this._attrsByLName[key];
631 var isnew;
632 if (!attr) {
633 attr = new Attr(this, lname, prefix, ns);
634 isnew = true;
635 this._attrsByLName[key] = attr;
636 if (this._attributes) {
637 this._attributes[this._attrKeys.length] = attr;
638 }
639 this._attrKeys.push(key);
640
641 // We also have to make the attr searchable by qname.
642 // But we have to be careful because there may already
643 // be an attr with this qname.
644 this._addQName(attr);
645 }
646 else if (false /* changed in DOM 4 */) {
647 // Calling setAttributeNS() can change the prefix of an
648 // existing attribute in DOM 2/3.
649 if (attr.prefix !== prefix) {
650 // Unbind the old qname
651 this._removeQName(attr);
652 // Update the prefix
653 attr.prefix = prefix;
654 // Bind the new qname
655 this._addQName(attr);
656 }
657
658 }
659 attr.value = value; // Automatically sends mutation event
660 if (isnew && this._newattrhook) this._newattrhook(qname, value);
661 }},
662
663 // Do error checking then call _setAttributeNS
664 setAttributeNS: { value: function setAttributeNS(ns, qname, value) {
665 // Convert parameter types according to WebIDL
666 ns = (ns === null || ns === undefined || ns === '') ? null : String(ns);
667 qname = String(qname);
668 if (!xml.isValidQName(qname)) utils.InvalidCharacterError();
669
670 var pos = qname.indexOf(':');
671 var prefix = (pos < 0) ? null : qname.substring(0, pos);
672
673 if ((prefix !== null && ns === null) ||
674 (prefix === 'xml' && ns !== NAMESPACE.XML) ||
675 ((qname === 'xmlns' || prefix === 'xmlns') &&
676 (ns !== NAMESPACE.XMLNS)) ||
677 (ns === NAMESPACE.XMLNS &&
678 !(qname === 'xmlns' || prefix === 'xmlns')))
679 utils.NamespaceError();
680
681 this._setAttributeNS(ns, qname, String(value));
682 }},
683
684 setAttributeNode: { value: function setAttributeNode(attr) {
685 if (attr.ownerElement !== null && attr.ownerElement !== this) {
686 throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);
687 }
688 var result = null;
689 var oldAttrs = this._attrsByQName[attr.name];
690 if (oldAttrs) {
691 if (!Array.isArray(oldAttrs)) { oldAttrs = [ oldAttrs ]; }
692 if (oldAttrs.some(function(a) { return a===attr; })) {
693 return attr;
694 } else if (attr.ownerElement !== null) {
695 throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);
696 }
697 oldAttrs.forEach(function(a) { this.removeAttributeNode(a); }, this);
698 result = oldAttrs[0];
699 }
700 this.setAttributeNodeNS(attr);
701 return result;
702 }},
703
704 setAttributeNodeNS: { value: function setAttributeNodeNS(attr) {
705 if (attr.ownerElement !== null) {
706 throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR);
707 }
708 var ns = attr.namespaceURI;
709 var key = (ns === null ? '' : ns) + '|' + attr.localName;
710 var oldAttr = this._attrsByLName[key];
711 if (oldAttr) { this.removeAttributeNode(oldAttr); }
712 attr._setOwnerElement(this);
713 this._attrsByLName[key] = attr;
714 if (this._attributes) {
715 this._attributes[this._attrKeys.length] = attr;
716 }
717 this._attrKeys.push(key);
718 this._addQName(attr);
719 if (this._newattrhook) this._newattrhook(attr.name, attr.value);
720 return oldAttr || null;
721 }},
722
723 removeAttribute: { value: function removeAttribute(qname) {
724 qname = String(qname);
725 if (/[A-Z]/.test(qname) && this.isHTML)
726 qname = utils.toASCIILowerCase(qname);
727
728 var attr = this._attrsByQName[qname];
729 if (!attr) return;
730
731 // If there is more than one match for this qname
732 // so don't delete the qname mapping, just remove the first
733 // element from it.
734 if (Array.isArray(attr)) {
735 if (attr.length > 2) {
736 attr = attr.shift(); // remove it from the array
737 }
738 else {
739 this._attrsByQName[qname] = attr[1];
740 attr = attr[0];
741 }
742 }
743 else {
744 // only a single match, so remove the qname mapping
745 this._attrsByQName[qname] = undefined;
746 }
747
748 var ns = attr.namespaceURI;
749 // Now attr is the removed attribute. Figure out its
750 // ns+lname key and remove it from the other mapping as well.
751 var key = (ns === null ? '' : ns) + '|' + attr.localName;
752 this._attrsByLName[key] = undefined;
753
754 var i = this._attrKeys.indexOf(key);
755 if (this._attributes) {
756 Array.prototype.splice.call(this._attributes, i, 1);
757 this._attributes[qname] = undefined;
758 }
759 this._attrKeys.splice(i, 1);
760
761 // Onchange handler for the attribute
762 var onchange = attr.onchange;
763 attr._setOwnerElement(null);
764 if (onchange) {
765 onchange.call(attr, this, attr.localName, attr.value, null);
766 }
767 // Mutation event
768 if (this.rooted) this.ownerDocument.mutateRemoveAttr(attr);
769 }},
770
771 removeAttributeNS: { value: function removeAttributeNS(ns, lname) {
772 ns = (ns === undefined || ns === null) ? '' : String(ns);
773 lname = String(lname);
774 var key = ns + '|' + lname;
775 var attr = this._attrsByLName[key];
776 if (!attr) return;
777
778 this._attrsByLName[key] = undefined;
779
780 var i = this._attrKeys.indexOf(key);
781 if (this._attributes) {
782 Array.prototype.splice.call(this._attributes, i, 1);
783 }
784 this._attrKeys.splice(i, 1);
785
786 // Now find the same Attr object in the qname mapping and remove it
787 // But be careful because there may be more than one match.
788 this._removeQName(attr);
789
790 // Onchange handler for the attribute
791 var onchange = attr.onchange;
792 attr._setOwnerElement(null);
793 if (onchange) {
794 onchange.call(attr, this, attr.localName, attr.value, null);
795 }
796 // Mutation event
797 if (this.rooted) this.ownerDocument.mutateRemoveAttr(attr);
798 }},
799
800 removeAttributeNode: { value: function removeAttributeNode(attr) {
801 var ns = attr.namespaceURI;
802 var key = (ns === null ? '' : ns) + '|' + attr.localName;
803 if (this._attrsByLName[key] !== attr) {
804 utils.NotFoundError();
805 }
806 this.removeAttributeNS(ns, attr.localName);
807 return attr;
808 }},
809
810 getAttributeNames: { value: function getAttributeNames() {
811 var elt = this;
812 return this._attrKeys.map(function(key) {
813 return elt._attrsByLName[key].name;
814 });
815 }},
816
817 // This 'raw' version of getAttribute is used by the getter functions
818 // of reflected attributes. It skips some error checking and
819 // namespace steps
820 _getattr: { value: function _getattr(qname) {
821 // Assume that qname is already lowercased, so don't do it here.
822 // Also don't check whether attr is an array: a qname with no
823 // prefix will never have two matching Attr objects (because
824 // setAttributeNS doesn't allow a non-null namespace with a
825 // null prefix.
826 var attr = this._attrsByQName[qname];
827 return attr ? attr.value : null;
828 }},
829
830 // The raw version of setAttribute for reflected idl attributes.
831 _setattr: { value: function _setattr(qname, value) {
832 var attr = this._attrsByQName[qname];
833 var isnew;
834 if (!attr) {
835 attr = this._newattr(qname);
836 isnew = true;
837 }
838 attr.value = String(value);
839 if (this._attributes) this._attributes[qname] = attr;
840 if (isnew && this._newattrhook) this._newattrhook(qname, value);
841 }},
842
843 // Create a new Attr object, insert it, and return it.
844 // Used by setAttribute() and by set()
845 _newattr: { value: function _newattr(qname) {
846 var attr = new Attr(this, qname, null, null);
847 var key = '|' + qname;
848 this._attrsByQName[qname] = attr;
849 this._attrsByLName[key] = attr;
850 if (this._attributes) {
851 this._attributes[this._attrKeys.length] = attr;
852 }
853 this._attrKeys.push(key);
854 return attr;
855 }},
856
857 // Add a qname->Attr mapping to the _attrsByQName object, taking into
858 // account that there may be more than one attr object with the
859 // same qname
860 _addQName: { value: function(attr) {
861 var qname = attr.name;
862 var existing = this._attrsByQName[qname];
863 if (!existing) {
864 this._attrsByQName[qname] = attr;
865 }
866 else if (Array.isArray(existing)) {
867 existing.push(attr);
868 }
869 else {
870 this._attrsByQName[qname] = [existing, attr];
871 }
872 if (this._attributes) this._attributes[qname] = attr;
873 }},
874
875 // Remove a qname->Attr mapping to the _attrsByQName object, taking into
876 // account that there may be more than one attr object with the
877 // same qname
878 _removeQName: { value: function(attr) {
879 var qname = attr.name;
880 var target = this._attrsByQName[qname];
881
882 if (Array.isArray(target)) {
883 var idx = target.indexOf(attr);
884 utils.assert(idx !== -1); // It must be here somewhere
885 if (target.length === 2) {
886 this._attrsByQName[qname] = target[1-idx];
887 if (this._attributes) {
888 this._attributes[qname] = this._attrsByQName[qname];
889 }
890 } else {
891 target.splice(idx, 1);
892 if (this._attributes && this._attributes[qname] === attr) {
893 this._attributes[qname] = target[0];
894 }
895 }
896 }
897 else {
898 utils.assert(target === attr); // If only one, it must match
899 this._attrsByQName[qname] = undefined;
900 if (this._attributes) {
901 this._attributes[qname] = undefined;
902 }
903 }
904 }},
905
906 // Return the number of attributes
907 _numattrs: { get: function() { return this._attrKeys.length; }},
908 // Return the nth Attr object
909 _attr: { value: function(n) {
910 return this._attrsByLName[this._attrKeys[n]];
911 }},
912
913 // Define getters and setters for an 'id' property that reflects
914 // the content attribute 'id'.
915 id: attributes.property({name: 'id'}),
916
917 // Define getters and setters for a 'className' property that reflects
918 // the content attribute 'class'.
919 className: attributes.property({name: 'class'}),
920
921 classList: { get: function() {
922 var self = this;
923 if (this._classList) {
924 return this._classList;
925 }
926 var dtlist = new DOMTokenList(
927 function() {
928 return self.className || "";
929 },
930 function(v) {
931 self.className = v;
932 }
933 );
934 this._classList = dtlist;
935 return dtlist;
936 }, set: function(v) { this.className = v; }},
937
938 matches: { value: function(selector) {
939 return select.matches(this, selector);
940 }},
941
942 closest: { value: function(selector) {
943 var el = this;
944 do {
945 if (el.matches && el.matches(selector)) { return el; }
946 el = el.parentElement || el.parentNode;
947 } while (el !== null && el.nodeType === Node.ELEMENT_NODE);
948 return null;
949 }},
950
951 querySelector: { value: function(selector) {
952 return select(selector, this)[0];
953 }},
954
955 querySelectorAll: { value: function(selector) {
956 var nodes = select(selector, this);
957 return nodes.item ? nodes : new NodeList(nodes);
958 }}
959
960 });
961
962 Object.defineProperties(Element.prototype, ChildNode);
963 Object.defineProperties(Element.prototype, NonDocumentTypeChildNode);
964
965 // Register special handling for the id attribute
966 attributes.registerChangeHandler(Element, 'id',
967 function(element, lname, oldval, newval) {
968 if (element.rooted) {
969 if (oldval) {
970 element.ownerDocument.delId(oldval, element);
971 }
972 if (newval) {
973 element.ownerDocument.addId(newval, element);
974 }
975 }
976 }
977 );
978 attributes.registerChangeHandler(Element, 'class',
979 function(element, lname, oldval, newval) {
980 if (element._classList) { element._classList._update(); }
981 }
982 );
983
984 // The Attr class represents a single attribute. The values in
985 // _attrsByQName and _attrsByLName are instances of this class.
986 function Attr(elt, lname, prefix, namespace, value) {
987 // localName and namespace are constant for any attr object.
988 // But value may change. And so can prefix, and so, therefore can name.
989 this.localName = lname;
990 this.prefix = (prefix===null || prefix==='') ? null : ('' + prefix);
991 this.namespaceURI = (namespace===null || namespace==='') ? null : ('' + namespace);
992 this.data = value;
993 // Set ownerElement last to ensure it is hooked up to onchange handler
994 this._setOwnerElement(elt);
995 }
996
997 // In DOM 3 Attr was supposed to extend Node; in DOM 4 that was abandoned.
998 Attr.prototype = Object.create(Object.prototype, {
999 ownerElement: {
1000 get: function() { return this._ownerElement; },
1001 },
1002 _setOwnerElement: { value: function _setOwnerElement(elt) {
1003 this._ownerElement = elt;
1004 if (this.prefix === null && this.namespaceURI === null && elt) {
1005 this.onchange = elt._attributeChangeHandlers[this.localName];
1006 } else {
1007 this.onchange = null;
1008 }
1009 }},
1010
1011 name: { get: function() {
1012 return this.prefix ? this.prefix + ':' + this.localName : this.localName;
1013 }},
1014
1015 specified: { get: function() {
1016 // Deprecated
1017 return true;
1018 }},
1019
1020 value: {
1021 get: function() {
1022 return this.data;
1023 },
1024 set: function(value) {
1025 var oldval = this.data;
1026 value = (value === undefined) ? '' : value + '';
1027 if (value === oldval) return;
1028
1029 this.data = value;
1030
1031 // Run the onchange hook for the attribute
1032 // if there is one.
1033 if (this.ownerElement) {
1034 if (this.onchange)
1035 this.onchange(this.ownerElement,this.localName, oldval, value);
1036
1037 // Generate a mutation event if the element is rooted
1038 if (this.ownerElement.rooted)
1039 this.ownerElement.ownerDocument.mutateAttr(this, oldval);
1040 }
1041 },
1042 },
1043
1044 cloneNode: { value: function cloneNode(deep) {
1045 // Both this method and Document#createAttribute*() create unowned Attrs
1046 return new Attr(
1047 null, this.localName, this.prefix, this.namespaceURI, this.data
1048 );
1049 }},
1050
1051 // Legacy aliases (see gh#70 and https://dom.spec.whatwg.org/#interface-attr)
1052 nodeType: { get: function() { return Node.ATTRIBUTE_NODE; } },
1053 nodeName: { get: function() { return this.name; } },
1054 nodeValue: {
1055 get: function() { return this.value; },
1056 set: function(v) { this.value = v; },
1057 },
1058 textContent: {
1059 get: function() { return this.value; },
1060 set: function(v) {
1061 if (v === null || v === undefined) { v = ''; }
1062 this.value = v;
1063 },
1064 },
1065 innerText: {
1066 get: function() { return this.value; },
1067 set: function(v) {
1068 if (v === null || v === undefined) { v = ''; }
1069 this.value = v;
1070 },
1071 },
1072 });
1073 // Sneakily export this class for use by Document.createAttribute()
1074 Element._Attr = Attr;
1075
1076 // The attributes property of an Element will be an instance of this class.
1077 // This class is really just a dummy, though. It only defines a length
1078 // property and an item() method. The AttrArrayProxy that
1079 // defines the public API just uses the Element object itself.
1080 function AttributesArray(elt) {
1081 NamedNodeMap.call(this, elt);
1082 for (var name in elt._attrsByQName) {
1083 this[name] = elt._attrsByQName[name];
1084 }
1085 for (var i = 0; i < elt._attrKeys.length; i++) {
1086 this[i] = elt._attrsByLName[elt._attrKeys[i]];
1087 }
1088 }
1089 AttributesArray.prototype = Object.create(NamedNodeMap.prototype, {
1090 length: { get: function() {
1091 return this.element._attrKeys.length;
1092 }, set: function() { /* ignore */ } },
1093 item: { value: function(n) {
1094 /* jshint bitwise: false */
1095 n = n >>> 0;
1096 if (n >= this.length) { return null; }
1097 return this.element._attrsByLName[this.element._attrKeys[n]];
1098 /* jshint bitwise: true */
1099 } },
1100 });
1101
1102 // We can't make direct array access work (without Proxies, node >=6)
1103 // but we can make `Array.from(node.attributes)` and for-of loops work.
1104 if (globalThis.Symbol?.iterator) {
1105 AttributesArray.prototype[globalThis.Symbol.iterator] = function() {
1106 var i=0, n=this.length, self=this;
1107 return {
1108 next: function() {
1109 if (i<n) return { value: self.item(i++) };
1110 return { done: true };
1111 }
1112 };
1113 };
1114 }
1115
1116
1117 // The children property of an Element will be an instance of this class.
1118 // It defines length, item() and namedItem() and will be wrapped by an
1119 // HTMLCollection when exposed through the DOM.
1120 function ChildrenCollection(e) {
1121 this.element = e;
1122 this.updateCache();
1123 }
1124
1125 ChildrenCollection.prototype = Object.create(Object.prototype, {
1126 length: { get: function() {
1127 this.updateCache();
1128 return this.childrenByNumber.length;
1129 } },
1130 item: { value: function item(n) {
1131 this.updateCache();
1132 return this.childrenByNumber[n] || null;
1133 } },
1134
1135 namedItem: { value: function namedItem(name) {
1136 this.updateCache();
1137 return this.childrenByName[name] || null;
1138 } },
1139
1140 // This attribute returns the entire name->element map.
1141 // It is not part of the HTMLCollection API, but we need it in
1142 // src/HTMLCollectionProxy
1143 namedItems: { get: function() {
1144 this.updateCache();
1145 return this.childrenByName;
1146 } },
1147
1148 updateCache: { value: function updateCache() {
1149 var namedElts = /^(a|applet|area|embed|form|frame|frameset|iframe|img|object)$/;
1150 if (this.lastModTime !== this.element.lastModTime) {
1151 this.lastModTime = this.element.lastModTime;
1152
1153 var n = this.childrenByNumber && this.childrenByNumber.length || 0;
1154 for(var i = 0; i < n; i++) {
1155 this[i] = undefined;
1156 }
1157
1158 this.childrenByNumber = [];
1159 this.childrenByName = Object.create(null);
1160
1161 for (var c = this.element.firstChild; c !== null; c = c.nextSibling) {
1162 if (c.nodeType === Node.ELEMENT_NODE) {
1163
1164 this[this.childrenByNumber.length] = c;
1165 this.childrenByNumber.push(c);
1166
1167 // XXX Are there any requirements about the namespace
1168 // of the id property?
1169 var id = c.getAttribute('id');
1170
1171 // If there is an id that is not already in use...
1172 if (id && !this.childrenByName[id])
1173 this.childrenByName[id] = c;
1174
1175 // For certain HTML elements we check the name attribute
1176 var name = c.getAttribute('name');
1177 if (name &&
1178 this.element.namespaceURI === NAMESPACE.HTML &&
1179 namedElts.test(this.element.localName) &&
1180 !this.childrenByName[name])
1181 this.childrenByName[id] = c;
1182 }
1183 }
1184 }
1185 } },
1186 });
1187
1188 // These functions return predicates for filtering elements.
1189 // They're used by the Document and Element classes for methods like
1190 // getElementsByTagName and getElementsByClassName
1191
1192 function localNameElementFilter(lname) {
1193 return function(e) { return e.localName === lname; };
1194 }
1195
1196 function htmlLocalNameElementFilter(lname) {
1197 var lclname = utils.toASCIILowerCase(lname);
1198 if (lclname === lname)
1199 return localNameElementFilter(lname);
1200
1201 return function(e) {
1202 return e.isHTML ? e.localName === lclname : e.localName === lname;
1203 };
1204 }
1205
1206 function namespaceElementFilter(ns) {
1207 return function(e) { return e.namespaceURI === ns; };
1208 }
1209
1210 function namespaceLocalNameElementFilter(ns, lname) {
1211 return function(e) {
1212 return e.namespaceURI === ns && e.localName === lname;
1213 };
1214 }
1215
1216 function classNamesElementFilter(names) {
1217 return function(e) {
1218 return names.every(function(n) { return e.classList.contains(n); });
1219 };
1220 }
1221
1222 function elementNameFilter(name) {
1223 return function(e) {
1224 // All the *HTML elements* in the document with the given name attribute
1225 if (e.namespaceURI !== NAMESPACE.HTML) { return false; }
1226 return e.getAttribute('name') === name;
1227 };
1228 }