parser.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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