parser.js 42 KB

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