MpHtmlParser.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /**
  2. * html 解析器
  3. * @tutorial https://github.com/jin-yufeng/Parser
  4. * @version 20200728
  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. 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 flag, tmp = [];
  105. for (let i = text.length, c; c = text[--i];)
  106. if (!blankChar[c]) {
  107. tmp.unshift(c);
  108. if (!flag) flag = 1;
  109. } else {
  110. if (tmp[0] != ' ') tmp.unshift(' ');
  111. if (c == '\n' && flag == void 0) flag = 0;
  112. }
  113. if (flag == 0) return;
  114. text = tmp.join('');
  115. }
  116. this.siblings().push({
  117. type: 'text',
  118. text: this.decode(text)
  119. });
  120. }
  121. // 设置元素节点
  122. MpHtmlParser.prototype.setNode = function() {
  123. var node = {
  124. name: this.tagName.toLowerCase(),
  125. attrs: this.attrs
  126. },
  127. close = cfg.selfClosingTags[node.name];
  128. if (this.options.nodes.length) node.type = 'node';
  129. this.attrs = {};
  130. if (!cfg.ignoreTags[node.name]) {
  131. // 处理属性
  132. var attrs = node.attrs,
  133. style = this.CssHandler.match(node.name, attrs, node) + (attrs.style || ''),
  134. styleObj = {};
  135. if (attrs.id) {
  136. if (this.options.compress & 1) attrs.id = void 0;
  137. else if (this.options.useAnchor) this.bubble();
  138. }
  139. if ((this.options.compress & 2) && attrs.class) attrs.class = void 0;
  140. switch (node.name) {
  141. case 'a':
  142. case 'ad': // #ifdef APP-PLUS
  143. case 'iframe':
  144. // #endif
  145. this.bubble();
  146. break;
  147. case 'font':
  148. if (attrs.color) {
  149. styleObj['color'] = attrs.color;
  150. attrs.color = void 0;
  151. }
  152. if (attrs.face) {
  153. styleObj['font-family'] = attrs.face;
  154. attrs.face = void 0;
  155. }
  156. if (attrs.size) {
  157. var size = parseInt(attrs.size);
  158. if (size < 1) size = 1;
  159. else if (size > 7) size = 7;
  160. var map = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'];
  161. styleObj['font-size'] = map[size - 1];
  162. attrs.size = void 0;
  163. }
  164. break;
  165. case 'embed':
  166. // #ifndef APP-PLUS
  167. var src = node.attrs.src || '',
  168. type = node.attrs.type || '';
  169. if (type.includes('video') || src.includes('.mp4') || src.includes('.3gp') || src.includes('.m3u8'))
  170. node.name = 'video';
  171. else if (type.includes('audio') || src.includes('.m4a') || src.includes('.wav') || src.includes('.mp3') || src.includes(
  172. '.aac'))
  173. node.name = 'audio';
  174. else break;
  175. if (node.attrs.autostart)
  176. node.attrs.autoplay = 'T';
  177. node.attrs.controls = 'T';
  178. // #endif
  179. // #ifdef APP-PLUS
  180. this.bubble();
  181. break;
  182. // #endif
  183. case 'video':
  184. case 'audio':
  185. if (!attrs.id) attrs.id = node.name + (++this[`${node.name}Num`]);
  186. else this[`${node.name}Num`]++;
  187. if (node.name == 'video') {
  188. if (this.videoNum > 3)
  189. node.lazyLoad = 1;
  190. if (attrs.width) {
  191. styleObj.width = parseFloat(attrs.width) + (attrs.width.includes('%') ? '%' : 'px');
  192. attrs.width = void 0;
  193. }
  194. if (attrs.height) {
  195. styleObj.height = parseFloat(attrs.height) + (attrs.height.includes('%') ? '%' : 'px');
  196. attrs.height = void 0;
  197. }
  198. }
  199. if (!attrs.controls && !attrs.autoplay) attrs.controls = 'T';
  200. attrs.source = [];
  201. if (attrs.src) {
  202. attrs.source.push(attrs.src);
  203. attrs.src = void 0;
  204. }
  205. this.bubble();
  206. break;
  207. case 'td':
  208. case 'th':
  209. if (attrs.colspan || attrs.rowspan)
  210. for (var k = this.STACK.length, item; item = this.STACK[--k];)
  211. if (item.name == 'table') {
  212. item.c = void 0;
  213. break;
  214. }
  215. }
  216. if (attrs.align) {
  217. styleObj['text-align'] = attrs.align;
  218. attrs.align = void 0;
  219. }
  220. // 压缩 style
  221. var styles = style.split(';');
  222. style = '';
  223. for (var i = 0, len = styles.length; i < len; i++) {
  224. var info = styles[i].split(':');
  225. if (info.length < 2) continue;
  226. let key = info[0].trim().toLowerCase(),
  227. value = info.slice(1).join(':').trim();
  228. if (value[0] == '-' || value.includes('safe'))
  229. style += `;${key}:${value}`;
  230. else if (!styleObj[key] || value.includes('import') || !styleObj[key].includes('import'))
  231. styleObj[key] = value;
  232. }
  233. if (node.name == 'img') {
  234. if (attrs.src && !attrs.ignore) {
  235. if (this.bubble())
  236. attrs.i = (this.imgNum++).toString();
  237. else attrs.ignore = 'T';
  238. }
  239. if (attrs.ignore) {
  240. style += ';-webkit-touch-callout:none';
  241. styleObj['max-width'] = '100%';
  242. }
  243. var width;
  244. if (styleObj.width) width = styleObj.width;
  245. else if (attrs.width) width = attrs.width.includes('%') ? attrs.width : attrs.width + 'px';
  246. if (width) {
  247. styleObj.width = width;
  248. attrs.width = '100%';
  249. if (parseInt(width) > windowWidth) {
  250. styleObj.height = '';
  251. if (attrs.height) attrs.height = void 0;
  252. }
  253. }
  254. if (styleObj.height) {
  255. attrs.height = styleObj.height;
  256. styleObj.height = '';
  257. } else if (attrs.height && !attrs.height.includes('%'))
  258. attrs.height += 'px';
  259. }
  260. for (var key in styleObj) {
  261. var value = styleObj[key];
  262. if (!value) continue;
  263. if (key.includes('flex') || key == 'order' || key == 'self-align') node.c = 1;
  264. // 填充链接
  265. if (value.includes('url')) {
  266. var j = value.indexOf('(');
  267. if (j++ != -1) {
  268. while (value[j] == '"' || value[j] == "'" || blankChar[value[j]]) j++;
  269. value = value.substr(0, j) + this.getUrl(value.substr(j));
  270. }
  271. }
  272. // 转换 rpx
  273. else if (value.includes('rpx'))
  274. value = value.replace(/[0-9.]+\s*rpx/g, $ => parseFloat($) * windowWidth / 750 + 'px');
  275. else if (key == 'white-space' && value.includes('pre') && !close)
  276. this.pre = node.pre = true;
  277. style += `;${key}:${value}`;
  278. }
  279. style = style.substr(1);
  280. if (style) attrs.style = style;
  281. if (!close) {
  282. node.children = [];
  283. if (node.name == 'pre' && cfg.highlight) {
  284. this.remove(node);
  285. this.pre = node.pre = true;
  286. }
  287. this.siblings().push(node);
  288. this.STACK.push(node);
  289. } else if (!cfg.filter || cfg.filter(node, this) != false)
  290. this.siblings().push(node);
  291. } else {
  292. if (!close) this.remove(node);
  293. else if (node.name == 'source') {
  294. var parent = this.parent();
  295. if (parent && (parent.name == 'video' || parent.name == 'audio') && node.attrs.src)
  296. parent.attrs.source.push(node.attrs.src);
  297. } else if (node.name == 'base' && !this.domain) this.domain = node.attrs.href;
  298. }
  299. if (this.data[this.i] == '/') this.i++;
  300. this.start = this.i + 1;
  301. this.state = this.Text;
  302. }
  303. // 移除标签
  304. MpHtmlParser.prototype.remove = function(node) {
  305. var name = node.name,
  306. j = this.i;
  307. // 处理 svg
  308. var handleSvg = () => {
  309. var src = this.data.substring(j, this.i + 1);
  310. if (!node.attrs.xmlns) src = ' xmlns="http://www.w3.org/2000/svg"' + src;
  311. var i = j;
  312. while (this.data[j] != '<') j--;
  313. src = this.data.substring(j, i).replace("viewbox", "viewBox") + src;
  314. var parent = this.parent();
  315. if (node.attrs.width == '100%' && parent && (parent.attrs.style || '').includes('inline'))
  316. parent.attrs.style = 'width:300px;max-width:100%;' + parent.attrs.style;
  317. this.siblings().push({
  318. name: 'img',
  319. attrs: {
  320. src: 'data:image/svg+xml;utf8,' + src.replace(/#/g, '%23'),
  321. style: (/vertical[^;]+/.exec(node.attrs.style) || []).shift(),
  322. ignore: 'T'
  323. }
  324. })
  325. }
  326. if (node.name == 'svg' && this.data[j] == '/') return handleSvg(this.i++);
  327. while (1) {
  328. if ((this.i = this.data.indexOf('</', this.i + 1)) == -1) {
  329. if (name == 'pre' || name == 'svg') this.i = j;
  330. else this.i = this.data.length;
  331. return;
  332. }
  333. this.start = (this.i += 2);
  334. while (!blankChar[this.data[this.i]] && !this.isClose()) this.i++;
  335. if (this.section().toLowerCase() == name) {
  336. // 代码块高亮
  337. if (name == 'pre') {
  338. this.data = this.data.substr(0, j + 1) + cfg.highlight(this.data.substring(j + 1, this.i - 5), node.attrs) + this.data
  339. .substr(this.i - 5);
  340. return this.i = j;
  341. } else if (name == 'style')
  342. this.CssHandler.getStyle(this.data.substring(j + 1, this.i - 7));
  343. else if (name == 'title')
  344. this.DOM.title = this.data.substring(j + 1, this.i - 7);
  345. if ((this.i = this.data.indexOf('>', this.i)) == -1) this.i = this.data.length;
  346. if (name == 'svg') handleSvg();
  347. return;
  348. }
  349. }
  350. }
  351. // 节点出栈处理
  352. MpHtmlParser.prototype.popNode = function(node) {
  353. // 空白符处理
  354. if (node.pre) {
  355. node.pre = this.pre = void 0;
  356. for (let i = this.STACK.length; i--;)
  357. if (this.STACK[i].pre)
  358. this.pre = true;
  359. }
  360. var siblings = this.siblings(),
  361. len = siblings.length,
  362. childs = node.children;
  363. if (node.name == 'head' || (cfg.filter && cfg.filter(node, this) == false))
  364. return siblings.pop();
  365. var attrs = node.attrs;
  366. // 替换一些标签名
  367. if (cfg.blockTags[node.name]) node.name = 'div';
  368. else if (!cfg.trustTags[node.name]) node.name = 'span';
  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 == '!' || 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;