html2json.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. import wxDiscode from './wxDiscode';
  15. import HTMLParser from './htmlparser';
  16. function makeMap(str) {
  17. const obj = {};
  18. const items = str.split(',');
  19. for (let i = 0; i < items.length; i += 1) obj[items[i]] = true;
  20. return obj;
  21. }
  22. // Block Elements - HTML 5
  23. const block = makeMap('br,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. // #ifdef APP
  25. const inline = makeMap('a,abbr,acronym,applet,b,basefont,bdo,big,button,cite,del,dfn,em,font,i,iframe,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var');
  26. // #endif
  27. // #ifndef APP
  28. const inline = makeMap('a,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');
  29. // #endif
  30. // Elements that you can, intentionally, leave open
  31. // (and which close themselves)
  32. const closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr');
  33. function removeDOCTYPE(html) {
  34. const isDocument = /<body.*>([^]*)<\/body>/.test(html);
  35. return isDocument ? RegExp.$1 : html;
  36. }
  37. function trimHtml(html) {
  38. return html
  39. .replace(/<!--.*?-->/gi, '')
  40. .replace(/\/\*.*?\*\//gi, '')
  41. .replace(/[ ]+</gi, '<')
  42. .replace(/<script[^]*<\/script>/gi, '')
  43. .replace(/<style[^]*<\/style>/gi, '');
  44. }
  45. function getScreenInfo() {
  46. const screen = {};
  47. wx.getSystemInfo({
  48. success: (res) => {
  49. screen.width = res.windowWidth;
  50. screen.height = res.windowHeight;
  51. },
  52. });
  53. return screen;
  54. }
  55. function html2json(html, customHandler, imageProp, host) {
  56. // 处理字符串
  57. html = removeDOCTYPE(html);
  58. html = trimHtml(html);
  59. html = wxDiscode.strDiscode(html);
  60. // 生成node节点
  61. const bufArray = [];
  62. const results = {
  63. nodes: [],
  64. imageUrls: [],
  65. };
  66. const screen = getScreenInfo();
  67. function Node(tag) {
  68. this.node = 'element';
  69. this.tag = tag;
  70. this.$screen = screen;
  71. }
  72. HTMLParser(html, {
  73. start(tag, attrs, unary) {
  74. // node for this element
  75. const node = new Node(tag);
  76. if (bufArray.length !== 0) {
  77. const parent = bufArray[0];
  78. if (parent.nodes === undefined) {
  79. parent.nodes = [];
  80. }
  81. }
  82. if (block[tag]) {
  83. node.tagType = 'block';
  84. } else if (inline[tag]) {
  85. node.tagType = 'inline';
  86. } else if (closeSelf[tag]) {
  87. node.tagType = 'closeSelf';
  88. }
  89. node.attr = attrs.reduce((pre, attr) => {
  90. const { name } = attr;
  91. let { value } = attr;
  92. if (name === 'class') {
  93. node.classStr = value;
  94. }
  95. // has multi attibutes
  96. // make it array of attribute
  97. if (name === 'style') {
  98. node.styleStr = value;
  99. }
  100. if (value.match(/ /)) {
  101. value = value.split(' ');
  102. }
  103. // if attr already exists
  104. // merge it
  105. if (pre[name]) {
  106. if (Array.isArray(pre[name])) {
  107. // already array, push to last
  108. pre[name].push(value);
  109. } else {
  110. // single value, make it array
  111. pre[name] = [pre[name], value];
  112. }
  113. } else {
  114. // not exist, put it
  115. pre[name] = value;
  116. }
  117. return pre;
  118. }, {});
  119. // 优化样式相关属性
  120. if (node.classStr) {
  121. node.classStr += ` ${node.tag}`;
  122. } else {
  123. node.classStr = node.tag;
  124. }
  125. if (node.tagType === 'inline') {
  126. node.classStr += ' inline';
  127. }
  128. // 对img添加额外数据
  129. if (node.tag === 'img') {
  130. let imgUrl = node.attr.src;
  131. imgUrl = wxDiscode.urlToHttpUrl(imgUrl, imageProp.domain);
  132. Object.assign(node.attr, imageProp, {
  133. src: imgUrl || '',
  134. });
  135. if (imgUrl) {
  136. results.imageUrls.push(imgUrl);
  137. }
  138. }
  139. // 处理a标签属性
  140. if (node.tag === 'a') {
  141. node.attr.href = node.attr.href || '';
  142. }
  143. // 处理font标签样式属性
  144. if (node.tag === 'font') {
  145. const fontSize = [
  146. 'x-small',
  147. 'small',
  148. 'medium',
  149. 'large',
  150. 'x-large',
  151. 'xx-large',
  152. '-webkit-xxx-large',
  153. ];
  154. const styleAttrs = {
  155. color: 'color',
  156. face: 'font-family',
  157. size: 'font-size',
  158. };
  159. if (!node.styleStr) node.styleStr = '';
  160. Object.keys(styleAttrs).forEach((key) => {
  161. if (node.attr[key]) {
  162. const value = key === 'size' ? fontSize[node.attr[key] - 1] : node.attr[key];
  163. node.styleStr += `${styleAttrs[key]}: ${value};`;
  164. }
  165. });
  166. }
  167. // 临时记录source资源
  168. if (node.tag === 'source') {
  169. results.source = node.attr.src;
  170. }
  171. if (customHandler.start) {
  172. customHandler.start(node, results);
  173. }
  174. if (unary) {
  175. // if this tag doesn't have end tag
  176. // like <img src="hoge.png"/>
  177. // add to parents
  178. const parent = bufArray[0] || results;
  179. if (parent.nodes === undefined) {
  180. parent.nodes = [];
  181. }
  182. parent.nodes.push(node);
  183. } else {
  184. bufArray.unshift(node);
  185. }
  186. },
  187. end(tag) {
  188. // merge into parent tag
  189. const node = bufArray.shift();
  190. if (node.tag !== tag) {
  191. console.error('invalid state: mismatch end tag');
  192. }
  193. // 当有缓存source资源时于于video补上src资源
  194. if (node.tag === 'video' && results.source) {
  195. node.attr.src = results.source;
  196. delete results.source;
  197. }
  198. if (customHandler.end) {
  199. customHandler.end(node, results);
  200. }
  201. if (bufArray.length === 0) {
  202. results.nodes.push(node);
  203. } else {
  204. const parent = bufArray[0];
  205. if (!parent.nodes) {
  206. parent.nodes = [];
  207. }
  208. parent.nodes.push(node);
  209. }
  210. },
  211. chars(text) {
  212. if (!text.trim()) return;
  213. const node = {
  214. node: 'text',
  215. text,
  216. };
  217. if (customHandler.chars) {
  218. customHandler.chars(node, results);
  219. }
  220. if (bufArray.length === 0) {
  221. results.nodes.push(node);
  222. } else {
  223. const parent = bufArray[0];
  224. if (parent.nodes === undefined) {
  225. parent.nodes = [];
  226. }
  227. parent.nodes.push(node);
  228. }
  229. },
  230. });
  231. return results;
  232. }
  233. export default html2json;