MpHtmlParser.js 18 KB

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