html2json.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. var __placeImgeUrlHttps = "https";
  2. var __emojisReg = '';
  3. var __emojisBaseSrc = '';
  4. var __emojis = {};
  5. var aDiscode = require('./aDiscode.js');
  6. var HTMLParser = require('./htmlparser.js');
  7. // Empty Elements - HTML 5
  8. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  9. // Block Elements - HTML 5
  10. 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");
  11. // Inline Elements - HTML 5
  12. 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");
  13. // Elements that you can, intentionally, leave open
  14. // (and which close themselves)
  15. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  16. // Attributes that have their values filled in disabled="disabled"
  17. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  18. // Special Elements (can contain anything)
  19. var special = makeMap("wxxxcode-style,script,style,view,scroll-view,block");
  20. function makeMap(str) {
  21. var obj = {}, items = str.split(",");
  22. for (var i = 0; i < items.length; i++)
  23. obj[items[i]] = true;
  24. return obj;
  25. }
  26. function q(v) {
  27. return '"' + v + '"';
  28. }
  29. function removeDOCTYPE(html) {
  30. return html
  31. .replace(/<\?xml.*\?>\n/, '')
  32. .replace(/<.*!doctype.*\>\n/, '')
  33. .replace(/<.*!DOCTYPE.*\>\n/, '');
  34. }
  35. function trimHtml(html) {
  36. return html
  37. .replace(/\r?\n+/g, '')
  38. .replace(/<!--.*?-->/ig, '')
  39. .replace(/\/\*.*?\*\//ig, '')
  40. .replace(/[ ]+</ig, '<')
  41. }
  42. function html2json(html, bindName) {
  43. //处理字符串
  44. html = removeDOCTYPE(html);
  45. html = trimHtml(html);
  46. html = aDiscode.strDiscode(html);
  47. // console.log(html)
  48. //生成node节点
  49. var bufArray = [];
  50. var results = {
  51. node: bindName,
  52. nodes: [],
  53. images:[],
  54. imageUrls:[]
  55. };
  56. var index = 0;
  57. HTMLParser(html, {
  58. start: function (tag, attrs, unary) {
  59. //debug(tag, attrs, unary);
  60. // node for this element
  61. var node = {
  62. node: 'element',
  63. tag: tag,
  64. };
  65. if (bufArray.length === 0) {
  66. node.index = index.toString()
  67. index += 1
  68. } else {
  69. var parent = bufArray[0];
  70. if (parent.nodes === undefined) {
  71. parent.nodes = [];
  72. }
  73. node.index = parent.index + '.' + parent.nodes.length
  74. }
  75. if (block[tag]) {
  76. node.tagType = "block";
  77. } else if (inline[tag]) {
  78. node.tagType = "inline";
  79. } else if (closeSelf[tag]) {
  80. node.tagType = "closeSelf";
  81. }
  82. if (attrs.length !== 0) {
  83. node.attr = attrs.reduce(function (pre, attr) {
  84. var name = attr.name;
  85. var value = attr.value;
  86. if (name == 'class') {
  87. // console.dir(value);
  88. // value = value.join("")
  89. node.classStr = value;
  90. }
  91. // has multi attibutes
  92. // make it array of attribute
  93. if (name == 'style') {
  94. // console.dir(value);
  95. // value = value.join("")
  96. node.styleStr = value;
  97. }
  98. if (value.match(/ /)) {
  99. value = value.split(' ');
  100. }
  101. // if attr already exists
  102. // merge it
  103. if (pre[name]) {
  104. if (Array.isArray(pre[name])) {
  105. // already array, push to last
  106. pre[name].push(value);
  107. } else {
  108. // single value, make it array
  109. pre[name] = [pre[name], value];
  110. }
  111. } else {
  112. // not exist, put it
  113. pre[name] = value;
  114. }
  115. return pre;
  116. }, {});
  117. }
  118. //对img添加额外数据
  119. if (node.tag === 'img') {
  120. node.imgIndex = results.images.length;
  121. var imgUrl = node.attr.src;
  122. if (imgUrl[0] == '') {
  123. imgUrl.splice(0, 1);
  124. }
  125. imgUrl = aDiscode.urlToHttpUrl(imgUrl, __placeImgeUrlHttps);
  126. node.attr.src = imgUrl;
  127. node.from = bindName;
  128. results.images.push(node);
  129. results.imageUrls.push(imgUrl);
  130. }
  131. // 处理font标签样式属性
  132. if (node.tag === 'font') {
  133. var fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
  134. var styleAttrs = {
  135. 'color': 'color',
  136. 'face': 'font-family',
  137. 'size': 'font-size'
  138. };
  139. if (!node.attr.style) node.attr.style = [];
  140. if (!node.styleStr) node.styleStr = '';
  141. for (var key in styleAttrs) {
  142. if (node.attr[key]) {
  143. var value = key === 'size' ? fontSize[node.attr[key]-1] : node.attr[key];
  144. node.attr.style.push(styleAttrs[key]);
  145. node.attr.style.push(value);
  146. node.styleStr += styleAttrs[key] + ': ' + value + ';';
  147. }
  148. }
  149. }
  150. //临时记录source资源
  151. if(node.tag === 'source'){
  152. results.source = node.attr.src;
  153. }
  154. if (unary) {
  155. // if this tag doesn't have end tag
  156. // like <img src="hoge.png"/>
  157. // add to parents
  158. var parent = bufArray[0] || results;
  159. if (parent.nodes === undefined) {
  160. parent.nodes = [];
  161. }
  162. parent.nodes.push(node);
  163. } else {
  164. bufArray.unshift(node);
  165. }
  166. },
  167. end: function (tag) {
  168. //debug(tag);
  169. // merge into parent tag
  170. var node = bufArray.shift();
  171. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  172. //当有缓存source资源时于于video补上src资源
  173. if(node.tag === 'video' && results.source){
  174. node.attr.src = results.source;
  175. delete results.source;
  176. }
  177. if (bufArray.length === 0) {
  178. results.nodes.push(node);
  179. } else {
  180. var parent = bufArray[0];
  181. if (parent.nodes === undefined) {
  182. parent.nodes = [];
  183. }
  184. parent.nodes.push(node);
  185. }
  186. },
  187. chars: function (text) {
  188. //debug(text);
  189. var node = {
  190. node: 'text',
  191. text: text,
  192. textArray:transEmojiStr(text)
  193. };
  194. if (bufArray.length === 0) {
  195. node.index = index.toString()
  196. index += 1
  197. results.nodes.push(node);
  198. } else {
  199. var parent = bufArray[0];
  200. if (parent.nodes === undefined) {
  201. parent.nodes = [];
  202. }
  203. node.index = parent.index + '.' + parent.nodes.length
  204. parent.nodes.push(node);
  205. }
  206. },
  207. comment: function (text) {
  208. //debug(text);
  209. // var node = {
  210. // node: 'comment',
  211. // text: text,
  212. // };
  213. // var parent = bufArray[0];
  214. // if (parent.nodes === undefined) {
  215. // parent.nodes = [];
  216. // }
  217. // parent.nodes.push(node);
  218. },
  219. });
  220. return results;
  221. };
  222. function transEmojiStr(str){
  223. // var eReg = new RegExp("["+__reg+' '+"]");
  224. // str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  225. var emojiObjs = [];
  226. //如果正则表达式为空
  227. if(__emojisReg.length == 0 || !__emojis){
  228. var emojiObj = {}
  229. emojiObj.node = "text";
  230. emojiObj.text = str;
  231. array = [emojiObj];
  232. return array;
  233. }
  234. //这个地方需要调整
  235. str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  236. var eReg = new RegExp("[:]");
  237. var array = str.split(eReg);
  238. for(var i = 0; i < array.length; i++){
  239. var ele = array[i];
  240. var emojiObj = {};
  241. if(__emojis[ele]){
  242. emojiObj.node = "element";
  243. emojiObj.tag = "emoji";
  244. emojiObj.text = __emojis[ele];
  245. emojiObj.baseSrc= __emojisBaseSrc;
  246. }else{
  247. emojiObj.node = "text";
  248. emojiObj.text = ele;
  249. }
  250. emojiObjs.push(emojiObj);
  251. }
  252. return emojiObjs;
  253. }
  254. function emojisInit(reg='',baseSrc="/aParse/emojis/",emojis){
  255. __emojisReg = reg;
  256. __emojisBaseSrc=baseSrc;
  257. __emojis=emojis;
  258. }
  259. module.exports = {
  260. html2json: html2json,
  261. emojisInit:emojisInit
  262. };