parser.js 41 KB

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