C端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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