dom.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. var conventions = require("./conventions");
  2. var NAMESPACE = conventions.NAMESPACE;
  3. /**
  4. * A prerequisite for `[].filter`, to drop elements that are empty
  5. * @param {string} input
  6. * @returns {boolean}
  7. */
  8. function notEmptyString (input) {
  9. return input !== ''
  10. }
  11. /**
  12. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  13. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  14. *
  15. * @param {string} input
  16. * @returns {string[]} (can be empty)
  17. */
  18. function splitOnASCIIWhitespace(input) {
  19. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  20. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []
  21. }
  22. /**
  23. * Adds element as a key to current if it is not already present.
  24. *
  25. * @param {Record<string, boolean | undefined>} current
  26. * @param {string} element
  27. * @returns {Record<string, boolean | undefined>}
  28. */
  29. function orderedSetReducer (current, element) {
  30. if (!current.hasOwnProperty(element)) {
  31. current[element] = true;
  32. }
  33. return current;
  34. }
  35. /**
  36. * @see https://infra.spec.whatwg.org/#ordered-set
  37. * @param {string} input
  38. * @returns {string[]}
  39. */
  40. function toOrderedSet(input) {
  41. if (!input) return [];
  42. var list = splitOnASCIIWhitespace(input);
  43. return Object.keys(list.reduce(orderedSetReducer, {}))
  44. }
  45. /**
  46. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  47. * which we can not rely on being available.
  48. *
  49. * @param {any[]} list
  50. * @returns {function(any): boolean}
  51. */
  52. function arrayIncludes (list) {
  53. return function(element) {
  54. return list && list.indexOf(element) !== -1;
  55. }
  56. }
  57. function copy(src,dest){
  58. for(var p in src){
  59. dest[p] = src[p];
  60. }
  61. }
  62. /**
  63. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  64. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  65. */
  66. function _extends(Class,Super){
  67. var pt = Class.prototype;
  68. if(!(pt instanceof Super)){
  69. function t(){};
  70. t.prototype = Super.prototype;
  71. t = new t();
  72. copy(pt,t);
  73. Class.prototype = pt = t;
  74. }
  75. if(pt.constructor != Class){
  76. if(typeof Class != 'function'){
  77. console.error("unknown Class:"+Class)
  78. }
  79. pt.constructor = Class
  80. }
  81. }
  82. // Node Types
  83. var NodeType = {}
  84. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  85. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  86. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  87. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  88. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  89. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  90. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  91. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  92. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  93. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  94. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  95. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  96. // ExceptionCode
  97. var ExceptionCode = {}
  98. var ExceptionMessage = {};
  99. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  100. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  101. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  102. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  103. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  104. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  105. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  106. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  107. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  108. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  109. //level2
  110. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  111. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  112. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  113. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  114. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  115. /**
  116. * DOM Level 2
  117. * Object DOMException
  118. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  119. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  120. */
  121. function DOMException(code, message) {
  122. if(message instanceof Error){
  123. var error = message;
  124. }else{
  125. error = this;
  126. Error.call(this, ExceptionMessage[code]);
  127. this.message = ExceptionMessage[code];
  128. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  129. }
  130. error.code = code;
  131. if(message) this.message = this.message + ": " + message;
  132. return error;
  133. };
  134. DOMException.prototype = Error.prototype;
  135. copy(ExceptionCode,DOMException)
  136. /**
  137. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  138. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  139. * The items in the NodeList are accessible via an integral index, starting from 0.
  140. */
  141. function NodeList() {
  142. };
  143. NodeList.prototype = {
  144. /**
  145. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  146. * @standard level1
  147. */
  148. length:0,
  149. /**
  150. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  151. * @standard level1
  152. * @param index unsigned long
  153. * Index into the collection.
  154. * @return Node
  155. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  156. */
  157. item: function(index) {
  158. return this[index] || null;
  159. },
  160. toString:function(isHTML,nodeFilter){
  161. for(var buf = [], i = 0;i<this.length;i++){
  162. serializeToString(this[i],buf,isHTML,nodeFilter);
  163. }
  164. return buf.join('');
  165. }
  166. };
  167. function LiveNodeList(node,refresh){
  168. this._node = node;
  169. this._refresh = refresh
  170. _updateLiveList(this);
  171. }
  172. function _updateLiveList(list){
  173. var inc = list._node._inc || list._node.ownerDocument._inc;
  174. if(list._inc != inc){
  175. var ls = list._refresh(list._node);
  176. //console.log(ls.length)
  177. __set__(list,'length',ls.length);
  178. copy(ls,list);
  179. list._inc = inc;
  180. }
  181. }
  182. LiveNodeList.prototype.item = function(i){
  183. _updateLiveList(this);
  184. return this[i];
  185. }
  186. _extends(LiveNodeList,NodeList);
  187. /**
  188. * Objects implementing the NamedNodeMap interface are used
  189. * to represent collections of nodes that can be accessed by name.
  190. * Note that NamedNodeMap does not inherit from NodeList;
  191. * NamedNodeMaps are not maintained in any particular order.
  192. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  193. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  194. * and does not imply that the DOM specifies an order to these Nodes.
  195. * NamedNodeMap objects in the DOM are live.
  196. * used for attributes or DocumentType entities
  197. */
  198. function NamedNodeMap() {
  199. };
  200. function _findNodeIndex(list,node){
  201. var i = list.length;
  202. while(i--){
  203. if(list[i] === node){return i}
  204. }
  205. }
  206. function _addNamedNode(el,list,newAttr,oldAttr){
  207. if(oldAttr){
  208. list[_findNodeIndex(list,oldAttr)] = newAttr;
  209. }else{
  210. list[list.length++] = newAttr;
  211. }
  212. if(el){
  213. newAttr.ownerElement = el;
  214. var doc = el.ownerDocument;
  215. if(doc){
  216. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  217. _onAddAttribute(doc,el,newAttr);
  218. }
  219. }
  220. }
  221. function _removeNamedNode(el,list,attr){
  222. //console.log('remove attr:'+attr)
  223. var i = _findNodeIndex(list,attr);
  224. if(i>=0){
  225. var lastIndex = list.length-1
  226. while(i<lastIndex){
  227. list[i] = list[++i]
  228. }
  229. list.length = lastIndex;
  230. if(el){
  231. var doc = el.ownerDocument;
  232. if(doc){
  233. _onRemoveAttribute(doc,el,attr);
  234. attr.ownerElement = null;
  235. }
  236. }
  237. }else{
  238. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  239. }
  240. }
  241. NamedNodeMap.prototype = {
  242. length:0,
  243. item:NodeList.prototype.item,
  244. getNamedItem: function(key) {
  245. // if(key.indexOf(':')>0 || key == 'xmlns'){
  246. // return null;
  247. // }
  248. //console.log()
  249. var i = this.length;
  250. while(i--){
  251. var attr = this[i];
  252. //console.log(attr.nodeName,key)
  253. if(attr.nodeName == key){
  254. return attr;
  255. }
  256. }
  257. },
  258. setNamedItem: function(attr) {
  259. var el = attr.ownerElement;
  260. if(el && el!=this._ownerElement){
  261. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  262. }
  263. var oldAttr = this.getNamedItem(attr.nodeName);
  264. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  265. return oldAttr;
  266. },
  267. /* returns Node */
  268. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  269. var el = attr.ownerElement, oldAttr;
  270. if(el && el!=this._ownerElement){
  271. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  272. }
  273. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  274. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  275. return oldAttr;
  276. },
  277. /* returns Node */
  278. removeNamedItem: function(key) {
  279. var attr = this.getNamedItem(key);
  280. _removeNamedNode(this._ownerElement,this,attr);
  281. return attr;
  282. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  283. //for level2
  284. removeNamedItemNS:function(namespaceURI,localName){
  285. var attr = this.getNamedItemNS(namespaceURI,localName);
  286. _removeNamedNode(this._ownerElement,this,attr);
  287. return attr;
  288. },
  289. getNamedItemNS: function(namespaceURI, localName) {
  290. var i = this.length;
  291. while(i--){
  292. var node = this[i];
  293. if(node.localName == localName && node.namespaceURI == namespaceURI){
  294. return node;
  295. }
  296. }
  297. return null;
  298. }
  299. };
  300. /**
  301. * The DOMImplementation interface represents an object providing methods
  302. * which are not dependent on any particular document.
  303. * Such an object is returned by the `Document.implementation` property.
  304. *
  305. * __The individual methods describe the differences compared to the specs.__
  306. *
  307. * @constructor
  308. *
  309. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  310. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  311. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  312. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  313. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  314. */
  315. function DOMImplementation() {
  316. }
  317. DOMImplementation.prototype = {
  318. /**
  319. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  320. * The different implementations fairly diverged in what kind of features were reported.
  321. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  322. *
  323. * @deprecated It is deprecated and modern browsers return true in all cases.
  324. *
  325. * @param {string} feature
  326. * @param {string} [version]
  327. * @returns {boolean} always true
  328. *
  329. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  330. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  331. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  332. */
  333. hasFeature: function(feature, version) {
  334. return true;
  335. },
  336. /**
  337. * Creates an XML Document object of the specified type with its document element.
  338. *
  339. * __It behaves slightly different from the description in the living standard__:
  340. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  341. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  342. * - this implementation is not validating names or qualified names
  343. * (when parsing XML strings, the SAX parser takes care of that)
  344. *
  345. * @param {string|null} namespaceURI
  346. * @param {string} qualifiedName
  347. * @param {DocumentType=null} doctype
  348. * @returns {Document}
  349. *
  350. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  351. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  352. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  353. *
  354. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  355. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  356. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  357. */
  358. createDocument: function(namespaceURI, qualifiedName, doctype){
  359. var doc = new Document();
  360. doc.implementation = this;
  361. doc.childNodes = new NodeList();
  362. doc.doctype = doctype || null;
  363. if (doctype){
  364. doc.appendChild(doctype);
  365. }
  366. if (qualifiedName){
  367. var root = doc.createElementNS(namespaceURI, qualifiedName);
  368. doc.appendChild(root);
  369. }
  370. return doc;
  371. },
  372. /**
  373. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  374. *
  375. * __This behavior is slightly different from the in the specs__:
  376. * - this implementation is not validating names or qualified names
  377. * (when parsing XML strings, the SAX parser takes care of that)
  378. *
  379. * @param {string} qualifiedName
  380. * @param {string} [publicId]
  381. * @param {string} [systemId]
  382. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  383. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  384. *
  385. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  386. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  387. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  388. *
  389. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  390. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  391. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  392. */
  393. createDocumentType: function(qualifiedName, publicId, systemId){
  394. var node = new DocumentType();
  395. node.name = qualifiedName;
  396. node.nodeName = qualifiedName;
  397. node.publicId = publicId || '';
  398. node.systemId = systemId || '';
  399. return node;
  400. }
  401. };
  402. /**
  403. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  404. */
  405. function Node() {
  406. };
  407. Node.prototype = {
  408. firstChild : null,
  409. lastChild : null,
  410. previousSibling : null,
  411. nextSibling : null,
  412. attributes : null,
  413. parentNode : null,
  414. childNodes : null,
  415. ownerDocument : null,
  416. nodeValue : null,
  417. namespaceURI : null,
  418. prefix : null,
  419. localName : null,
  420. // Modified in DOM Level 2:
  421. insertBefore:function(newChild, refChild){//raises
  422. return _insertBefore(this,newChild,refChild);
  423. },
  424. replaceChild:function(newChild, oldChild){//raises
  425. this.insertBefore(newChild,oldChild);
  426. if(oldChild){
  427. this.removeChild(oldChild);
  428. }
  429. },
  430. removeChild:function(oldChild){
  431. return _removeChild(this,oldChild);
  432. },
  433. appendChild:function(newChild){
  434. return this.insertBefore(newChild,null);
  435. },
  436. hasChildNodes:function(){
  437. return this.firstChild != null;
  438. },
  439. cloneNode:function(deep){
  440. return cloneNode(this.ownerDocument||this,this,deep);
  441. },
  442. // Modified in DOM Level 2:
  443. normalize:function(){
  444. var child = this.firstChild;
  445. while(child){
  446. var next = child.nextSibling;
  447. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  448. this.removeChild(next);
  449. child.appendData(next.data);
  450. }else{
  451. child.normalize();
  452. child = next;
  453. }
  454. }
  455. },
  456. // Introduced in DOM Level 2:
  457. isSupported:function(feature, version){
  458. return this.ownerDocument.implementation.hasFeature(feature,version);
  459. },
  460. // Introduced in DOM Level 2:
  461. hasAttributes:function(){
  462. return this.attributes.length>0;
  463. },
  464. /**
  465. * Look up the prefix associated to the given namespace URI, starting from this node.
  466. * **The default namespace declarations are ignored by this method.**
  467. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  468. *
  469. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  470. *
  471. * @param {string | null} namespaceURI
  472. * @returns {string | null}
  473. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  474. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  475. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  476. * @see https://github.com/xmldom/xmldom/issues/322
  477. */
  478. lookupPrefix:function(namespaceURI){
  479. var el = this;
  480. while(el){
  481. var map = el._nsMap;
  482. //console.dir(map)
  483. if(map){
  484. for(var n in map){
  485. if(map[n] == namespaceURI){
  486. return n;
  487. }
  488. }
  489. }
  490. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  491. }
  492. return null;
  493. },
  494. // Introduced in DOM Level 3:
  495. lookupNamespaceURI:function(prefix){
  496. var el = this;
  497. while(el){
  498. var map = el._nsMap;
  499. //console.dir(map)
  500. if(map){
  501. if(prefix in map){
  502. return map[prefix] ;
  503. }
  504. }
  505. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  506. }
  507. return null;
  508. },
  509. // Introduced in DOM Level 3:
  510. isDefaultNamespace:function(namespaceURI){
  511. var prefix = this.lookupPrefix(namespaceURI);
  512. return prefix == null;
  513. }
  514. };
  515. function _xmlEncoder(c){
  516. return c == '<' && '&lt;' ||
  517. c == '>' && '&gt;' ||
  518. c == '&' && '&amp;' ||
  519. c == '"' && '&quot;' ||
  520. '&#'+c.charCodeAt()+';'
  521. }
  522. copy(NodeType,Node);
  523. copy(NodeType,Node.prototype);
  524. /**
  525. * @param callback return true for continue,false for break
  526. * @return boolean true: break visit;
  527. */
  528. function _visitNode(node,callback){
  529. if(callback(node)){
  530. return true;
  531. }
  532. if(node = node.firstChild){
  533. do{
  534. if(_visitNode(node,callback)){return true}
  535. }while(node=node.nextSibling)
  536. }
  537. }
  538. function Document(){
  539. }
  540. function _onAddAttribute(doc,el,newAttr){
  541. doc && doc._inc++;
  542. var ns = newAttr.namespaceURI ;
  543. if(ns === NAMESPACE.XMLNS){
  544. //update namespace
  545. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  546. }
  547. }
  548. function _onRemoveAttribute(doc,el,newAttr,remove){
  549. doc && doc._inc++;
  550. var ns = newAttr.namespaceURI ;
  551. if(ns === NAMESPACE.XMLNS){
  552. //update namespace
  553. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  554. }
  555. }
  556. function _onUpdateChild(doc,el,newChild){
  557. if(doc && doc._inc){
  558. doc._inc++;
  559. //update childNodes
  560. var cs = el.childNodes;
  561. if(newChild){
  562. cs[cs.length++] = newChild;
  563. }else{
  564. //console.log(1)
  565. var child = el.firstChild;
  566. var i = 0;
  567. while(child){
  568. cs[i++] = child;
  569. child =child.nextSibling;
  570. }
  571. cs.length = i;
  572. }
  573. }
  574. }
  575. /**
  576. * attributes;
  577. * children;
  578. *
  579. * writeable properties:
  580. * nodeValue,Attr:value,CharacterData:data
  581. * prefix
  582. */
  583. function _removeChild(parentNode,child){
  584. var previous = child.previousSibling;
  585. var next = child.nextSibling;
  586. if(previous){
  587. previous.nextSibling = next;
  588. }else{
  589. parentNode.firstChild = next
  590. }
  591. if(next){
  592. next.previousSibling = previous;
  593. }else{
  594. parentNode.lastChild = previous;
  595. }
  596. _onUpdateChild(parentNode.ownerDocument,parentNode);
  597. return child;
  598. }
  599. /**
  600. * preformance key(refChild == null)
  601. */
  602. function _insertBefore(parentNode,newChild,nextChild){
  603. var cp = newChild.parentNode;
  604. if(cp){
  605. cp.removeChild(newChild);//remove and update
  606. }
  607. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  608. var newFirst = newChild.firstChild;
  609. if (newFirst == null) {
  610. return newChild;
  611. }
  612. var newLast = newChild.lastChild;
  613. }else{
  614. newFirst = newLast = newChild;
  615. }
  616. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  617. newFirst.previousSibling = pre;
  618. newLast.nextSibling = nextChild;
  619. if(pre){
  620. pre.nextSibling = newFirst;
  621. }else{
  622. parentNode.firstChild = newFirst;
  623. }
  624. if(nextChild == null){
  625. parentNode.lastChild = newLast;
  626. }else{
  627. nextChild.previousSibling = newLast;
  628. }
  629. do{
  630. newFirst.parentNode = parentNode;
  631. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  632. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  633. //console.log(parentNode.lastChild.nextSibling == null)
  634. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  635. newChild.firstChild = newChild.lastChild = null;
  636. }
  637. return newChild;
  638. }
  639. function _appendSingleChild(parentNode,newChild){
  640. var cp = newChild.parentNode;
  641. if(cp){
  642. var pre = parentNode.lastChild;
  643. cp.removeChild(newChild);//remove and update
  644. var pre = parentNode.lastChild;
  645. }
  646. var pre = parentNode.lastChild;
  647. newChild.parentNode = parentNode;
  648. newChild.previousSibling = pre;
  649. newChild.nextSibling = null;
  650. if(pre){
  651. pre.nextSibling = newChild;
  652. }else{
  653. parentNode.firstChild = newChild;
  654. }
  655. parentNode.lastChild = newChild;
  656. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  657. return newChild;
  658. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  659. }
  660. Document.prototype = {
  661. //implementation : null,
  662. nodeName : '#document',
  663. nodeType : DOCUMENT_NODE,
  664. /**
  665. * The DocumentType node of the document.
  666. *
  667. * @readonly
  668. * @type DocumentType
  669. */
  670. doctype : null,
  671. documentElement : null,
  672. _inc : 1,
  673. insertBefore : function(newChild, refChild){//raises
  674. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  675. var child = newChild.firstChild;
  676. while(child){
  677. var next = child.nextSibling;
  678. this.insertBefore(child,refChild);
  679. child = next;
  680. }
  681. return newChild;
  682. }
  683. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  684. this.documentElement = newChild;
  685. }
  686. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  687. },
  688. removeChild : function(oldChild){
  689. if(this.documentElement == oldChild){
  690. this.documentElement = null;
  691. }
  692. return _removeChild(this,oldChild);
  693. },
  694. // Introduced in DOM Level 2:
  695. importNode : function(importedNode,deep){
  696. return importNode(this,importedNode,deep);
  697. },
  698. // Introduced in DOM Level 2:
  699. getElementById : function(id){
  700. var rtv = null;
  701. _visitNode(this.documentElement,function(node){
  702. if(node.nodeType == ELEMENT_NODE){
  703. if(node.getAttribute('id') == id){
  704. rtv = node;
  705. return true;
  706. }
  707. }
  708. })
  709. return rtv;
  710. },
  711. /**
  712. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  713. * of all child elements which have **all** of the given class name(s).
  714. *
  715. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  716. *
  717. *
  718. * Warning: This is a live LiveNodeList.
  719. * Changes in the DOM will reflect in the array as the changes occur.
  720. * If an element selected by this array no longer qualifies for the selector,
  721. * it will automatically be removed. Be aware of this for iteration purposes.
  722. *
  723. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  724. *
  725. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  726. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  727. */
  728. getElementsByClassName: function(classNames) {
  729. var classNamesSet = toOrderedSet(classNames)
  730. return new LiveNodeList(this, function(base) {
  731. var ls = [];
  732. if (classNamesSet.length > 0) {
  733. _visitNode(base.documentElement, function(node) {
  734. if(node !== base && node.nodeType === ELEMENT_NODE) {
  735. var nodeClassNames = node.getAttribute('class')
  736. // can be null if the attribute does not exist
  737. if (nodeClassNames) {
  738. // before splitting and iterating just compare them for the most common case
  739. var matches = classNames === nodeClassNames;
  740. if (!matches) {
  741. var nodeClassNamesSet = toOrderedSet(nodeClassNames)
  742. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet))
  743. }
  744. if(matches) {
  745. ls.push(node);
  746. }
  747. }
  748. }
  749. });
  750. }
  751. return ls;
  752. });
  753. },
  754. //document factory method:
  755. createElement : function(tagName){
  756. var node = new Element();
  757. node.ownerDocument = this;
  758. node.nodeName = tagName;
  759. node.tagName = tagName;
  760. node.localName = tagName;
  761. node.childNodes = new NodeList();
  762. var attrs = node.attributes = new NamedNodeMap();
  763. attrs._ownerElement = node;
  764. return node;
  765. },
  766. createDocumentFragment : function(){
  767. var node = new DocumentFragment();
  768. node.ownerDocument = this;
  769. node.childNodes = new NodeList();
  770. return node;
  771. },
  772. createTextNode : function(data){
  773. var node = new Text();
  774. node.ownerDocument = this;
  775. node.appendData(data)
  776. return node;
  777. },
  778. createComment : function(data){
  779. var node = new Comment();
  780. node.ownerDocument = this;
  781. node.appendData(data)
  782. return node;
  783. },
  784. createCDATASection : function(data){
  785. var node = new CDATASection();
  786. node.ownerDocument = this;
  787. node.appendData(data)
  788. return node;
  789. },
  790. createProcessingInstruction : function(target,data){
  791. var node = new ProcessingInstruction();
  792. node.ownerDocument = this;
  793. node.tagName = node.target = target;
  794. node.nodeValue= node.data = data;
  795. return node;
  796. },
  797. createAttribute : function(name){
  798. var node = new Attr();
  799. node.ownerDocument = this;
  800. node.name = name;
  801. node.nodeName = name;
  802. node.localName = name;
  803. node.specified = true;
  804. return node;
  805. },
  806. createEntityReference : function(name){
  807. var node = new EntityReference();
  808. node.ownerDocument = this;
  809. node.nodeName = name;
  810. return node;
  811. },
  812. // Introduced in DOM Level 2:
  813. createElementNS : function(namespaceURI,qualifiedName){
  814. var node = new Element();
  815. var pl = qualifiedName.split(':');
  816. var attrs = node.attributes = new NamedNodeMap();
  817. node.childNodes = new NodeList();
  818. node.ownerDocument = this;
  819. node.nodeName = qualifiedName;
  820. node.tagName = qualifiedName;
  821. node.namespaceURI = namespaceURI;
  822. if(pl.length == 2){
  823. node.prefix = pl[0];
  824. node.localName = pl[1];
  825. }else{
  826. //el.prefix = null;
  827. node.localName = qualifiedName;
  828. }
  829. attrs._ownerElement = node;
  830. return node;
  831. },
  832. // Introduced in DOM Level 2:
  833. createAttributeNS : function(namespaceURI,qualifiedName){
  834. var node = new Attr();
  835. var pl = qualifiedName.split(':');
  836. node.ownerDocument = this;
  837. node.nodeName = qualifiedName;
  838. node.name = qualifiedName;
  839. node.namespaceURI = namespaceURI;
  840. node.specified = true;
  841. if(pl.length == 2){
  842. node.prefix = pl[0];
  843. node.localName = pl[1];
  844. }else{
  845. //el.prefix = null;
  846. node.localName = qualifiedName;
  847. }
  848. return node;
  849. }
  850. };
  851. _extends(Document,Node);
  852. function Element() {
  853. this._nsMap = {};
  854. };
  855. Element.prototype = {
  856. nodeType : ELEMENT_NODE,
  857. hasAttribute : function(name){
  858. return this.getAttributeNode(name)!=null;
  859. },
  860. getAttribute : function(name){
  861. var attr = this.getAttributeNode(name);
  862. return attr && attr.value || '';
  863. },
  864. getAttributeNode : function(name){
  865. return this.attributes.getNamedItem(name);
  866. },
  867. setAttribute : function(name, value){
  868. var attr = this.ownerDocument.createAttribute(name);
  869. attr.value = attr.nodeValue = "" + value;
  870. this.setAttributeNode(attr)
  871. },
  872. removeAttribute : function(name){
  873. var attr = this.getAttributeNode(name)
  874. attr && this.removeAttributeNode(attr);
  875. },
  876. //four real opeartion method
  877. appendChild:function(newChild){
  878. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  879. return this.insertBefore(newChild,null);
  880. }else{
  881. return _appendSingleChild(this,newChild);
  882. }
  883. },
  884. setAttributeNode : function(newAttr){
  885. return this.attributes.setNamedItem(newAttr);
  886. },
  887. setAttributeNodeNS : function(newAttr){
  888. return this.attributes.setNamedItemNS(newAttr);
  889. },
  890. removeAttributeNode : function(oldAttr){
  891. //console.log(this == oldAttr.ownerElement)
  892. return this.attributes.removeNamedItem(oldAttr.nodeName);
  893. },
  894. //get real attribute name,and remove it by removeAttributeNode
  895. removeAttributeNS : function(namespaceURI, localName){
  896. var old = this.getAttributeNodeNS(namespaceURI, localName);
  897. old && this.removeAttributeNode(old);
  898. },
  899. hasAttributeNS : function(namespaceURI, localName){
  900. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  901. },
  902. getAttributeNS : function(namespaceURI, localName){
  903. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  904. return attr && attr.value || '';
  905. },
  906. setAttributeNS : function(namespaceURI, qualifiedName, value){
  907. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  908. attr.value = attr.nodeValue = "" + value;
  909. this.setAttributeNode(attr)
  910. },
  911. getAttributeNodeNS : function(namespaceURI, localName){
  912. return this.attributes.getNamedItemNS(namespaceURI, localName);
  913. },
  914. getElementsByTagName : function(tagName){
  915. return new LiveNodeList(this,function(base){
  916. var ls = [];
  917. _visitNode(base,function(node){
  918. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  919. ls.push(node);
  920. }
  921. });
  922. return ls;
  923. });
  924. },
  925. getElementsByTagNameNS : function(namespaceURI, localName){
  926. return new LiveNodeList(this,function(base){
  927. var ls = [];
  928. _visitNode(base,function(node){
  929. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  930. ls.push(node);
  931. }
  932. });
  933. return ls;
  934. });
  935. }
  936. };
  937. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  938. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  939. _extends(Element,Node);
  940. function Attr() {
  941. };
  942. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  943. _extends(Attr,Node);
  944. function CharacterData() {
  945. };
  946. CharacterData.prototype = {
  947. data : '',
  948. substringData : function(offset, count) {
  949. return this.data.substring(offset, offset+count);
  950. },
  951. appendData: function(text) {
  952. text = this.data+text;
  953. this.nodeValue = this.data = text;
  954. this.length = text.length;
  955. },
  956. insertData: function(offset,text) {
  957. this.replaceData(offset,0,text);
  958. },
  959. appendChild:function(newChild){
  960. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  961. },
  962. deleteData: function(offset, count) {
  963. this.replaceData(offset,count,"");
  964. },
  965. replaceData: function(offset, count, text) {
  966. var start = this.data.substring(0,offset);
  967. var end = this.data.substring(offset+count);
  968. text = start + text + end;
  969. this.nodeValue = this.data = text;
  970. this.length = text.length;
  971. }
  972. }
  973. _extends(CharacterData,Node);
  974. function Text() {
  975. };
  976. Text.prototype = {
  977. nodeName : "#text",
  978. nodeType : TEXT_NODE,
  979. splitText : function(offset) {
  980. var text = this.data;
  981. var newText = text.substring(offset);
  982. text = text.substring(0, offset);
  983. this.data = this.nodeValue = text;
  984. this.length = text.length;
  985. var newNode = this.ownerDocument.createTextNode(newText);
  986. if(this.parentNode){
  987. this.parentNode.insertBefore(newNode, this.nextSibling);
  988. }
  989. return newNode;
  990. }
  991. }
  992. _extends(Text,CharacterData);
  993. function Comment() {
  994. };
  995. Comment.prototype = {
  996. nodeName : "#comment",
  997. nodeType : COMMENT_NODE
  998. }
  999. _extends(Comment,CharacterData);
  1000. function CDATASection() {
  1001. };
  1002. CDATASection.prototype = {
  1003. nodeName : "#cdata-section",
  1004. nodeType : CDATA_SECTION_NODE
  1005. }
  1006. _extends(CDATASection,CharacterData);
  1007. function DocumentType() {
  1008. };
  1009. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1010. _extends(DocumentType,Node);
  1011. function Notation() {
  1012. };
  1013. Notation.prototype.nodeType = NOTATION_NODE;
  1014. _extends(Notation,Node);
  1015. function Entity() {
  1016. };
  1017. Entity.prototype.nodeType = ENTITY_NODE;
  1018. _extends(Entity,Node);
  1019. function EntityReference() {
  1020. };
  1021. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1022. _extends(EntityReference,Node);
  1023. function DocumentFragment() {
  1024. };
  1025. DocumentFragment.prototype.nodeName = "#document-fragment";
  1026. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1027. _extends(DocumentFragment,Node);
  1028. function ProcessingInstruction() {
  1029. }
  1030. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1031. _extends(ProcessingInstruction,Node);
  1032. function XMLSerializer(){}
  1033. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  1034. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  1035. }
  1036. Node.prototype.toString = nodeSerializeToString;
  1037. function nodeSerializeToString(isHtml,nodeFilter){
  1038. var buf = [];
  1039. var refNode = this.nodeType == 9 && this.documentElement || this;
  1040. var prefix = refNode.prefix;
  1041. var uri = refNode.namespaceURI;
  1042. if(uri && prefix == null){
  1043. //console.log(prefix)
  1044. var prefix = refNode.lookupPrefix(uri);
  1045. if(prefix == null){
  1046. //isHTML = true;
  1047. var visibleNamespaces=[
  1048. {namespace:uri,prefix:null}
  1049. //{namespace:uri,prefix:''}
  1050. ]
  1051. }
  1052. }
  1053. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  1054. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1055. return buf.join('');
  1056. }
  1057. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  1058. var prefix = node.prefix || '';
  1059. var uri = node.namespaceURI;
  1060. // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  1061. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  1062. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  1063. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  1064. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  1065. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  1066. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  1067. if (!uri) {
  1068. return false;
  1069. }
  1070. if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {
  1071. return false;
  1072. }
  1073. var i = visibleNamespaces.length
  1074. while (i--) {
  1075. var ns = visibleNamespaces[i];
  1076. // get namespace prefix
  1077. if (ns.prefix === prefix) {
  1078. return ns.namespace !== uri;
  1079. }
  1080. }
  1081. return true;
  1082. }
  1083. /**
  1084. * Well-formed constraint: No < in Attribute Values
  1085. * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
  1086. * @see https://www.w3.org/TR/xml/#CleanAttrVals
  1087. * @see https://www.w3.org/TR/xml/#NT-AttValue
  1088. */
  1089. function addSerializedAttribute(buf, qualifiedName, value) {
  1090. buf.push(' ', qualifiedName, '="', value.replace(/[<&"]/g,_xmlEncoder), '"')
  1091. }
  1092. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  1093. if (!visibleNamespaces) {
  1094. visibleNamespaces = [];
  1095. }
  1096. if(nodeFilter){
  1097. node = nodeFilter(node);
  1098. if(node){
  1099. if(typeof node == 'string'){
  1100. buf.push(node);
  1101. return;
  1102. }
  1103. }else{
  1104. return;
  1105. }
  1106. //buf.sort.apply(attrs, attributeSorter);
  1107. }
  1108. switch(node.nodeType){
  1109. case ELEMENT_NODE:
  1110. var attrs = node.attributes;
  1111. var len = attrs.length;
  1112. var child = node.firstChild;
  1113. var nodeName = node.tagName;
  1114. isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML
  1115. var prefixedNodeName = nodeName
  1116. if (!isHTML && !node.prefix && node.namespaceURI) {
  1117. var defaultNS
  1118. // lookup current default ns from `xmlns` attribute
  1119. for (var ai = 0; ai < attrs.length; ai++) {
  1120. if (attrs.item(ai).name === 'xmlns') {
  1121. defaultNS = attrs.item(ai).value
  1122. break
  1123. }
  1124. }
  1125. if (!defaultNS) {
  1126. // lookup current default ns in visibleNamespaces
  1127. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1128. var namespace = visibleNamespaces[nsi]
  1129. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  1130. defaultNS = namespace.namespace
  1131. break
  1132. }
  1133. }
  1134. }
  1135. if (defaultNS !== node.namespaceURI) {
  1136. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1137. var namespace = visibleNamespaces[nsi]
  1138. if (namespace.namespace === node.namespaceURI) {
  1139. if (namespace.prefix) {
  1140. prefixedNodeName = namespace.prefix + ':' + nodeName
  1141. }
  1142. break
  1143. }
  1144. }
  1145. }
  1146. }
  1147. buf.push('<', prefixedNodeName);
  1148. for(var i=0;i<len;i++){
  1149. // add namespaces for attributes
  1150. var attr = attrs.item(i);
  1151. if (attr.prefix == 'xmlns') {
  1152. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1153. }else if(attr.nodeName == 'xmlns'){
  1154. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1155. }
  1156. }
  1157. for(var i=0;i<len;i++){
  1158. var attr = attrs.item(i);
  1159. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  1160. var prefix = attr.prefix||'';
  1161. var uri = attr.namespaceURI;
  1162. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  1163. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1164. }
  1165. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  1166. }
  1167. // add namespace for current node
  1168. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  1169. var prefix = node.prefix||'';
  1170. var uri = node.namespaceURI;
  1171. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  1172. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1173. }
  1174. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  1175. buf.push('>');
  1176. //if is cdata child node
  1177. if(isHTML && /^script$/i.test(nodeName)){
  1178. while(child){
  1179. if(child.data){
  1180. buf.push(child.data);
  1181. }else{
  1182. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1183. }
  1184. child = child.nextSibling;
  1185. }
  1186. }else
  1187. {
  1188. while(child){
  1189. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1190. child = child.nextSibling;
  1191. }
  1192. }
  1193. buf.push('</',prefixedNodeName,'>');
  1194. }else{
  1195. buf.push('/>');
  1196. }
  1197. // remove added visible namespaces
  1198. //visibleNamespaces.length = startVisibleNamespaces;
  1199. return;
  1200. case DOCUMENT_NODE:
  1201. case DOCUMENT_FRAGMENT_NODE:
  1202. var child = node.firstChild;
  1203. while(child){
  1204. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1205. child = child.nextSibling;
  1206. }
  1207. return;
  1208. case ATTRIBUTE_NODE:
  1209. return addSerializedAttribute(buf, node.name, node.value);
  1210. case TEXT_NODE:
  1211. /**
  1212. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  1213. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  1214. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  1215. * `&amp;` and `&lt;` respectively.
  1216. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  1217. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  1218. * when that string is not marking the end of a CDATA section.
  1219. *
  1220. * In the content of elements, character data is any string of characters
  1221. * which does not contain the start-delimiter of any markup
  1222. * and does not include the CDATA-section-close delimiter, `]]>`.
  1223. *
  1224. * @see https://www.w3.org/TR/xml/#NT-CharData
  1225. */
  1226. return buf.push(node.data
  1227. .replace(/[<&]/g,_xmlEncoder)
  1228. .replace(/]]>/g, ']]&gt;')
  1229. );
  1230. case CDATA_SECTION_NODE:
  1231. return buf.push( '<![CDATA[',node.data,']]>');
  1232. case COMMENT_NODE:
  1233. return buf.push( "<!--",node.data,"-->");
  1234. case DOCUMENT_TYPE_NODE:
  1235. var pubid = node.publicId;
  1236. var sysid = node.systemId;
  1237. buf.push('<!DOCTYPE ',node.name);
  1238. if(pubid){
  1239. buf.push(' PUBLIC ', pubid);
  1240. if (sysid && sysid!='.') {
  1241. buf.push(' ', sysid);
  1242. }
  1243. buf.push('>');
  1244. }else if(sysid && sysid!='.'){
  1245. buf.push(' SYSTEM ', sysid, '>');
  1246. }else{
  1247. var sub = node.internalSubset;
  1248. if(sub){
  1249. buf.push(" [",sub,"]");
  1250. }
  1251. buf.push(">");
  1252. }
  1253. return;
  1254. case PROCESSING_INSTRUCTION_NODE:
  1255. return buf.push( "<?",node.target," ",node.data,"?>");
  1256. case ENTITY_REFERENCE_NODE:
  1257. return buf.push( '&',node.nodeName,';');
  1258. //case ENTITY_NODE:
  1259. //case NOTATION_NODE:
  1260. default:
  1261. buf.push('??',node.nodeName);
  1262. }
  1263. }
  1264. function importNode(doc,node,deep){
  1265. var node2;
  1266. switch (node.nodeType) {
  1267. case ELEMENT_NODE:
  1268. node2 = node.cloneNode(false);
  1269. node2.ownerDocument = doc;
  1270. //var attrs = node2.attributes;
  1271. //var len = attrs.length;
  1272. //for(var i=0;i<len;i++){
  1273. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1274. //}
  1275. case DOCUMENT_FRAGMENT_NODE:
  1276. break;
  1277. case ATTRIBUTE_NODE:
  1278. deep = true;
  1279. break;
  1280. //case ENTITY_REFERENCE_NODE:
  1281. //case PROCESSING_INSTRUCTION_NODE:
  1282. ////case TEXT_NODE:
  1283. //case CDATA_SECTION_NODE:
  1284. //case COMMENT_NODE:
  1285. // deep = false;
  1286. // break;
  1287. //case DOCUMENT_NODE:
  1288. //case DOCUMENT_TYPE_NODE:
  1289. //cannot be imported.
  1290. //case ENTITY_NODE:
  1291. //case NOTATION_NODE:
  1292. //can not hit in level3
  1293. //default:throw e;
  1294. }
  1295. if(!node2){
  1296. node2 = node.cloneNode(false);//false
  1297. }
  1298. node2.ownerDocument = doc;
  1299. node2.parentNode = null;
  1300. if(deep){
  1301. var child = node.firstChild;
  1302. while(child){
  1303. node2.appendChild(importNode(doc,child,deep));
  1304. child = child.nextSibling;
  1305. }
  1306. }
  1307. return node2;
  1308. }
  1309. //
  1310. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1311. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1312. function cloneNode(doc,node,deep){
  1313. var node2 = new node.constructor();
  1314. for(var n in node){
  1315. var v = node[n];
  1316. if(typeof v != 'object' ){
  1317. if(v != node2[n]){
  1318. node2[n] = v;
  1319. }
  1320. }
  1321. }
  1322. if(node.childNodes){
  1323. node2.childNodes = new NodeList();
  1324. }
  1325. node2.ownerDocument = doc;
  1326. switch (node2.nodeType) {
  1327. case ELEMENT_NODE:
  1328. var attrs = node.attributes;
  1329. var attrs2 = node2.attributes = new NamedNodeMap();
  1330. var len = attrs.length
  1331. attrs2._ownerElement = node2;
  1332. for(var i=0;i<len;i++){
  1333. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  1334. }
  1335. break;;
  1336. case ATTRIBUTE_NODE:
  1337. deep = true;
  1338. }
  1339. if(deep){
  1340. var child = node.firstChild;
  1341. while(child){
  1342. node2.appendChild(cloneNode(doc,child,deep));
  1343. child = child.nextSibling;
  1344. }
  1345. }
  1346. return node2;
  1347. }
  1348. function __set__(object,key,value){
  1349. object[key] = value
  1350. }
  1351. //do dynamic
  1352. try{
  1353. if(Object.defineProperty){
  1354. Object.defineProperty(LiveNodeList.prototype,'length',{
  1355. get:function(){
  1356. _updateLiveList(this);
  1357. return this.$$length;
  1358. }
  1359. });
  1360. Object.defineProperty(Node.prototype,'textContent',{
  1361. get:function(){
  1362. return getTextContent(this);
  1363. },
  1364. set:function(data){
  1365. switch(this.nodeType){
  1366. case ELEMENT_NODE:
  1367. case DOCUMENT_FRAGMENT_NODE:
  1368. while(this.firstChild){
  1369. this.removeChild(this.firstChild);
  1370. }
  1371. if(data || String(data)){
  1372. this.appendChild(this.ownerDocument.createTextNode(data));
  1373. }
  1374. break;
  1375. default:
  1376. this.data = data;
  1377. this.value = data;
  1378. this.nodeValue = data;
  1379. }
  1380. }
  1381. })
  1382. function getTextContent(node){
  1383. switch(node.nodeType){
  1384. case ELEMENT_NODE:
  1385. case DOCUMENT_FRAGMENT_NODE:
  1386. var buf = [];
  1387. node = node.firstChild;
  1388. while(node){
  1389. if(node.nodeType!==7 && node.nodeType !==8){
  1390. buf.push(getTextContent(node));
  1391. }
  1392. node = node.nextSibling;
  1393. }
  1394. return buf.join('');
  1395. default:
  1396. return node.nodeValue;
  1397. }
  1398. }
  1399. __set__ = function(object,key,value){
  1400. //console.log(value)
  1401. object['$$'+key] = value
  1402. }
  1403. }
  1404. }catch(e){//ie8
  1405. }
  1406. //if(typeof require == 'function'){
  1407. exports.DocumentType = DocumentType;
  1408. exports.DOMException = DOMException;
  1409. exports.DOMImplementation = DOMImplementation;
  1410. exports.Element = Element;
  1411. exports.Node = Node;
  1412. exports.NodeList = NodeList;
  1413. exports.XMLSerializer = XMLSerializer;
  1414. //}