html2json.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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(
  24. "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",
  25. );
  26. // Inline Elements - HTML 5
  27. const inline = makeMap(
  28. "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. );
  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 =
  163. key === "size" ? fontSize[node.attr[key] - 1] : node.attr[key];
  164. node.styleStr += `${styleAttrs[key]}: ${value};`;
  165. }
  166. });
  167. }
  168. // 临时记录source资源
  169. if (node.tag === "source") {
  170. results.source = node.attr.src;
  171. }
  172. if (customHandler.start) {
  173. customHandler.start(node, results);
  174. }
  175. if (unary) {
  176. // if this tag doesn't have end tag
  177. // like <img src="hoge.png"/>
  178. // add to parents
  179. const parent = bufArray[0] || results;
  180. if (parent.nodes === undefined) {
  181. parent.nodes = [];
  182. }
  183. parent.nodes.push(node);
  184. } else {
  185. bufArray.unshift(node);
  186. }
  187. },
  188. end(tag) {
  189. // merge into parent tag
  190. const node = bufArray.shift();
  191. if (node.tag !== tag) {
  192. console.error("invalid state: mismatch end tag");
  193. }
  194. // 当有缓存source资源时于于video补上src资源
  195. if (node.tag === "video" && results.source) {
  196. node.attr.src = results.source;
  197. delete results.source;
  198. }
  199. if (customHandler.end) {
  200. customHandler.end(node, results);
  201. }
  202. if (bufArray.length === 0) {
  203. results.nodes.push(node);
  204. } else {
  205. const parent = bufArray[0];
  206. if (!parent.nodes) {
  207. parent.nodes = [];
  208. }
  209. parent.nodes.push(node);
  210. }
  211. },
  212. chars(text) {
  213. if (!text.trim()) return;
  214. const node = {
  215. node: "text",
  216. text,
  217. };
  218. if (customHandler.chars) {
  219. customHandler.chars(node, results);
  220. }
  221. if (bufArray.length === 0) {
  222. results.nodes.push(node);
  223. } else {
  224. const parent = bufArray[0];
  225. if (parent.nodes === undefined) {
  226. parent.nodes = [];
  227. }
  228. parent.nodes.push(node);
  229. }
  230. },
  231. });
  232. return results;
  233. }
  234. export default html2json;