MpHtmlParser.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /* eslint-disable */
  2. /**
  3. * html 解析器
  4. * @tutorial https://github.com/jin-yufeng/Parser
  5. * @version 20200615
  6. * @author JinYufeng
  7. * @listens MIT
  8. */
  9. const cfg = require('./config.js'),
  10. blankChar = cfg.blankChar,
  11. CssHandler = require('./CssHandler.js'),
  12. windowWidth = uni.getSystemInfoSync().windowWidth;
  13. var emoji;
  14. function MpHtmlParser(data, options = {}) {
  15. this.attrs = {};
  16. this.CssHandler = new CssHandler(options.tagStyle, windowWidth);
  17. this.data = data;
  18. this.domain = options.domain;
  19. this.DOM = [];
  20. this.i = this.start = this.audioNum = this.imgNum = this.videoNum = 0;
  21. options.prot = (this.domain || '').includes('://') ? this.domain.split('://')[0] : 'http';
  22. this.options = options;
  23. this.state = this.Text;
  24. this.STACK = [];
  25. // 工具函数
  26. this.bubble = () => {
  27. for (var i = this.STACK.length, item; item = this.STACK[--i];) {
  28. if (cfg.richOnlyTags[item.name]) {
  29. if (item.name == 'table' && !Object.hasOwnProperty.call(item, 'c')) item.c = 1;
  30. return false;
  31. }
  32. item.c = 1;
  33. }
  34. return true;
  35. };
  36. this.decode = (val, amp) => {
  37. var i = -1,
  38. j, en;
  39. while (1) {
  40. if ((i = val.indexOf('&', i + 1)) == -1) break;
  41. if ((j = val.indexOf(';', i + 2)) == -1) break;
  42. if (val[i + 1] == '#') {
  43. en = parseInt((val[i + 2] == 'x' ? '0' : '') + val.substring(i + 2, j));
  44. if (!isNaN(en)) val = val.substr(0, i) + String.fromCharCode(en) + val.substr(j + 1);
  45. } else {
  46. en = val.substring(i + 1, j);
  47. if (cfg.entities[en] || en == amp)
  48. val = val.substr(0, i) + (cfg.entities[en] || '&') + val.substr(j + 1);
  49. }
  50. }
  51. return val;
  52. };
  53. this.getUrl = url => {
  54. if (url[0] == '/') {
  55. if (url[1] == '/') url = this.options.prot + ':' + url;
  56. else if (this.domain) url = this.domain + url;
  57. } else if (this.domain && url.indexOf('data:') != 0 && !url.includes('://'))
  58. url = this.domain + '/' + url;
  59. return url;
  60. };
  61. this.isClose = () => this.data[this.i] == '>' || (this.data[this.i] == '/' && this.data[this.i + 1] == '>');
  62. this.section = () => this.data.substring(this.start, this.i);
  63. this.parent = () => this.STACK[this.STACK.length - 1];
  64. this.siblings = () => this.STACK.length ? this.parent().children : this.DOM;
  65. }
  66. MpHtmlParser.prototype.parse = function() {
  67. if (emoji) this.data = emoji.parseEmoji(this.data);
  68. for (var c; c = this.data[this.i]; this.i++)
  69. this.state(c);
  70. if (this.state == this.Text) this.setText();
  71. while (this.STACK.length) this.popNode(this.STACK.pop());
  72. return this.DOM;
  73. };
  74. // 设置属性
  75. MpHtmlParser.prototype.setAttr = function() {
  76. var name = this.attrName.toLowerCase(),
  77. val = this.attrVal;
  78. if (cfg.boolAttrs[name]) this.attrs[name] = 'T';
  79. else if (val) {
  80. if (name == 'src' || (name == 'data-src' && !this.attrs.src)) this.attrs.src = this.getUrl(this.decode(val, 'amp'));
  81. else if (name == 'href' || name == 'style') this.attrs[name] = this.decode(val, 'amp');
  82. else if (name.substr(0, 5) != 'data-') this.attrs[name] = val;
  83. }
  84. this.attrVal = '';
  85. while (blankChar[this.data[this.i]]) this.i++;
  86. if (this.isClose()) this.setNode();
  87. else {
  88. this.start = this.i;
  89. this.state = this.AttrName;
  90. }
  91. };
  92. // 设置文本节点
  93. MpHtmlParser.prototype.setText = function() {
  94. var back, text = this.section();
  95. if (!text) return;
  96. text = (cfg.onText && cfg.onText(text, () => back = true)) || text;
  97. if (back) {
  98. this.data = this.data.substr(0, this.start) + text + this.data.substr(this.i);
  99. let j = this.start + text.length;
  100. for (this.i = this.start; this.i < j; this.i++) this.state(this.data[this.i]);
  101. return;
  102. }
  103. if (!this.pre) {
  104. // 合并空白符
  105. var tmp = [];
  106. for (let i = text.length, c; c = text[--i];)
  107. if (!blankChar[c] || (!blankChar[tmp[0]] && (c = ' '))) tmp.unshift(c);
  108. text = tmp.join('');
  109. }
  110. this.siblings().push({
  111. type: 'text',
  112. text: this.decode(text)
  113. });
  114. };
  115. // 设置元素节点
  116. MpHtmlParser.prototype.setNode = function() {
  117. var node = {
  118. name: this.tagName.toLowerCase(),
  119. attrs: this.attrs
  120. },
  121. close = cfg.selfClosingTags[node.name];
  122. this.attrs = {};
  123. if (!cfg.ignoreTags[node.name]) {
  124. // 处理属性
  125. var attrs = node.attrs,
  126. style = this.CssHandler.match(node.name, attrs, node) + (attrs.style || ''),
  127. styleObj = {};
  128. if (attrs.id) {
  129. if (this.options.compress & 1) attrs.id = void 0;
  130. else if (this.options.useAnchor) this.bubble();
  131. }
  132. if ((this.options.compress & 2) && attrs.class) attrs.class = void 0;
  133. switch (node.name) {
  134. case 'a':
  135. case 'ad': // #ifdef APP-PLUS
  136. case 'iframe':
  137. // #endif
  138. this.bubble();
  139. break;
  140. case 'font':
  141. if (attrs.color) {
  142. styleObj['color'] = attrs.color;
  143. attrs.color = void 0;
  144. }
  145. if (attrs.face) {
  146. styleObj['font-family'] = attrs.face;
  147. attrs.face = void 0;
  148. }
  149. if (attrs.size) {
  150. var size = parseInt(attrs.size);
  151. if (size < 1) size = 1;
  152. else if (size > 7) size = 7;
  153. var map = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'];
  154. styleObj['font-size'] = map[size - 1];
  155. attrs.size = void 0;
  156. }
  157. break;
  158. case 'embed':
  159. // #ifndef APP-PLUS
  160. var src = node.attrs.src || '',
  161. type = node.attrs.type || '';
  162. if (type.includes('video') || src.includes('.mp4') || src.includes('.3gp') || src.includes('.m3u8'))
  163. node.name = 'video';
  164. else if (type.includes('audio') || src.includes('.m4a') || src.includes('.wav') || src.includes('.mp3') || src.includes(
  165. '.aac'))
  166. node.name = 'audio';
  167. else break;
  168. if (node.attrs.autostart)
  169. node.attrs.autoplay = 'T';
  170. node.attrs.controls = 'T';
  171. // #endif
  172. // #ifdef APP-PLUS
  173. this.bubble();
  174. break;
  175. // #endif
  176. case 'video':
  177. case 'audio':
  178. if (!attrs.id) attrs.id = node.name + (++this[`${node.name}Num`]);
  179. else this[`${node.name}Num`]++;
  180. if (node.name == 'video') {
  181. if (this.videoNum > 3)
  182. node.lazyLoad = 1;
  183. if (attrs.width) {
  184. styleObj.width = parseFloat(attrs.width) + (attrs.width.includes('%') ? '%' : 'px');
  185. attrs.width = void 0;
  186. }
  187. if (attrs.height) {
  188. styleObj.height = parseFloat(attrs.height) + (attrs.height.includes('%') ? '%' : 'px');
  189. attrs.height = void 0;
  190. }
  191. }
  192. attrs.source = [];
  193. if (attrs.src) {
  194. attrs.source.push(attrs.src);
  195. attrs.src = void 0;
  196. }
  197. this.bubble();
  198. break;
  199. case 'td':
  200. case 'th':
  201. if (attrs.colspan || attrs.rowspan)
  202. for (var k = this.STACK.length, item; item = this.STACK[--k];)
  203. if (item.name == 'table') {
  204. item.c = void 0;
  205. break;
  206. }
  207. }
  208. if (attrs.align) {
  209. styleObj['text-align'] = attrs.align;
  210. attrs.align = void 0;
  211. }
  212. // 压缩 style
  213. var styles = style.split(';');
  214. style = '';
  215. for (var i = 0, len = styles.length; i < len; i++) {
  216. var info = styles[i].split(':');
  217. if (info.length < 2) continue;
  218. let key = info[0].trim().toLowerCase(),
  219. value = info.slice(1).join(':').trim();
  220. if (value.includes('-webkit') || value.includes('-moz') || value.includes('-ms') || value.includes('-o') || value.includes(
  221. 'safe'))
  222. style += `;${key}:${value}`;
  223. else if (!styleObj[key] || value.includes('import') || !styleObj[key].includes('import'))
  224. styleObj[key] = value;
  225. }
  226. if (node.name == 'img') {
  227. if (attrs.src && !attrs.ignore) {
  228. if (this.bubble())
  229. attrs.i = (this.imgNum++).toString();
  230. else attrs.ignore = 'T';
  231. }
  232. if (attrs.ignore) {
  233. style += ';-webkit-touch-callout:none';
  234. styleObj['max-width'] = '100%';
  235. }
  236. var width;
  237. if (styleObj.width) width = styleObj.width;
  238. else if (attrs.width) width = attrs.width.includes('%') ? attrs.width : attrs.width + 'px';
  239. if (width) {
  240. styleObj.width = width;
  241. attrs.width = '100%';
  242. if (parseInt(width) > windowWidth) {
  243. styleObj.height = '';
  244. if (attrs.height) attrs.height = void 0;
  245. }
  246. }
  247. if (styleObj.height) {
  248. attrs.height = styleObj.height;
  249. styleObj.height = '';
  250. } else if (attrs.height && !attrs.height.includes('%'))
  251. attrs.height += 'px';
  252. }
  253. for (var key in styleObj) {
  254. var value = styleObj[key];
  255. if (!value) continue;
  256. if (key.includes('flex') || key == 'order' || key == 'self-align') node.c = 1;
  257. // 填充链接
  258. if (value.includes('url')) {
  259. var j = value.indexOf('(');
  260. if (j++ != -1) {
  261. while (value[j] == '"' || value[j] == '\'' || blankChar[value[j]]) j++;
  262. value = value.substr(0, j) + this.getUrl(value.substr(j));
  263. }
  264. }
  265. // 转换 rpx
  266. else if (value.includes('rpx'))
  267. value = value.replace(/[0-9.]+\s*rpx/g, $ => parseFloat($) * windowWidth / 750 + 'px');
  268. else if (key == 'white-space' && value.includes('pre'))
  269. this.pre = node.pre = true;
  270. style += `;${key}:${value}`;
  271. }
  272. style = style.substr(1);
  273. if (style) attrs.style = style;
  274. if (!close) {
  275. node.children = [];
  276. if (node.name == 'pre' && cfg.highlight) {
  277. this.remove(node);
  278. this.pre = node.pre = true;
  279. }
  280. this.siblings().push(node);
  281. this.STACK.push(node);
  282. } else if (!cfg.filter || cfg.filter(node, this) != false)
  283. this.siblings().push(node);
  284. } else {
  285. if (!close) this.remove(node);
  286. else if (node.name == 'source') {
  287. var parent = this.parent();
  288. if (parent && (parent.name == 'video' || parent.name == 'audio') && node.attrs.src)
  289. parent.attrs.source.push(node.attrs.src);
  290. } else if (node.name == 'base' && !this.domain) this.domain = node.attrs.href;
  291. }
  292. if (this.data[this.i] == '/') this.i++;
  293. this.start = this.i + 1;
  294. this.state = this.Text;
  295. };
  296. // 移除标签
  297. MpHtmlParser.prototype.remove = function(node) {
  298. var name = node.name,
  299. j = this.i;
  300. // 处理 svg
  301. var handleSvg = () => {
  302. var src = this.data.substring(j, this.i + 1);
  303. if (!node.attrs.xmlns) src = ' xmlns="http://www.w3.org/2000/svg"' + src;
  304. var i = j;
  305. while (this.data[j] != '<') j--;
  306. src = this.data.substring(j, i) + src;
  307. var parent = this.parent();
  308. if (node.attrs.width == '100%' && parent && (parent.attrs.style || '').includes('inline'))
  309. parent.attrs.style = 'width:300px;max-width:100%;' + parent.attrs.style;
  310. this.siblings().push({
  311. name: 'img',
  312. attrs: {
  313. src: 'data:image/svg+xml;utf8,' + src.replace(/#/g, '%23'),
  314. style: (/vertical[^;]+/.exec(node.attrs.style) || []).shift(),
  315. ignore: 'T'
  316. }
  317. });
  318. };
  319. if (node.name == 'svg' && this.data[j] == '/') return handleSvg(this.i++);
  320. while (1) {
  321. if ((this.i = this.data.indexOf('</', this.i + 1)) == -1) {
  322. if (name == 'pre' || name == 'svg') this.i = j;
  323. else this.i = this.data.length;
  324. return;
  325. }
  326. this.start = (this.i += 2);
  327. while (!blankChar[this.data[this.i]] && !this.isClose()) this.i++;
  328. if (this.section().toLowerCase() == name) {
  329. // 代码块高亮
  330. if (name == 'pre') {
  331. this.data = this.data.substr(0, j + 1) + cfg.highlight(this.data.substring(j + 1, this.i - 5), node.attrs) + this.data
  332. .substr(this.i - 5);
  333. return this.i = j;
  334. } else if (name == 'style')
  335. this.CssHandler.getStyle(this.data.substring(j + 1, this.i - 7));
  336. else if (name == 'title')
  337. this.DOM.title = this.data.substring(j + 1, this.i - 7);
  338. if ((this.i = this.data.indexOf('>', this.i)) == -1) this.i = this.data.length;
  339. if (name == 'svg') handleSvg();
  340. return;
  341. }
  342. }
  343. };
  344. // 节点出栈处理
  345. MpHtmlParser.prototype.popNode = function(node) {
  346. // 空白符处理
  347. if (node.pre) {
  348. node.pre = this.pre = void 0;
  349. for (let i = this.STACK.length; i--;)
  350. if (this.STACK[i].pre)
  351. this.pre = true;
  352. }
  353. var siblings = this.siblings(),
  354. len = siblings.length,
  355. childs = node.children;
  356. if (node.name == 'head' || (cfg.filter && cfg.filter(node, this) == false))
  357. return siblings.pop();
  358. var attrs = node.attrs;
  359. // 替换一些标签名
  360. if (cfg.blockTags[node.name]) node.name = 'div';
  361. else if (!cfg.trustTags[node.name]) node.name = 'span';
  362. // 去除块标签前后空串
  363. if (node.name == 'div' || node.name == 'p' || node.name[0] == 't') {
  364. if (len > 1 && siblings[len - 2].text == ' ')
  365. siblings.splice(--len - 1, 1);
  366. if (childs.length && childs[childs.length - 1].text == ' ')
  367. childs.pop();
  368. }
  369. // 处理列表
  370. if (node.c && (node.name == 'ul' || node.name == 'ol')) {
  371. if ((node.attrs.style || '').includes('list-style:none')) {
  372. for (let i = 0, child; child = childs[i++];)
  373. if (child.name == 'li')
  374. child.name = 'div';
  375. } else if (node.name == 'ul') {
  376. var floor = 1;
  377. for (let i = this.STACK.length; i--;)
  378. if (this.STACK[i].name == 'ul') floor++;
  379. if (floor != 1)
  380. for (let i = childs.length; i--;)
  381. childs[i].floor = floor;
  382. } else {
  383. for (let i = 0, num = 1, child; child = childs[i++];)
  384. if (child.name == 'li') {
  385. child.type = 'ol';
  386. child.num = ((num, type) => {
  387. if (type == 'a') return String.fromCharCode(97 + (num - 1) % 26);
  388. if (type == 'A') return String.fromCharCode(65 + (num - 1) % 26);
  389. if (type == 'i' || type == 'I') {
  390. num = (num - 1) % 99 + 1;
  391. var one = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
  392. ten = ['X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
  393. res = (ten[Math.floor(num / 10) - 1] || '') + (one[num % 10 - 1] || '');
  394. if (type == 'i') return res.toLowerCase();
  395. return res;
  396. }
  397. return num;
  398. })(num++, attrs.type) + '.';
  399. }
  400. }
  401. }
  402. // 处理表格的边框
  403. if (node.name == 'table') {
  404. var padding = attrs.cellpadding,
  405. spacing = attrs.cellspacing,
  406. border = attrs.border;
  407. if (node.c) {
  408. this.bubble();
  409. attrs.style = (attrs.style || '') + ';display:table';
  410. if (!padding) padding = 2;
  411. if (!spacing) spacing = 2;
  412. }
  413. if (border) attrs.style = `border:${border}px solid gray;${attrs.style || ''}`;
  414. if (spacing) attrs.style = `border-spacing:${spacing}px;${attrs.style || ''}`;
  415. if (border || padding || node.c)
  416. (function f(ns) {
  417. for (var i = 0, n; n = ns[i]; i++) {
  418. if (n.type == 'text') continue;
  419. var style = n.attrs.style || '';
  420. if (node.c && n.name[0] == 't') {
  421. n.c = 1;
  422. style += ';display:table-' + (n.name == 'th' || n.name == 'td' ? 'cell' : (n.name == 'tr' ? 'row' : 'row-group'));
  423. }
  424. if (n.name == 'th' || n.name == 'td') {
  425. if (border) style = `border:${border}px solid gray;${style}`;
  426. if (padding) style = `padding:${padding}px;${style}`;
  427. } else f(n.children || []);
  428. if (style) n.attrs.style = style;
  429. }
  430. })(childs);
  431. if (this.options.autoscroll) {
  432. var table = Object.assign({}, node);
  433. node.name = 'div';
  434. node.attrs = {
  435. style: 'overflow:scroll'
  436. };
  437. node.children = [table];
  438. }
  439. }
  440. this.CssHandler.pop && this.CssHandler.pop(node);
  441. // 自动压缩
  442. if (node.name == 'div' && !Object.keys(attrs).length && childs.length == 1 && childs[0].name == 'div')
  443. siblings[len - 1] = childs[0];
  444. };
  445. // 状态机
  446. MpHtmlParser.prototype.Text = function(c) {
  447. if (c == '<') {
  448. var next = this.data[this.i + 1],
  449. isLetter = c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  450. if (isLetter(next)) {
  451. this.setText();
  452. this.start = this.i + 1;
  453. this.state = this.TagName;
  454. } else if (next == '/') {
  455. this.setText();
  456. if (isLetter(this.data[++this.i + 1])) {
  457. this.start = this.i + 1;
  458. this.state = this.EndTag;
  459. } else this.Comment();
  460. } else if (next == '!') {
  461. this.setText();
  462. this.Comment();
  463. }
  464. }
  465. };
  466. MpHtmlParser.prototype.Comment = function() {
  467. var key;
  468. if (this.data.substring(this.i + 2, this.i + 4) == '--') key = '-->';
  469. else if (this.data.substring(this.i + 2, this.i + 9) == '[CDATA[') key = ']]>';
  470. else key = '>';
  471. if ((this.i = this.data.indexOf(key, this.i + 2)) == -1) this.i = this.data.length;
  472. else this.i += key.length - 1;
  473. this.start = this.i + 1;
  474. this.state = this.Text;
  475. };
  476. MpHtmlParser.prototype.TagName = function(c) {
  477. if (blankChar[c]) {
  478. this.tagName = this.section();
  479. while (blankChar[this.data[this.i]]) this.i++;
  480. if (this.isClose()) this.setNode();
  481. else {
  482. this.start = this.i;
  483. this.state = this.AttrName;
  484. }
  485. } else if (this.isClose()) {
  486. this.tagName = this.section();
  487. this.setNode();
  488. }
  489. };
  490. MpHtmlParser.prototype.AttrName = function(c) {
  491. if (c == '=' || blankChar[c] || this.isClose()) {
  492. this.attrName = this.section();
  493. if (blankChar[c])
  494. while (blankChar[this.data[++this.i]]) ;
  495. if (this.data[this.i] == '=') {
  496. while (blankChar[this.data[++this.i]]) ;
  497. this.start = this.i--;
  498. this.state = this.AttrValue;
  499. } else this.setAttr();
  500. }
  501. };
  502. MpHtmlParser.prototype.AttrValue = function(c) {
  503. if (c == '"' || c == '\'') {
  504. this.start++;
  505. if ((this.i = this.data.indexOf(c, this.i + 1)) == -1) return this.i = this.data.length;
  506. this.attrVal = this.section();
  507. this.i++;
  508. } else {
  509. for (; !blankChar[this.data[this.i]] && !this.isClose(); this.i++) ;
  510. this.attrVal = this.section();
  511. }
  512. this.setAttr();
  513. };
  514. MpHtmlParser.prototype.EndTag = function(c) {
  515. if (blankChar[c] || c == '>' || c == '/') {
  516. var name = this.section().toLowerCase();
  517. for (var i = this.STACK.length; i--;)
  518. if (this.STACK[i].name == name) break;
  519. if (i != -1) {
  520. var node;
  521. while ((node = this.STACK.pop()).name != name) this.popNode(node);
  522. this.popNode(node);
  523. } else if (name == 'p' || name == 'br')
  524. this.siblings().push({
  525. name,
  526. attrs: {}
  527. });
  528. this.i = this.data.indexOf('>', this.i);
  529. this.start = this.i + 1;
  530. if (this.i == -1) this.i = this.data.length;
  531. else this.state = this.Text;
  532. }
  533. };
  534. module.exports = MpHtmlParser;