dom.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. /**
  557. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  558. * Passing `newChild` means it will be appended.
  559. * Otherwise it's assumed that an item has been removed,
  560. * and `el.firstNode` and it's `.nextSibling` are used
  561. * to walk the current list of child nodes.
  562. *
  563. * @param {Document} doc
  564. * @param {Node} el
  565. * @param {Node} [newChild]
  566. * @private
  567. */
  568. function _onUpdateChild (doc, el, newChild) {
  569. if(doc && doc._inc){
  570. doc._inc++;
  571. //update childNodes
  572. var cs = el.childNodes;
  573. if (newChild) {
  574. cs[cs.length++] = newChild;
  575. } else {
  576. var child = el.firstChild;
  577. var i = 0;
  578. while (child) {
  579. cs[i++] = child;
  580. child = child.nextSibling;
  581. }
  582. cs.length = i;
  583. delete cs[cs.length];
  584. }
  585. }
  586. }
  587. /**
  588. * Removes the connections between `parentNode` and `child`
  589. * and any existing `child.previousSibling` or `child.nextSibling`.
  590. *
  591. * @see https://github.com/xmldom/xmldom/issues/135
  592. * @see https://github.com/xmldom/xmldom/issues/145
  593. *
  594. * @param {Node} parentNode
  595. * @param {Node} child
  596. * @returns {Node} the child that was removed.
  597. * @private
  598. */
  599. function _removeChild (parentNode, child) {
  600. var previous = child.previousSibling;
  601. var next = child.nextSibling;
  602. if (previous) {
  603. previous.nextSibling = next;
  604. } else {
  605. parentNode.firstChild = next;
  606. }
  607. if (next) {
  608. next.previousSibling = previous;
  609. } else {
  610. parentNode.lastChild = previous;
  611. }
  612. child.parentNode = null;
  613. child.previousSibling = null;
  614. child.nextSibling = null;
  615. _onUpdateChild(parentNode.ownerDocument, parentNode);
  616. return child;
  617. }
  618. /**
  619. * preformance key(refChild == null)
  620. */
  621. function _insertBefore(parentNode,newChild,nextChild){
  622. var cp = newChild.parentNode;
  623. if(cp){
  624. cp.removeChild(newChild);//remove and update
  625. }
  626. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  627. var newFirst = newChild.firstChild;
  628. if (newFirst == null) {
  629. return newChild;
  630. }
  631. var newLast = newChild.lastChild;
  632. }else{
  633. newFirst = newLast = newChild;
  634. }
  635. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  636. newFirst.previousSibling = pre;
  637. newLast.nextSibling = nextChild;
  638. if(pre){
  639. pre.nextSibling = newFirst;
  640. }else{
  641. parentNode.firstChild = newFirst;
  642. }
  643. if(nextChild == null){
  644. parentNode.lastChild = newLast;
  645. }else{
  646. nextChild.previousSibling = newLast;
  647. }
  648. do{
  649. newFirst.parentNode = parentNode;
  650. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  651. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  652. //console.log(parentNode.lastChild.nextSibling == null)
  653. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  654. newChild.firstChild = newChild.lastChild = null;
  655. }
  656. return newChild;
  657. }
  658. /**
  659. * Appends `newChild` to `parentNode`.
  660. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  661. *
  662. * @see https://github.com/xmldom/xmldom/issues/135
  663. * @see https://github.com/xmldom/xmldom/issues/145
  664. * @param {Node} parentNode
  665. * @param {Node} newChild
  666. * @returns {Node}
  667. * @private
  668. */
  669. function _appendSingleChild (parentNode, newChild) {
  670. if (newChild.parentNode) {
  671. newChild.parentNode.removeChild(newChild);
  672. }
  673. newChild.parentNode = parentNode;
  674. newChild.previousSibling = parentNode.lastChild;
  675. newChild.nextSibling = null;
  676. if (newChild.previousSibling) {
  677. newChild.previousSibling.nextSibling = newChild;
  678. } else {
  679. parentNode.firstChild = newChild;
  680. }
  681. parentNode.lastChild = newChild;
  682. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  683. return newChild;
  684. }
  685. Document.prototype = {
  686. //implementation : null,
  687. nodeName : '#document',
  688. nodeType : DOCUMENT_NODE,
  689. /**
  690. * The DocumentType node of the document.
  691. *
  692. * @readonly
  693. * @type DocumentType
  694. */
  695. doctype : null,
  696. documentElement : null,
  697. _inc : 1,
  698. insertBefore : function(newChild, refChild){//raises
  699. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  700. var child = newChild.firstChild;
  701. while(child){
  702. var next = child.nextSibling;
  703. this.insertBefore(child,refChild);
  704. child = next;
  705. }
  706. return newChild;
  707. }
  708. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  709. this.documentElement = newChild;
  710. }
  711. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  712. },
  713. removeChild : function(oldChild){
  714. if(this.documentElement == oldChild){
  715. this.documentElement = null;
  716. }
  717. return _removeChild(this,oldChild);
  718. },
  719. // Introduced in DOM Level 2:
  720. importNode : function(importedNode,deep){
  721. return importNode(this,importedNode,deep);
  722. },
  723. // Introduced in DOM Level 2:
  724. getElementById : function(id){
  725. var rtv = null;
  726. _visitNode(this.documentElement,function(node){
  727. if(node.nodeType == ELEMENT_NODE){
  728. if(node.getAttribute('id') == id){
  729. rtv = node;
  730. return true;
  731. }
  732. }
  733. })
  734. return rtv;
  735. },
  736. /**
  737. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  738. * of all child elements which have **all** of the given class name(s).
  739. *
  740. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  741. *
  742. *
  743. * Warning: This is a live LiveNodeList.
  744. * Changes in the DOM will reflect in the array as the changes occur.
  745. * If an element selected by this array no longer qualifies for the selector,
  746. * it will automatically be removed. Be aware of this for iteration purposes.
  747. *
  748. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  749. *
  750. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  751. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  752. */
  753. getElementsByClassName: function(classNames) {
  754. var classNamesSet = toOrderedSet(classNames)
  755. return new LiveNodeList(this, function(base) {
  756. var ls = [];
  757. if (classNamesSet.length > 0) {
  758. _visitNode(base.documentElement, function(node) {
  759. if(node !== base && node.nodeType === ELEMENT_NODE) {
  760. var nodeClassNames = node.getAttribute('class')
  761. // can be null if the attribute does not exist
  762. if (nodeClassNames) {
  763. // before splitting and iterating just compare them for the most common case
  764. var matches = classNames === nodeClassNames;
  765. if (!matches) {
  766. var nodeClassNamesSet = toOrderedSet(nodeClassNames)
  767. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet))
  768. }
  769. if(matches) {
  770. ls.push(node);
  771. }
  772. }
  773. }
  774. });
  775. }
  776. return ls;
  777. });
  778. },
  779. //document factory method:
  780. createElement : function(tagName){
  781. var node = new Element();
  782. node.ownerDocument = this;
  783. node.nodeName = tagName;
  784. node.tagName = tagName;
  785. node.localName = tagName;
  786. node.childNodes = new NodeList();
  787. var attrs = node.attributes = new NamedNodeMap();
  788. attrs._ownerElement = node;
  789. return node;
  790. },
  791. createDocumentFragment : function(){
  792. var node = new DocumentFragment();
  793. node.ownerDocument = this;
  794. node.childNodes = new NodeList();
  795. return node;
  796. },
  797. createTextNode : function(data){
  798. var node = new Text();
  799. node.ownerDocument = this;
  800. node.appendData(data)
  801. return node;
  802. },
  803. createComment : function(data){
  804. var node = new Comment();
  805. node.ownerDocument = this;
  806. node.appendData(data)
  807. return node;
  808. },
  809. createCDATASection : function(data){
  810. var node = new CDATASection();
  811. node.ownerDocument = this;
  812. node.appendData(data)
  813. return node;
  814. },
  815. createProcessingInstruction : function(target,data){
  816. var node = new ProcessingInstruction();
  817. node.ownerDocument = this;
  818. node.tagName = node.target = target;
  819. node.nodeValue= node.data = data;
  820. return node;
  821. },
  822. createAttribute : function(name){
  823. var node = new Attr();
  824. node.ownerDocument = this;
  825. node.name = name;
  826. node.nodeName = name;
  827. node.localName = name;
  828. node.specified = true;
  829. return node;
  830. },
  831. createEntityReference : function(name){
  832. var node = new EntityReference();
  833. node.ownerDocument = this;
  834. node.nodeName = name;
  835. return node;
  836. },
  837. // Introduced in DOM Level 2:
  838. createElementNS : function(namespaceURI,qualifiedName){
  839. var node = new Element();
  840. var pl = qualifiedName.split(':');
  841. var attrs = node.attributes = new NamedNodeMap();
  842. node.childNodes = new NodeList();
  843. node.ownerDocument = this;
  844. node.nodeName = qualifiedName;
  845. node.tagName = qualifiedName;
  846. node.namespaceURI = namespaceURI;
  847. if(pl.length == 2){
  848. node.prefix = pl[0];
  849. node.localName = pl[1];
  850. }else{
  851. //el.prefix = null;
  852. node.localName = qualifiedName;
  853. }
  854. attrs._ownerElement = node;
  855. return node;
  856. },
  857. // Introduced in DOM Level 2:
  858. createAttributeNS : function(namespaceURI,qualifiedName){
  859. var node = new Attr();
  860. var pl = qualifiedName.split(':');
  861. node.ownerDocument = this;
  862. node.nodeName = qualifiedName;
  863. node.name = qualifiedName;
  864. node.namespaceURI = namespaceURI;
  865. node.specified = true;
  866. if(pl.length == 2){
  867. node.prefix = pl[0];
  868. node.localName = pl[1];
  869. }else{
  870. //el.prefix = null;
  871. node.localName = qualifiedName;
  872. }
  873. return node;
  874. }
  875. };
  876. _extends(Document,Node);
  877. function Element() {
  878. this._nsMap = {};
  879. };
  880. Element.prototype = {
  881. nodeType : ELEMENT_NODE,
  882. hasAttribute : function(name){
  883. return this.getAttributeNode(name)!=null;
  884. },
  885. getAttribute : function(name){
  886. var attr = this.getAttributeNode(name);
  887. return attr && attr.value || '';
  888. },
  889. getAttributeNode : function(name){
  890. return this.attributes.getNamedItem(name);
  891. },
  892. setAttribute : function(name, value){
  893. var attr = this.ownerDocument.createAttribute(name);
  894. attr.value = attr.nodeValue = "" + value;
  895. this.setAttributeNode(attr)
  896. },
  897. removeAttribute : function(name){
  898. var attr = this.getAttributeNode(name)
  899. attr && this.removeAttributeNode(attr);
  900. },
  901. //four real opeartion method
  902. appendChild:function(newChild){
  903. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  904. return this.insertBefore(newChild,null);
  905. }else{
  906. return _appendSingleChild(this,newChild);
  907. }
  908. },
  909. setAttributeNode : function(newAttr){
  910. return this.attributes.setNamedItem(newAttr);
  911. },
  912. setAttributeNodeNS : function(newAttr){
  913. return this.attributes.setNamedItemNS(newAttr);
  914. },
  915. removeAttributeNode : function(oldAttr){
  916. //console.log(this == oldAttr.ownerElement)
  917. return this.attributes.removeNamedItem(oldAttr.nodeName);
  918. },
  919. //get real attribute name,and remove it by removeAttributeNode
  920. removeAttributeNS : function(namespaceURI, localName){
  921. var old = this.getAttributeNodeNS(namespaceURI, localName);
  922. old && this.removeAttributeNode(old);
  923. },
  924. hasAttributeNS : function(namespaceURI, localName){
  925. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  926. },
  927. getAttributeNS : function(namespaceURI, localName){
  928. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  929. return attr && attr.value || '';
  930. },
  931. setAttributeNS : function(namespaceURI, qualifiedName, value){
  932. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  933. attr.value = attr.nodeValue = "" + value;
  934. this.setAttributeNode(attr)
  935. },
  936. getAttributeNodeNS : function(namespaceURI, localName){
  937. return this.attributes.getNamedItemNS(namespaceURI, localName);
  938. },
  939. getElementsByTagName : function(tagName){
  940. return new LiveNodeList(this,function(base){
  941. var ls = [];
  942. _visitNode(base,function(node){
  943. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  944. ls.push(node);
  945. }
  946. });
  947. return ls;
  948. });
  949. },
  950. getElementsByTagNameNS : function(namespaceURI, localName){
  951. return new LiveNodeList(this,function(base){
  952. var ls = [];
  953. _visitNode(base,function(node){
  954. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  955. ls.push(node);
  956. }
  957. });
  958. return ls;
  959. });
  960. }
  961. };
  962. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  963. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  964. _extends(Element,Node);
  965. function Attr() {
  966. };
  967. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  968. _extends(Attr,Node);
  969. function CharacterData() {
  970. };
  971. CharacterData.prototype = {
  972. data : '',
  973. substringData : function(offset, count) {
  974. return this.data.substring(offset, offset+count);
  975. },
  976. appendData: function(text) {
  977. text = this.data+text;
  978. this.nodeValue = this.data = text;
  979. this.length = text.length;
  980. },
  981. insertData: function(offset,text) {
  982. this.replaceData(offset,0,text);
  983. },
  984. appendChild:function(newChild){
  985. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  986. },
  987. deleteData: function(offset, count) {
  988. this.replaceData(offset,count,"");
  989. },
  990. replaceData: function(offset, count, text) {
  991. var start = this.data.substring(0,offset);
  992. var end = this.data.substring(offset+count);
  993. text = start + text + end;
  994. this.nodeValue = this.data = text;
  995. this.length = text.length;
  996. }
  997. }
  998. _extends(CharacterData,Node);
  999. function Text() {
  1000. };
  1001. Text.prototype = {
  1002. nodeName : "#text",
  1003. nodeType : TEXT_NODE,
  1004. splitText : function(offset) {
  1005. var text = this.data;
  1006. var newText = text.substring(offset);
  1007. text = text.substring(0, offset);
  1008. this.data = this.nodeValue = text;
  1009. this.length = text.length;
  1010. var newNode = this.ownerDocument.createTextNode(newText);
  1011. if(this.parentNode){
  1012. this.parentNode.insertBefore(newNode, this.nextSibling);
  1013. }
  1014. return newNode;
  1015. }
  1016. }
  1017. _extends(Text,CharacterData);
  1018. function Comment() {
  1019. };
  1020. Comment.prototype = {
  1021. nodeName : "#comment",
  1022. nodeType : COMMENT_NODE
  1023. }
  1024. _extends(Comment,CharacterData);
  1025. function CDATASection() {
  1026. };
  1027. CDATASection.prototype = {
  1028. nodeName : "#cdata-section",
  1029. nodeType : CDATA_SECTION_NODE
  1030. }
  1031. _extends(CDATASection,CharacterData);
  1032. function DocumentType() {
  1033. };
  1034. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1035. _extends(DocumentType,Node);
  1036. function Notation() {
  1037. };
  1038. Notation.prototype.nodeType = NOTATION_NODE;
  1039. _extends(Notation,Node);
  1040. function Entity() {
  1041. };
  1042. Entity.prototype.nodeType = ENTITY_NODE;
  1043. _extends(Entity,Node);
  1044. function EntityReference() {
  1045. };
  1046. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1047. _extends(EntityReference,Node);
  1048. function DocumentFragment() {
  1049. };
  1050. DocumentFragment.prototype.nodeName = "#document-fragment";
  1051. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1052. _extends(DocumentFragment,Node);
  1053. function ProcessingInstruction() {
  1054. }
  1055. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1056. _extends(ProcessingInstruction,Node);
  1057. function XMLSerializer(){}
  1058. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  1059. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  1060. }
  1061. Node.prototype.toString = nodeSerializeToString;
  1062. function nodeSerializeToString(isHtml,nodeFilter){
  1063. var buf = [];
  1064. var refNode = this.nodeType == 9 && this.documentElement || this;
  1065. var prefix = refNode.prefix;
  1066. var uri = refNode.namespaceURI;
  1067. if(uri && prefix == null){
  1068. //console.log(prefix)
  1069. var prefix = refNode.lookupPrefix(uri);
  1070. if(prefix == null){
  1071. //isHTML = true;
  1072. var visibleNamespaces=[
  1073. {namespace:uri,prefix:null}
  1074. //{namespace:uri,prefix:''}
  1075. ]
  1076. }
  1077. }
  1078. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  1079. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1080. return buf.join('');
  1081. }
  1082. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  1083. var prefix = node.prefix || '';
  1084. var uri = node.namespaceURI;
  1085. // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  1086. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  1087. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  1088. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  1089. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  1090. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  1091. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  1092. if (!uri) {
  1093. return false;
  1094. }
  1095. if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) {
  1096. return false;
  1097. }
  1098. var i = visibleNamespaces.length
  1099. while (i--) {
  1100. var ns = visibleNamespaces[i];
  1101. // get namespace prefix
  1102. if (ns.prefix === prefix) {
  1103. return ns.namespace !== uri;
  1104. }
  1105. }
  1106. return true;
  1107. }
  1108. /**
  1109. * Well-formed constraint: No < in Attribute Values
  1110. * > The replacement text of any entity referred to directly or indirectly
  1111. * > in an attribute value must not contain a <.
  1112. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  1113. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  1114. *
  1115. * Literal whitespace other than space that appear in attribute values
  1116. * are serialized as their entity references, so they will be preserved.
  1117. * (In contrast to whitespace literals in the input which are normalized to spaces)
  1118. * @see https://www.w3.org/TR/xml11/#AVNormalize
  1119. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  1120. */
  1121. function addSerializedAttribute(buf, qualifiedName, value) {
  1122. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"')
  1123. }
  1124. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  1125. if (!visibleNamespaces) {
  1126. visibleNamespaces = [];
  1127. }
  1128. if(nodeFilter){
  1129. node = nodeFilter(node);
  1130. if(node){
  1131. if(typeof node == 'string'){
  1132. buf.push(node);
  1133. return;
  1134. }
  1135. }else{
  1136. return;
  1137. }
  1138. //buf.sort.apply(attrs, attributeSorter);
  1139. }
  1140. switch(node.nodeType){
  1141. case ELEMENT_NODE:
  1142. var attrs = node.attributes;
  1143. var len = attrs.length;
  1144. var child = node.firstChild;
  1145. var nodeName = node.tagName;
  1146. isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML
  1147. var prefixedNodeName = nodeName
  1148. if (!isHTML && !node.prefix && node.namespaceURI) {
  1149. var defaultNS
  1150. // lookup current default ns from `xmlns` attribute
  1151. for (var ai = 0; ai < attrs.length; ai++) {
  1152. if (attrs.item(ai).name === 'xmlns') {
  1153. defaultNS = attrs.item(ai).value
  1154. break
  1155. }
  1156. }
  1157. if (!defaultNS) {
  1158. // lookup current default ns in visibleNamespaces
  1159. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1160. var namespace = visibleNamespaces[nsi]
  1161. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  1162. defaultNS = namespace.namespace
  1163. break
  1164. }
  1165. }
  1166. }
  1167. if (defaultNS !== node.namespaceURI) {
  1168. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  1169. var namespace = visibleNamespaces[nsi]
  1170. if (namespace.namespace === node.namespaceURI) {
  1171. if (namespace.prefix) {
  1172. prefixedNodeName = namespace.prefix + ':' + nodeName
  1173. }
  1174. break
  1175. }
  1176. }
  1177. }
  1178. }
  1179. buf.push('<', prefixedNodeName);
  1180. for(var i=0;i<len;i++){
  1181. // add namespaces for attributes
  1182. var attr = attrs.item(i);
  1183. if (attr.prefix == 'xmlns') {
  1184. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1185. }else if(attr.nodeName == 'xmlns'){
  1186. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1187. }
  1188. }
  1189. for(var i=0;i<len;i++){
  1190. var attr = attrs.item(i);
  1191. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  1192. var prefix = attr.prefix||'';
  1193. var uri = attr.namespaceURI;
  1194. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  1195. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1196. }
  1197. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  1198. }
  1199. // add namespace for current node
  1200. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  1201. var prefix = node.prefix||'';
  1202. var uri = node.namespaceURI;
  1203. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  1204. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1205. }
  1206. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  1207. buf.push('>');
  1208. //if is cdata child node
  1209. if(isHTML && /^script$/i.test(nodeName)){
  1210. while(child){
  1211. if(child.data){
  1212. buf.push(child.data);
  1213. }else{
  1214. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1215. }
  1216. child = child.nextSibling;
  1217. }
  1218. }else
  1219. {
  1220. while(child){
  1221. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1222. child = child.nextSibling;
  1223. }
  1224. }
  1225. buf.push('</',prefixedNodeName,'>');
  1226. }else{
  1227. buf.push('/>');
  1228. }
  1229. // remove added visible namespaces
  1230. //visibleNamespaces.length = startVisibleNamespaces;
  1231. return;
  1232. case DOCUMENT_NODE:
  1233. case DOCUMENT_FRAGMENT_NODE:
  1234. var child = node.firstChild;
  1235. while(child){
  1236. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  1237. child = child.nextSibling;
  1238. }
  1239. return;
  1240. case ATTRIBUTE_NODE:
  1241. return addSerializedAttribute(buf, node.name, node.value);
  1242. case TEXT_NODE:
  1243. /**
  1244. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  1245. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  1246. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  1247. * `&amp;` and `&lt;` respectively.
  1248. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  1249. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  1250. * when that string is not marking the end of a CDATA section.
  1251. *
  1252. * In the content of elements, character data is any string of characters
  1253. * which does not contain the start-delimiter of any markup
  1254. * and does not include the CDATA-section-close delimiter, `]]>`.
  1255. *
  1256. * @see https://www.w3.org/TR/xml/#NT-CharData
  1257. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  1258. */
  1259. return buf.push(node.data
  1260. .replace(/[<&>]/g,_xmlEncoder)
  1261. );
  1262. case CDATA_SECTION_NODE:
  1263. return buf.push( '<![CDATA[',node.data,']]>');
  1264. case COMMENT_NODE:
  1265. return buf.push( "<!--",node.data,"-->");
  1266. case DOCUMENT_TYPE_NODE:
  1267. var pubid = node.publicId;
  1268. var sysid = node.systemId;
  1269. buf.push('<!DOCTYPE ',node.name);
  1270. if(pubid){
  1271. buf.push(' PUBLIC ', pubid);
  1272. if (sysid && sysid!='.') {
  1273. buf.push(' ', sysid);
  1274. }
  1275. buf.push('>');
  1276. }else if(sysid && sysid!='.'){
  1277. buf.push(' SYSTEM ', sysid, '>');
  1278. }else{
  1279. var sub = node.internalSubset;
  1280. if(sub){
  1281. buf.push(" [",sub,"]");
  1282. }
  1283. buf.push(">");
  1284. }
  1285. return;
  1286. case PROCESSING_INSTRUCTION_NODE:
  1287. return buf.push( "<?",node.target," ",node.data,"?>");
  1288. case ENTITY_REFERENCE_NODE:
  1289. return buf.push( '&',node.nodeName,';');
  1290. //case ENTITY_NODE:
  1291. //case NOTATION_NODE:
  1292. default:
  1293. buf.push('??',node.nodeName);
  1294. }
  1295. }
  1296. function importNode(doc,node,deep){
  1297. var node2;
  1298. switch (node.nodeType) {
  1299. case ELEMENT_NODE:
  1300. node2 = node.cloneNode(false);
  1301. node2.ownerDocument = doc;
  1302. //var attrs = node2.attributes;
  1303. //var len = attrs.length;
  1304. //for(var i=0;i<len;i++){
  1305. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1306. //}
  1307. case DOCUMENT_FRAGMENT_NODE:
  1308. break;
  1309. case ATTRIBUTE_NODE:
  1310. deep = true;
  1311. break;
  1312. //case ENTITY_REFERENCE_NODE:
  1313. //case PROCESSING_INSTRUCTION_NODE:
  1314. ////case TEXT_NODE:
  1315. //case CDATA_SECTION_NODE:
  1316. //case COMMENT_NODE:
  1317. // deep = false;
  1318. // break;
  1319. //case DOCUMENT_NODE:
  1320. //case DOCUMENT_TYPE_NODE:
  1321. //cannot be imported.
  1322. //case ENTITY_NODE:
  1323. //case NOTATION_NODE:
  1324. //can not hit in level3
  1325. //default:throw e;
  1326. }
  1327. if(!node2){
  1328. node2 = node.cloneNode(false);//false
  1329. }
  1330. node2.ownerDocument = doc;
  1331. node2.parentNode = null;
  1332. if(deep){
  1333. var child = node.firstChild;
  1334. while(child){
  1335. node2.appendChild(importNode(doc,child,deep));
  1336. child = child.nextSibling;
  1337. }
  1338. }
  1339. return node2;
  1340. }
  1341. //
  1342. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1343. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1344. function cloneNode(doc,node,deep){
  1345. var node2 = new node.constructor();
  1346. for(var n in node){
  1347. var v = node[n];
  1348. if(typeof v != 'object' ){
  1349. if(v != node2[n]){
  1350. node2[n] = v;
  1351. }
  1352. }
  1353. }
  1354. if(node.childNodes){
  1355. node2.childNodes = new NodeList();
  1356. }
  1357. node2.ownerDocument = doc;
  1358. switch (node2.nodeType) {
  1359. case ELEMENT_NODE:
  1360. var attrs = node.attributes;
  1361. var attrs2 = node2.attributes = new NamedNodeMap();
  1362. var len = attrs.length
  1363. attrs2._ownerElement = node2;
  1364. for(var i=0;i<len;i++){
  1365. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  1366. }
  1367. break;;
  1368. case ATTRIBUTE_NODE:
  1369. deep = true;
  1370. }
  1371. if(deep){
  1372. var child = node.firstChild;
  1373. while(child){
  1374. node2.appendChild(cloneNode(doc,child,deep));
  1375. child = child.nextSibling;
  1376. }
  1377. }
  1378. return node2;
  1379. }
  1380. function __set__(object,key,value){
  1381. object[key] = value
  1382. }
  1383. //do dynamic
  1384. try{
  1385. if(Object.defineProperty){
  1386. Object.defineProperty(LiveNodeList.prototype,'length',{
  1387. get:function(){
  1388. _updateLiveList(this);
  1389. return this.$$length;
  1390. }
  1391. });
  1392. Object.defineProperty(Node.prototype,'textContent',{
  1393. get:function(){
  1394. return getTextContent(this);
  1395. },
  1396. set:function(data){
  1397. switch(this.nodeType){
  1398. case ELEMENT_NODE:
  1399. case DOCUMENT_FRAGMENT_NODE:
  1400. while(this.firstChild){
  1401. this.removeChild(this.firstChild);
  1402. }
  1403. if(data || String(data)){
  1404. this.appendChild(this.ownerDocument.createTextNode(data));
  1405. }
  1406. break;
  1407. default:
  1408. this.data = data;
  1409. this.value = data;
  1410. this.nodeValue = data;
  1411. }
  1412. }
  1413. })
  1414. function getTextContent(node){
  1415. switch(node.nodeType){
  1416. case ELEMENT_NODE:
  1417. case DOCUMENT_FRAGMENT_NODE:
  1418. var buf = [];
  1419. node = node.firstChild;
  1420. while(node){
  1421. if(node.nodeType!==7 && node.nodeType !==8){
  1422. buf.push(getTextContent(node));
  1423. }
  1424. node = node.nextSibling;
  1425. }
  1426. return buf.join('');
  1427. default:
  1428. return node.nodeValue;
  1429. }
  1430. }
  1431. __set__ = function(object,key,value){
  1432. //console.log(value)
  1433. object['$$'+key] = value
  1434. }
  1435. }
  1436. }catch(e){//ie8
  1437. }
  1438. //if(typeof require == 'function'){
  1439. exports.DocumentType = DocumentType;
  1440. exports.DOMException = DOMException;
  1441. exports.DOMImplementation = DOMImplementation;
  1442. exports.Element = Element;
  1443. exports.Node = Node;
  1444. exports.NodeList = NodeList;
  1445. exports.XMLSerializer = XMLSerializer;
  1446. //}