parser.js 42 KB

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