html2json.js 7.8 KB

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