parser.js 39 KB

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