parser.js 36 KB

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