parser.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. "use strict";
  2. /**
  3. * @fileoverview html 解析器
  4. */
  5. // 配置
  6. var config = {
  7. // 信任的标签(保持标签名不变)
  8. trustTags: makeMap('a,abbr,ad,audio,b,blockquote,br,code,col,colgroup,dd,del,dl,dt,div,em,fieldset,h1,h2,h3,h4,h5,h6,hr,i,img,ins,label,legend,li,ol,p,q,ruby,rt,source,span,strong,sub,sup,table,tbody,td,tfoot,th,thead,tr,title,ul,video'),
  9. // 块级标签(转为 div,其他的非信任标签转为 span)
  10. blockTags: makeMap('address,article,aside,body,caption,center,cite,footer,header,html,nav,pre,section'),
  11. // 要移除的标签
  12. ignoreTags: makeMap('area,base,canvas,embed,frame,head,iframe,input,link,map,meta,param,rp,script,source,style,textarea,title,track,wbr'),
  13. // 自闭合的标签
  14. voidTags: makeMap('area,base,br,col,circle,ellipse,embed,frame,hr,img,input,line,link,meta,param,path,polygon,rect,source,track,use,wbr'),
  15. // html 实体
  16. entities: {
  17. lt: '<',
  18. gt: '>',
  19. quot: '"',
  20. apos: "'",
  21. ensp: "\u2002",
  22. emsp: "\u2003",
  23. nbsp: '\xA0',
  24. semi: ';',
  25. ndash: '–',
  26. mdash: '—',
  27. middot: '·',
  28. lsquo: '‘',
  29. rsquo: '’',
  30. ldquo: '“',
  31. rdquo: '”',
  32. bull: '•',
  33. hellip: '…'
  34. },
  35. // 默认的标签样式
  36. tagStyle: {
  37. // #ifndef APP-PLUS-NVUE
  38. address: 'font-style:italic',
  39. big: 'display:inline;font-size:1.2em',
  40. caption: 'display:table-caption;text-align:center',
  41. center: 'text-align:center',
  42. cite: 'font-style:italic',
  43. dd: 'margin-left:40px',
  44. mark: 'background-color:yellow',
  45. pre: 'font-family:monospace;white-space:pre',
  46. s: 'text-decoration:line-through',
  47. small: 'display:inline;font-size:0.8em',
  48. u: 'text-decoration:underline' // #endif
  49. }
  50. };
  51. var windowWidth = uni.getSystemInfoSync().windowWidth;
  52. var blankChar = makeMap(' ,\r,\n,\t,\f');
  53. var idIndex = 0; // #ifdef H5 || APP-PLUS
  54. config.ignoreTags.iframe = void 0;
  55. config.trustTags.iframe = true;
  56. config.ignoreTags.embed = void 0;
  57. config.trustTags.embed = true; // #endif
  58. // #ifdef APP-PLUS-NVUE
  59. config.ignoreTags.source = void 0;
  60. config.ignoreTags.style = void 0; // #endif
  61. /**
  62. * @description 创建 map
  63. * @param {String} str 逗号分隔
  64. */
  65. function makeMap(str) {
  66. var map = Object.create(null),
  67. list = str.split(',');
  68. for (var i = list.length; i--;) {
  69. map[list[i]] = true;
  70. }
  71. return map;
  72. }
  73. /**
  74. * @description 解码 html 实体
  75. * @param {String} str 要解码的字符串
  76. * @param {Boolean} amp 要不要解码 &amp;
  77. * @returns {String} 解码后的字符串
  78. */
  79. function decodeEntity(str, amp) {
  80. var i = str.indexOf('&');
  81. while (i != -1) {
  82. var j = str.indexOf(';', i + 3),
  83. code = void 0;
  84. if (j == -1) break;
  85. if (str[i + 1] == '#') {
  86. // &#123; 形式的实体
  87. code = parseInt((str[i + 2] == 'x' ? '0' : '') + str.substring(i + 2, j));
  88. if (!isNaN(code)) str = str.substr(0, i) + String.fromCharCode(code) + str.substr(j + 1);
  89. } else {
  90. // &nbsp; 形式的实体
  91. code = str.substring(i + 1, j);
  92. if (config.entities[code] || code == 'amp' && amp) str = str.substr(0, i) + (config.entities[code] || '&') + str.substr(j + 1);
  93. }
  94. i = str.indexOf('&', i + 1);
  95. }
  96. return str;
  97. }
  98. /**
  99. * @description html 解析器
  100. * @param {Object} vm 组件实例
  101. */
  102. function parser(vm) {
  103. this.options = vm || {};
  104. this.tagStyle = Object.assign(config.tagStyle, this.options.tagStyle);
  105. this.imgList = vm.imgList || [];
  106. this.plugins = vm.plugins || [];
  107. this.attrs = Object.create(null);
  108. this.stack = [];
  109. this.nodes = [];
  110. }
  111. /**
  112. * @description 执行解析
  113. * @param {String} content 要解析的文本
  114. */
  115. parser.prototype.parse = function (content) {
  116. // 插件处理
  117. for (var i = this.plugins.length; i--;) {
  118. if (this.plugins[i].onUpdate) content = this.plugins[i].onUpdate(content, config) || content;
  119. }
  120. new lexer(this).parse(content); // 出栈未闭合的标签
  121. while (this.stack.length) {
  122. this.popNode();
  123. }
  124. return this.nodes;
  125. };
  126. /**
  127. * @description 将标签暴露出来(不被 rich-text 包含)
  128. */
  129. parser.prototype.expose = function () {
  130. // #ifndef APP-PLUS-NVUE
  131. for (var i = this.stack.length; i--;) {
  132. var item = this.stack[i];
  133. if (item.name == 'a' || item.c) return;
  134. item.c = 1;
  135. } // #endif
  136. };
  137. /**
  138. * @description 处理插件
  139. * @param {Object} node 要处理的标签
  140. * @returns {Boolean} 是否要移除此标签
  141. */
  142. parser.prototype.hook = function (node) {
  143. for (var i = this.plugins.length; i--;) {
  144. if (this.plugins[i].onParse && this.plugins[i].onParse(node, this) == false) return false;
  145. }
  146. return true;
  147. };
  148. /**
  149. * @description 将链接拼接上主域名
  150. * @param {String} url 需要拼接的链接
  151. * @returns {String} 拼接后的链接
  152. */
  153. parser.prototype.getUrl = function (url) {
  154. var domain = this.options.domain;
  155. if (url[0] == '/') {
  156. // // 开头的补充协议名
  157. if (url[1] == '/') url = (domain ? domain.split('://')[0] : 'http') + ':' + url; // 否则补充整个域名
  158. else if (domain) url = domain + url;
  159. } else if (domain && !url.includes('data:') && !url.includes('://')) url = domain + '/' + url;
  160. return url;
  161. };
  162. /**
  163. * @description 解析样式表
  164. * @param {Object} node 标签
  165. * @returns {Object}
  166. */
  167. parser.prototype.parseStyle = function (node) {
  168. var attrs = node.attrs,
  169. list = (this.tagStyle[node.name] || '').split(';').concat((attrs.style || '').split(';')),
  170. styleObj = {},
  171. tmp = '';
  172. if (attrs.id) {
  173. // 暴露锚点
  174. if (this.options.useAnchor) this.expose();else if (node.name != 'img' && node.name != 'a' && node.name != 'video' && node.name != 'audio') attrs.id = void 0;
  175. } // 转换 width 和 height 属性
  176. if (attrs.width) {
  177. styleObj.width = parseFloat(attrs.width) + (attrs.width.includes('%') ? '%' : 'px');
  178. attrs.width = void 0;
  179. }
  180. if (attrs.height) {
  181. styleObj.height = parseFloat(attrs.height) + (attrs.height.includes('%') ? '%' : 'px');
  182. attrs.height = void 0;
  183. }
  184. for (var i = 0, len = list.length; i < len; i++) {
  185. var info = list[i].split(':');
  186. if (info.length < 2) continue;
  187. var key = info.shift().trim().toLowerCase(),
  188. value = info.join(':').trim(); // 兼容性的 css 不压缩
  189. if (value[0] == '-' && value.lastIndexOf('-') > 0 || value.includes('safe')) tmp += ";".concat(key, ":").concat(value); // 重复的样式进行覆盖
  190. else if (!styleObj[key] || value.includes('import') || !styleObj[key].includes('import')) {
  191. // 填充链接
  192. if (value.includes('url')) {
  193. var j = value.indexOf('(') + 1;
  194. if (j) {
  195. while (value[j] == '"' || value[j] == "'" || blankChar[value[j]]) {
  196. j++;
  197. }
  198. value = value.substr(0, j) + this.getUrl(value.substr(j));
  199. }
  200. } // 转换 rpx(rich-text 内部不支持 rpx)
  201. else if (value.includes('rpx')) value = value.replace(/[0-9.]+\s*rpx/g, function ($) {
  202. return parseFloat($) * windowWidth / 750 + 'px';
  203. });
  204. styleObj[key] = value;
  205. }
  206. }
  207. node.attrs.style = tmp;
  208. return styleObj;
  209. };
  210. /**
  211. * @description 解析到标签名
  212. * @param {String} name 标签名
  213. * @private
  214. */
  215. parser.prototype.onTagName = function (name) {
  216. this.tagName = this.xml ? name : name.toLowerCase();
  217. if (this.tagName == 'svg') this.xml = true; // svg 标签内大小写敏感
  218. };
  219. /**
  220. * @description 解析到属性名
  221. * @param {String} name 属性名
  222. * @private
  223. */
  224. parser.prototype.onAttrName = function (name) {
  225. name = this.xml ? name : name.toLowerCase();
  226. if (name.substr(0, 5) == 'data-') {
  227. // data-src 自动转为 src
  228. if (name == 'data-src' && !this.attrs.src) this.attrName = 'src'; // a 和 img 标签保留 data- 的属性,可以在 imgtap 和 linktap 事件中使用
  229. else if (this.tagName == 'img' || this.tagName == 'a') this.attrName = name; // 剩余的移除以减小大小
  230. else this.attrName = void 0;
  231. } else {
  232. this.attrName = name;
  233. this.attrs[name] = 'T'; // boolean 型属性缺省设置
  234. }
  235. };
  236. /**
  237. * @description 解析到属性值
  238. * @param {String} val 属性值
  239. * @private
  240. */
  241. parser.prototype.onAttrVal = function (val) {
  242. var name = this.attrName || ''; // 部分属性进行实体解码
  243. if (name == 'style' || name == 'href') this.attrs[name] = decodeEntity(val, true); // 拼接主域名
  244. else if (name.includes('src')) this.attrs[name] = this.getUrl(decodeEntity(val, true));else if (name) this.attrs[name] = val;
  245. };
  246. /**
  247. * @description 解析到标签开始
  248. * @param {Boolean} selfClose 是否有自闭合标识 />
  249. * @private
  250. */
  251. parser.prototype.onOpenTag = function (selfClose) {
  252. // 拼装 node
  253. var node = Object.create(null);
  254. node.name = this.tagName;
  255. node.attrs = this.attrs;
  256. this.attrs = Object.create(null);
  257. var attrs = node.attrs,
  258. parent = this.stack[this.stack.length - 1],
  259. siblings = parent ? parent.children : this.nodes,
  260. close = this.xml ? selfClose : config.voidTags[node.name]; // 转换 embed 标签
  261. if (node.name == 'embed') {
  262. // #ifndef H5 || APP-PLUS
  263. var src = attrs.src || ''; // 按照后缀名和 type 将 embed 转为 video 或 audio
  264. if (src.includes('.mp4') || src.includes('.3gp') || src.includes('.m3u8') || (attrs.type || '').includes('video')) node.name = 'video';else if (src.includes('.mp3') || src.includes('.wav') || src.includes('.aac') || src.includes('.m4a') || (attrs.type || '').includes('audio')) node.name = 'audio';
  265. if (attrs.autostart) attrs.autoplay = 'T';
  266. attrs.controls = 'T'; // #endif
  267. // #ifdef H5 || APP-PLUS
  268. this.expose(); // #endif
  269. } // #ifndef APP-PLUS-NVUE
  270. // 处理音视频
  271. if (node.name == 'video' || node.name == 'audio') {
  272. // 设置 id 以便获取 context
  273. if (node.name == 'video' && !attrs.id) attrs.id = 'v' + idIndex++; // 没有设置 controls 也没有设置 autoplay 的自动设置 controls
  274. if (!attrs.controls && !attrs.autoplay) attrs.controls = 'T'; // 用数组存储所有可用的 source
  275. node.src = [];
  276. if (attrs.src) {
  277. node.src.push(attrs.src);
  278. attrs.src = void 0;
  279. }
  280. this.expose();
  281. } // #endif
  282. // 处理自闭合标签
  283. if (close) {
  284. if (!this.hook(node) || config.ignoreTags[node.name]) {
  285. // 通过 base 标签设置主域名
  286. if (node.name == 'base' && !this.options.domain) this.options.domain = attrs.href; // #ifndef APP-PLUS-NVUE
  287. // 设置 source 标签(仅父节点为 video 或 audio 时有效)
  288. else if (node.name == 'source' && parent && (parent.name == 'video' || parent.name == 'audio') && attrs.src) parent.src.push(attrs.src); // #endif
  289. return;
  290. } // 解析 style
  291. var styleObj = this.parseStyle(node); // 处理图片
  292. if (node.name == 'img') {
  293. if (attrs.src) {
  294. // 标记 webp
  295. if (attrs.src.includes('webp')) node.webp = 'T'; // data url 图片如果没有设置 original-src 默认为不可预览的小图片
  296. if (attrs.src.includes('data:') && !attrs['original-src']) attrs.ignore = 'T';
  297. if (!attrs.ignore || node.webp || attrs.src.includes('cloud://')) {
  298. for (var i = this.stack.length; i--;) {
  299. var item = this.stack[i];
  300. if (item.name == 'a') {
  301. node.a = item.attrs;
  302. break;
  303. } // #ifndef H5 || APP-PLUS
  304. var style = item.attrs.style || '';
  305. if (style.includes('flex:') && !style.includes('flex:0') && !style.includes('flex: 0') && (!styleObj.width || !styleObj.width.includes('%'))) {
  306. styleObj.width = '100% !important';
  307. styleObj.height = '';
  308. for (var j = i + 1; j < this.stack.length; j++) {
  309. this.stack[j].attrs.style = (this.stack[j].attrs.style || '').replace('inline-', '');
  310. }
  311. } else if (style.includes('flex') && styleObj.width == '100%') {
  312. for (var _j = i + 1; _j < this.stack.length; _j++) {
  313. var _style = this.stack[_j].attrs.style || '';
  314. if (!_style.includes(';width') && !_style.includes(' width') && _style.indexOf('width') != 0) {
  315. styleObj.width = '';
  316. break;
  317. }
  318. }
  319. } else if (style.includes('inline-block')) {
  320. if (styleObj.width && styleObj.width[styleObj.width.length - 1] == '%') {
  321. item.attrs.style += ';max-width:' + styleObj.width;
  322. styleObj.width = '';
  323. } else item.attrs.style += ';max-width:100%';
  324. } // #endif
  325. item.c = 1;
  326. }
  327. attrs.i = this.imgList.length.toString();
  328. var _src = attrs['original-src'] || attrs.src; // #ifndef H5 || MP-ALIPAY || APP-PLUS || MP-360
  329. if (this.imgList.includes(_src)) {
  330. // 如果有重复的链接则对域名进行随机大小写变换避免预览时错位
  331. var _i = _src.indexOf('://');
  332. if (_i != -1) {
  333. _i += 3;
  334. var newSrc = _src.substr(0, _i);
  335. for (; _i < _src.length; _i++) {
  336. if (_src[_i] == '/') break;
  337. newSrc += Math.random() > 0.5 ? _src[_i].toUpperCase() : _src[_i];
  338. }
  339. newSrc += _src.substr(_i);
  340. _src = newSrc;
  341. }
  342. } // #endif
  343. this.imgList.push(_src); // #ifdef H5 || APP-PLUS
  344. if (this.options.lazyLoad) {
  345. attrs['data-src'] = attrs.src;
  346. attrs.src = void 0;
  347. } // #endif
  348. }
  349. }
  350. if (styleObj.display == 'inline') styleObj.display = ''; // #ifndef APP-PLUS-NVUE
  351. if (attrs.ignore) {
  352. styleObj['max-width'] = styleObj['max-width'] || '100%';
  353. attrs.style += ';-webkit-touch-callout:none';
  354. } // #endif
  355. // 设置的宽度超出屏幕,为避免变形,高度转为自动
  356. if (parseInt(styleObj.width) > windowWidth) styleObj.height = void 0; // 记录是否设置了宽高
  357. if (styleObj.width) {
  358. if (styleObj.width.includes('auto')) styleObj.width = '';else {
  359. node.w = 'T';
  360. if (styleObj.height && !styleObj.height.includes('auto')) node.h = 'T';
  361. }
  362. }
  363. } else if (node.name == 'svg') {
  364. siblings.push(node);
  365. this.stack.push(node);
  366. this.popNode();
  367. return;
  368. }
  369. for (var key in styleObj) {
  370. if (styleObj[key]) attrs.style += ";".concat(key, ":").concat(styleObj[key].replace(' !important', ''));
  371. }
  372. attrs.style = attrs.style.substr(1) || void 0;
  373. } else {
  374. if (node.name == 'pre' || (attrs.style || '').includes('white-space') && attrs.style.includes('pre')) this.pre = node.pre = true;
  375. node.children = [];
  376. this.stack.push(node);
  377. } // 加入节点树
  378. siblings.push(node);
  379. };
  380. /**
  381. * @description 解析到标签结束
  382. * @param {String} name 标签名
  383. * @private
  384. */
  385. parser.prototype.onCloseTag = function (name) {
  386. // 依次出栈到匹配为止
  387. name = this.xml ? name : name.toLowerCase();
  388. var i;
  389. for (i = this.stack.length; i--;) {
  390. if (this.stack[i].name == name) break;
  391. }
  392. if (i != -1) {
  393. while (this.stack.length > i) {
  394. this.popNode();
  395. }
  396. } else if (name == 'p' || name == 'br') {
  397. var siblings = this.stack.length ? this.stack[this.stack.length - 1].children : this.nodes;
  398. siblings.push({
  399. name: name,
  400. attrs: {}
  401. });
  402. }
  403. };
  404. /**
  405. * @description 处理标签出栈
  406. * @private
  407. */
  408. parser.prototype.popNode = function () {
  409. var node = this.stack.pop(),
  410. attrs = node.attrs,
  411. children = node.children,
  412. parent = this.stack[this.stack.length - 1],
  413. siblings = parent ? parent.children : this.nodes;
  414. if (!this.hook(node) || config.ignoreTags[node.name]) {
  415. // 获取标题
  416. if (node.name == 'title' && children.length && children[0].type == 'text' && this.options.setTitle) uni.setNavigationBarTitle({
  417. title: children[0].text
  418. });
  419. siblings.pop();
  420. return;
  421. }
  422. if (node.pre) {
  423. // 是否合并空白符标识
  424. node.pre = this.pre = void 0;
  425. for (var i = this.stack.length; i--;) {
  426. if (this.stack[i].pre) this.pre = true;
  427. }
  428. }
  429. var styleObj = {}; // 转换 svg
  430. if (node.name == 'svg') {
  431. // #ifndef APP-PLUS-NVUE
  432. var src = '',
  433. style = attrs.style;
  434. attrs.style = '';
  435. attrs.xmlns = 'http://www.w3.org/2000/svg';
  436. (function traversal(node) {
  437. src += '<' + node.name;
  438. for (var item in node.attrs) {
  439. var val = node.attrs[item];
  440. if (val) {
  441. if (item == 'viewbox') item = 'viewBox';
  442. src += " ".concat(item, "=\"").concat(val, "\"");
  443. }
  444. }
  445. if (!node.children) src += '/>';else {
  446. src += '>';
  447. for (var _i2 = 0; _i2 < node.children.length; _i2++) {
  448. traversal(node.children[_i2]);
  449. }
  450. src += '</' + node.name + '>';
  451. }
  452. })(node);
  453. node.name = 'img';
  454. node.attrs = {
  455. src: 'data:image/svg+xml;utf8,' + src.replace(/#/g, '%23'),
  456. style: style,
  457. ignore: 'T'
  458. };
  459. node.children = void 0; // #endif
  460. this.xml = false;
  461. return;
  462. } // #ifndef APP-PLUS-NVUE
  463. // 转换 align 属性
  464. if (attrs.align) {
  465. if (node.name == 'table') {
  466. if (attrs.align == 'center') styleObj['margin-inline-start'] = styleObj['margin-inline-end'] = 'auto';else styleObj["float"] = attrs.align;
  467. } else styleObj['text-align'] = attrs.align;
  468. attrs.align = void 0;
  469. } // 转换 font 标签的属性
  470. if (node.name == 'font') {
  471. if (attrs.color) {
  472. styleObj.color = attrs.color;
  473. attrs.color = void 0;
  474. }
  475. if (attrs.face) {
  476. styleObj['font-family'] = attrs.face;
  477. attrs.face = void 0;
  478. }
  479. if (attrs.size) {
  480. var size = parseInt(attrs.size);
  481. if (!isNaN(size)) {
  482. if (size < 1) size = 1;else if (size > 7) size = 7;
  483. styleObj['font-size'] = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'][size - 1];
  484. }
  485. attrs.size = void 0;
  486. }
  487. } // #endif
  488. // 一些编辑器的自带 class
  489. if ((attrs["class"] || '').includes('align-center')) styleObj['text-align'] = 'center';
  490. Object.assign(styleObj, this.parseStyle(node));
  491. if (parseInt(styleObj.width) > windowWidth) {
  492. styleObj['max-width'] = '100%';
  493. styleObj['box-sizing'] = 'border-box';
  494. } // #ifndef APP-PLUS-NVUE
  495. if (config.blockTags[node.name]) node.name = 'div'; // 未知标签转为 span,避免无法显示
  496. else if (!config.trustTags[node.name] && !this.xml) node.name = 'span';
  497. if (node.name == 'a' || node.name == 'ad' // #ifdef H5 || APP-PLUS
  498. || node.name == 'iframe' // #endif
  499. ) this.expose(); // #ifdef APP-PLUS
  500. else if (node.name == 'video') {
  501. var str = '<video style="width:100%;height:100%"'; // 空白图占位
  502. if (!attrs.poster && !attrs.autoplay) attrs.poster = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'/>";
  503. for (var item in attrs) {
  504. if (attrs[item]) str += ' ' + item + '="' + attrs[item] + '"';
  505. }
  506. if (this.options.pauseVideo) str += ' onplay="for(var e=document.getElementsByTagName(\'video\'),t=0;t<e.length;t++)e[t]!=this&&e[t].pause()"';
  507. str += '>';
  508. for (var _i3 = 0; _i3 < node.src.length; _i3++) {
  509. str += '<source src="' + node.src[_i3] + '">';
  510. }
  511. str += '</video>';
  512. node.html = str;
  513. } // #endif
  514. // 列表处理
  515. else if ((node.name == 'ul' || node.name == 'ol') && node.c) {
  516. var types = {
  517. a: 'lower-alpha',
  518. A: 'upper-alpha',
  519. i: 'lower-roman',
  520. I: 'upper-roman'
  521. };
  522. if (types[attrs.type]) {
  523. attrs.style += ';list-style-type:' + types[attrs.type];
  524. attrs.type = void 0;
  525. }
  526. for (var _i4 = children.length; _i4--;) {
  527. if (children[_i4].name == 'li') children[_i4].c = 1;
  528. }
  529. } // 表格处理
  530. else if (node.name == 'table') {
  531. // cellpadding、cellspacing、border 这几个常用表格属性需要通过转换实现
  532. var padding = parseFloat(attrs.cellpadding),
  533. spacing = parseFloat(attrs.cellspacing),
  534. border = parseFloat(attrs.border);
  535. if (node.c) {
  536. // padding 和 spacing 默认 2
  537. if (isNaN(padding)) padding = 2;
  538. if (isNaN(spacing)) spacing = 2;
  539. }
  540. if (border) attrs.style += ';border:' + border + 'px solid gray';
  541. if (node.flag && node.c) {
  542. // 有 colspan 或 rowspan 且含有链接的表格通过 grid 布局实现
  543. styleObj.display = 'grid';
  544. if (spacing) {
  545. styleObj['grid-gap'] = spacing + 'px';
  546. styleObj.padding = spacing + 'px';
  547. } // 无间隔的情况下避免边框重叠
  548. else if (border) attrs.style += ';border-left:0;border-top:0';
  549. var width = [],
  550. // 表格的列宽
  551. trList = [],
  552. // tr 列表
  553. cells = [],
  554. // 保存新的单元格
  555. map = {}; // 被合并单元格占用的格子
  556. (function traversal(nodes) {
  557. for (var _i5 = 0; _i5 < nodes.length; _i5++) {
  558. if (nodes[_i5].name == 'tr') trList.push(nodes[_i5]);else traversal(nodes[_i5].children || []);
  559. }
  560. })(children);
  561. for (var row = 1; row <= trList.length; row++) {
  562. var col = 1;
  563. for (var j = 0; j < trList[row - 1].children.length; j++, col++) {
  564. var td = trList[row - 1].children[j];
  565. if (td.name == 'td' || td.name == 'th') {
  566. // 这个格子被上面的单元格占用,则列号++
  567. while (map[row + '.' + col]) {
  568. col++;
  569. }
  570. var _style2 = td.attrs.style || '',
  571. start = _style2.indexOf('width') ? _style2.indexOf(';width') : 0; // 提取出 td 的宽度
  572. if (start != -1) {
  573. var end = _style2.indexOf(';', start + 6);
  574. if (end == -1) end = _style2.length;
  575. if (!td.attrs.colspan) width[col] = _style2.substring(start ? start + 7 : 6, end);
  576. _style2 = _style2.substr(0, start) + _style2.substr(end);
  577. }
  578. _style2 += (border ? ";border:".concat(border, "px solid gray") + (spacing ? '' : ';border-right:0;border-bottom:0') : '') + (padding ? ";padding:".concat(padding, "px") : ''); // 处理列合并
  579. if (td.attrs.colspan) {
  580. _style2 += ";grid-column-start:".concat(col, ";grid-column-end:").concat(col + parseInt(td.attrs.colspan));
  581. if (!td.attrs.rowspan) _style2 += ";grid-row-start:".concat(row, ";grid-row-end:").concat(row + 1);
  582. col += parseInt(td.attrs.colspan) - 1;
  583. } // 处理行合并
  584. if (td.attrs.rowspan) {
  585. _style2 += ";grid-row-start:".concat(row, ";grid-row-end:").concat(row + parseInt(td.attrs.rowspan));
  586. if (!td.attrs.colspan) _style2 += ";grid-column-start:".concat(col, ";grid-column-end:").concat(col + 1); // 记录下方单元格被占用
  587. for (var k = 1; k < td.attrs.rowspan; k++) {
  588. map[row + k + '.' + col] = 1;
  589. }
  590. }
  591. if (_style2) td.attrs.style = _style2;
  592. cells.push(td);
  593. }
  594. }
  595. if (row == 1) {
  596. var temp = '';
  597. for (var _i6 = 1; _i6 < col; _i6++) {
  598. temp += (width[_i6] ? width[_i6] : 'auto') + ' ';
  599. }
  600. styleObj['grid-template-columns'] = temp;
  601. }
  602. }
  603. node.children = cells;
  604. } else {
  605. // 没有使用合并单元格的表格通过 table 布局实现
  606. if (node.c) styleObj.display = 'table';
  607. if (!isNaN(spacing)) styleObj['border-spacing'] = spacing + 'px';
  608. if (border || padding) {
  609. // 遍历
  610. (function traversal(nodes) {
  611. for (var _i7 = 0; _i7 < nodes.length; _i7++) {
  612. var _td = nodes[_i7];
  613. if (_td.name == 'th' || _td.name == 'td') {
  614. if (border) _td.attrs.style = "border:".concat(border, "px solid gray;").concat(_td.attrs.style || '');
  615. if (padding) _td.attrs.style = "padding:".concat(padding, "px;").concat(_td.attrs.style || '');
  616. } else if (_td.children) traversal(_td.children);
  617. }
  618. })(children);
  619. }
  620. } // 给表格添加一个单独的横向滚动层
  621. if (this.options.scrollTable && !(attrs.style || '').includes('inline')) {
  622. var table = Object.assign({}, node);
  623. node.name = 'div';
  624. node.attrs = {
  625. style: 'overflow:auto'
  626. };
  627. node.children = [table];
  628. attrs = table.attrs;
  629. }
  630. } else if ((node.name == 'td' || node.name == 'th') && (attrs.colspan || attrs.rowspan)) {
  631. for (var _i8 = this.stack.length; _i8--;) {
  632. if (this.stack[_i8].name == 'table') {
  633. this.stack[_i8].flag = 1; // 指示含有合并单元格
  634. break;
  635. }
  636. }
  637. } // 转换 ruby
  638. else if (node.name == 'ruby') {
  639. node.name = 'span';
  640. for (var _i9 = 0; _i9 < children.length - 1; _i9++) {
  641. if (children[_i9].type == 'text' && children[_i9 + 1].name == 'rt') {
  642. children[_i9] = {
  643. name: 'div',
  644. attrs: {
  645. style: 'display:inline-block'
  646. },
  647. children: [{
  648. name: 'div',
  649. attrs: {
  650. style: 'font-size:50%;text-align:start'
  651. },
  652. children: children[_i9 + 1].children
  653. }, children[_i9]]
  654. };
  655. children.splice(_i9 + 1, 1);
  656. }
  657. }
  658. } else if (node.c) {
  659. node.c = 2;
  660. for (var _i10 = node.children.length; _i10--;) {
  661. if (!node.children[_i10].c || node.children[_i10].name == 'table') node.c = 1;
  662. }
  663. }
  664. if ((styleObj.display || '').includes('flex') && !node.c) for (var _i11 = children.length; _i11--;) {
  665. var _item = children[_i11];
  666. if (_item.f) {
  667. _item.attrs.style = (_item.attrs.style || '') + _item.f;
  668. _item.f = void 0;
  669. }
  670. } // flex 布局时部分样式需要提取到 rich-text 外层
  671. var flex = parent && (parent.attrs.style || '').includes('flex') // #ifdef MP-WEIXIN
  672. // 检查基础库版本 virtualHost 是否可用
  673. && !(node.c && wx.getNFCAdapter) // #endif
  674. // #ifndef MP-WEIXIN || MP-QQ || MP-BAIDU || MP-TOUTIAO
  675. && !node.c; // #endif
  676. if (flex) node.f = ';max-width:100%'; // #endif
  677. for (var key in styleObj) {
  678. if (styleObj[key]) {
  679. var val = ";".concat(key, ":").concat(styleObj[key].replace(' !important', '')); // #ifndef APP-PLUS-NVUE
  680. if (flex && (key.includes('flex') && key != 'flex-direction' || key == 'align-self' || styleObj[key][0] == '-' || key == 'width' && val.includes('%'))) {
  681. node.f += val;
  682. if (key == 'width') attrs.style += ';width:100%';
  683. } else // #endif
  684. attrs.style += val;
  685. }
  686. }
  687. attrs.style = attrs.style.substr(1) || void 0;
  688. };
  689. /**
  690. * @description 解析到文本
  691. * @param {String} text 文本内容
  692. */
  693. parser.prototype.onText = function (text) {
  694. if (!this.pre) {
  695. // 合并空白符
  696. var trim = '',
  697. flag;
  698. for (var i = 0, len = text.length; i < len; i++) {
  699. if (!blankChar[text[i]]) trim += text[i];else {
  700. if (trim[trim.length - 1] != ' ') trim += ' ';
  701. if (text[i] == '\n' && !flag) flag = true;
  702. }
  703. } // 去除含有换行符的空串
  704. if (trim == ' ' && flag) return;
  705. text = trim;
  706. }
  707. var node = Object.create(null);
  708. node.type = 'text';
  709. node.text = decodeEntity(text);
  710. if (this.hook(node)) {
  711. var siblings = this.stack.length ? this.stack[this.stack.length - 1].children : this.nodes;
  712. siblings.push(node);
  713. }
  714. };
  715. /**
  716. * @description html 词法分析器
  717. * @param {Object} handler 高层处理器
  718. */
  719. function lexer(handler) {
  720. this.handler = handler;
  721. }
  722. /**
  723. * @description 执行解析
  724. * @param {String} content 要解析的文本
  725. */
  726. lexer.prototype.parse = function (content) {
  727. this.content = content || '';
  728. this.i = 0; // 标记解析位置
  729. this.start = 0; // 标记一个单词的开始位置
  730. this.state = this.text; // 当前状态
  731. for (var len = this.content.length; this.i != -1 && this.i < len;) {
  732. this.state();
  733. }
  734. };
  735. /**
  736. * @description 检查标签是否闭合
  737. * @param {String} method 如果闭合要进行的操作
  738. * @returns {Boolean} 是否闭合
  739. * @private
  740. */
  741. lexer.prototype.checkClose = function (method) {
  742. var selfClose = this.content[this.i] == '/';
  743. if (this.content[this.i] == '>' || selfClose && this.content[this.i + 1] == '>') {
  744. if (method) this.handler[method](this.content.substring(this.start, this.i));
  745. this.i += selfClose ? 2 : 1;
  746. this.start = this.i;
  747. this.handler.onOpenTag(selfClose);
  748. if (this.handler.tagName == 'script') {
  749. this.i = this.content.indexOf('</', this.i);
  750. if (this.i != -1) {
  751. this.i += 2;
  752. this.start = this.i;
  753. }
  754. this.state = this.endTag;
  755. } else this.state = this.text;
  756. return true;
  757. }
  758. return false;
  759. };
  760. /**
  761. * @description 文本状态
  762. * @private
  763. */
  764. lexer.prototype.text = function () {
  765. this.i = this.content.indexOf('<', this.i); // 查找最近的标签
  766. if (this.i == -1) {
  767. // 没有标签了
  768. if (this.start < this.content.length) this.handler.onText(this.content.substring(this.start, this.content.length));
  769. return;
  770. }
  771. var c = this.content[this.i + 1];
  772. if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') {
  773. // 标签开头
  774. if (this.start != this.i) this.handler.onText(this.content.substring(this.start, this.i));
  775. this.start = ++this.i;
  776. this.state = this.tagName;
  777. } else if (c == '/' || c == '!' || c == '?') {
  778. if (this.start != this.i) this.handler.onText(this.content.substring(this.start, this.i));
  779. var next = this.content[this.i + 2];
  780. if (c == '/' && (next >= 'a' && next <= 'z' || next >= 'A' && next <= 'Z')) {
  781. // 标签结尾
  782. this.i += 2;
  783. this.start = this.i;
  784. return this.state = this.endTag;
  785. } // 处理注释
  786. var end = '-->';
  787. if (c != '!' || this.content[this.i + 2] != '-' || this.content[this.i + 3] != '-') end = '>';
  788. this.i = this.content.indexOf(end, this.i);
  789. if (this.i != -1) {
  790. this.i += end.length;
  791. this.start = this.i;
  792. }
  793. } else this.i++;
  794. };
  795. /**
  796. * @description 标签名状态
  797. * @private
  798. */
  799. lexer.prototype.tagName = function () {
  800. if (blankChar[this.content[this.i]]) {
  801. // 解析到标签名
  802. this.handler.onTagName(this.content.substring(this.start, this.i));
  803. while (blankChar[this.content[++this.i]]) {
  804. ;
  805. }
  806. if (this.i < this.content.length && !this.checkClose()) {
  807. this.start = this.i;
  808. this.state = this.attrName;
  809. }
  810. } else if (!this.checkClose('onTagName')) this.i++;
  811. };
  812. /**
  813. * @description 属性名状态
  814. * @private
  815. */
  816. lexer.prototype.attrName = function () {
  817. var c = this.content[this.i];
  818. if (blankChar[c] || c == '=') {
  819. // 解析到属性名
  820. this.handler.onAttrName(this.content.substring(this.start, this.i));
  821. var needVal = c == '=',
  822. len = this.content.length;
  823. while (++this.i < len) {
  824. c = this.content[this.i];
  825. if (!blankChar[c]) {
  826. if (this.checkClose()) return;
  827. if (needVal) {
  828. // 等号后遇到第一个非空字符
  829. this.start = this.i;
  830. return this.state = this.attrVal;
  831. }
  832. if (this.content[this.i] == '=') needVal = true;else {
  833. this.start = this.i;
  834. return this.state = this.attrName;
  835. }
  836. }
  837. }
  838. } else if (!this.checkClose('onAttrName')) this.i++;
  839. };
  840. /**
  841. * @description 属性值状态
  842. * @private
  843. */
  844. lexer.prototype.attrVal = function () {
  845. var c = this.content[this.i],
  846. len = this.content.length; // 有冒号的属性
  847. if (c == '"' || c == "'") {
  848. this.start = ++this.i;
  849. this.i = this.content.indexOf(c, this.i);
  850. if (this.i == -1) return;
  851. this.handler.onAttrVal(this.content.substring(this.start, this.i));
  852. } // 没有冒号的属性
  853. else for (; this.i < len; this.i++) {
  854. if (blankChar[this.content[this.i]]) {
  855. this.handler.onAttrVal(this.content.substring(this.start, this.i));
  856. break;
  857. } else if (this.checkClose('onAttrVal')) return;
  858. }
  859. while (blankChar[this.content[++this.i]]) {
  860. ;
  861. }
  862. if (this.i < len && !this.checkClose()) {
  863. this.start = this.i;
  864. this.state = this.attrName;
  865. }
  866. };
  867. /**
  868. * @description 结束标签状态
  869. * @returns {String} 结束的标签名
  870. * @private
  871. */
  872. lexer.prototype.endTag = function () {
  873. var c = this.content[this.i];
  874. if (blankChar[c] || c == '>' || c == '/') {
  875. this.handler.onCloseTag(this.content.substring(this.start, this.i));
  876. if (c != '>') {
  877. this.i = this.content.indexOf('>', this.i);
  878. if (this.i == -1) return;
  879. }
  880. this.start = ++this.i;
  881. this.state = this.text;
  882. } else this.i++;
  883. };
  884. module.exports = parser;