html2json.js 9.8 KB

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