parse_html.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
  2. var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
  3. var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
  4. var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
  5. // fixed by xxx 将 ins 标签从块级名单中移除
  6. var block = makeMap('a,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,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5
  7. var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,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'); // Elements that you can, intentionally, leave open
  8. // (and which close themselves)
  9. var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
  10. var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)
  11. var special = makeMap('script,style');
  12. function HTMLParser(html, handler) {
  13. var index;
  14. var chars;
  15. var match;
  16. var stack = [];
  17. var last = html;
  18. stack.last = function () {
  19. return this[this.length - 1];
  20. };
  21. while (html) {
  22. chars = true; // Make sure we're not in a script or style element
  23. if (!stack.last() || !special[stack.last()]) {
  24. // Comment
  25. if (html.indexOf('<!--') == 0) {
  26. index = html.indexOf('-->');
  27. if (index >= 0) {
  28. if (handler.comment) {
  29. handler.comment(html.substring(4, index));
  30. }
  31. html = html.substring(index + 3);
  32. chars = false;
  33. } // end tag
  34. } else if (html.indexOf('</') == 0) {
  35. match = html.match(endTag);
  36. if (match) {
  37. html = html.substring(match[0].length);
  38. match[0].replace(endTag, parseEndTag);
  39. chars = false;
  40. } // start tag
  41. } else if (html.indexOf('<') == 0) {
  42. match = html.match(startTag);
  43. if (match) {
  44. html = html.substring(match[0].length);
  45. match[0].replace(startTag, parseStartTag);
  46. chars = false;
  47. }
  48. }
  49. if (chars) {
  50. index = html.indexOf('<');
  51. var text = index < 0 ? html : html.substring(0, index);
  52. html = index < 0 ? '' : html.substring(index);
  53. if (handler.chars) {
  54. handler.chars(text);
  55. }
  56. }
  57. } else {
  58. html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
  59. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
  60. if (handler.chars) {
  61. handler.chars(text);
  62. }
  63. return '';
  64. });
  65. parseEndTag('', stack.last());
  66. }
  67. if (html == last) {
  68. throw 'Parse Error: ' + html;
  69. }
  70. last = html;
  71. } // Clean up any remaining tags
  72. parseEndTag();
  73. function parseStartTag(tag, tagName, rest, unary) {
  74. tagName = tagName.toLowerCase();
  75. if (block[tagName]) {
  76. while (stack.last() && inline[stack.last()]) {
  77. parseEndTag('', stack.last());
  78. }
  79. }
  80. if (closeSelf[tagName] && stack.last() == tagName) {
  81. parseEndTag('', tagName);
  82. }
  83. unary = empty[tagName] || !!unary;
  84. if (!unary) {
  85. stack.push(tagName);
  86. }
  87. if (handler.start) {
  88. var attrs = [];
  89. rest.replace(attr, function (match, name) {
  90. var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
  91. attrs.push({
  92. name: name,
  93. value: value,
  94. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
  95. });
  96. });
  97. if (handler.start) {
  98. handler.start(tagName, attrs, unary);
  99. }
  100. }
  101. }
  102. function parseEndTag(tag, tagName) {
  103. // If no tag name is provided, clean shop
  104. if (!tagName) {
  105. var pos = 0;
  106. } // Find the closest opened tag of the same type
  107. else {
  108. for (var pos = stack.length - 1; pos >= 0; pos--) {
  109. if (stack[pos] == tagName) {
  110. break;
  111. }
  112. }
  113. }
  114. if (pos >= 0) {
  115. // Close all the open elements, up the stack
  116. for (var i = stack.length - 1; i >= pos; i--) {
  117. if (handler.end) {
  118. handler.end(stack[i]);
  119. }
  120. } // Remove the open elements from the stack
  121. stack.length = pos;
  122. }
  123. }
  124. }
  125. function makeMap(str) {
  126. var obj = {};
  127. var items = str.split(',');
  128. for (var i = 0; i < items.length; i++) {
  129. obj[items[i]] = true;
  130. }
  131. return obj;
  132. }
  133. function removeDOCTYPE(html) {
  134. return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
  135. }
  136. function parseAttrs(attrs) {
  137. return attrs.reduce(function (pre, attr) {
  138. var value = attr.value;
  139. var name = attr.name;
  140. if (pre[name]) {
  141. pre[name] = pre[name] + " " + value;
  142. } else {
  143. pre[name] = value;
  144. }
  145. return pre;
  146. }, {});
  147. }
  148. function parseHtml(html) {
  149. html = removeDOCTYPE(html);
  150. var stacks = [];
  151. var results = {
  152. node: 'root',
  153. children: []
  154. };
  155. HTMLParser(html, {
  156. start: function start(tag, attrs, unary) {
  157. var node = {
  158. name: tag
  159. };
  160. if (attrs.length !== 0) {
  161. node.attrs = parseAttrs(attrs);
  162. }
  163. if (unary) {
  164. var parent = stacks[0] || results;
  165. if (!parent.children) {
  166. parent.children = [];
  167. }
  168. parent.children.push(node);
  169. } else {
  170. stacks.unshift(node);
  171. }
  172. },
  173. end: function end(tag) {
  174. var node = stacks.shift();
  175. if (node.name !== tag) console.error('invalid state: mismatch end tag');
  176. if (stacks.length === 0) {
  177. results.children.push(node);
  178. } else {
  179. var parent = stacks[0];
  180. if (!parent.children) {
  181. parent.children = [];
  182. }
  183. parent.children.push(node);
  184. }
  185. },
  186. chars: function chars(text) {
  187. var str = text
  188. var textArray = []
  189. for(let i=0;i<str.length;i++){
  190. let msg = {
  191. name: 'text',
  192. type: 'text',
  193. text: str[i]
  194. }
  195. textArray.push(msg);
  196. }
  197. // var node = {
  198. // name: 'text',
  199. // type: 'text',
  200. // text: text
  201. // };
  202. if (stacks.length === 0) {
  203. for(let i=0;i<textArray.length;i++){
  204. results.children.push(textArray[i]);
  205. }
  206. // results.children.push(node);
  207. } else {
  208. var parent = stacks[0];
  209. if (!parent.children) {
  210. parent.children = [];
  211. }
  212. for(let i=0;i<textArray.length;i++){
  213. parent.children.push(textArray[i]);
  214. }
  215. // parent.children.push(node);
  216. }
  217. },
  218. comment: function comment(text) {
  219. var node = {
  220. node: 'comment',
  221. text: text
  222. };
  223. var parent = stacks[0];
  224. if (!parent.children) {
  225. parent.children = [];
  226. }
  227. parent.children.push(node);
  228. }
  229. });
  230. return results.children;
  231. }
  232. export default parseHtml;