Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

262 строки
6.7 KiB

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