Debian Codegraph @

mixmark-io-domino/lib/Document.js

raw symbols SCIP
1 "use strict";
2 module.exports = Document;
3
4 var Node = require('./Node');
5 var NodeList = require('./NodeList');
6 var ContainerNode = require('./ContainerNode');
7 var Element = require('./Element');
8 var Text = require('./Text');
9 var Comment = require('./Comment');
10 var Event = require('./Event');
11 var DocumentFragment = require('./DocumentFragment');
12 var ProcessingInstruction = require('./ProcessingInstruction');
13 var DOMImplementation = require('./DOMImplementation');
14 var TreeWalker = require('./TreeWalker');
15 var NodeIterator = require('./NodeIterator');
16 var NodeFilter = require('./NodeFilter');
17 var URL = require('./URL');
18 var select = require('./select');
19 var events = require('./events');
20 var xml = require('./xmlnames');
21 var html = require('./htmlelts');
22 var svg = require('./svg');
23 var utils = require('./utils');
24 var MUTATE = require('./MutationConstants');
25 var NAMESPACE = utils.NAMESPACE;
26 var isApiWritable = require("./config").isApiWritable;
27
28 function Document(isHTML, address) {
29 ContainerNode.call(this);
30 this.nodeType = Node.DOCUMENT_NODE;
31 this.isHTML = isHTML;
32 this._address = address || 'about:blank';
33 this.readyState = 'loading';
34 this.implementation = new DOMImplementation(this);
35
36 // DOMCore says that documents are always associated with themselves
37 this.ownerDocument = null; // ... but W3C tests expect null
38 this._contentType = isHTML ? 'text/html' : 'application/xml';
39
40 // These will be initialized by our custom versions of
41 // appendChild and insertBefore that override the inherited
42 // Node methods.
43 // XXX: override those methods!
44 this.doctype = null;
45 this.documentElement = null;
46
47 // "Associated inert template document"
48 this._templateDocCache = null;
49 // List of active NodeIterators, see NodeIterator#_preremove()
50 this._nodeIterators = null;
51
52 // Documents are always rooted, by definition
53 this._nid = 1;
54 this._nextnid = 2; // For numbering children of the document
55 this._nodes = [null, this]; // nid to node map
56
57 // This maintains the mapping from element ids to element nodes.
58 // We may need to update this mapping every time a node is rooted
59 // or uprooted, and any time an attribute is added, removed or changed
60 // on a rooted element.
61 this.byId = Object.create(null);
62
63 // This property holds a monotonically increasing value akin to
64 // a timestamp used to record the last modification time of nodes
65 // and their subtrees. See the lastModTime attribute and modify()
66 // method of the Node class. And see FilteredElementList for an example
67 // of the use of lastModTime
68 this.modclock = 0;
69 }
70
71 // Map from lowercase event category names (used as arguments to
72 // createEvent()) to the property name in the impl object of the
73 // event constructor.
74 var supportedEvents = {
75 event: 'Event',
76 customevent: 'CustomEvent',
77 uievent: 'UIEvent',
78 mouseevent: 'MouseEvent'
79 };
80
81 // Certain arguments to document.createEvent() must be treated specially
82 var replacementEvent = {
83 events: 'event',
84 htmlevents: 'event',
85 mouseevents: 'mouseevent',
86 mutationevents: 'mutationevent',
87 uievents: 'uievent'
88 };
89
90 var mirrorAttr = function(f, name, defaultValue) {
91 return {
92 get: function() {
93 var o = f.call(this);
94 if (o) { return o[name]; }
95 return defaultValue;
96 },
97 set: function(value) {
98 var o = f.call(this);
99 if (o) { o[name] = value; }
100 },
101 };
102 };
103
104 /** @spec https://dom.spec.whatwg.org/#validate-and-extract */
105 function validateAndExtract(namespace, qualifiedName) {
106 var prefix, localName, pos;
107 if (namespace==='') { namespace = null; }
108 // See https://github.com/whatwg/dom/issues/671
109 // and https://github.com/whatwg/dom/issues/319
110 if (!xml.isValidQName(qualifiedName)) {
111 utils.InvalidCharacterError();
112 }
113 prefix = null;
114 localName = qualifiedName;
115
116 pos = qualifiedName.indexOf(':');
117 if (pos >= 0) {
118 prefix = qualifiedName.substring(0, pos);
119 localName = qualifiedName.substring(pos+1);
120 }
121 if (prefix !== null && namespace === null) {
122 utils.NamespaceError();
123 }
124 if (prefix === 'xml' && namespace !== NAMESPACE.XML) {
125 utils.NamespaceError();
126 }
127 if ((prefix === 'xmlns' || qualifiedName === 'xmlns') &&
128 namespace !== NAMESPACE.XMLNS) {
129 utils.NamespaceError();
130 }
131 if (namespace === NAMESPACE.XMLNS && !(prefix==='xmlns' || qualifiedName==='xmlns')) {
132 utils.NamespaceError();
133 }
134 return { namespace: namespace, prefix: prefix, localName: localName };
135 }
136
137 Document.prototype = Object.create(ContainerNode.prototype, {
138 // This method allows dom.js to communicate with a renderer
139 // that displays the document in some way
140 // XXX: I should probably move this to the window object
141 _setMutationHandler: { value: function(handler) {
142 this.mutationHandler = handler;
143 }},
144
145 // This method allows dom.js to receive event notifications
146 // from the renderer.
147 // XXX: I should probably move this to the window object
148 _dispatchRendererEvent: { value: function(targetNid, type, details) {
149 var target = this._nodes[targetNid];
150 if (!target) return;
151 target._dispatchEvent(new Event(type, details), true);
152 }},
153
154 nodeName: { value: '#document'},
155 nodeValue: {
156 get: function() {
157 return null;
158 },
159 set: function() {}
160 },
161
162 // XXX: DOMCore may remove documentURI, so it is NYI for now
163 documentURI: { get: function() { return this._address; }, set: utils.nyi },
164 compatMode: { get: function() {
165 // The _quirks property is set by the HTML parser
166 return this._quirks ? 'BackCompat' : 'CSS1Compat';
167 }},
168
169 createTextNode: { value: function(data) {
170 return new Text(this, String(data));
171 }},
172 createComment: { value: function(data) {
173 return new Comment(this, data);
174 }},
175 createDocumentFragment: { value: function() {
176 return new DocumentFragment(this);
177 }},
178 createProcessingInstruction: { value: function(target, data) {
179 if (!xml.isValidName(target) || data.indexOf('?>') !== -1)
180 utils.InvalidCharacterError();
181 return new ProcessingInstruction(this, target, data);
182 }},
183
184 createAttribute: { value: function(localName) {
185 localName = String(localName);
186 if (!xml.isValidName(localName)) utils.InvalidCharacterError();
187 if (this.isHTML) {
188 localName = utils.toASCIILowerCase(localName);
189 }
190 return new Element._Attr(null, localName, null, null, '');
191 }},
192 createAttributeNS: { value: function(namespace, qualifiedName) {
193 // Convert parameter types according to WebIDL
194 namespace =
195 (namespace === null || namespace === undefined || namespace === '') ? null :
196 String(namespace);
197 qualifiedName = String(qualifiedName);
198 var ve = validateAndExtract(namespace, qualifiedName);
199 return new Element._Attr(null, ve.localName, ve.prefix, ve.namespace, '');
200 }},
201
202 createElement: { value: function(localName) {
203 localName = String(localName);
204 if (!xml.isValidName(localName)) utils.InvalidCharacterError();
205 // Per spec, namespace should be HTML namespace if "context object is
206 // an HTML document or context object's content type is
207 // "application/xhtml+xml", and null otherwise.
208 if (this.isHTML) {
209 if (/[A-Z]/.test(localName))
210 localName = utils.toASCIILowerCase(localName);
211 return html.createElement(this, localName, null);
212 } else if (this.contentType === 'application/xhtml+xml') {
213 return html.createElement(this, localName, null);
214 } else {
215 return new Element(this, localName, null, null);
216 }
217 }, writable: isApiWritable },
218
219 createElementNS: { value: function(namespace, qualifiedName) {
220 // Convert parameter types according to WebIDL
221 namespace =
222 (namespace === null || namespace === undefined || namespace === '') ? null :
223 String(namespace);
224 qualifiedName = String(qualifiedName);
225 var ve = validateAndExtract(namespace, qualifiedName);
226 return this._createElementNS(ve.localName, ve.namespace, ve.prefix);
227 }, writable: isApiWritable },
228
229 // This is used directly by HTML parser, which allows it to create
230 // elements with localNames containing ':' and non-default namespaces
231 _createElementNS: { value: function(localName, namespace, prefix) {
232 if (namespace === NAMESPACE.HTML) {
233 return html.createElement(this, localName, prefix);
234 }
235 else if (namespace === NAMESPACE.SVG) {
236 return svg.createElement(this, localName, prefix);
237 }
238
239 return new Element(this, localName, namespace, prefix);
240 }},
241
242 createEvent: { value: function createEvent(interfaceName) {
243 interfaceName = interfaceName.toLowerCase();
244 var name = replacementEvent[interfaceName] || interfaceName;
245 var constructor = events[supportedEvents[name]];
246
247 if (constructor) {
248 var e = new constructor();
249 e._initialized = false;
250 return e;
251 }
252 else {
253 utils.NotSupportedError();
254 }
255 }},
256
257 // See: http://www.w3.org/TR/dom/#dom-document-createtreewalker
258 createTreeWalker: {value: function (root, whatToShow, filter) {
259 if (!root) { throw new TypeError("root argument is required"); }
260 if (!(root instanceof Node)) { throw new TypeError("root not a node"); }
261 whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : (+whatToShow);
262 filter = filter === undefined ? null : filter;
263
264 return new TreeWalker(root, whatToShow, filter);
265 }},
266
267 // See: http://www.w3.org/TR/dom/#dom-document-createnodeiterator
268 createNodeIterator: {value: function (root, whatToShow, filter) {
269 if (!root) { throw new TypeError("root argument is required"); }
270 if (!(root instanceof Node)) { throw new TypeError("root not a node"); }
271 whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : (+whatToShow);
272 filter = filter === undefined ? null : filter;
273
274 return new NodeIterator(root, whatToShow, filter);
275 }},
276
277 _attachNodeIterator: { value: function(ni) {
278 // XXX ideally this should be a weak reference from Document to NodeIterator
279 if (!this._nodeIterators) { this._nodeIterators = []; }
280 this._nodeIterators.push(ni);
281 }},
282
283 _detachNodeIterator: { value: function(ni) {
284 // ni should always be in list of node iterators
285 var idx = this._nodeIterators.indexOf(ni);
286 this._nodeIterators.splice(idx, 1);
287 }},
288
289 _preremoveNodeIterators: { value: function(toBeRemoved) {
290 if (this._nodeIterators) {
291 this._nodeIterators.forEach(function(ni) { ni._preremove(toBeRemoved); });
292 }
293 }},
294
295 // Maintain the documentElement and
296 // doctype properties of the document. Each of the following
297 // methods chains to the Node implementation of the method
298 // to do the actual inserting, removal or replacement.
299
300 _updateDocTypeElement: { value: function _updateDocTypeElement() {
301 this.doctype = this.documentElement = null;
302 for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) {
303 if (kid.nodeType === Node.DOCUMENT_TYPE_NODE)
304 this.doctype = kid;
305 else if (kid.nodeType === Node.ELEMENT_NODE)
306 this.documentElement = kid;
307 }
308 }},
309
310 insertBefore: { value: function insertBefore(child, refChild) {
311 Node.prototype.insertBefore.call(this, child, refChild);
312 this._updateDocTypeElement();
313 return child;
314 }},
315
316 replaceChild: { value: function replaceChild(node, child) {
317 Node.prototype.replaceChild.call(this, node, child);
318 this._updateDocTypeElement();
319 return child;
320 }},
321
322 removeChild: { value: function removeChild(child) {
323 Node.prototype.removeChild.call(this, child);
324 this._updateDocTypeElement();
325 return child;
326 }},
327
328 getElementById: { value: function(id) {
329 var n = this.byId[id];
330 if (!n) return null;
331 if (n instanceof MultiId) { // there was more than one element with this id
332 return n.getFirst();
333 }
334 return n;
335 }},
336
337 _hasMultipleElementsWithId: { value: function(id) {
338 // Used internally by querySelectorAll optimization
339 return (this.byId[id] instanceof MultiId);
340 }},
341
342 // Just copy this method from the Element prototype
343 getElementsByName: { value: Element.prototype.getElementsByName },
344 getElementsByTagName: { value: Element.prototype.getElementsByTagName },
345 getElementsByTagNameNS: { value: Element.prototype.getElementsByTagNameNS },
346 getElementsByClassName: { value: Element.prototype.getElementsByClassName },
347
348 adoptNode: { value: function adoptNode(node) {
349 if (node.nodeType === Node.DOCUMENT_NODE) utils.NotSupportedError();
350 if (node.nodeType === Node.ATTRIBUTE_NODE) { return node; }
351
352 if (node.parentNode) node.parentNode.removeChild(node);
353
354 if (node.ownerDocument !== this)
355 recursivelySetOwner(node, this);
356
357 return node;
358 }},
359
360 importNode: { value: function importNode(node, deep) {
361 return this.adoptNode(node.cloneNode(deep));
362 }, writable: isApiWritable },
363
364 // The following attributes and methods are from the HTML spec
365 origin: { get: function origin() { return null; } },
366 characterSet: { get: function characterSet() { return "UTF-8"; } },
367 contentType: { get: function contentType() { return this._contentType; } },
368 URL: { get: function URL() { return this._address; } },
369 domain: { get: utils.nyi, set: utils.nyi },
370 referrer: { get: utils.nyi },
371 cookie: { get: utils.nyi, set: utils.nyi },
372 lastModified: { get: utils.nyi },
373 location: {
374 get: function() {
375 return this.defaultView ? this.defaultView.location : null; // gh #75
376 },
377 set: utils.nyi
378 },
379 _titleElement: {
380 get: function() {
381 // The title element of a document is the first title element in the
382 // document in tree order, if there is one, or null otherwise.
383 return this.getElementsByTagName('title').item(0) || null;
384 }
385 },
386 title: {
387 get: function() {
388 var elt = this._titleElement;
389 // The child text content of the title element, or '' if null.
390 var value = elt ? elt.textContent : '';
391 // Strip and collapse whitespace in value
392 return value.replace(/[ \t\n\r\f]+/g, ' ').replace(/(^ )|( $)/g, '');
393 },
394 set: function(value) {
395 var elt = this._titleElement;
396 var head = this.head;
397 if (!elt && !head) { return; /* according to spec */ }
398 if (!elt) {
399 elt = this.createElement('title');
400 head.appendChild(elt);
401 }
402 elt.textContent = value;
403 }
404 },
405 dir: mirrorAttr(function() {
406 var htmlElement = this.documentElement;
407 if (htmlElement && htmlElement.tagName === 'HTML') { return htmlElement; }
408 }, 'dir', ''),
409 fgColor: mirrorAttr(function() { return this.body; }, 'text', ''),
410 linkColor: mirrorAttr(function() { return this.body; }, 'link', ''),
411 vlinkColor: mirrorAttr(function() { return this.body; }, 'vLink', ''),
412 alinkColor: mirrorAttr(function() { return this.body; }, 'aLink', ''),
413 bgColor: mirrorAttr(function() { return this.body; }, 'bgColor', ''),
414
415 // Historical aliases of Document#characterSet
416 charset: { get: function() { return this.characterSet; } },
417 inputEncoding: { get: function() { return this.characterSet; } },
418
419 scrollingElement: {
420 get: function() {
421 return this._quirks ? this.body : this.documentElement;
422 }
423 },
424
425 // Return the first <body> child of the document element.
426 // XXX For now, setting this attribute is not implemented.
427 body: {
428 get: function() {
429 return namedHTMLChild(this.documentElement, 'body');
430 },
431 set: utils.nyi
432 },
433 // Return the first <head> child of the document element.
434 head: { get: function() {
435 return namedHTMLChild(this.documentElement, 'head');
436 }},
437 images: { get: utils.nyi },
438 embeds: { get: utils.nyi },
439 plugins: { get: utils.nyi },
440 links: { get: utils.nyi },
441 forms: { get: utils.nyi },
442 scripts: { get: utils.nyi },
443 applets: { get: function() { return []; } },
444 activeElement: { get: function() { return null; } },
445 innerHTML: {
446 get: function() { return this.serialize(); },
447 set: utils.nyi
448 },
449 outerHTML: {
450 get: function() { return this.serialize(); },
451 set: utils.nyi
452 },
453
454 write: { value: function(args) {
455 if (!this.isHTML) utils.InvalidStateError();
456
457 // XXX: still have to implement the ignore part
458 if (!this._parser /* && this._ignore_destructive_writes > 0 */ )
459 return;
460
461 if (!this._parser) {
462 // XXX call document.open, etc.
463 }
464
465 var s = arguments.join('');
466
467 // If the Document object's reload override flag is set, then
468 // append the string consisting of the concatenation of all the
469 // arguments to the method to the Document's reload override
470 // buffer.
471 // XXX: don't know what this is about. Still have to do it
472
473 // If there is no pending parsing-blocking script, have the
474 // tokenizer process the characters that were inserted, one at a
475 // time, processing resulting tokens as they are emitted, and
476 // stopping when the tokenizer reaches the insertion point or when
477 // the processing of the tokenizer is aborted by the tree
478 // construction stage (this can happen if a script end tag token is
479 // emitted by the tokenizer).
480
481 // XXX: still have to do the above. Sounds as if we don't
482 // always call parse() here. If we're blocked, then we just
483 // insert the text into the stream but don't parse it reentrantly...
484
485 // Invoke the parser reentrantly
486 this._parser.parse(s);
487 }},
488
489 writeln: { value: function writeln(args) {
490 this.write(Array.prototype.join.call(arguments, '') + '\n');
491 }},
492
493 open: { value: function() {
494 this.documentElement = null;
495 }},
496
497 close: { value: function() {
498 this.readyState = 'interactive';
499 this._dispatchEvent(new Event('readystatechange'), true);
500 this._dispatchEvent(new Event('DOMContentLoaded'), true);
501 this.readyState = 'complete';
502 this._dispatchEvent(new Event('readystatechange'), true);
503 if (this.defaultView) {
504 this.defaultView._dispatchEvent(new Event('load'), true);
505 }
506 }},
507
508 // Utility methods
509 clone: { value: function clone() {
510 var d = new Document(this.isHTML, this._address);
511 d._quirks = this._quirks;
512 d._contentType = this._contentType;
513 return d;
514 }},
515
516 // We need to adopt the nodes if we do a deep clone
517 cloneNode: { value: function cloneNode(deep) {
518 var clone = Node.prototype.cloneNode.call(this, false);
519 if (deep) {
520 for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) {
521 clone._appendChild(clone.importNode(kid, true));
522 }
523 }
524 clone._updateDocTypeElement();
525 return clone;
526 }},
527
528 isEqual: { value: function isEqual(n) {
529 // Any two documents are shallowly equal.
530 // Node.isEqualNode will also test the children
531 return true;
532 }},
533
534 // Implementation-specific function. Called when a text, comment,
535 // or pi value changes.
536 mutateValue: { value: function(node) {
537 if (this.mutationHandler) {
538 this.mutationHandler({
539 type: MUTATE.VALUE,
540 target: node,
541 data: node.data
542 });
543 }
544 }},
545
546 // Invoked when an attribute's value changes. Attr holds the new
547 // value. oldval is the old value. Attribute mutations can also
548 // involve changes to the prefix (and therefore the qualified name)
549 mutateAttr: { value: function(attr, oldval) {
550 // Manage id->element mapping for getElementsById()
551 // XXX: this special case id handling should not go here,
552 // but in the attribute declaration for the id attribute
553 /*
554 if (attr.localName === 'id' && attr.namespaceURI === null) {
555 if (oldval) delId(oldval, attr.ownerElement);
556 addId(attr.value, attr.ownerElement);
557 }
558 */
559 if (this.mutationHandler) {
560 this.mutationHandler({
561 type: MUTATE.ATTR,
562 target: attr.ownerElement,
563 attr: attr
564 });
565 }
566 }},
567
568 // Used by removeAttribute and removeAttributeNS for attributes.
569 mutateRemoveAttr: { value: function(attr) {
570 /*
571 * This is now handled in Attributes.js
572 // Manage id to element mapping
573 if (attr.localName === 'id' && attr.namespaceURI === null) {
574 this.delId(attr.value, attr.ownerElement);
575 }
576 */
577 if (this.mutationHandler) {
578 this.mutationHandler({
579 type: MUTATE.REMOVE_ATTR,
580 target: attr.ownerElement,
581 attr: attr
582 });
583 }
584 }},
585
586 // Called by Node.removeChild, etc. to remove a rooted element from
587 // the tree. Only needs to generate a single mutation event when a
588 // node is removed, but must recursively mark all descendants as not
589 // rooted.
590 mutateRemove: { value: function(node) {
591 // Send a single mutation event
592 if (this.mutationHandler) {
593 this.mutationHandler({
594 type: MUTATE.REMOVE,
595 target: node.parentNode,
596 node: node
597 });
598 }
599
600 // Mark this and all descendants as not rooted
601 recursivelyUproot(node);
602 }},
603
604 // Called when a new element becomes rooted. It must recursively
605 // generate mutation events for each of the children, and mark them all
606 // as rooted.
607 mutateInsert: { value: function(node) {
608 // Mark node and its descendants as rooted
609 recursivelyRoot(node);
610
611 // Send a single mutation event
612 if (this.mutationHandler) {
613 this.mutationHandler({
614 type: MUTATE.INSERT,
615 target: node.parentNode,
616 node: node
617 });
618 }
619 }},
620
621 // Called when a rooted element is moved within the document
622 mutateMove: { value: function(node) {
623 if (this.mutationHandler) {
624 this.mutationHandler({
625 type: MUTATE.MOVE,
626 target: node
627 });
628 }
629 }},
630
631
632 // Add a mapping from id to n for n.ownerDocument
633 addId: { value: function addId(id, n) {
634 var val = this.byId[id];
635 if (!val) {
636 this.byId[id] = n;
637 }
638 else {
639 // TODO: Add a way to opt-out console warnings
640 //console.warn('Duplicate element id ' + id);
641 if (!(val instanceof MultiId)) {
642 val = new MultiId(val);
643 this.byId[id] = val;
644 }
645 val.add(n);
646 }
647 }},
648
649 // Delete the mapping from id to n for n.ownerDocument
650 delId: { value: function delId(id, n) {
651 var val = this.byId[id];
652 utils.assert(val);
653
654 if (val instanceof MultiId) {
655 val.del(n);
656 if (val.length === 1) { // convert back to a single node
657 this.byId[id] = val.downgrade();
658 }
659 }
660 else {
661 this.byId[id] = undefined;
662 }
663 }},
664
665 _resolve: { value: function(href) {
666 //XXX: Cache the URL
667 return new URL(this._documentBaseURL).resolve(href);
668 }},
669
670 _documentBaseURL: { get: function() {
671 // XXX: This is not implemented correctly yet
672 var url = this._address;
673 if (url === 'about:blank') url = '/';
674
675 var base = this.querySelector('base[href]');
676 if (base) {
677 return new URL(url).resolve(base.getAttribute('href'));
678 }
679 return url;
680
681 // The document base URL of a Document object is the
682 // absolute URL obtained by running these substeps:
683
684 // Let fallback base url be the document's address.
685
686 // If fallback base url is about:blank, and the
687 // Document's browsing context has a creator browsing
688 // context, then let fallback base url be the document
689 // base URL of the creator Document instead.
690
691 // If the Document is an iframe srcdoc document, then
692 // let fallback base url be the document base URL of
693 // the Document's browsing context's browsing context
694 // container's Document instead.
695
696 // If there is no base element that has an href
697 // attribute, then the document base URL is fallback
698 // base url; abort these steps. Otherwise, let url be
699 // the value of the href attribute of the first such
700 // element.
701
702 // Resolve url relative to fallback base url (thus,
703 // the base href attribute isn't affected by xml:base
704 // attributes).
705
706 // The document base URL is the result of the previous
707 // step if it was successful; otherwise it is fallback
708 // base url.
709 }},
710
711 _templateDoc: { get: function() {
712 if (!this._templateDocCache) {
713 // "associated inert template document"
714 var newDoc = new Document(this.isHTML, this._address);
715 this._templateDocCache = newDoc._templateDocCache = newDoc;
716 }
717 return this._templateDocCache;
718 }},
719
720 querySelector: { value: function(selector) {
721 return select(selector, this)[0];
722 }},
723
724 querySelectorAll: { value: function(selector) {
725 var nodes = select(selector, this);
726 return nodes.item ? nodes : new NodeList(nodes);
727 }}
728
729 });
730
731
732 var eventHandlerTypes = [
733 'abort', 'canplay', 'canplaythrough', 'change', 'click', 'contextmenu',
734 'cuechange', 'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave',
735 'dragover', 'dragstart', 'drop', 'durationchange', 'emptied', 'ended',
736 'input', 'invalid', 'keydown', 'keypress', 'keyup', 'loadeddata',
737 'loadedmetadata', 'loadstart', 'mousedown', 'mousemove', 'mouseout',
738 'mouseover', 'mouseup', 'mousewheel', 'pause', 'play', 'playing',
739 'progress', 'ratechange', 'readystatechange', 'reset', 'seeked',
740 'seeking', 'select', 'show', 'stalled', 'submit', 'suspend',
741 'timeupdate', 'volumechange', 'waiting',
742
743 'blur', 'error', 'focus', 'load', 'scroll'
744 ];
745
746 // Add event handler idl attribute getters and setters to Document
747 eventHandlerTypes.forEach(function(type) {
748 // Define the event handler registration IDL attribute for this type
749 Object.defineProperty(Document.prototype, 'on' + type, {
750 get: function() {
751 return this._getEventHandler(type);
752 },
753 set: function(v) {
754 this._setEventHandler(type, v);
755 }
756 });
757 });
758
759 function namedHTMLChild(parent, name) {
760 if (parent && parent.isHTML) {
761 for (var kid = parent.firstChild; kid !== null; kid = kid.nextSibling) {
762 if (kid.nodeType === Node.ELEMENT_NODE &&
763 kid.localName === name &&
764 kid.namespaceURI === NAMESPACE.HTML) {
765 return kid;
766 }
767 }
768 }
769 return null;
770 }
771
772 function root(n) {
773 n._nid = n.ownerDocument._nextnid++;
774 n.ownerDocument._nodes[n._nid] = n;
775 // Manage id to element mapping
776 if (n.nodeType === Node.ELEMENT_NODE) {
777 var id = n.getAttribute('id');
778 if (id) n.ownerDocument.addId(id, n);
779
780 // Script elements need to know when they're inserted
781 // into the document
782 if (n._roothook) n._roothook();
783 }
784 }
785
786 function uproot(n) {
787 // Manage id to element mapping
788 if (n.nodeType === Node.ELEMENT_NODE) {
789 var id = n.getAttribute('id');
790 if (id) n.ownerDocument.delId(id, n);
791 }
792 n.ownerDocument._nodes[n._nid] = undefined;
793 n._nid = undefined;
794 }
795
796 function recursivelyRoot(node) {
797 root(node);
798 // XXX:
799 // accessing childNodes on a leaf node creates a new array the
800 // first time, so be careful to write this loop so that it
801 // doesn't do that. node is polymorphic, so maybe this is hard to
802 // optimize? Try switching on nodeType?
803 /*
804 if (node.hasChildNodes()) {
805 var kids = node.childNodes;
806 for(var i = 0, n = kids.length; i < n; i++)
807 recursivelyRoot(kids[i]);
808 }
809 */
810 if (node.nodeType === Node.ELEMENT_NODE) {
811 for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling)
812 recursivelyRoot(kid);
813 }
814 }
815
816 function recursivelyUproot(node) {
817 uproot(node);
818 for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling)
819 recursivelyUproot(kid);
820 }
821
822 function recursivelySetOwner(node, owner) {
823 node.ownerDocument = owner;
824 node._lastModTime = undefined; // mod times are document-based
825 if (Object.prototype.hasOwnProperty.call(node, '_tagName')) {
826 node._tagName = undefined; // Element subclasses might need to change case
827 }
828 for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling)
829 recursivelySetOwner(kid, owner);
830 }
831
832 // A class for storing multiple nodes with the same ID
833 function MultiId(node) {
834 this.nodes = Object.create(null);
835 this.nodes[node._nid] = node;
836 this.length = 1;
837 this.firstNode = undefined;
838 }
839
840 // Add a node to the list, with O(1) time
841 MultiId.prototype.add = function(node) {
842 if (!this.nodes[node._nid]) {
843 this.nodes[node._nid] = node;
844 this.length++;
845 this.firstNode = undefined;
846 }
847 };
848
849 // Remove a node from the list, with O(1) time
850 MultiId.prototype.del = function(node) {
851 if (this.nodes[node._nid]) {
852 delete this.nodes[node._nid];
853 this.length--;
854 this.firstNode = undefined;
855 }
856 };
857
858 // Get the first node from the list, in the document order
859 // Takes O(N) time in the size of the list, with a cache that is invalidated
860 // when the list is modified.
861 MultiId.prototype.getFirst = function() {
862 /* jshint bitwise: false */
863 if (!this.firstNode) {
864 var nid;
865 for (nid in this.nodes) {
866 if (this.firstNode === undefined ||
867 this.firstNode.compareDocumentPosition(this.nodes[nid]) & Node.DOCUMENT_POSITION_PRECEDING) {
868 this.firstNode = this.nodes[nid];
869 }
870 }
871 }
872 return this.firstNode;
873 };
874
875 // If there is only one node left, return it. Otherwise return "this".
876 MultiId.prototype.downgrade = function() {
877 if (this.length === 1) {
878 var nid;
879 for (nid in this.nodes) {
880 return this.nodes[nid];
881 }
882 }
883 return this;
884 };