html2json.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /**
  2. * author: Di (微信小程序开发工程师)
  3. * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
  4. * 垂直微信小程序开发交流社区
  5. *
  6. * github地址: https://github.com/icindy/wxParse
  7. *
  8. * for: 微信小程序富文本解析
  9. * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
  10. */
  11. var __placeImgeUrlHttps = "https";
  12. var __emojisReg = '';
  13. var __emojisBaseSrc = '';
  14. var __emojis = {};
  15. var wxDiscode = require('wxDiscode.js');
  16. var HTMLParser = require('htmlparser.js');
  17. // Empty Elements - HTML 5
  18. var empty = makeMap(
  19. "area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  20. // Block Elements - HTML 5
  21. var block = makeMap(
  22. "br,a,code,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"
  23. );
  24. // Inline Elements - HTML 5
  25. var inline = makeMap(
  26. "abbr,acronym,applet,b,basefont,bdo,big,button,cite,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"
  27. );
  28. // Elements that you can, intentionally, leave open
  29. // (and which close themselves)
  30. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  31. // Attributes that have their values filled in disabled="disabled"
  32. var fillAttrs = makeMap(
  33. "checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  34. // Special Elements (can contain anything)
  35. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  36. function makeMap(str) {
  37. var obj = {},
  38. items = str.split(",");
  39. for (var i = 0; i < items.length; i++)
  40. obj[items[i]] = true;
  41. return obj;
  42. }
  43. function q(v) {
  44. return '"' + v + '"';
  45. }
  46. function removeDOCTYPE(html) {
  47. return html
  48. .replace(/<\?xml.*\?>\n/, '')
  49. .replace(/<!doctype.*\>\n/, '')
  50. .replace(/<!DOCTYPE.*\>\n/, '');
  51. }
  52. function html2json(html, bindName) {
  53. //处理字符串
  54. html = removeDOCTYPE(html);
  55. html = wxDiscode.strDiscode(html);
  56. //生成node节点
  57. var bufArray = [];
  58. var results = {
  59. node: bindName,
  60. nodes: [],
  61. images: [],
  62. imageUrls: []
  63. };
  64. HTMLParser(html, {
  65. start: function(tag, attrs, unary) {
  66. //debug(tag, attrs, unary);
  67. // node for this element
  68. var node = {
  69. node: 'element',
  70. tag: tag,
  71. };
  72. if (block[tag]) {
  73. node.tagType = "block";
  74. } else if (inline[tag]) {
  75. node.tagType = "inline";
  76. } else if (closeSelf[tag]) {
  77. node.tagType = "closeSelf";
  78. }
  79. if (attrs.length !== 0) {
  80. node.attr = attrs.reduce(function(pre, attr) {
  81. var name = attr.name;
  82. var value = attr.value;
  83. if (name == 'class') {
  84. // console.dir(value);
  85. // value = value.join("")
  86. node.classStr = value;
  87. }
  88. // has multi attibutes
  89. // make it array of attribute
  90. if (name == 'style') {
  91. // console.dir(value);
  92. // value = value.join("")
  93. node.styleStr = value;
  94. }
  95. if (value.match(/ /)) {
  96. value = value.split(' ');
  97. }
  98. // if attr already exists
  99. // merge it
  100. if (pre[name]) {
  101. if (Array.isArray(pre[name])) {
  102. // already array, push to last
  103. pre[name].push(value);
  104. } else {
  105. // single value, make it array
  106. pre[name] = [pre[name], value];
  107. }
  108. } else {
  109. // not exist, put it
  110. pre[name] = value;
  111. }
  112. return pre;
  113. }, {});
  114. }
  115. //对img添加额外数据
  116. if (node.tag === 'img') {
  117. node.imgIndex = results.images.length;
  118. var imgUrl = node.attr.src;
  119. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  120. node.attr.src = imgUrl;
  121. node.from = bindName;
  122. results.images.push(node);
  123. results.imageUrls.push(imgUrl);
  124. }
  125. // 处理iframe的地址
  126. if (node.tag === 'iframe') {
  127. node.src = node.attr.src;
  128. }
  129. if (unary) {
  130. // if this tag dosen't have end tag
  131. // like <img src="hoge.png"/>
  132. // add to parents
  133. var parent = bufArray[0] || results;
  134. if (parent.nodes === undefined) {
  135. parent.nodes = [];
  136. }
  137. parent.nodes.push(node);
  138. } else {
  139. bufArray.unshift(node);
  140. }
  141. },
  142. end: function(tag) {
  143. //debug(tag);
  144. // merge into parent tag
  145. var node = bufArray.shift();
  146. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  147. if (bufArray.length === 0) {
  148. results.nodes.push(node);
  149. } else {
  150. var parent = bufArray[0];
  151. if (parent.nodes === undefined) {
  152. parent.nodes = [];
  153. }
  154. parent.nodes.push(node);
  155. }
  156. },
  157. chars: function(text) {
  158. //debug(text);
  159. var node = {
  160. node: 'text',
  161. text: text,
  162. textArray: transEmojiStr(text)
  163. };
  164. if (bufArray.length === 0) {
  165. results.nodes.push(node);
  166. } else {
  167. var parent = bufArray[0];
  168. if (parent.nodes === undefined) {
  169. parent.nodes = [];
  170. }
  171. parent.nodes.push(node);
  172. }
  173. },
  174. comment: function(text) {
  175. //debug(text);
  176. var node = {
  177. node: 'comment',
  178. text: text,
  179. };
  180. var parent = bufArray[0];
  181. if (parent.nodes === undefined) {
  182. parent.nodes = [];
  183. }
  184. parent.nodes.push(node);
  185. },
  186. });
  187. return results;
  188. };
  189. function transEmojiStr(str) {
  190. // var eReg = new RegExp("["+__reg+' '+"]");
  191. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  192. var emojiObjs = [];
  193. //如果正则表达式为空
  194. if (__emojisReg.length == 0 || !__emojis) {
  195. var emojiObj = {}
  196. emojiObj.node = "text";
  197. emojiObj.text = str;
  198. array = [emojiObj];
  199. return array;
  200. }
  201. //这个地方需要调整
  202. str = str.replace(/\[([^\[\]]+)\]/g, ':$1:')
  203. var eReg = new RegExp("[:]");
  204. var array = str.split(eReg);
  205. for (var i = 0; i < array.length; i++) {
  206. var ele = array[i];
  207. var emojiObj = {};
  208. if (__emojis[ele]) {
  209. emojiObj.node = "element";
  210. emojiObj.tag = "emoji";
  211. emojiObj.text = __emojis[ele];
  212. emojiObj.baseSrc = __emojisBaseSrc;
  213. } else {
  214. emojiObj.node = "text";
  215. emojiObj.text = ele;
  216. }
  217. emojiObjs.push(emojiObj);
  218. }
  219. return emojiObjs;
  220. }
  221. function emojisInit(reg = '', baseSrc = "/wxParse/emojis/", emojis) {
  222. __emojisReg = reg;
  223. __emojisBaseSrc = baseSrc;
  224. __emojis = emojis;
  225. }
  226. module.exports = {
  227. html2json: html2json,
  228. emojisInit: emojisInit
  229. };