MpHtmlParser.js 17 KB

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