排队支付小程序
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.

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