PageRenderTime 166ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/ajax/libs//1.3.6/defiant.js

https://gitlab.com/Mirros/cdnjs
JavaScript | 867 lines | 625 code | 38 blank | 204 comment | 53 complexity | 9609f1b17acd4eb28956360a62a72433 MD5 | raw file
  1. /*
  2. * defiant.js [v1.3.5]
  3. * http://www.defiantjs.com
  4. * Copyright (c) 2013-2015, Hakan Bilgin <hbi@longscript.com>
  5. * Licensed under the MIT License
  6. */
  7. /*
  8. * x10.js v0.1.3
  9. * Web worker wrapper with simple interface
  10. *
  11. * Copyright (c) 2013-2015, Hakan Bilgin <hbi@longscript.com>
  12. * Licensed under the MIT License
  13. */
  14. (function(window, undefined) {
  15. //'use strict';
  16. var x10 = {
  17. init: function() {
  18. return this;
  19. },
  20. work_handler: function(event) {
  21. var args = Array.prototype.slice.call(event.data, 1),
  22. func = event.data[0],
  23. ret = tree[func].apply(tree, args);
  24. // return process finish
  25. postMessage([func, ret]);
  26. },
  27. setup: function(tree) {
  28. var url = window.URL || window.webkitURL,
  29. script = 'var tree = {'+ this.parse(tree).join(',') +'};',
  30. blob = new Blob([script + 'self.addEventListener("message", '+ this.work_handler.toString() +', false);'],
  31. {type: 'text/javascript'}),
  32. worker = new Worker(url.createObjectURL(blob));
  33. // thread pipe
  34. worker.onmessage = function(event) {
  35. var args = Array.prototype.slice.call(event.data, 1),
  36. func = event.data[0];
  37. x10.observer.emit('x10:'+ func, args);
  38. };
  39. return worker;
  40. },
  41. call_handler: function(func, worker) {
  42. return function() {
  43. var args = Array.prototype.slice.call(arguments, 0, -1),
  44. callback = arguments[arguments.length-1];
  45. // add method name
  46. args.unshift(func);
  47. // listen for 'done'
  48. x10.observer.on('x10:'+ func, function(event) {
  49. callback(event.detail[0]);
  50. });
  51. // start worker
  52. worker.postMessage(args);
  53. };
  54. },
  55. compile: function(hash) {
  56. var worker = this.setup(typeof(hash) === 'function' ? {func: hash} : hash),
  57. obj = {},
  58. fn;
  59. // create return object
  60. if (typeof(hash) === 'function') {
  61. obj.func = this.call_handler('func', worker);
  62. return obj.func;
  63. } else {
  64. for (fn in hash) {
  65. obj[fn] = this.call_handler(fn, worker);
  66. }
  67. return obj;
  68. }
  69. },
  70. parse: function(tree, isArray) {
  71. var hash = [],
  72. key,
  73. val,
  74. v;
  75. for (key in tree) {
  76. v = tree[key];
  77. // handle null
  78. if (v === null) {
  79. hash.push(key +':null');
  80. continue;
  81. }
  82. // handle undefined
  83. if (v === undefined) {
  84. hash.push(key +':undefined');
  85. continue;
  86. }
  87. switch (v.constructor) {
  88. case Date: val = 'new Date('+ v.valueOf() +')'; break;
  89. case Object: val = '{'+ this.parse(v).join(',') +'}'; break;
  90. case Array: val = '['+ this.parse(v, true).join(',') +']'; break;
  91. case String: val = '"'+ v.replace(/"/g, '\\"') +'"'; break;
  92. case RegExp:
  93. case Function: val = v.toString(); break;
  94. default: val = v;
  95. }
  96. if (isArray) hash.push(val);
  97. else hash.push(key +':'+ val);
  98. }
  99. return hash;
  100. },
  101. // simple event emitter
  102. observer: (function() {
  103. var stack = {};
  104. return {
  105. on: function(type, fn) {
  106. if (!stack[type]) {
  107. stack[type] = [];
  108. }
  109. stack[type].unshift(fn);
  110. },
  111. off: function(type, fn) {
  112. if (!stack[type]) return;
  113. var i = stack[type].indexOf(fn);
  114. stack[type].splice(i,1);
  115. },
  116. emit: function(type, detail) {
  117. if (!stack[type]) return;
  118. var event = {
  119. type : type,
  120. detail : detail,
  121. isCanceled : false,
  122. cancelBubble : function() {
  123. this.isCanceled = true;
  124. }
  125. },
  126. len = stack[type].length;
  127. while(len--) {
  128. if (event.isCanceled) return;
  129. stack[type][len](event);
  130. }
  131. }
  132. };
  133. })()
  134. };
  135. if (typeof module === "undefined") {
  136. // publish x10
  137. window.x10 = x10.init();
  138. } else {
  139. module.exports = x10.init();
  140. }
  141. })(this);
  142. (function(window, module, undefined) {
  143. 'use strict';
  144. var Defiant = {
  145. is_ie : /(msie|trident)/i.test(navigator.userAgent),
  146. is_safari : /safari/i.test(navigator.userAgent),
  147. env : 'production',
  148. xml_decl : '<?xml version="1.0" encoding="utf-8"?>',
  149. namespace : 'xmlns:d="defiant-namespace"',
  150. tabsize : 4,
  151. render: function(template, data) {
  152. var processor = new XSLTProcessor(),
  153. span = document.createElement('span'),
  154. opt = {match: '/'},
  155. tmpltXpath,
  156. scripts,
  157. temp,
  158. sorter;
  159. // handle arguments
  160. switch (typeof(template)) {
  161. case 'object':
  162. this.extend(opt, template);
  163. if (!opt.data) opt.data = data;
  164. break;
  165. case 'string':
  166. opt.template = template;
  167. opt.data = data;
  168. break;
  169. default:
  170. throw 'error';
  171. }
  172. opt.data = JSON.toXML(opt.data);
  173. tmpltXpath = '//xsl:template[@name="'+ opt.template +'"]';
  174. if (!this.xsl_template) this.gatherTemplates();
  175. if (opt.sorter) {
  176. sorter = this.node.selectSingleNode(this.xsl_template, tmpltXpath +'//xsl:for-each//xsl:sort');
  177. if (sorter) {
  178. if (opt.sorter.order) sorter.setAttribute('order', opt.sorter.order);
  179. if (opt.sorter.select) sorter.setAttribute('select', opt.sorter.select);
  180. sorter.setAttribute('data-type', opt.sorter.type || 'text');
  181. }
  182. }
  183. temp = this.node.selectSingleNode(this.xsl_template, tmpltXpath);
  184. temp.setAttribute('match', opt.match);
  185. processor.importStylesheet(this.xsl_template);
  186. span.appendChild(processor.transformToFragment(opt.data, document));
  187. temp.removeAttribute('match');
  188. if (this.is_safari) {
  189. scripts = span.getElementsByTagName('script');
  190. for (var i=0, il=scripts.length; i<il; i++) scripts[i].defer = true;
  191. }
  192. return span.innerHTML;
  193. },
  194. gatherTemplates: function() {
  195. var scripts = document.getElementsByTagName('script'),
  196. str = '',
  197. i = 0,
  198. il = scripts.length;
  199. for (; i<il; i++) {
  200. if (scripts[i].type === 'defiant/xsl-template') str += scripts[i].innerHTML;
  201. }
  202. this.xsl_template = this.xmlFromString('<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" '+ this.namespace +'>'+ str.replace(/defiant:(\w+)/g, '$1') +'</xsl:stylesheet>');
  203. },
  204. getSnapshot: function(data, callback) {
  205. return JSON.toXML(data, callback || true);
  206. },
  207. xmlFromString: function(str) {
  208. var parser,
  209. doc;
  210. str = str.replace(/>\s{1,}</g, '><');
  211. if (str.trim().match(/<\?xml/) === null) {
  212. str = this.xml_decl + str;
  213. }
  214. if (this.is_ie) {
  215. doc = new ActiveXObject('Msxml2.DOMDocument');
  216. doc.loadXML(str);
  217. if (str.indexOf('xsl:stylesheet') === -1) {
  218. doc.setProperty('SelectionLanguage', 'XPath');
  219. }
  220. } else {
  221. parser = new DOMParser();
  222. doc = parser.parseFromString(str, 'text/xml');
  223. }
  224. return doc;
  225. },
  226. extend: function(src, dest) {
  227. for (var content in dest) {
  228. if (!src[content] || typeof(dest[content]) !== 'object') {
  229. src[content] = dest[content];
  230. } else {
  231. this.extend(src[content], dest[content]);
  232. }
  233. }
  234. return src;
  235. },
  236. node: {}
  237. };
  238. // Export
  239. window.Defiant = module.exports = Defiant;
  240. })(
  241. typeof window !== 'undefined' ? window : {},
  242. typeof module !== 'undefined' ? module : {}
  243. );
  244. if (typeof(XSLTProcessor) === 'undefined') {
  245. // emulating XSLT Processor (enough to be used in defiant)
  246. var XSLTProcessor = function() {};
  247. XSLTProcessor.prototype = {
  248. importStylesheet: function(xsldoc) {
  249. this.xsldoc = xsldoc;
  250. },
  251. transformToFragment: function(data, doc) {
  252. var str = data.transformNode(this.xsldoc),
  253. span = document.createElement('span');
  254. span.innerHTML = str;
  255. return span;
  256. }
  257. };
  258. } else if (typeof(XSLTProcessor) !== 'function' && !XSLTProcessor) {
  259. // throw error
  260. throw 'XSLTProcessor transformNode not implemented';
  261. }
  262. // extending STRING
  263. if (!String.prototype.fill) {
  264. String.prototype.fill = function(i,c) {
  265. var str = this;
  266. c = c || ' ';
  267. for (; str.length<i; str+=c){}
  268. return str;
  269. };
  270. }
  271. if (!String.prototype.trim) {
  272. String.prototype.trim = function () {
  273. return this.replace(/^\s+|\s+$/gm, '');
  274. };
  275. }
  276. if (!String.prototype.xTransform) {
  277. String.prototype.xTransform = function () {
  278. var str = this;
  279. if (this.indexOf('translate(') === -1) {
  280. str = this.replace(/contains\(([^,]+),([^\\)]+)\)/g, function(c,h,n) {
  281. var a = 'abcdefghijklmnopqrstuvwxyz',
  282. q = n.trim().slice(-1);
  283. return "contains(translate("+ h +", "+ q + a.toUpperCase() + q +", "+ q + a + q +"),"+ n.toLowerCase() +")";
  284. });
  285. }
  286. return str.toString();
  287. };
  288. }
  289. /* jshint ignore:start */
  290. if (typeof(JSON) === 'undefined') {
  291. window.JSON = {
  292. parse: function (sJSON) { return eval("(" + sJSON + ")"); },
  293. stringify: function (vContent) {
  294. if (vContent instanceof Object) {
  295. var sOutput = "";
  296. if (vContent.constructor === Array) {
  297. for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ",", nId++);
  298. return "[" + sOutput.substr(0, sOutput.length - 1) + "]";
  299. }
  300. if (vContent.toString !== Object.prototype.toString) {
  301. return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\"";
  302. }
  303. for (var sProp in vContent) {
  304. sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringify(vContent[sProp]) + ",";
  305. }
  306. return "{" + sOutput.substr(0, sOutput.length - 1) + "}";
  307. }
  308. return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent);
  309. }
  310. };
  311. }
  312. /* jshint ignore:end */
  313. if (!JSON.toXML) {
  314. JSON.toXML = function(tree, callback) {
  315. 'use strict';
  316. var interpreter = {
  317. map : [],
  318. rx_validate_name : /^(?!xml)[a-z_][\w\d.:]*$/i,
  319. rx_node : /<(.+?)( .*?)>/,
  320. rx_constructor : /<(.+?)( d:contr=".*?")>/,
  321. rx_namespace : / xmlns\:d="defiant\-namespace"/,
  322. rx_data : /(<.+?>)(.*?)(<\/d:data>)/i,
  323. rx_function : /function (\w+)/i,
  324. namespace : 'xmlns:d="defiant-namespace"',
  325. to_xml_str: function(tree) {
  326. return {
  327. str: this.hash_to_xml(null, tree),
  328. map: this.map
  329. };
  330. },
  331. hash_to_xml: function(name, tree, array_child) {
  332. var is_array = tree.constructor === Array,
  333. elem = [],
  334. attr = [],
  335. key,
  336. val,
  337. val_is_array,
  338. type,
  339. is_attr,
  340. cname,
  341. constr,
  342. cnName,
  343. i;
  344. for (key in tree) {
  345. val = tree[key];
  346. if (val === null || val === undefined || val.toString() === 'NaN') val = null;
  347. is_attr = key.slice(0,1) === '@';
  348. cname = array_child ? name : key;
  349. if (cname == +cname && tree.constructor !== Object) cname = 'd:item';
  350. if (val === null) {
  351. constr = null;
  352. cnName = false;
  353. } else {
  354. constr = val.constructor;
  355. cnName = constr.toString().match(this.rx_function)[1];
  356. }
  357. if (is_attr) {
  358. attr.push( cname.slice(1) +'="'+ this.escape_xml(val) +'"' );
  359. if (cnName !== 'String') attr.push( 'd:'+ cname.slice(1) +'="'+ cnName +'"' );
  360. } else if (val === null) {
  361. elem.push( this.scalar_to_xml( cname, val ) );
  362. } else {
  363. switch (constr) {
  364. case Function:
  365. // if constructor is function, then it's not a JSON structure
  366. throw 'JSON data should not contain functions. Please check jour structure.';
  367. /* falls through */
  368. case Object:
  369. elem.push( this.hash_to_xml( cname, val ) );
  370. break;
  371. case Array:
  372. if (key === cname) {
  373. val_is_array = val.constructor === Array;
  374. if (val_is_array) {
  375. i = val.length;
  376. while (i--) {
  377. if (val[i] === null || !val[i] || val[i].constructor === Array) val_is_array = true;
  378. if (!val_is_array && val[i].constructor === Object) val_is_array = true;
  379. }
  380. }
  381. elem.push( this.scalar_to_xml( cname, val, val_is_array ) );
  382. break;
  383. }
  384. /* falls through */
  385. case String:
  386. if (typeof(val) === 'string') {
  387. val = val.toString().replace(/\&/g, '&amp;')
  388. .replace(/\r|\n/g, '&#13;');
  389. }
  390. if (cname === '#text') {
  391. // prepare map
  392. this.map.push(tree);
  393. attr.push('d:mi="'+ this.map.length +'"');
  394. attr.push('d:constr="'+ cnName +'"');
  395. elem.push( this.escape_xml(val) );
  396. break;
  397. }
  398. /* falls through */
  399. case Number:
  400. case Boolean:
  401. if (cname === '#text' && cnName !== 'String') {
  402. // prepare map
  403. this.map.push(tree);
  404. attr.push('d:mi="'+ this.map.length +'"');
  405. attr.push('d:constr="'+ cnName +'"');
  406. elem.push( this.escape_xml(val) );
  407. break;
  408. }
  409. elem.push( this.scalar_to_xml( cname, val ) );
  410. break;
  411. }
  412. }
  413. }
  414. if (!name) {
  415. name = 'd:data';
  416. attr.push(this.namespace);
  417. if (is_array) attr.push('d:constr="Array"');
  418. }
  419. if (name.match(this.rx_validate_name) === null) {
  420. attr.push( 'd:name="'+ name +'"' );
  421. name = 'd:name';
  422. }
  423. if (array_child) return elem.join('');
  424. // prepare map
  425. this.map.push(tree);
  426. attr.push('d:mi="'+ this.map.length +'"');
  427. return '<'+ name + (attr.length ? ' '+ attr.join(' ') : '') + (elem.length ? '>'+ elem.join('') +'</'+ name +'>' : '/>' );
  428. },
  429. scalar_to_xml: function(name, val, override) {
  430. var attr = '',
  431. text,
  432. constr,
  433. cnName;
  434. // check whether the nodename is valid
  435. if (name.match(this.rx_validate_name) === null) {
  436. attr += ' d:name="'+ name +'"';
  437. name = 'd:name';
  438. override = false;
  439. }
  440. if (val === null || val.toString() === 'NaN') val = null;
  441. if (val === null) return '<'+ name +' d:constr="null"/>';
  442. if (val.length === 1 && val[0].constructor === Object) {
  443. text = this.hash_to_xml(false, val[0]);
  444. var a1 = text.match(this.rx_node),
  445. a2 = text.match(this.rx_constructor);
  446. a1 = (a1 !== null)? a1[2]
  447. .replace(this.rx_namespace, '')
  448. .replace(/>/, '')
  449. .replace(/"\/$/, '"') : '';
  450. a2 = (a2 !== null)? a2[2] : '';
  451. text = text.match(this.rx_data);
  452. text = (text !== null)? text[2] : '';
  453. return '<'+ name + a1 +' '+ a2 +' d:type="ArrayItem">'+ text +'</'+ name +'>';
  454. } else if (val.length === 0 && val.constructor === Array) {
  455. return '<'+ name +' d:constr="Array"/>';
  456. }
  457. // else
  458. if (override) {
  459. return this.hash_to_xml( name, val, true );
  460. }
  461. constr = val.constructor;
  462. cnName = constr.toString().match(this.rx_function)[1];
  463. text = (constr === Array) ? this.hash_to_xml( 'd:item', val, true )
  464. : this.escape_xml(val);
  465. attr += ' d:constr="'+ cnName +'"';
  466. // prepare map
  467. this.map.push(val);
  468. attr += ' d:mi="'+ this.map.length +'"';
  469. return (name === '#text') ? this.escape_xml(val) : '<'+ name + attr +'>'+ text +'</'+ name +'>';
  470. },
  471. escape_xml: function(text) {
  472. return String(text) .replace(/</g, '&lt;')
  473. .replace(/>/g, '&gt;')
  474. .replace(/"/g, '&quot;')
  475. .replace(/&nbsp;/g, '&#160;');
  476. }
  477. },
  478. processed,
  479. doc,
  480. task;
  481. // depending on request
  482. switch (typeof callback) {
  483. case 'function':
  484. // compile interpreter with 'x10.js'
  485. task = x10.compile(interpreter);
  486. // parse in a dedicated thread
  487. task.to_xml_str(tree, function(processed) {
  488. // snapshot distinctly improves performance
  489. callback({
  490. doc: Defiant.xmlFromString(processed.str),
  491. src: tree,
  492. map: processed.map
  493. });
  494. });
  495. return;
  496. case 'boolean':
  497. processed = interpreter.to_xml_str.call(interpreter, tree);
  498. // return snapshot
  499. return {
  500. doc: Defiant.xmlFromString(processed.str),
  501. src: tree,
  502. map: processed.map
  503. };
  504. default:
  505. processed = interpreter.to_xml_str.call(interpreter, tree);
  506. doc = Defiant.xmlFromString(processed.str);
  507. this.search.map = processed.map;
  508. return doc;
  509. }
  510. };
  511. }
  512. if (!JSON.search) {
  513. JSON.search = function(tree, xpath, single) {
  514. 'use strict';
  515. var isSnapshot = tree.doc && tree.doc.nodeType,
  516. doc = isSnapshot ? tree.doc : JSON.toXML(tree),
  517. map = isSnapshot ? tree.map : this.search.map,
  518. src = isSnapshot ? tree.src : tree,
  519. xres = Defiant.node[ single ? 'selectSingleNode' : 'selectNodes' ](doc, xpath.xTransform()),
  520. ret = [],
  521. mapIndex,
  522. i;
  523. if (single) xres = [xres];
  524. i = xres.length;
  525. while (i--) {
  526. switch(xres[i].nodeType) {
  527. case 2:
  528. case 3:
  529. ret.unshift( xres[i].nodeValue );
  530. break;
  531. default:
  532. mapIndex = +xres[i].getAttribute('d:mi');
  533. //if (map[mapIndex-1] !== false) {
  534. ret.unshift( map[mapIndex-1] );
  535. //}
  536. }
  537. }
  538. // if environment = development, add search tracing
  539. if (Defiant.env === 'development') {
  540. this.trace = JSON.mtrace(src, ret, xres);
  541. }
  542. return ret;
  543. };
  544. }
  545. if (!JSON.mtrace) {
  546. JSON.mtrace = function(root, hits, xres) {
  547. 'use strict';
  548. var win = window,
  549. stringify = JSON.stringify,
  550. sroot = stringify( root, null, '\t' ).replace(/\t/g, ''),
  551. trace = [],
  552. i = 0,
  553. il = xres.length,
  554. od = il ? xres[i].ownerDocument.documentElement : false,
  555. map = this.search.map,
  556. hstr,
  557. cConstr,
  558. fIndex = 0,
  559. mIndex,
  560. lStart,
  561. lEnd;
  562. for (; i<il; i++) {
  563. switch (xres[i].nodeType) {
  564. case 2:
  565. cConstr = xres[i].ownerElement ? xres[i].ownerElement.getAttribute('d:'+ xres[i].nodeName) : 'String';
  566. hstr = '"@'+ xres[i].nodeName +'": '+ win[ cConstr ]( hits[i] );
  567. mIndex = sroot.indexOf(hstr);
  568. lEnd = 0;
  569. break;
  570. case 3:
  571. cConstr = xres[i].parentNode.getAttribute('d:constr');
  572. hstr = win[ cConstr ]( hits[i] );
  573. hstr = '"'+ xres[i].parentNode.nodeName +'": '+ (hstr === 'Number' ? hstr : '"'+ hstr +'"');
  574. mIndex = sroot.indexOf(hstr);
  575. lEnd = 0;
  576. break;
  577. default:
  578. if (xres[i] === od) continue;
  579. if (xres[i].getAttribute('d:constr') === 'String' || xres[i].getAttribute('d:constr') === 'Number') {
  580. cConstr = xres[i].getAttribute('d:constr');
  581. hstr = win[ cConstr ]( hits[i] );
  582. mIndex = sroot.indexOf(hstr, fIndex);
  583. hstr = '"'+ xres[i].nodeName +'": '+ (cConstr === 'Number' ? hstr : '"'+ hstr +'"');
  584. lEnd = 0;
  585. fIndex = mIndex + 1;
  586. } else {
  587. hstr = stringify( hits[i], null, '\t' ).replace(/\t/g, '');
  588. mIndex = sroot.indexOf(hstr);
  589. lEnd = hstr.match(/\n/g).length;
  590. }
  591. }
  592. lStart = sroot.substring(0,mIndex).match(/\n/g).length+1;
  593. trace.push([lStart, lEnd]);
  594. }
  595. return trace;
  596. };
  597. }
  598. Defiant.node.selectNodes = function(XNode, XPath) {
  599. if (XNode.evaluate) {
  600. var ns = XNode.createNSResolver(XNode.documentElement),
  601. qI = XNode.evaluate(XPath, XNode, ns, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
  602. res = [],
  603. i = 0,
  604. il = qI.snapshotLength;
  605. for (; i<il; i++) {
  606. res.push( qI.snapshotItem(i) );
  607. }
  608. return res;
  609. } else {
  610. return XNode.selectNodes(XPath);
  611. }
  612. };
  613. Defiant.node.selectSingleNode = function(XNode, XPath) {
  614. if (XNode.evaluate) {
  615. var xI = this.selectNodes(XNode, XPath);
  616. return (xI.length > 0)? xI[0] : null;
  617. } else {
  618. return XNode.selectSingleNode(XPath);
  619. }
  620. };
  621. Defiant.node.prettyPrint = function(node) {
  622. var root = Defiant,
  623. tabs = root.tabsize,
  624. decl = root.xml_decl.toLowerCase(),
  625. ser,
  626. xstr;
  627. if (root.is_ie) {
  628. xstr = node.xml;
  629. } else {
  630. ser = new XMLSerializer();
  631. xstr = ser.serializeToString(node);
  632. }
  633. if (root.env !== 'development') {
  634. // if environment is not development, remove defiant related info
  635. xstr = xstr.replace(/ \w+\:d=".*?"| d\:\w+=".*?"/g, '');
  636. }
  637. var str = xstr.trim().replace(/(>)\s*(<)(\/*)/g, '$1\n$2$3'),
  638. lines = str.split('\n'),
  639. indent = -1,
  640. i = 0,
  641. il = lines.length,
  642. start,
  643. end;
  644. for (; i<il; i++) {
  645. if (i === 0 && lines[i].toLowerCase() === decl) continue;
  646. start = lines[i].match(/<[A-Za-z_\:]+.*?>/g) !== null;
  647. //start = lines[i].match(/<[^\/]+>/g) !== null;
  648. end = lines[i].match(/<\/[\w\:]+>/g) !== null;
  649. if (lines[i].match(/<.*?\/>/g) !== null) start = end = true;
  650. if (start) indent++;
  651. lines[i] = String().fill(indent, '\t') + lines[i];
  652. if (start && end) indent--;
  653. if (!start && end) indent--;
  654. }
  655. return lines.join('\n').replace(/\t/g, String().fill(tabs, ' '));
  656. };
  657. Defiant.node.toJSON = function(xnode, stringify) {
  658. 'use strict';
  659. var interpret = function(leaf) {
  660. var obj = {},
  661. win = window,
  662. attr,
  663. type,
  664. item,
  665. cname,
  666. cConstr,
  667. cval,
  668. text,
  669. i, il, a;
  670. switch (leaf.nodeType) {
  671. case 1:
  672. cConstr = leaf.getAttribute('d:constr');
  673. if (cConstr === 'Array') obj = [];
  674. else if (cConstr === 'String' && leaf.textContent === '') obj = '';
  675. attr = leaf.attributes;
  676. i = 0;
  677. il = attr.length;
  678. for (; i<il; i++) {
  679. a = attr.item(i);
  680. if (a.nodeName.match(/\:d|d\:/g) !== null) continue;
  681. cConstr = leaf.getAttribute('d:'+ a.nodeName);
  682. if (cConstr && cConstr !== 'undefined') {
  683. if (a.nodeValue === 'null') cval = null;
  684. else cval = win[ cConstr ]( (a.nodeValue === 'false') ? '' : a.nodeValue );
  685. } else {
  686. cval = a.nodeValue;
  687. }
  688. obj['@'+ a.nodeName] = cval;
  689. }
  690. break;
  691. case 3:
  692. type = leaf.parentNode.getAttribute('d:type');
  693. cval = (type) ? win[ type ]( leaf.nodeValue === 'false' ? '' : leaf.nodeValue ) : leaf.nodeValue;
  694. obj = cval;
  695. break;
  696. }
  697. if (leaf.hasChildNodes()) {
  698. i = 0;
  699. il = leaf.childNodes.length;
  700. for(; i<il; i++) {
  701. item = leaf.childNodes.item(i);
  702. cname = item.nodeName;
  703. attr = leaf.attributes;
  704. if (cname === 'd:name') {
  705. cname = item.getAttribute('d:name');
  706. }
  707. if (cname === '#text') {
  708. cConstr = leaf.getAttribute('d:constr');
  709. if (cConstr === 'undefined') cConstr = undefined;
  710. text = item.textContent || item.text;
  711. cval = cConstr === 'Boolean' && text === 'false' ? '' : text;
  712. if (!cConstr && !attr.length) obj = cval;
  713. else if (cConstr && il === 1) {
  714. obj = win[cConstr](cval);
  715. } else if (!leaf.hasChildNodes()) {
  716. obj[cname] = (cConstr)? win[cConstr](cval) : cval;
  717. } else {
  718. if (attr.length < 3) obj = (cConstr)? win[cConstr](cval) : cval;
  719. else obj[cname] = (cConstr)? win[cConstr](cval) : cval;
  720. }
  721. } else {
  722. if (item.getAttribute('d:constr') === 'null') {
  723. if (obj[cname] && obj[cname].push) obj[cname].push(null);
  724. else if (item.previousSibling) obj[cname] = [obj[cname], null];
  725. else obj[cname] = [obj[cname]];
  726. continue;
  727. }
  728. if (obj[cname]) {
  729. if (obj[cname].push) obj[cname].push(interpret(item));
  730. else obj[cname] = [obj[cname], interpret(item)];
  731. continue;
  732. }
  733. cConstr = item.getAttribute('d:constr');
  734. switch (cConstr) {
  735. case 'null':
  736. if (obj.push) obj.push(null);
  737. else obj[cname] = null;
  738. break;
  739. case 'Array':
  740. //console.log( Defiant.node.prettyPrint(item) );
  741. if (item.parentNode.firstChild === item && cConstr === 'Array' && cname !== 'd:item') {
  742. if (cname === 'd:item' || cConstr === 'Array') {
  743. cval = interpret(item);
  744. obj[cname] = cval.length ? [cval] : cval;
  745. } else {
  746. obj[cname] = interpret(item);
  747. }
  748. }
  749. else if (obj.push) obj.push( interpret(item) );
  750. else obj[cname] = interpret(item);
  751. break;
  752. case 'String':
  753. case 'Number':
  754. case 'Boolean':
  755. text = item.textContent || item.text;
  756. cval = cConstr === 'Boolean' && text === 'false' ? '' : text;
  757. if (obj.push) obj.push( win[cConstr](cval) );
  758. else obj[cname] = interpret(item);
  759. break;
  760. default:
  761. if (obj.push) obj.push( interpret( item ) );
  762. else obj[cname] = interpret( item );
  763. }
  764. }
  765. }
  766. }
  767. if (leaf.nodeType === 1 && leaf.getAttribute('d:type') === 'ArrayItem') {
  768. obj = [obj];
  769. }
  770. return obj;
  771. },
  772. node = (xnode.nodeType === 9) ? xnode.documentElement : xnode,
  773. ret = interpret(node),
  774. rn = ret[node.nodeName];
  775. // exclude root, if "this" is root node
  776. if (node === node.ownerDocument.documentElement && rn && rn.constructor === Array) {
  777. ret = rn;
  778. }
  779. if (stringify && stringify.toString() === 'true') stringify = '\t';
  780. return stringify ? JSON.stringify(ret, null, stringify) : ret;
  781. };
  782. // check if jQuery is present
  783. if (typeof(jQuery) !== 'undefined') {
  784. (function ( $ ) {
  785. 'use strict';
  786. $.fn.defiant = function(template, xpath) {
  787. this.html( Defiant.render(template, xpath) );
  788. return this;
  789. };
  790. }(jQuery));
  791. }