parser.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /**
  2. * @fileoverview html 解析器
  3. */
  4. // 配置
  5. const config = {
  6. // 信任的标签(保持标签名不变)
  7. 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'),
  8. // 块级标签(转为 div,其他的非信任标签转为 span)
  9. blockTags: makeMap('address,article,aside,body,caption,center,cite,footer,header,html,nav,pre,section'),
  10. // #ifdef (MP-WEIXIN || MP-QQ || APP-PLUS || MP-360) && VUE3
  11. // 行内标签
  12. inlineTags: makeMap('abbr,b,big,code,del,em,i,ins,label,q,small,span,strong,sub,sup'),
  13. // #endif
  14. // 要移除的标签
  15. ignoreTags: makeMap('area,base,canvas,embed,frame,head,iframe,input,link,map,meta,param,rp,script,source,style,textarea,title,track,wbr'),
  16. // 自闭合的标签
  17. voidTags: makeMap('area,base,br,col,circle,ellipse,embed,frame,hr,img,input,line,link,meta,param,path,polygon,rect,source,track,use,wbr'),
  18. // html 实体
  19. entities: {
  20. lt: '<',
  21. gt: '>',
  22. quot: '"',
  23. apos: "'",
  24. ensp: '\u2002',
  25. emsp: '\u2003',
  26. nbsp: '\xA0',
  27. semi: ';',
  28. ndash: '–',
  29. mdash: '—',
  30. middot: '·',
  31. lsquo: '‘',
  32. rsquo: '’',
  33. ldquo: '“',
  34. rdquo: '”',
  35. bull: '•',
  36. hellip: '…',
  37. larr: '←',
  38. uarr: '↑',
  39. rarr: '→',
  40. darr: '↓'
  41. },
  42. // 默认的标签样式
  43. tagStyle: {
  44. // #ifndef APP-PLUS-NVUE
  45. address: 'font-style:italic',
  46. big: 'display:inline;font-size:1.2em',
  47. caption: 'display:table-caption;text-align:center',
  48. center: 'text-align:center',
  49. cite: 'font-style:italic',
  50. dd: 'margin-left:40px',
  51. mark: 'background-color:yellow',
  52. pre: 'font-family:monospace;white-space:pre',
  53. s: 'text-decoration:line-through',
  54. small: 'display:inline;font-size:0.8em',
  55. strike: 'text-decoration:line-through',
  56. u: 'text-decoration:underline'
  57. // #endif
  58. },
  59. // svg 大小写对照表
  60. svgDict: {
  61. animatetransform: 'animateTransform',
  62. lineargradient: 'linearGradient',
  63. viewbox: 'viewBox',
  64. attributename: 'attributeName',
  65. repeatcount: 'repeatCount',
  66. repeatdur: 'repeatDur'
  67. }
  68. }
  69. const tagSelector={}
  70. const {
  71. windowWidth,
  72. // #ifdef MP-WEIXIN
  73. system
  74. // #endif
  75. } = uni.getSystemInfoSync()
  76. const blankChar = makeMap(' ,\r,\n,\t,\f')
  77. let idIndex = 0
  78. // #ifdef H5 || APP-PLUS
  79. config.ignoreTags.iframe = undefined
  80. config.trustTags.iframe = true
  81. config.ignoreTags.embed = undefined
  82. config.trustTags.embed = true
  83. // #endif
  84. // #ifdef APP-PLUS-NVUE
  85. config.ignoreTags.source = undefined
  86. config.ignoreTags.style = undefined
  87. // #endif
  88. /**
  89. * @description 创建 map
  90. * @param {String} str 逗号分隔
  91. */
  92. function makeMap (str) {
  93. const map = Object.create(null)
  94. const list = str.split(',')
  95. for (let i = list.length; i--;) {
  96. map[list[i]] = true
  97. }
  98. return map
  99. }
  100. /**
  101. * @description 解码 html 实体
  102. * @param {String} str 要解码的字符串
  103. * @param {Boolean} amp 要不要解码 &amp;
  104. * @returns {String} 解码后的字符串
  105. */
  106. function decodeEntity (str, amp) {
  107. let i = str.indexOf('&')
  108. while (i !== -1) {
  109. const j = str.indexOf(';', i + 3)
  110. let code
  111. if (j === -1) break
  112. if (str[i + 1] === '#') {
  113. // &#123; 形式的实体
  114. code = parseInt((str[i + 2] === 'x' ? '0' : '') + str.substring(i + 2, j))
  115. if (!isNaN(code)) {
  116. str = str.substr(0, i) + String.fromCharCode(code) + str.substr(j + 1)
  117. }
  118. } else {
  119. // &nbsp; 形式的实体
  120. code = str.substring(i + 1, j)
  121. if (config.entities[code] || (code === 'amp' && amp)) {
  122. str = str.substr(0, i) + (config.entities[code] || '&') + str.substr(j + 1)
  123. }
  124. }
  125. i = str.indexOf('&', i + 1)
  126. }
  127. return str
  128. }
  129. /**
  130. * @description 合并多个块级标签,加快长内容渲染
  131. * @param {Array} nodes 要合并的标签数组
  132. */
  133. function mergeNodes (nodes) {
  134. let i = nodes.length - 1
  135. for (let j = i; j >= -1; j--) {
  136. if (j === -1 || nodes[j].c || !nodes[j].name || (nodes[j].name !== 'div' && nodes[j].name !== 'p' && nodes[j].name[0] !== 'h') || (nodes[j].attrs.style || '').includes('inline')) {
  137. if (i - j >= 5) {
  138. nodes.splice(j + 1, i - j, {
  139. name: 'div',
  140. attrs: {},
  141. children: nodes.slice(j + 1, i + 1)
  142. })
  143. }
  144. i = j - 1
  145. }
  146. }
  147. }
  148. /**
  149. * @description html 解析器
  150. * @param {Object} vm 组件实例
  151. */
  152. function Parser (vm) {
  153. this.options = vm || {}
  154. this.tagStyle = Object.assign({}, config.tagStyle, this.options.tagStyle)
  155. this.imgList = vm.imgList || []
  156. this.imgList._unloadimgs = 0
  157. this.plugins = vm.plugins || []
  158. this.attrs = Object.create(null)
  159. this.stack = []
  160. this.nodes = []
  161. this.pre = (this.options.containerStyle || '').includes('white-space') && this.options.containerStyle.includes('pre') ? 2 : 0
  162. }
  163. /**
  164. * @description 执行解析
  165. * @param {String} content 要解析的文本
  166. */
  167. Parser.prototype.parse = function (content) {
  168. // 插件处理
  169. for (let i = this.plugins.length; i--;) {
  170. if (this.plugins[i].onUpdate) {
  171. content = this.plugins[i].onUpdate(content, config) || content
  172. }
  173. }
  174. new Lexer(this).parse(content)
  175. // 出栈未闭合的标签
  176. while (this.stack.length) {
  177. this.popNode()
  178. }
  179. if (this.nodes.length > 50) {
  180. mergeNodes(this.nodes)
  181. }
  182. return this.nodes
  183. }
  184. /**
  185. * @description 将标签暴露出来(不被 rich-text 包含)
  186. */
  187. Parser.prototype.expose = function () {
  188. // #ifndef APP-PLUS-NVUE
  189. for (let i = this.stack.length; i--;) {
  190. const item = this.stack[i]
  191. if (item.c || item.name === 'a' || item.name === 'video' || item.name === 'audio') return
  192. item.c = 1
  193. }
  194. // #endif
  195. }
  196. /**
  197. * @description 处理插件
  198. * @param {Object} node 要处理的标签
  199. * @returns {Boolean} 是否要移除此标签
  200. */
  201. Parser.prototype.hook = function (node) {
  202. for (let i = this.plugins.length; i--;) {
  203. if (this.plugins[i].onParse && this.plugins[i].onParse(node, this) === false) {
  204. return false
  205. }
  206. }
  207. return true
  208. }
  209. /**
  210. * @description 将链接拼接上主域名
  211. * @param {String} url 需要拼接的链接
  212. * @returns {String} 拼接后的链接
  213. */
  214. Parser.prototype.getUrl = function (url) {
  215. if (url.startsWith('data:')) {
  216. var imgPath = uni.env.USER_DATA_PATH + '/e-invoice' + Date.parse(new Date()) + '.png';
  217. var imageData = url.replace(/^data:image\/\w+;base64,/, "");
  218. var fs = uni.getFileSystemManager();
  219. fs.writeFileSync(imgPath, imageData, "base64");
  220. fs.close();
  221. url = imgPath
  222. }
  223. const domain = this.options.domain
  224. if (url[0] === '/') {
  225. if (url[1] === '/') {
  226. // // 开头的补充协议名
  227. url = (domain ? domain.split('://')[0] : 'http') + ':' + url
  228. } else if (domain) {
  229. // 否则补充整个域名
  230. url = domain + url
  231. } /* #ifdef APP-PLUS */ else {
  232. url = plus.io.convertLocalFileSystemURL(url)
  233. } /* #endif */
  234. } else if (!url.includes('data:') && !url.includes('://')) {
  235. if (domain) {
  236. url = domain + '/' + url
  237. } /* #ifdef APP-PLUS */ else {
  238. url = plus.io.convertLocalFileSystemURL(url)
  239. } /* #endif */
  240. }
  241. return url
  242. }
  243. /**
  244. * @description 解析样式表
  245. * @param {Object} node 标签
  246. * @returns {Object}
  247. */
  248. Parser.prototype.parseStyle = function (node) {
  249. const attrs = node.attrs
  250. const list = (this.tagStyle[node.name] || '').split(';').concat((attrs.style || '').split(';'))
  251. const styleObj = {}
  252. let tmp = ''
  253. if (attrs.id && !this.xml) {
  254. // 暴露锚点
  255. if (this.options.useAnchor) {
  256. this.expose()
  257. } else if (node.name !== 'img' && node.name !== 'a' && node.name !== 'video' && node.name !== 'audio') {
  258. attrs.id = undefined
  259. }
  260. }
  261. // 转换 width 和 height 属性
  262. if (attrs.width) {
  263. styleObj.width = parseFloat(attrs.width) + (attrs.width.includes('%') ? '%' : 'px')
  264. attrs.width = undefined
  265. }
  266. if (attrs.height) {
  267. styleObj.height = parseFloat(attrs.height) + (attrs.height.includes('%') ? '%' : 'px')
  268. attrs.height = undefined
  269. }
  270. for (let i = 0, len = list.length; i < len; i++) {
  271. const info = list[i].split(':')
  272. if (info.length < 2) continue
  273. const key = info.shift().trim().toLowerCase()
  274. let value = info.join(':').trim()
  275. if ((value[0] === '-' && value.lastIndexOf('-') > 0) || value.includes('safe')) {
  276. // 兼容性的 css 不压缩
  277. tmp += `;${key}:${value}`
  278. } else if (!styleObj[key] || value.includes('import') || !styleObj[key].includes('import')) {
  279. // 重复的样式进行覆盖
  280. if (value.includes('url')) {
  281. // 填充链接
  282. let j = value.indexOf('(') + 1
  283. if (j) {
  284. while (value[j] === '"' || value[j] === "'" || blankChar[value[j]]) {
  285. j++
  286. }
  287. value = value.substr(0, j) + this.getUrl(value.substr(j))
  288. }
  289. } else if (value.includes('rpx')) {
  290. // 转换 rpx(rich-text 内部不支持 rpx)
  291. value = value.replace(/[0-9.]+\s*rpx/g, $ => parseFloat($) * windowWidth / 750 + 'px')
  292. }
  293. styleObj[key] = value
  294. }
  295. }
  296. node.attrs.style = tmp
  297. return styleObj
  298. }
  299. /**
  300. * @description 解析到标签名
  301. * @param {String} name 标签名
  302. * @private
  303. */
  304. Parser.prototype.onTagName = function (name) {
  305. this.tagName = this.xml ? name : name.toLowerCase()
  306. if (this.tagName === 'svg') {
  307. this.xml = (this.xml || 0) + 1 // svg 标签内大小写敏感
  308. config.ignoreTags.style = undefined // svg 标签内 style 可用
  309. }
  310. }
  311. /**
  312. * @description 解析到属性名
  313. * @param {String} name 属性名
  314. * @private
  315. */
  316. Parser.prototype.onAttrName = function (name) {
  317. name = this.xml ? name : name.toLowerCase()
  318. if (name.substr(0, 5) === 'data-') {
  319. if (name === 'data-src' && !this.attrs.src) {
  320. // data-src 自动转为 src
  321. this.attrName = 'src'
  322. } else if (this.tagName === 'img' || this.tagName === 'a') {
  323. // a 和 img 标签保留 data- 的属性,可以在 imgtap 和 linktap 事件中使用
  324. this.attrName = name
  325. } else {
  326. // 剩余的移除以减小大小
  327. this.attrName = undefined
  328. }
  329. } else {
  330. this.attrName = name
  331. this.attrs[name] = 'T' // boolean 型属性缺省设置
  332. }
  333. }
  334. /**
  335. * @description 解析到属性值
  336. * @param {String} val 属性值
  337. * @private
  338. */
  339. Parser.prototype.onAttrVal = function (val) {
  340. const name = this.attrName || ''
  341. if (name === 'style' || name === 'href') {
  342. // 部分属性进行实体解码
  343. this.attrs[name] = decodeEntity(val, true)
  344. } else if (name.includes('src')) {
  345. // 拼接主域名
  346. this.attrs[name] = this.getUrl(decodeEntity(val, true))
  347. } else if (name) {
  348. this.attrs[name] = val
  349. }
  350. }
  351. /**
  352. * @description 解析到标签开始
  353. * @param {Boolean} selfClose 是否有自闭合标识 />
  354. * @private
  355. */
  356. Parser.prototype.onOpenTag = function (selfClose) {
  357. // 拼装 node
  358. const node = Object.create(null)
  359. node.name = this.tagName
  360. node.attrs = this.attrs
  361. // 避免因为自动 diff 使得 type 被设置为 null 导致部分内容不显示
  362. if (this.options.nodes.length) {
  363. node.type = 'node'
  364. }
  365. this.attrs = Object.create(null)
  366. const attrs = node.attrs
  367. const parent = this.stack[this.stack.length - 1]
  368. const siblings = parent ? parent.children : this.nodes
  369. const close = this.xml ? selfClose : config.voidTags[node.name]
  370. // 替换标签名选择器
  371. if (tagSelector[node.name]) {
  372. attrs.class = tagSelector[node.name] + (attrs.class ? ' ' + attrs.class : '')
  373. }
  374. // 转换 embed 标签
  375. if (node.name === 'embed') {
  376. // #ifndef H5 || APP-PLUS
  377. const src = attrs.src || ''
  378. // 按照后缀名和 type 将 embed 转为 video 或 audio
  379. if (src.includes('.mp4') || src.includes('.3gp') || src.includes('.m3u8') || (attrs.type || '').includes('video')) {
  380. node.name = 'video'
  381. } else if (src.includes('.mp3') || src.includes('.wav') || src.includes('.aac') || src.includes('.m4a') || (attrs.type || '').includes('audio')) {
  382. node.name = 'audio'
  383. }
  384. if (attrs.autostart) {
  385. attrs.autoplay = 'T'
  386. }
  387. attrs.controls = 'T'
  388. // #endif
  389. // #ifdef H5 || APP-PLUS
  390. this.expose()
  391. // #endif
  392. }
  393. // #ifndef APP-PLUS-NVUE
  394. // 处理音视频
  395. if (node.name === 'video' || node.name === 'audio') {
  396. // 设置 id 以便获取 context
  397. if (node.name === 'video' && !attrs.id) {
  398. attrs.id = 'v' + idIndex++
  399. }
  400. // 没有设置 controls 也没有设置 autoplay 的自动设置 controls
  401. if (!attrs.controls && !attrs.autoplay) {
  402. attrs.controls = 'T'
  403. }
  404. // 用数组存储所有可用的 source
  405. node.src = []
  406. if (attrs.src) {
  407. node.src.push(attrs.src)
  408. attrs.src = undefined
  409. }
  410. this.expose()
  411. }
  412. // #endif
  413. // 处理自闭合标签
  414. if (close) {
  415. if (!this.hook(node) || config.ignoreTags[node.name]) {
  416. // 通过 base 标签设置主域名
  417. if (node.name === 'base' && !this.options.domain) {
  418. this.options.domain = attrs.href
  419. } /* #ifndef APP-PLUS-NVUE */ else if (node.name === 'source' && parent && (parent.name === 'video' || parent.name === 'audio') && attrs.src) {
  420. // 设置 source 标签(仅父节点为 video 或 audio 时有效)
  421. parent.src.push(attrs.src)
  422. } /* #endif */
  423. return
  424. }
  425. // 解析 style
  426. const styleObj = this.parseStyle(node)
  427. // 处理图片
  428. if (node.name === 'img') {
  429. if (attrs.src) {
  430. // 标记 webp
  431. if (attrs.src.includes('webp')) {
  432. node.webp = 'T'
  433. }
  434. // data url 图片如果没有设置 original-src 默认为不可预览的小图片
  435. if (attrs.src.includes('data:') && !attrs['original-src']) {
  436. attrs.ignore = 'T'
  437. }
  438. if (!attrs.ignore || node.webp || attrs.src.includes('cloud://')) {
  439. for (let i = this.stack.length; i--;) {
  440. const item = this.stack[i]
  441. if (item.name === 'a') {
  442. node.a = item.attrs
  443. }
  444. if (item.name === 'table' && !node.webp && !attrs.src.includes('cloud://')) {
  445. if (!styleObj.display || styleObj.display.includes('inline')) {
  446. node.t = 'inline-block'
  447. } else {
  448. node.t = styleObj.display
  449. }
  450. styleObj.display = undefined
  451. }
  452. // #ifndef H5 || APP-PLUS
  453. const style = item.attrs.style || ''
  454. if (style.includes('flex:') && !style.includes('flex:0') && !style.includes('flex: 0') && (!styleObj.width || parseInt(styleObj.width) > 100)) {
  455. styleObj.width = '100% !important'
  456. styleObj.height = ''
  457. for (let j = i + 1; j < this.stack.length; j++) {
  458. this.stack[j].attrs.style = (this.stack[j].attrs.style || '').replace('inline-', '')
  459. }
  460. } else if (style.includes('flex') && styleObj.width === '100%') {
  461. for (let j = i + 1; j < this.stack.length; j++) {
  462. const style = this.stack[j].attrs.style || ''
  463. if (!style.includes(';width') && !style.includes(' width') && style.indexOf('width') !== 0) {
  464. styleObj.width = ''
  465. break
  466. }
  467. }
  468. } else if (style.includes('inline-block')) {
  469. if (styleObj.width && styleObj.width[styleObj.width.length - 1] === '%') {
  470. item.attrs.style += ';max-width:' + styleObj.width
  471. styleObj.width = ''
  472. } else {
  473. item.attrs.style += ';max-width:100%'
  474. }
  475. }
  476. // #endif
  477. item.c = 1
  478. }
  479. attrs.i = this.imgList.length.toString()
  480. let src = attrs['original-src'] || attrs.src
  481. // #ifndef H5 || MP-ALIPAY || APP-PLUS || MP-360
  482. if (this.imgList.includes(src)) {
  483. // 如果有重复的链接则对域名进行随机大小写变换避免预览时错位
  484. let i = src.indexOf('://')
  485. if (i !== -1) {
  486. i += 3
  487. let newSrc = src.substr(0, i)
  488. for (; i < src.length; i++) {
  489. if (src[i] === '/') break
  490. newSrc += Math.random() > 0.5 ? src[i].toUpperCase() : src[i]
  491. }
  492. newSrc += src.substr(i)
  493. src = newSrc
  494. }
  495. }
  496. // #endif
  497. this.imgList.push(src)
  498. if (!node.t) {
  499. this.imgList._unloadimgs += 1
  500. }
  501. // #ifdef H5 || APP-PLUS
  502. if (this.options.lazyLoad) {
  503. attrs['data-src'] = attrs.src
  504. attrs.src = undefined
  505. }
  506. // #endif
  507. }
  508. }
  509. if (styleObj.display === 'inline') {
  510. styleObj.display = ''
  511. }
  512. // #ifndef APP-PLUS-NVUE
  513. if (attrs.ignore) {
  514. styleObj['max-width'] = styleObj['max-width'] || '100%'
  515. attrs.style += ';-webkit-touch-callout:none'
  516. }
  517. // #endif
  518. // 设置的宽度超出屏幕,为避免变形,高度转为自动
  519. if (parseInt(styleObj.width) > windowWidth) {
  520. styleObj.height = undefined
  521. }
  522. // 记录是否设置了宽高
  523. if (!isNaN(parseInt(styleObj.width))) {
  524. node.w = 'T'
  525. }
  526. if (!isNaN(parseInt(styleObj.height)) && (!styleObj.height.includes('%') || (parent && (parent.attrs.style || '').includes('height')))) {
  527. node.h = 'T'
  528. }
  529. } else if (node.name === 'svg') {
  530. siblings.push(node)
  531. this.stack.push(node)
  532. this.popNode()
  533. return
  534. }
  535. for (const key in styleObj) {
  536. if (styleObj[key]) {
  537. attrs.style += `;${key}:${styleObj[key].replace(' !important', '')}`
  538. }
  539. }
  540. attrs.style = attrs.style.substr(1) || undefined
  541. // #ifdef (MP-WEIXIN || MP-QQ) && VUE3
  542. if (!attrs.style) {
  543. delete attrs.style
  544. }
  545. // #endif
  546. } else {
  547. if ((node.name === 'pre' || ((attrs.style || '').includes('white-space') && attrs.style.includes('pre'))) && this.pre !== 2) {
  548. this.pre = node.pre = 1
  549. }
  550. node.children = []
  551. this.stack.push(node)
  552. }
  553. // 加入节点树
  554. siblings.push(node)
  555. }
  556. /**
  557. * @description 解析到标签结束
  558. * @param {String} name 标签名
  559. * @private
  560. */
  561. Parser.prototype.onCloseTag = function (name) {
  562. // 依次出栈到匹配为止
  563. name = this.xml ? name : name.toLowerCase()
  564. let i
  565. for (i = this.stack.length; i--;) {
  566. if (this.stack[i].name === name) break
  567. }
  568. if (i !== -1) {
  569. while (this.stack.length > i) {
  570. this.popNode()
  571. }
  572. } else if (name === 'p' || name === 'br') {
  573. const siblings = this.stack.length ? this.stack[this.stack.length - 1].children : this.nodes
  574. siblings.push({
  575. name,
  576. attrs: {
  577. class: tagSelector[name] || '',
  578. style: this.tagStyle[name] || ''
  579. }
  580. })
  581. }
  582. }
  583. /**
  584. * @description 处理标签出栈
  585. * @private
  586. */
  587. Parser.prototype.popNode = function () {
  588. const node = this.stack.pop()
  589. let attrs = node.attrs
  590. const children = node.children
  591. const parent = this.stack[this.stack.length - 1]
  592. const siblings = parent ? parent.children : this.nodes
  593. if (!this.hook(node) || config.ignoreTags[node.name]) {
  594. // 获取标题
  595. if (node.name === 'title' && children.length && children[0].type === 'text' && this.options.setTitle) {
  596. uni.setNavigationBarTitle({
  597. title: children[0].text
  598. })
  599. }
  600. siblings.pop()
  601. return
  602. }
  603. if (node.pre && this.pre !== 2) {
  604. // 是否合并空白符标识
  605. this.pre = node.pre = undefined
  606. for (let i = this.stack.length; i--;) {
  607. if (this.stack[i].pre) {
  608. this.pre = 1
  609. }
  610. }
  611. }
  612. const styleObj = {}
  613. // 转换 svg
  614. if (node.name === 'svg') {
  615. if (this.xml > 1) {
  616. // 多层 svg 嵌套
  617. this.xml--
  618. return
  619. }
  620. // #ifdef APP-PLUS-NVUE
  621. (function traversal (node) {
  622. if (node.name) {
  623. // 调整 svg 的大小写
  624. node.name = config.svgDict[node.name] || node.name
  625. for (const item in node.attrs) {
  626. if (config.svgDict[item]) {
  627. node.attrs[config.svgDict[item]] = node.attrs[item]
  628. node.attrs[item] = undefined
  629. }
  630. }
  631. for (let i = 0; i < (node.children || []).length; i++) {
  632. traversal(node.children[i])
  633. }
  634. }
  635. })(node)
  636. // #endif
  637. // #ifndef APP-PLUS-NVUE
  638. let src = ''
  639. const style = attrs.style
  640. attrs.style = ''
  641. attrs.xmlns = 'http://www.w3.org/2000/svg';
  642. (function traversal (node) {
  643. if (node.type === 'text') {
  644. src += node.text
  645. return
  646. }
  647. const name = config.svgDict[node.name] || node.name
  648. src += '<' + name
  649. for (const item in node.attrs) {
  650. const val = node.attrs[item]
  651. if (val) {
  652. src += ` ${config.svgDict[item] || item}="${val}"`
  653. }
  654. }
  655. if (!node.children) {
  656. src += '/>'
  657. } else {
  658. src += '>'
  659. for (let i = 0; i < node.children.length; i++) {
  660. traversal(node.children[i])
  661. }
  662. src += '</' + name + '>'
  663. }
  664. })(node)
  665. node.name = 'img'
  666. node.attrs = {
  667. src: 'data:image/svg+xml;utf8,' + src.replace(/#/g, '%23'),
  668. style,
  669. ignore: 'T'
  670. }
  671. node.children = undefined
  672. // #endif
  673. this.xml = false
  674. config.ignoreTags.style = true
  675. return
  676. }
  677. // #ifndef APP-PLUS-NVUE
  678. // 转换 align 属性
  679. if (attrs.align) {
  680. if (node.name === 'table') {
  681. if (attrs.align === 'center') {
  682. styleObj['margin-inline-start'] = styleObj['margin-inline-end'] = 'auto'
  683. } else {
  684. styleObj.float = attrs.align
  685. }
  686. } else {
  687. styleObj['text-align'] = attrs.align
  688. }
  689. attrs.align = undefined
  690. }
  691. // 转换 dir 属性
  692. if (attrs.dir) {
  693. styleObj.direction = attrs.dir
  694. attrs.dir = undefined
  695. }
  696. // 转换 font 标签的属性
  697. if (node.name === 'font') {
  698. if (attrs.color) {
  699. styleObj.color = attrs.color
  700. attrs.color = undefined
  701. }
  702. if (attrs.face) {
  703. styleObj['font-family'] = attrs.face
  704. attrs.face = undefined
  705. }
  706. if (attrs.size) {
  707. let size = parseInt(attrs.size)
  708. if (!isNaN(size)) {
  709. if (size < 1) {
  710. size = 1
  711. } else if (size > 7) {
  712. size = 7
  713. }
  714. styleObj['font-size'] = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'xxx-large'][size - 1]
  715. }
  716. attrs.size = undefined
  717. }
  718. }
  719. // #endif
  720. // 一些编辑器的自带 class
  721. if ((attrs.class || '').includes('align-center')) {
  722. styleObj['text-align'] = 'center'
  723. }
  724. Object.assign(styleObj, this.parseStyle(node))
  725. if (node.name !== 'table' && parseInt(styleObj.width) > windowWidth) {
  726. styleObj['max-width'] = '100%'
  727. styleObj['box-sizing'] = 'border-box'
  728. }
  729. // #ifndef APP-PLUS-NVUE
  730. if (config.blockTags[node.name]) {
  731. node.name = 'div'
  732. } else if (!config.trustTags[node.name] && !this.xml) {
  733. // 未知标签转为 span,避免无法显示
  734. node.name = 'span'
  735. }
  736. if (node.name === 'a' || node.name === 'ad'
  737. // #ifdef H5 || APP-PLUS
  738. || node.name === 'iframe' // eslint-disable-line
  739. // #endif
  740. ) {
  741. this.expose()
  742. } else if (node.name === 'video') {
  743. if ((styleObj.height || '').includes('auto')) {
  744. styleObj.height = undefined
  745. }
  746. /* #ifdef APP-PLUS */
  747. let str = '<video style="width:100%;height:100%"'
  748. for (const item in attrs) {
  749. if (attrs[item]) {
  750. str += ' ' + item + '="' + attrs[item] + '"'
  751. }
  752. }
  753. if (this.options.pauseVideo) {
  754. str += ' onplay="this.dispatchEvent(new CustomEvent(\'vplay\',{bubbles:!0}));for(var e=document.getElementsByTagName(\'video\'),t=0;t<e.length;t++)e[t]!=this&&e[t].pause()"'
  755. }
  756. str += '>'
  757. for (let i = 0; i < node.src.length; i++) {
  758. str += '<source src="' + node.src[i] + '">'
  759. }
  760. str += '</video>'
  761. node.html = str
  762. /* #endif */
  763. } else if ((node.name === 'ul' || node.name === 'ol') && node.c) {
  764. // 列表处理
  765. const types = {
  766. a: 'lower-alpha',
  767. A: 'upper-alpha',
  768. i: 'lower-roman',
  769. I: 'upper-roman'
  770. }
  771. if (types[attrs.type]) {
  772. attrs.style += ';list-style-type:' + types[attrs.type]
  773. attrs.type = undefined
  774. }
  775. for (let i = children.length; i--;) {
  776. if (children[i].name === 'li') {
  777. children[i].c = 1
  778. }
  779. }
  780. } else if (node.name === 'table') {
  781. // 表格处理
  782. // cellpadding、cellspacing、border 这几个常用表格属性需要通过转换实现
  783. let padding = parseFloat(attrs.cellpadding)
  784. let spacing = parseFloat(attrs.cellspacing)
  785. const border = parseFloat(attrs.border)
  786. const bordercolor = styleObj['border-color']
  787. const borderstyle = styleObj['border-style']
  788. if (node.c) {
  789. // padding 和 spacing 默认 2
  790. if (isNaN(padding)) {
  791. padding = 2
  792. }
  793. if (isNaN(spacing)) {
  794. spacing = 2
  795. }
  796. }
  797. if (border) {
  798. attrs.style += `;border:${border}px ${borderstyle || 'solid'} ${bordercolor || 'gray'}`
  799. }
  800. if (node.flag && node.c) {
  801. // 有 colspan 或 rowspan 且含有链接的表格通过 grid 布局实现
  802. styleObj.display = 'grid'
  803. if (spacing) {
  804. styleObj['grid-gap'] = spacing + 'px'
  805. styleObj.padding = spacing + 'px'
  806. } else if (border) {
  807. // 无间隔的情况下避免边框重叠
  808. attrs.style += ';border-left:0;border-top:0'
  809. }
  810. const width = [] // 表格的列宽
  811. const trList = [] // tr 列表
  812. const cells = [] // 保存新的单元格
  813. const map = {}; // 被合并单元格占用的格子
  814. (function traversal (nodes) {
  815. for (let i = 0; i < nodes.length; i++) {
  816. if (nodes[i].name === 'tr') {
  817. trList.push(nodes[i])
  818. } else {
  819. traversal(nodes[i].children || [])
  820. }
  821. }
  822. })(children)
  823. for (let row = 1; row <= trList.length; row++) {
  824. let col = 1
  825. for (let j = 0; j < trList[row - 1].children.length; j++) {
  826. const td = trList[row - 1].children[j]
  827. if (td.name === 'td' || td.name === 'th') {
  828. // 这个格子被上面的单元格占用,则列号++
  829. while (map[row + '.' + col]) {
  830. col++
  831. }
  832. let style = td.attrs.style || ''
  833. let start = style.indexOf('width') ? style.indexOf(';width') : 0
  834. // 提取出 td 的宽度
  835. if (start !== -1) {
  836. let end = style.indexOf(';', start + 6)
  837. if (end === -1) {
  838. end = style.length
  839. }
  840. if (!td.attrs.colspan) {
  841. width[col] = style.substring(start ? start + 7 : 6, end)
  842. }
  843. style = style.substr(0, start) + style.substr(end)
  844. }
  845. // 设置竖直对齐
  846. style += ';display:flex'
  847. start = style.indexOf('vertical-align')
  848. if (start !== -1) {
  849. const val = style.substr(start + 15, 10)
  850. if (val.includes('middle')) {
  851. style += ';align-items:center'
  852. } else if (val.includes('bottom')) {
  853. style += ';align-items:flex-end'
  854. }
  855. } else {
  856. style += ';align-items:center'
  857. }
  858. // 设置水平对齐
  859. start = style.indexOf('text-align')
  860. if (start !== -1) {
  861. const val = style.substr(start + 11, 10)
  862. if (val.includes('center')) {
  863. style += ';justify-content: center'
  864. } else if (val.includes('right')) {
  865. style += ';justify-content: right'
  866. }
  867. }
  868. style = (border ? `;border:${border}px ${borderstyle || 'solid'} ${bordercolor || 'gray'}` + (spacing ? '' : ';border-right:0;border-bottom:0') : '') + (padding ? `;padding:${padding}px` : '') + ';' + style
  869. // 处理列合并
  870. if (td.attrs.colspan) {
  871. style += `;grid-column-start:${col};grid-column-end:${col + parseInt(td.attrs.colspan)}`
  872. if (!td.attrs.rowspan) {
  873. style += `;grid-row-start:${row};grid-row-end:${row + 1}`
  874. }
  875. col += parseInt(td.attrs.colspan) - 1
  876. }
  877. // 处理行合并
  878. if (td.attrs.rowspan) {
  879. style += `;grid-row-start:${row};grid-row-end:${row + parseInt(td.attrs.rowspan)}`
  880. if (!td.attrs.colspan) {
  881. style += `;grid-column-start:${col};grid-column-end:${col + 1}`
  882. }
  883. // 记录下方单元格被占用
  884. for (let rowspan = 1; rowspan < td.attrs.rowspan; rowspan++) {
  885. for (let colspan = 0; colspan < (td.attrs.colspan || 1); colspan++) {
  886. map[(row + rowspan) + '.' + (col - colspan)] = 1
  887. }
  888. }
  889. }
  890. if (style) {
  891. td.attrs.style = style
  892. }
  893. cells.push(td)
  894. col++
  895. }
  896. }
  897. if (row === 1) {
  898. let temp = ''
  899. for (let i = 1; i < col; i++) {
  900. temp += (width[i] ? width[i] : 'auto') + ' '
  901. }
  902. styleObj['grid-template-columns'] = temp
  903. }
  904. }
  905. node.children = cells
  906. } else {
  907. // 没有使用合并单元格的表格通过 table 布局实现
  908. if (node.c) {
  909. styleObj.display = 'table'
  910. }
  911. if (!isNaN(spacing)) {
  912. styleObj['border-spacing'] = spacing + 'px'
  913. }
  914. if (border || padding) {
  915. // 遍历
  916. (function traversal (nodes) {
  917. for (let i = 0; i < nodes.length; i++) {
  918. const td = nodes[i]
  919. if (td.name === 'th' || td.name === 'td') {
  920. if (border) {
  921. td.attrs.style = `border:${border}px ${borderstyle || 'solid'} ${bordercolor || 'gray'};${td.attrs.style || ''}`
  922. }
  923. if (padding) {
  924. td.attrs.style = `padding:${padding}px;${td.attrs.style || ''}`
  925. }
  926. } else if (td.children) {
  927. traversal(td.children)
  928. }
  929. }
  930. })(children)
  931. }
  932. }
  933. // 给表格添加一个单独的横向滚动层
  934. if (this.options.scrollTable && !(attrs.style || '').includes('inline')) {
  935. const table = Object.assign({}, node)
  936. node.name = 'div'
  937. node.attrs = {
  938. style: 'overflow:auto'
  939. }
  940. node.children = [table]
  941. attrs = table.attrs
  942. }
  943. } else if ((node.name === 'td' || node.name === 'th') && (attrs.colspan || attrs.rowspan)) {
  944. for (let i = this.stack.length; i--;) {
  945. if (this.stack[i].name === 'table') {
  946. this.stack[i].flag = 1 // 指示含有合并单元格
  947. break
  948. }
  949. }
  950. } else if (node.name === 'ruby') {
  951. // 转换 ruby
  952. node.name = 'span'
  953. for (let i = 0; i < children.length - 1; i++) {
  954. if (children[i].type === 'text' && children[i + 1].name === 'rt') {
  955. children[i] = {
  956. name: 'div',
  957. attrs: {
  958. style: 'display:inline-block;text-align:center'
  959. },
  960. children: [{
  961. name: 'div',
  962. attrs: {
  963. style: 'font-size:50%;' + (children[i + 1].attrs.style || '')
  964. },
  965. children: children[i + 1].children
  966. }, children[i]]
  967. }
  968. children.splice(i + 1, 1)
  969. }
  970. }
  971. } else if (node.c) {
  972. (function traversal (node) {
  973. node.c = 2
  974. for (let i = node.children.length; i--;) {
  975. const child = node.children[i]
  976. // #ifdef (MP-WEIXIN || MP-QQ || APP-PLUS || MP-360) && VUE3
  977. if (child.name && (config.inlineTags[child.name] || ((child.attrs.style || '').includes('inline') && child.children)) && !child.c) {
  978. traversal(child)
  979. }
  980. // #endif
  981. if (!child.c || child.name === 'table') {
  982. node.c = 1
  983. }
  984. }
  985. })(node)
  986. }
  987. if ((styleObj.display || '').includes('flex') && !node.c) {
  988. for (let i = children.length; i--;) {
  989. const item = children[i]
  990. if (item.f) {
  991. item.attrs.style = (item.attrs.style || '') + item.f
  992. item.f = undefined
  993. }
  994. }
  995. }
  996. // flex 布局时部分样式需要提取到 rich-text 外层
  997. const flex = parent && ((parent.attrs.style || '').includes('flex') || (parent.attrs.style || '').includes('grid'))
  998. // #ifdef MP-WEIXIN
  999. // 检查基础库版本 virtualHost 是否可用
  1000. && !(node.c && wx.getNFCAdapter) // eslint-disable-line
  1001. // #endif
  1002. // #ifndef MP-WEIXIN || MP-QQ || MP-BAIDU || MP-TOUTIAO
  1003. && !node.c // eslint-disable-line
  1004. // #endif
  1005. if (flex) {
  1006. node.f = ';max-width:100%'
  1007. }
  1008. if (children.length >= 50 && node.c && !(styleObj.display || '').includes('flex')) {
  1009. mergeNodes(children)
  1010. }
  1011. // #endif
  1012. for (const key in styleObj) {
  1013. if (styleObj[key]) {
  1014. const val = `;${key}:${styleObj[key].replace(' !important', '')}`
  1015. /* #ifndef APP-PLUS-NVUE */
  1016. if (flex && ((key.includes('flex') && key !== 'flex-direction') || key === 'align-self' || key.includes('grid') || styleObj[key][0] === '-' || (key.includes('width') && val.includes('%')))) {
  1017. node.f += val
  1018. if (key === 'width') {
  1019. attrs.style += ';width:100%'
  1020. }
  1021. } else /* #endif */ {
  1022. attrs.style += val
  1023. }
  1024. }
  1025. }
  1026. attrs.style = attrs.style.substr(1) || undefined
  1027. // #ifdef (MP-WEIXIN || MP-QQ) && VUE3
  1028. for (const key in attrs) {
  1029. if (!attrs[key]) {
  1030. delete attrs[key]
  1031. }
  1032. }
  1033. // #endif
  1034. }
  1035. /**
  1036. * @description 解析到文本
  1037. * @param {String} text 文本内容
  1038. */
  1039. Parser.prototype.onText = function (text) {
  1040. if (!this.pre) {
  1041. // 合并空白符
  1042. let trim = ''
  1043. let flag
  1044. for (let i = 0, len = text.length; i < len; i++) {
  1045. if (!blankChar[text[i]]) {
  1046. trim += text[i]
  1047. } else {
  1048. if (trim[trim.length - 1] !== ' ') {
  1049. trim += ' '
  1050. }
  1051. if (text[i] === '\n' && !flag) {
  1052. flag = true
  1053. }
  1054. }
  1055. }
  1056. // 去除含有换行符的空串
  1057. if (trim === ' ') {
  1058. if (flag) return
  1059. // #ifdef VUE3
  1060. else {
  1061. const parent = this.stack[this.stack.length - 1]
  1062. if (parent && parent.name[0] === 't') return
  1063. }
  1064. // #endif
  1065. }
  1066. text = trim
  1067. }
  1068. const node = Object.create(null)
  1069. node.type = 'text'
  1070. // #ifdef (MP-BAIDU || MP-ALIPAY || MP-TOUTIAO) && VUE3
  1071. node.attrs = {}
  1072. // #endif
  1073. node.text = decodeEntity(text)
  1074. if (this.hook(node)) {
  1075. // #ifdef MP-WEIXIN
  1076. if (this.options.selectable === 'force' && system.includes('iOS') && !uni.canIUse('rich-text.user-select')) {
  1077. this.expose()
  1078. }
  1079. // #endif
  1080. const siblings = this.stack.length ? this.stack[this.stack.length - 1].children : this.nodes
  1081. siblings.push(node)
  1082. }
  1083. }
  1084. /**
  1085. * @description html 词法分析器
  1086. * @param {Object} handler 高层处理器
  1087. */
  1088. function Lexer (handler) {
  1089. this.handler = handler
  1090. }
  1091. /**
  1092. * @description 执行解析
  1093. * @param {String} content 要解析的文本
  1094. */
  1095. Lexer.prototype.parse = function (content) {
  1096. this.content = content || ''
  1097. this.i = 0 // 标记解析位置
  1098. this.start = 0 // 标记一个单词的开始位置
  1099. this.state = this.text // 当前状态
  1100. for (let len = this.content.length; this.i !== -1 && this.i < len;) {
  1101. this.state()
  1102. }
  1103. }
  1104. /**
  1105. * @description 检查标签是否闭合
  1106. * @param {String} method 如果闭合要进行的操作
  1107. * @returns {Boolean} 是否闭合
  1108. * @private
  1109. */
  1110. Lexer.prototype.checkClose = function (method) {
  1111. const selfClose = this.content[this.i] === '/'
  1112. if (this.content[this.i] === '>' || (selfClose && this.content[this.i + 1] === '>')) {
  1113. if (method) {
  1114. this.handler[method](this.content.substring(this.start, this.i))
  1115. }
  1116. this.i += selfClose ? 2 : 1
  1117. this.start = this.i
  1118. this.handler.onOpenTag(selfClose)
  1119. if (this.handler.tagName === 'script') {
  1120. this.i = this.content.indexOf('</', this.i)
  1121. if (this.i !== -1) {
  1122. this.i += 2
  1123. this.start = this.i
  1124. }
  1125. this.state = this.endTag
  1126. } else {
  1127. this.state = this.text
  1128. }
  1129. return true
  1130. }
  1131. return false
  1132. }
  1133. /**
  1134. * @description 文本状态
  1135. * @private
  1136. */
  1137. Lexer.prototype.text = function () {
  1138. this.i = this.content.indexOf('<', this.i) // 查找最近的标签
  1139. if (this.i === -1) {
  1140. // 没有标签了
  1141. if (this.start < this.content.length) {
  1142. this.handler.onText(this.content.substring(this.start, this.content.length))
  1143. }
  1144. return
  1145. }
  1146. const c = this.content[this.i + 1]
  1147. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
  1148. // 标签开头
  1149. if (this.start !== this.i) {
  1150. this.handler.onText(this.content.substring(this.start, this.i))
  1151. }
  1152. this.start = ++this.i
  1153. this.state = this.tagName
  1154. } else if (c === '/' || c === '!' || c === '?') {
  1155. if (this.start !== this.i) {
  1156. this.handler.onText(this.content.substring(this.start, this.i))
  1157. }
  1158. const next = this.content[this.i + 2]
  1159. if (c === '/' && ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
  1160. // 标签结尾
  1161. this.i += 2
  1162. this.start = this.i
  1163. this.state = this.endTag
  1164. return
  1165. }
  1166. // 处理注释
  1167. let end = '-->'
  1168. if (c !== '!' || this.content[this.i + 2] !== '-' || this.content[this.i + 3] !== '-') {
  1169. end = '>'
  1170. }
  1171. this.i = this.content.indexOf(end, this.i)
  1172. if (this.i !== -1) {
  1173. this.i += end.length
  1174. this.start = this.i
  1175. }
  1176. } else {
  1177. this.i++
  1178. }
  1179. }
  1180. /**
  1181. * @description 标签名状态
  1182. * @private
  1183. */
  1184. Lexer.prototype.tagName = function () {
  1185. if (blankChar[this.content[this.i]]) {
  1186. // 解析到标签名
  1187. this.handler.onTagName(this.content.substring(this.start, this.i))
  1188. while (blankChar[this.content[++this.i]]);
  1189. if (this.i < this.content.length && !this.checkClose()) {
  1190. this.start = this.i
  1191. this.state = this.attrName
  1192. }
  1193. } else if (!this.checkClose('onTagName')) {
  1194. this.i++
  1195. }
  1196. }
  1197. /**
  1198. * @description 属性名状态
  1199. * @private
  1200. */
  1201. Lexer.prototype.attrName = function () {
  1202. let c = this.content[this.i]
  1203. if (blankChar[c] || c === '=') {
  1204. // 解析到属性名
  1205. this.handler.onAttrName(this.content.substring(this.start, this.i))
  1206. let needVal = c === '='
  1207. const len = this.content.length
  1208. while (++this.i < len) {
  1209. c = this.content[this.i]
  1210. if (!blankChar[c]) {
  1211. if (this.checkClose()) return
  1212. if (needVal) {
  1213. // 等号后遇到第一个非空字符
  1214. this.start = this.i
  1215. this.state = this.attrVal
  1216. return
  1217. }
  1218. if (this.content[this.i] === '=') {
  1219. needVal = true
  1220. } else {
  1221. this.start = this.i
  1222. this.state = this.attrName
  1223. return
  1224. }
  1225. }
  1226. }
  1227. } else if (!this.checkClose('onAttrName')) {
  1228. this.i++
  1229. }
  1230. }
  1231. /**
  1232. * @description 属性值状态
  1233. * @private
  1234. */
  1235. Lexer.prototype.attrVal = function () {
  1236. const c = this.content[this.i]
  1237. const len = this.content.length
  1238. if (c === '"' || c === "'") {
  1239. // 有冒号的属性
  1240. this.start = ++this.i
  1241. this.i = this.content.indexOf(c, this.i)
  1242. if (this.i === -1) return
  1243. this.handler.onAttrVal(this.content.substring(this.start, this.i))
  1244. } else {
  1245. // 没有冒号的属性
  1246. for (; this.i < len; this.i++) {
  1247. if (blankChar[this.content[this.i]]) {
  1248. this.handler.onAttrVal(this.content.substring(this.start, this.i))
  1249. break
  1250. } else if (this.checkClose('onAttrVal')) return
  1251. }
  1252. }
  1253. while (blankChar[this.content[++this.i]]);
  1254. if (this.i < len && !this.checkClose()) {
  1255. this.start = this.i
  1256. this.state = this.attrName
  1257. }
  1258. }
  1259. /**
  1260. * @description 结束标签状态
  1261. * @returns {String} 结束的标签名
  1262. * @private
  1263. */
  1264. Lexer.prototype.endTag = function () {
  1265. const c = this.content[this.i]
  1266. if (blankChar[c] || c === '>' || c === '/') {
  1267. this.handler.onCloseTag(this.content.substring(this.start, this.i))
  1268. if (c !== '>') {
  1269. this.i = this.content.indexOf('>', this.i)
  1270. if (this.i === -1) return
  1271. }
  1272. this.start = ++this.i
  1273. this.state = this.text
  1274. } else {
  1275. this.i++
  1276. }
  1277. }
  1278. export default Parser