html2json.js 7.6 KB

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