You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

535 regels
13 KiB

  1. <template>
  2. <view id="_root" :class="(selectable ? '_select ' : '') + '_root'" :style="containerStyle">
  3. <slot v-if="!nodes[0]" />
  4. <!-- #ifndef APP-PLUS-NVUE -->
  5. <node v-else :childs="nodes" :opts="[lazyLoad, loadingImg, errorImg, showImgMenu, selectable]" name="span" />
  6. <!-- #endif -->
  7. <!-- #ifdef APP-PLUS-NVUE -->
  8. <web-view ref="web" src="/static/app-plus/mp-html/local.html" :style="'margin-top:-2px;height:' + height + 'px'" @onPostMessage="_onMessage" />
  9. <!-- #endif -->
  10. </view>
  11. </template>
  12. <script>
  13. /**
  14. * mp-html v2.5.1
  15. * @description 富文本组件
  16. * @tutorial https://github.com/jin-yufeng/mp-html
  17. * @property {String} container-style 容器的样式
  18. * @property {String} content 用于渲染的 html 字符串
  19. * @property {Boolean} copy-link 是否允许外部链接被点击时自动复制
  20. * @property {String} domain 主域名,用于拼接链接
  21. * @property {String} error-img 图片出错时的占位图链接
  22. * @property {Boolean} lazy-load 是否开启图片懒加载
  23. * @property {string} loading-img 图片加载过程中的占位图链接
  24. * @property {Boolean} pause-video 是否在播放一个视频时自动暂停其他视频
  25. * @property {Boolean} preview-img 是否允许图片被点击时自动预览
  26. * @property {Boolean} scroll-table 是否给每个表格添加一个滚动层使其能单独横向滚动
  27. * @property {Boolean | String} selectable 是否开启长按复制
  28. * @property {Boolean} set-title 是否将 title 标签的内容设置到页面标题
  29. * @property {Boolean} show-img-menu 是否允许图片被长按时显示菜单
  30. * @property {Object} tag-style 标签的默认样式
  31. * @property {Boolean | Number} use-anchor 是否使用锚点链接
  32. * @event {Function} load dom 结构加载完毕时触发
  33. * @event {Function} ready 所有图片加载完毕时触发
  34. * @event {Function} imgtap 图片被点击时触发
  35. * @event {Function} linktap 链接被点击时触发
  36. * @event {Function} play 音视频播放时触发
  37. * @event {Function} error 媒体加载出错时触发
  38. */
  39. // #ifndef APP-PLUS-NVUE
  40. import node from './node/node'
  41. // #endif
  42. import Parser from './parser'
  43. const plugins = []
  44. // #ifdef APP-PLUS-NVUE
  45. const dom = weex.requireModule('dom')
  46. // #endif
  47. export default {
  48. name: 'up-parse',
  49. data() {
  50. return {
  51. nodes: [],
  52. // #ifdef APP-PLUS-NVUE
  53. height: 3
  54. // #endif
  55. }
  56. },
  57. props: {
  58. containerStyle: {
  59. type: String,
  60. default: ''
  61. },
  62. content: {
  63. type: String,
  64. default: ''
  65. },
  66. copyLink: {
  67. type: [Boolean, String],
  68. default: true
  69. },
  70. domain: String,
  71. errorImg: {
  72. type: String,
  73. default: ''
  74. },
  75. lazyLoad: {
  76. type: [Boolean, String],
  77. default: false
  78. },
  79. loadingImg: {
  80. type: String,
  81. default: ''
  82. },
  83. pauseVideo: {
  84. type: [Boolean, String],
  85. default: true
  86. },
  87. previewImg: {
  88. type: [Boolean, String],
  89. default: true
  90. },
  91. scrollTable: [Boolean, String],
  92. selectable: [Boolean, String],
  93. setTitle: {
  94. type: [Boolean, String],
  95. default: true
  96. },
  97. showImgMenu: {
  98. type: [Boolean, String],
  99. default: true
  100. },
  101. tagStyle: Object,
  102. useAnchor: [Boolean, Number]
  103. },
  104. // #ifdef VUE3
  105. emits: ['load', 'ready', 'imgtap', 'linktap', 'play', 'error'],
  106. // #endif
  107. // #ifndef APP-PLUS-NVUE
  108. components: {
  109. node
  110. },
  111. // #endif
  112. watch: {
  113. content(content) {
  114. this.setContent(content)
  115. }
  116. },
  117. created() {
  118. this.plugins = []
  119. for (let i = plugins.length; i--;) {
  120. this.plugins.push(new plugins[i](this))
  121. }
  122. },
  123. mounted() {
  124. if (this.content && !this.nodes.length) {
  125. this.setContent(this.content)
  126. }
  127. },
  128. beforeUnmount() {
  129. this._hook('onDetached')
  130. },
  131. methods: {
  132. /**
  133. * @description 规范化链接地址
  134. * @param {any} href
  135. * @return {String}
  136. */
  137. normalizeHref(href) {
  138. return typeof href === 'string' ? href.trim() : ''
  139. },
  140. /**
  141. * @description 判断是否为外部链接
  142. * @param {String} href
  143. * @return {Boolean}
  144. */
  145. isExternalLink(href) {
  146. return href.split('?')[0].includes('://')
  147. },
  148. /**
  149. * @description 打开外部链接
  150. * @param {String} href
  151. */
  152. openExternalLink(href) {
  153. // #ifdef APP-PLUS
  154. try {
  155. plus.runtime.openWeb(href)
  156. } catch (e) { }
  157. // #endif
  158. // #ifdef APP-HARMONY
  159. try {
  160. plus.runtime.openURL(href)
  161. } catch (e) { }
  162. // #endif
  163. },
  164. /**
  165. * @description 将锚点跳转的范围限定在一个 scroll-view 内
  166. * @param {Object} page scroll-view 所在页面的示例
  167. * @param {String} selector scroll-view 的选择器
  168. * @param {String} scrollTop scroll-view scroll-top 属性绑定的变量名
  169. */
  170. in(page, selector, scrollTop) {
  171. // #ifndef APP-PLUS-NVUE
  172. if (page && selector && scrollTop) {
  173. this._in = {
  174. page,
  175. selector,
  176. scrollTop
  177. }
  178. }
  179. // #endif
  180. },
  181. /**
  182. * @description 锚点跳转
  183. * @param {String} id 要跳转的锚点 id
  184. * @param {Number} offset 跳转位置的偏移量
  185. * @returns {Promise}
  186. */
  187. navigateTo(id, offset) {
  188. return new Promise((resolve, reject) => {
  189. if (!this.useAnchor) {
  190. reject(Error('Anchor is disabled'))
  191. return
  192. }
  193. offset = offset || parseInt(this.useAnchor) || 0
  194. // #ifdef APP-PLUS-NVUE
  195. if (!id) {
  196. dom.scrollToElement(this.$refs.web, {
  197. offset
  198. })
  199. resolve()
  200. } else {
  201. this._navigateTo = {
  202. resolve,
  203. reject,
  204. offset
  205. }
  206. this.$refs.web.evalJs('uni.postMessage({data:{action:"getOffset",offset:(document.getElementById(' + id + ')||{}).offsetTop}})')
  207. }
  208. // #endif
  209. // #ifndef APP-PLUS-NVUE
  210. let deep = ' '
  211. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  212. deep = '>>>'
  213. // #endif
  214. const selector = uni.createSelectorQuery()
  215. // #ifndef MP-ALIPAY
  216. .in(this._in ? this._in.page : this)
  217. // #endif
  218. .select((this._in ? this._in.selector : '._root') + (id ? `${deep}#${id}` : '')).boundingClientRect()
  219. if (this._in) {
  220. selector.select(this._in.selector).scrollOffset()
  221. .select(this._in.selector).boundingClientRect()
  222. } else {
  223. // 获取 scroll-view 的位置和滚动距离
  224. selector.selectViewport().scrollOffset() // 获取窗口的滚动距离
  225. }
  226. selector.exec(res => {
  227. if (!res[0]) {
  228. reject(Error('Label not found'))
  229. return
  230. }
  231. const scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + offset
  232. if (this._in) {
  233. // scroll-view 跳转
  234. this._in.page[this._in.scrollTop] = scrollTop
  235. } else {
  236. // 页面跳转
  237. uni.pageScrollTo({
  238. scrollTop,
  239. duration: 300
  240. })
  241. }
  242. resolve()
  243. })
  244. // #endif
  245. })
  246. },
  247. /**
  248. * @description 获取文本内容
  249. * @return {String}
  250. */
  251. getText(nodes) {
  252. let text = '';
  253. (function traversal(nodes) {
  254. for (let i = 0; i < nodes.length; i++) {
  255. const node = nodes[i]
  256. if (node.type === 'text') {
  257. text += node.text.replace(/&amp;/g, '&')
  258. } else if (node.name === 'br') {
  259. text += '\n'
  260. } else {
  261. // 块级标签前后加换行
  262. const isBlock = node.name === 'p' || node.name === 'div' || node.name === 'tr' || node.name === 'li' || (node.name[0] === 'h' && node.name[1] > '0' && node.name[1] < '7')
  263. if (isBlock && text && text[text.length - 1] !== '\n') {
  264. text += '\n'
  265. }
  266. // 递归获取子节点的文本
  267. if (node.children) {
  268. traversal(node.children)
  269. }
  270. if (isBlock && text[text.length - 1] !== '\n') {
  271. text += '\n'
  272. } else if (node.name === 'td' || node.name === 'th') {
  273. text += '\t'
  274. }
  275. }
  276. }
  277. })(nodes || this.nodes)
  278. return text
  279. },
  280. /**
  281. * @description 获取内容大小和位置
  282. * @return {Promise}
  283. */
  284. getRect() {
  285. return new Promise((resolve, reject) => {
  286. uni.createSelectorQuery()
  287. // #ifndef MP-ALIPAY
  288. .in(this)
  289. // #endif
  290. .select('#_root').boundingClientRect().exec(res => res[0] ? resolve(res[0]) : reject(Error('Root label not found')))
  291. })
  292. },
  293. /**
  294. * @description 暂停播放媒体
  295. */
  296. pauseMedia() {
  297. for (let i = (this._videos || []).length; i--;) {
  298. this._videos[i].pause()
  299. }
  300. // #ifdef APP-PLUS
  301. const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].pause()'
  302. // #ifndef APP-PLUS-NVUE
  303. let page = this.$parent
  304. while (!page.$scope) page = page.$parent
  305. page.$scope.$getAppWebview().evalJS(command)
  306. // #endif
  307. // #ifdef APP-PLUS-NVUE
  308. this.$refs.web.evalJs(command)
  309. // #endif
  310. // #endif
  311. },
  312. /**
  313. * @description 设置媒体播放速率
  314. * @param {Number} rate 播放速率
  315. */
  316. setPlaybackRate(rate) {
  317. this.playbackRate = rate
  318. for (let i = (this._videos || []).length; i--;) {
  319. this._videos[i].playbackRate(rate)
  320. }
  321. // #ifdef APP-PLUS
  322. const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].playbackRate=' + rate
  323. // #ifndef APP-PLUS-NVUE
  324. let page = this.$parent
  325. while (!page.$scope) page = page.$parent
  326. page.$scope.$getAppWebview().evalJS(command)
  327. // #endif
  328. // #ifdef APP-PLUS-NVUE
  329. this.$refs.web.evalJs(command)
  330. // #endif
  331. // #endif
  332. },
  333. /**
  334. * @description 设置内容
  335. * @param {String} content html 内容
  336. * @param {Boolean} append 是否在尾部追加
  337. */
  338. setContent(content, append) {
  339. if (!append || !this.imgList) {
  340. this.imgList = []
  341. }
  342. const nodes = new Parser(this).parse(content)
  343. // #ifdef APP-PLUS-NVUE
  344. if (this._ready) {
  345. this._set(nodes, append)
  346. }
  347. // #endif
  348. this.$set(this, 'nodes', append ? (this.nodes || []).concat(nodes) : nodes)
  349. // #ifndef APP-PLUS-NVUE
  350. this._videos = []
  351. this.$nextTick(() => {
  352. this._hook('onLoad')
  353. this.$emit('load')
  354. })
  355. if (this.lazyLoad || this.imgList._unloadimgs < this.imgList.length / 2) {
  356. // 设置懒加载,每 350ms 获取高度,不变则认为加载完毕
  357. let height = 0
  358. const callback = rect => {
  359. if (!rect || !rect.height) rect = {}
  360. // 350ms 总高度无变化就触发 ready 事件
  361. if (rect.height === height) {
  362. this.$emit('ready', rect)
  363. } else {
  364. height = rect.height
  365. setTimeout(() => {
  366. this.getRect().then(callback).catch(callback)
  367. }, 350)
  368. }
  369. }
  370. this.getRect().then(callback).catch(callback)
  371. } else {
  372. // 未设置懒加载,等待所有图片加载完毕
  373. if (!this.imgList._unloadimgs) {
  374. this.getRect().then(rect => {
  375. this.$emit('ready', rect)
  376. }).catch(() => {
  377. this.$emit('ready', {})
  378. })
  379. }
  380. }
  381. // #endif
  382. },
  383. /**
  384. * @description 调用插件钩子函数
  385. */
  386. _hook(name) {
  387. for (let i = plugins.length; i--;) {
  388. if (this.plugins[i][name]) {
  389. this.plugins[i][name]()
  390. }
  391. }
  392. },
  393. // #ifdef APP-PLUS-NVUE
  394. /**
  395. * @description 设置内容
  396. */
  397. _set(nodes, append) {
  398. this.$refs.web.evalJs('setContent(' + JSON.stringify(nodes).replace(/%22/g, '') + ',' + JSON.stringify([this.containerStyle.replace(/(?:margin|padding)[^;]+/g, ''), this.errorImg, this.loadingImg, this.pauseVideo, this.scrollTable, this.selectable]) + ',' + append + ')')
  399. },
  400. /**
  401. * @description 接收到 web-view 消息
  402. */
  403. _onMessage(e) {
  404. const message = e.detail.data[0]
  405. switch (message.action) {
  406. // web-view 初始化完毕
  407. case 'onJSBridgeReady':
  408. this._ready = true
  409. if (this.nodes) {
  410. this._set(this.nodes)
  411. }
  412. break
  413. // 内容 dom 加载完毕
  414. case 'onLoad':
  415. this.height = message.height
  416. this._hook('onLoad')
  417. this.$emit('load')
  418. break
  419. // 所有图片加载完毕
  420. case 'onReady':
  421. this.getRect().then(res => {
  422. this.$emit('ready', res)
  423. }).catch(() => {
  424. this.$emit('ready', {})
  425. })
  426. break
  427. // 总高度发生变化
  428. case 'onHeightChange':
  429. this.height = message.height
  430. break
  431. // 图片点击
  432. case 'onImgTap':
  433. this.$emit('imgtap', message.attrs)
  434. if (this.previewImg) {
  435. uni.previewImage({
  436. current: parseInt(message.attrs.i),
  437. urls: this.imgList
  438. })
  439. }
  440. break
  441. // 链接点击
  442. case 'onLinkTap': {
  443. const href = this.normalizeHref(message.attrs.href)
  444. this.$emit('linktap', message.attrs)
  445. if (href) {
  446. // 锚点跳转
  447. if (href[0] === '#') {
  448. if (this.useAnchor) {
  449. dom.scrollToElement(this.$refs.web, {
  450. offset: message.offset
  451. })
  452. }
  453. } else if (this.isExternalLink(href)) {
  454. // 打开外链
  455. if (this.copyLink) {
  456. this.openExternalLink(href)
  457. }
  458. } else {
  459. uni.navigateTo({
  460. url: href,
  461. fail() {
  462. uni.switchTab({
  463. url: href
  464. })
  465. }
  466. })
  467. }
  468. }
  469. break
  470. }
  471. case 'onPlay':
  472. this.$emit('play')
  473. break
  474. // 获取到锚点的偏移量
  475. case 'getOffset':
  476. if (typeof message.offset === 'number') {
  477. dom.scrollToElement(this.$refs.web, {
  478. offset: message.offset + this._navigateTo.offset
  479. })
  480. this._navigateTo.resolve()
  481. } else {
  482. this._navigateTo.reject(Error('Label not found'))
  483. }
  484. break
  485. // 点击
  486. case 'onClick':
  487. this.$emit('tap')
  488. this.$emit('click')
  489. break
  490. // 出错
  491. case 'onError':
  492. this.$emit('error', {
  493. source: message.source,
  494. attrs: message.attrs
  495. })
  496. }
  497. }
  498. // #endif
  499. }
  500. }
  501. </script>
  502. <style>
  503. /* #ifndef APP-PLUS-NVUE */
  504. /* 根节点样式 */
  505. ._root {
  506. padding: 1px 0;
  507. overflow-x: auto;
  508. overflow-y: hidden;
  509. -webkit-overflow-scrolling: touch;
  510. }
  511. /* 长按复制 */
  512. ._select {
  513. user-select: text;
  514. }
  515. /* #endif */
  516. </style>