htmlToWxml.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /**
  2. * Created by kevenfeng on 2016/10/12.
  3. */
  4. // Regular Expressions for parsing tags and attributes
  5. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
  6. endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/,
  7. attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
  8. // Empty Elements - HTML 5
  9. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  10. // Block Elements - HTML 5
  11. var block = makeMap("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video");
  12. // Inline Elements - HTML 5
  13. var inline = makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");
  14. // Elements that you can, intentionally, leave open
  15. // (and which close themselves)
  16. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  17. // Attributes that have their values filled in disabled="disabled"
  18. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  19. // Special Elements (can contain anything)
  20. var special = makeMap("script,style");
  21. var HTMLParser = function (html, handler) {
  22. var index, chars, match, stack = [], last = html;
  23. stack.last = function () {
  24. return this[this.length - 1];
  25. };
  26. while (html) {
  27. chars = true;
  28. // Make sure we're not in a script or style element
  29. if (!stack.last() || !special[stack.last()]) {
  30. // Comment
  31. if (html.indexOf("<!--") == 0) {
  32. index = html.indexOf("-->");
  33. if (index >= 0) {
  34. if (handler.comment)
  35. handler.comment(html.substring(4, index));
  36. html = html.substring(index + 3);
  37. chars = false;
  38. }
  39. // end tag
  40. } else if (html.indexOf("</") == 0) {
  41. match = html.match(endTag);
  42. if (match) {
  43. html = html.substring(match[0].length);
  44. match[0].replace(endTag, parseEndTag);
  45. chars = false;
  46. }
  47. // start tag
  48. } else if (html.indexOf("<") == 0) {
  49. match = html.match(startTag);
  50. if (match) {
  51. html = html.substring(match[0].length);
  52. match[0].replace(startTag, parseStartTag);
  53. chars = false;
  54. }
  55. }
  56. if (chars) {
  57. index = html.indexOf("<");
  58. var text = index < 0 ? html : html.substring(0, index);
  59. html = index < 0 ? "" : html.substring(index);
  60. if (handler.chars)
  61. handler.chars(text);
  62. }
  63. } else {
  64. html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), function (all, text) {
  65. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, "$1$2");
  66. if (handler.chars)
  67. handler.chars(text);
  68. return "";
  69. });
  70. parseEndTag("", stack.last());
  71. }
  72. if (html == last)
  73. throw "Parse Error: " + html;
  74. last = html;
  75. }
  76. // Clean up any remaining tags
  77. parseEndTag();
  78. function parseStartTag(tag, tagName, rest, unary) {
  79. tagName = tagName.toLowerCase();
  80. if (block[tagName]) {
  81. while (stack.last() && inline[stack.last()]) {
  82. parseEndTag("", stack.last());
  83. }
  84. }
  85. if (closeSelf[tagName] && stack.last() == tagName) {
  86. parseEndTag("", tagName);
  87. }
  88. unary = empty[tagName] || !!unary;
  89. if (!unary)
  90. stack.push(tagName);
  91. if (handler.start) {
  92. var attrs = [];
  93. rest.replace(attr, function (match, name) {
  94. var value = arguments[2] ? arguments[2] :
  95. arguments[3] ? arguments[3] :
  96. arguments[4] ? arguments[4] :
  97. fillAttrs[name] ? name : "";
  98. attrs.push({
  99. name: name,
  100. value: value,
  101. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
  102. });
  103. });
  104. if (handler.start)
  105. handler.start(tagName, attrs, unary);
  106. }
  107. }
  108. function parseEndTag(tag, tagName) {
  109. // If no tag name is provided, clean shop
  110. if (!tagName)
  111. var pos = 0;
  112. // Find the closest opened tag of the same type
  113. else
  114. for (var pos = stack.length - 1; pos >= 0; pos--)
  115. if (stack[pos] == tagName)
  116. break;
  117. if (pos >= 0) {
  118. // Close all the open elements, up the stack
  119. for (var i = stack.length - 1; i >= pos; i--)
  120. if (handler.end)
  121. handler.end(stack[i]);
  122. // Remove the open elements from the stack
  123. stack.length = pos;
  124. }
  125. }
  126. };
  127. function makeMap(str) {
  128. var obj = {}, items = str.split(",");
  129. for (var i = 0; i < items.length; i++)
  130. obj[items[i]] = true;
  131. return obj;
  132. }
  133. var global = {};
  134. var debug = function () { };
  135. function q(v) {
  136. return '"' + v + '"';
  137. }
  138. function removeDOCTYPE(html) {
  139. return html
  140. .replace(/<\?xml.*\?>\n/, '')
  141. .replace(/<!doctype.*\>\n/, '')
  142. .replace(/<!DOCTYPE.*\>\n/, '');
  143. }
  144. global.html2json = function html2json(html) {
  145. html = removeDOCTYPE(html);
  146. var bufArray = [];
  147. var results = {
  148. node: 'root',
  149. child: [],
  150. };
  151. HTMLParser(html, {
  152. start: function (tag, attrs, unary) {
  153. debug(tag, attrs, unary);
  154. // node for this element
  155. var node = {
  156. node: 'element',
  157. tag: tag,
  158. };
  159. if (attrs.length !== 0) {
  160. node.attr = attrs.reduce(function (pre, attr) {
  161. var name = attr.name;
  162. var value = attr.value;
  163. // has multi attibutes
  164. // make it array of attribute
  165. if (value.match(/ /)) {
  166. value = value.split(' ');
  167. }
  168. // if attr already exists
  169. // merge it
  170. if (pre[name]) {
  171. if (Array.isArray(pre[name])) {
  172. // already array, push to last
  173. pre[name].push(value);
  174. } else {
  175. // single value, make it array
  176. pre[name] = [pre[name], value];
  177. }
  178. } else {
  179. // not exist, put it
  180. pre[name] = value;
  181. }
  182. return pre;
  183. }, {});
  184. }
  185. if (unary) {
  186. // if this tag dosen't have end tag
  187. // like <img src="hoge.png"/>
  188. // add to parents
  189. var parent = bufArray[0] || results;
  190. if (parent.child === undefined) {
  191. parent.child = [];
  192. }
  193. parent.child.push(node);
  194. } else {
  195. bufArray.unshift(node);
  196. }
  197. },
  198. end: function (tag) {
  199. debug(tag);
  200. // merge into parent tag
  201. var node = bufArray.shift();
  202. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  203. if (bufArray.length === 0) {
  204. results.child.push(node);
  205. } else {
  206. var parent = bufArray[0];
  207. if (parent.child === undefined) {
  208. parent.child = [];
  209. }
  210. parent.child.push(node);
  211. }
  212. },
  213. chars: function (text) {
  214. debug(text);
  215. var node = {
  216. node: 'text',
  217. text: text,
  218. };
  219. if (bufArray.length === 0) {
  220. results.child.push(node);
  221. } else {
  222. var parent = bufArray[0];
  223. if (parent.child === undefined) {
  224. parent.child = [];
  225. }
  226. parent.child.push(node);
  227. }
  228. },
  229. comment: function (text) {
  230. debug(text);
  231. var node = {
  232. node: 'comment',
  233. text: text,
  234. };
  235. var parent = bufArray[0];
  236. if (parent.child === undefined) {
  237. parent.child = [];
  238. }
  239. parent.child.push(node);
  240. },
  241. });
  242. return results;
  243. };
  244. global.json2html = function json2html(json) {
  245. // Empty Elements - HTML 4.01
  246. var empty = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'embed'];
  247. var child = '';
  248. if (json.child) {
  249. child = json.child.map(function (c) {
  250. return json2html(c);
  251. }).join('');
  252. }
  253. var attr = '';
  254. if (json.attr) {
  255. attr = Object.keys(json.attr).map(function (key) {
  256. var value = json.attr[key];
  257. if (Array.isArray(value)) value = value.join(' ');
  258. return key + '=' + q(value);
  259. }).join(' ');
  260. if (attr !== '') attr = ' ' + attr;
  261. }
  262. if (json.node === 'element') {
  263. var tag = json.tag;
  264. if (empty.indexOf(tag) > -1) {
  265. // empty element
  266. return '<' + json.tag + attr + '/>';
  267. }
  268. // non empty element
  269. var open = '<' + json.tag + attr + '>';
  270. var close = '</' + json.tag + '>';
  271. return open + child + close;
  272. }
  273. if (json.node === 'text') {
  274. return json.text;
  275. }
  276. if (json.node === 'comment') {
  277. return '<!--' + json.text + '-->';
  278. }
  279. if (json.node === 'root') {
  280. return child;
  281. }
  282. };
  283. var html2wxwebview = function (html) {
  284. var htmlNode = global.html2json(html);
  285. htmlNode = parseHtmlNode(htmlNode);
  286. htmlNode = arrangeNode(htmlNode);
  287. return htmlNode;
  288. }
  289. //整理节点
  290. var arrangeNode = function (htmlNode) {
  291. var arrangeArray = [];
  292. var nodeObj = [];
  293. for (var i = 0, j = htmlNode.length; i < j; i++) {
  294. if (i == 0) {
  295. if (htmlNode[i].type == "view") {
  296. continue;
  297. }
  298. arrangeArray.push(htmlNode[i]);
  299. } else {
  300. if (htmlNode[i].type == "view") {
  301. if (arrangeArray.length > 0) {
  302. var obj = {
  303. type: "view",
  304. child: arrangeArray
  305. }
  306. nodeObj.push(obj);
  307. }
  308. arrangeArray = [];
  309. } else if (htmlNode[i].type == "img") {
  310. if (arrangeArray.length > 0) {
  311. var obj = {
  312. type: "view",
  313. child: arrangeArray
  314. }
  315. nodeObj.push(obj);
  316. }
  317. var attr = htmlNode[i].attr;
  318. if (htmlNode[i].attr.width && htmlNode[i].attr.width.indexOf('%') === -1 && htmlNode[i].attr.width.indexOf('px') === -1) {
  319. htmlNode[i].attr.width = htmlNode[i].attr.width + 'px'
  320. }
  321. if (htmlNode[i].attr.height && htmlNode[i].attr.height.indexOf('%') === -1 && htmlNode[i].attr.height.indexOf('px') === -1) {
  322. htmlNode[i].attr.height = htmlNode[i].attr.height + 'px'
  323. }
  324. var obj = {
  325. type: "img",
  326. attr: attr
  327. }
  328. nodeObj.push(obj);
  329. arrangeArray = [];
  330. } else {
  331. arrangeArray.push(htmlNode[i]);
  332. if (i == (j - 1)) {
  333. var obj = {
  334. type: "view",
  335. child: arrangeArray
  336. }
  337. nodeObj.push(obj);
  338. }
  339. }
  340. }
  341. }
  342. return nodeObj;
  343. }
  344. //将html节点转成小程序可用的接口
  345. var parseHtmlNode = function (htmlNode) {
  346. var tagsArray = [];
  347. var parsetags = function (node) {
  348. var tag = {};
  349. if (node.node == "root") {
  350. } else if (node.node == "element") {
  351. switch (node.tag) {
  352. case "a":
  353. tag = {
  354. type: "a",
  355. text: node.child[0].text,
  356. }
  357. break;
  358. case "img":
  359. tag = {
  360. type: "img",
  361. text: node.text,
  362. }
  363. break;
  364. case "p":
  365. tag = {
  366. type: "view",
  367. text: node.text,
  368. }
  369. break;
  370. case "div":
  371. tag = {
  372. type: "view",
  373. text: node.text,
  374. }
  375. break;
  376. }
  377. } else if (node.node == "text") {
  378. tag = {
  379. type: "text",
  380. text: node.text,
  381. }
  382. }
  383. if (node.attr) {
  384. tag.attr = node.attr;
  385. }
  386. if (Object.keys(tag).length != 0) {
  387. // if(tag.text||node.tag=="img"){
  388. tagsArray.push(tag);
  389. // }
  390. }
  391. if (node.tag == "a") {//如果是a标签就不去解析他的child
  392. return;
  393. }
  394. var child = node.child;
  395. if (child) {
  396. for (var val in child) {
  397. parsetags(child[val]);
  398. }
  399. }
  400. }
  401. parsetags(htmlNode);
  402. return tagsArray;
  403. }
  404. module.exports = {
  405. html2json: html2wxwebview
  406. }