1
0

html2json.js 7.8 KB

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