html2json.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. // console.dir(value);
  78. // value = value.join("")
  79. node.classStr = value;
  80. }
  81. // has multi attibutes
  82. // make it array of attribute
  83. if (name == 'style') {
  84. // console.dir(value);
  85. // value = value.join("")
  86. node.styleStr = value;
  87. }
  88. if (value.match(/ /)) {
  89. value = value.split(' ');
  90. }
  91. // if attr already exists
  92. // merge it
  93. if (pre[name]) {
  94. if (Array.isArray(pre[name])) {
  95. // already array, push to last
  96. pre[name].push(value);
  97. } else {
  98. // single value, make it array
  99. pre[name] = [pre[name], value];
  100. }
  101. } else {
  102. // not exist, put it
  103. pre[name] = value;
  104. }
  105. return pre;
  106. }, {});
  107. }
  108. //对img添加额外数据
  109. if (node.tag === 'img') {
  110. node.imgIndex = results.images.length;
  111. var imgUrl = node.attr.src;
  112. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  113. node.attr.src = imgUrl;
  114. node.from = bindName;
  115. results.images.push(node);
  116. results.imageUrls.push(imgUrl);
  117. }
  118. if (unary) {
  119. // if this tag dosen't have end tag
  120. // like <img src="hoge.png"/>
  121. // add to parents
  122. var parent = bufArray[0] || results;
  123. if (parent.nodes === undefined) {
  124. parent.nodes = [];
  125. }
  126. parent.nodes.push(node);
  127. } else {
  128. bufArray.unshift(node);
  129. }
  130. },
  131. end: function (tag) {
  132. //debug(tag);
  133. // merge into parent tag
  134. var node = bufArray.shift();
  135. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  136. if (bufArray.length === 0) {
  137. results.nodes.push(node);
  138. } else {
  139. var parent = bufArray[0];
  140. if (parent.nodes === undefined) {
  141. parent.nodes = [];
  142. }
  143. parent.nodes.push(node);
  144. }
  145. },
  146. chars: function (text) {
  147. //debug(text);
  148. var node = {
  149. node: 'text',
  150. text: text,
  151. textArray:transEmojiStr(text)
  152. };
  153. if (bufArray.length === 0) {
  154. results.nodes.push(node);
  155. } else {
  156. var parent = bufArray[0];
  157. if (parent.nodes === undefined) {
  158. parent.nodes = [];
  159. }
  160. parent.nodes.push(node);
  161. }
  162. },
  163. comment: function (text) {
  164. //debug(text);
  165. var node = {
  166. node: 'comment',
  167. text: text,
  168. };
  169. var parent = bufArray[0];
  170. if (parent.nodes === undefined) {
  171. parent.nodes = [];
  172. }
  173. parent.nodes.push(node);
  174. },
  175. });
  176. return results;
  177. };
  178. function transEmojiStr(str){
  179. // var eReg = new RegExp("["+__reg+' '+"]");
  180. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  181. var emojiObjs = [];
  182. //如果正则表达式为空
  183. if(__emojisReg.length == 0 || !__emojis){
  184. var emojiObj = {}
  185. emojiObj.node = "text";
  186. emojiObj.text = str;
  187. array = [emojiObj];
  188. return array;
  189. }
  190. //这个地方需要调整
  191. str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  192. var eReg = new RegExp("[:]");
  193. var array = str.split(eReg);
  194. for(var i = 0; i < array.length; i++){
  195. var ele = array[i];
  196. var emojiObj = {};
  197. if(__emojis[ele]){
  198. emojiObj.node = "element";
  199. emojiObj.tag = "emoji";
  200. emojiObj.text = __emojis[ele];
  201. emojiObj.baseSrc= __emojisBaseSrc;
  202. }else{
  203. emojiObj.node = "text";
  204. emojiObj.text = ele;
  205. }
  206. emojiObjs.push(emojiObj);
  207. }
  208. return emojiObjs;
  209. }
  210. function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
  211. __emojisReg = reg;
  212. __emojisBaseSrc=baseSrc;
  213. __emojis=emojis;
  214. }
  215. module.exports = {
  216. html2json: html2json,
  217. emojisInit:emojisInit
  218. };