html2json.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. console.dir(value);
  100. // value = value.join("")
  101. node.classStr = value;
  102. }
  103. // has multi attibutes
  104. // make it array of attribute
  105. if (name == 'style') {
  106. // console.dir(value);
  107. // value = value.join("")
  108. node.styleStr = value;
  109. }
  110. if (value.match(/ /)) {
  111. value = value.split(' ');
  112. }
  113. // if attr already exists
  114. // merge it
  115. if (pre[name]) {
  116. if (Array.isArray(pre[name])) {
  117. // already array, push to last
  118. pre[name].push(value);
  119. } else {
  120. // single value, make it array
  121. pre[name] = [pre[name], value];
  122. }
  123. } else {
  124. // not exist, put it
  125. pre[name] = value;
  126. }
  127. return pre;
  128. }, {});
  129. }
  130. //对img添加额外数据
  131. if (node.tag === 'img') {
  132. node.imgIndex = results.images.length;
  133. var imgUrl = node.attr.src;
  134. if (imgUrl[0] == '') {
  135. imgUrl.splice(0, 1);
  136. }
  137. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  138. node.attr.src = imgUrl;
  139. node.from = bindName;
  140. results.images.push(node);
  141. results.imageUrls.push(imgUrl);
  142. }
  143. // 处理font标签样式属性
  144. if (node.tag === 'font') {
  145. var fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
  146. var styleAttrs = {
  147. 'color': 'color',
  148. 'face': 'font-family',
  149. 'size': 'font-size'
  150. };
  151. if (!node.attr.style) node.attr.style = [];
  152. if (!node.styleStr) node.styleStr = '';
  153. for (var key in styleAttrs) {
  154. if (node.attr[key]) {
  155. var value = key === 'size' ? fontSize[node.attr[key]-1] : node.attr[key];
  156. node.attr.style.push(styleAttrs[key]);
  157. node.attr.style.push(value);
  158. node.styleStr += styleAttrs[key] + ': ' + value + ';';
  159. }
  160. }
  161. }
  162. //临时记录source资源
  163. if(node.tag === 'source'){
  164. results.source = node.attr.src;
  165. }
  166. if (unary) {
  167. // if this tag doesn't have end tag
  168. // like <img src="hoge.png"/>
  169. // add to parents
  170. var parent = bufArray[0] || results;
  171. if (parent.nodes === undefined) {
  172. parent.nodes = [];
  173. }
  174. parent.nodes.push(node);
  175. } else {
  176. bufArray.unshift(node);
  177. }
  178. },
  179. end: function (tag) {
  180. //debug(tag);
  181. // merge into parent tag
  182. var node = bufArray.shift();
  183. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  184. //当有缓存source资源时于于video补上src资源
  185. if(node.tag === 'video' && results.source){
  186. node.attr.src = results.source;
  187. delete results.source;
  188. }
  189. if (bufArray.length === 0) {
  190. results.nodes.push(node);
  191. } else {
  192. var parent = bufArray[0];
  193. if (parent.nodes === undefined) {
  194. parent.nodes = [];
  195. }
  196. parent.nodes.push(node);
  197. }
  198. },
  199. chars: function (text) {
  200. //debug(text);
  201. var node = {
  202. node: 'text',
  203. text: text,
  204. textArray:transEmojiStr(text)
  205. };
  206. if (bufArray.length === 0) {
  207. node.index = index.toString()
  208. index += 1
  209. results.nodes.push(node);
  210. } else {
  211. var parent = bufArray[0];
  212. if (parent.nodes === undefined) {
  213. parent.nodes = [];
  214. }
  215. node.index = parent.index + '.' + parent.nodes.length
  216. parent.nodes.push(node);
  217. }
  218. },
  219. comment: function (text) {
  220. //debug(text);
  221. // var node = {
  222. // node: 'comment',
  223. // text: text,
  224. // };
  225. // var parent = bufArray[0];
  226. // if (parent.nodes === undefined) {
  227. // parent.nodes = [];
  228. // }
  229. // parent.nodes.push(node);
  230. },
  231. });
  232. return results;
  233. };
  234. function transEmojiStr(str){
  235. // var eReg = new RegExp("["+__reg+' '+"]");
  236. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  237. var emojiObjs = [];
  238. //如果正则表达式为空
  239. if(__emojisReg.length == 0 || !__emojis){
  240. var emojiObj = {}
  241. emojiObj.node = "text";
  242. emojiObj.text = str;
  243. array = [emojiObj];
  244. return array;
  245. }
  246. //这个地方需要调整
  247. str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  248. var eReg = new RegExp("[:]");
  249. var array = str.split(eReg);
  250. for(var i = 0; i < array.length; i++){
  251. var ele = array[i];
  252. var emojiObj = {};
  253. if(__emojis[ele]){
  254. emojiObj.node = "element";
  255. emojiObj.tag = "emoji";
  256. emojiObj.text = __emojis[ele];
  257. emojiObj.baseSrc= __emojisBaseSrc;
  258. }else{
  259. emojiObj.node = "text";
  260. emojiObj.text = ele;
  261. }
  262. emojiObjs.push(emojiObj);
  263. }
  264. return emojiObjs;
  265. }
  266. function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
  267. __emojisReg = reg;
  268. __emojisBaseSrc=baseSrc;
  269. __emojis=emojis;
  270. }
  271. module.exports = {
  272. html2json: html2json,
  273. emojisInit:emojisInit
  274. };