Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

MpHtmlParser.js 17 KiB

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