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.

505 lines
13 KiB

5 months ago
  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.4.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: 'u-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. // #ifdef VUE2
  129. // beforeDestroy()
  130. // #endif
  131. // #ifdef VUE3
  132. beforeUnmount()
  133. // #endif
  134. {
  135. this._hook('onDetached')
  136. },
  137. methods: {
  138. /**
  139. * @description 将锚点跳转的范围限定在一个 scroll-view
  140. * @param {Object} page scroll-view 所在页面的示例
  141. * @param {String} selector scroll-view 的选择器
  142. * @param {String} scrollTop scroll-view scroll-top 属性绑定的变量名
  143. */
  144. in(page, selector, scrollTop) {
  145. // #ifndef APP-PLUS-NVUE
  146. if (page && selector && scrollTop) {
  147. this._in = {
  148. page,
  149. selector,
  150. scrollTop
  151. }
  152. }
  153. // #endif
  154. },
  155. /**
  156. * @description 锚点跳转
  157. * @param {String} id 要跳转的锚点 id
  158. * @param {Number} offset 跳转位置的偏移量
  159. * @returns {Promise}
  160. */
  161. navigateTo(id, offset) {
  162. return new Promise((resolve, reject) => {
  163. if (!this.useAnchor) {
  164. reject(Error('Anchor is disabled'))
  165. return
  166. }
  167. offset = offset || parseInt(this.useAnchor) || 0
  168. // #ifdef APP-PLUS-NVUE
  169. if (!id) {
  170. dom.scrollToElement(this.$refs.web, {
  171. offset
  172. })
  173. resolve()
  174. } else {
  175. this._navigateTo = {
  176. resolve,
  177. reject,
  178. offset
  179. }
  180. this.$refs.web.evalJs('uni.postMessage({data:{action:"getOffset",offset:(document.getElementById(' + id + ')||{}).offsetTop}})')
  181. }
  182. // #endif
  183. // #ifndef APP-PLUS-NVUE
  184. let deep = ' '
  185. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  186. deep = '>>>'
  187. // #endif
  188. const selector = uni.createSelectorQuery()
  189. // #ifndef MP-ALIPAY
  190. .in(this._in ? this._in.page : this)
  191. // #endif
  192. .select((this._in ? this._in.selector : '._root') + (id ? `${deep}#${id}` : '')).boundingClientRect()
  193. if (this._in) {
  194. selector.select(this._in.selector).scrollOffset()
  195. .select(this._in.selector).boundingClientRect()
  196. } else {
  197. // 获取 scroll-view 的位置和滚动距离
  198. selector.selectViewport().scrollOffset() // 获取窗口的滚动距离
  199. }
  200. selector.exec(res => {
  201. if (!res[0]) {
  202. reject(Error('Label not found'))
  203. return
  204. }
  205. const scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + offset
  206. if (this._in) {
  207. // scroll-view 跳转
  208. this._in.page[this._in.scrollTop] = scrollTop
  209. } else {
  210. // 页面跳转
  211. uni.pageScrollTo({
  212. scrollTop,
  213. duration: 300
  214. })
  215. }
  216. resolve()
  217. })
  218. // #endif
  219. })
  220. },
  221. /**
  222. * @description 获取文本内容
  223. * @return {String}
  224. */
  225. getText(nodes) {
  226. let text = '';
  227. (function traversal(nodes) {
  228. for (let i = 0; i < nodes.length; i++) {
  229. const node = nodes[i]
  230. if (node.type === 'text') {
  231. text += node.text.replace(/&amp;/g, '&')
  232. } else if (node.name === 'br') {
  233. text += '\n'
  234. } else {
  235. // 块级标签前后加换行
  236. 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')
  237. if (isBlock && text && text[text.length - 1] !== '\n') {
  238. text += '\n'
  239. }
  240. // 递归获取子节点的文本
  241. if (node.children) {
  242. traversal(node.children)
  243. }
  244. if (isBlock && text[text.length - 1] !== '\n') {
  245. text += '\n'
  246. } else if (node.name === 'td' || node.name === 'th') {
  247. text += '\t'
  248. }
  249. }
  250. }
  251. })(nodes || this.nodes)
  252. return text
  253. },
  254. /**
  255. * @description 获取内容大小和位置
  256. * @return {Promise}
  257. */
  258. getRect() {
  259. return new Promise((resolve, reject) => {
  260. uni.createSelectorQuery()
  261. // #ifndef MP-ALIPAY
  262. .in(this)
  263. // #endif
  264. .select('#_root').boundingClientRect().exec(res => res[0] ? resolve(res[0]) : reject(Error('Root label not found')))
  265. })
  266. },
  267. /**
  268. * @description 暂停播放媒体
  269. */
  270. pauseMedia() {
  271. for (let i = (this._videos || []).length; i--;) {
  272. this._videos[i].pause()
  273. }
  274. // #ifdef APP-PLUS
  275. const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].pause()'
  276. // #ifndef APP-PLUS-NVUE
  277. let page = this.$parent
  278. while (!page.$scope) page = page.$parent
  279. page.$scope.$getAppWebview().evalJS(command)
  280. // #endif
  281. // #ifdef APP-PLUS-NVUE
  282. this.$refs.web.evalJs(command)
  283. // #endif
  284. // #endif
  285. },
  286. /**
  287. * @description 设置媒体播放速率
  288. * @param {Number} rate 播放速率
  289. */
  290. setPlaybackRate(rate) {
  291. this.playbackRate = rate
  292. for (let i = (this._videos || []).length; i--;) {
  293. this._videos[i].playbackRate(rate)
  294. }
  295. // #ifdef APP-PLUS
  296. const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].playbackRate=' + rate
  297. // #ifndef APP-PLUS-NVUE
  298. let page = this.$parent
  299. while (!page.$scope) page = page.$parent
  300. page.$scope.$getAppWebview().evalJS(command)
  301. // #endif
  302. // #ifdef APP-PLUS-NVUE
  303. this.$refs.web.evalJs(command)
  304. // #endif
  305. // #endif
  306. },
  307. /**
  308. * @description 设置内容
  309. * @param {String} content html 内容
  310. * @param {Boolean} append 是否在尾部追加
  311. */
  312. setContent(content, append) {
  313. if (!append || !this.imgList) {
  314. this.imgList = []
  315. }
  316. const nodes = new Parser(this).parse(content)
  317. // #ifdef APP-PLUS-NVUE
  318. if (this._ready) {
  319. this._set(nodes, append)
  320. }
  321. // #endif
  322. this.$set(this, 'nodes', append ? (this.nodes || []).concat(nodes) : nodes)
  323. // #ifndef APP-PLUS-NVUE
  324. this._videos = []
  325. this.$nextTick(() => {
  326. this._hook('onLoad')
  327. this.$emit('load')
  328. })
  329. if (this.lazyLoad || this.imgList._unloadimgs < this.imgList.length / 2) {
  330. // 设置懒加载,每 350ms 获取高度,不变则认为加载完毕
  331. let height = 0
  332. const callback = rect => {
  333. if (!rect || !rect.height) rect = {}
  334. // 350ms 总高度无变化就触发 ready 事件
  335. if (rect.height === height) {
  336. this.$emit('ready', rect)
  337. } else {
  338. height = rect.height
  339. setTimeout(() => {
  340. this.getRect().then(callback).catch(callback)
  341. }, 350)
  342. }
  343. }
  344. this.getRect().then(callback).catch(callback)
  345. } else {
  346. // 未设置懒加载,等待所有图片加载完毕
  347. if (!this.imgList._unloadimgs) {
  348. this.getRect().then(rect => {
  349. this.$emit('ready', rect)
  350. }).catch(() => {
  351. this.$emit('ready', {})
  352. })
  353. }
  354. }
  355. // #endif
  356. },
  357. /**
  358. * @description 调用插件钩子函数
  359. */
  360. _hook(name) {
  361. for (let i = plugins.length; i--;) {
  362. if (this.plugins[i][name]) {
  363. this.plugins[i][name]()
  364. }
  365. }
  366. },
  367. // #ifdef APP-PLUS-NVUE
  368. /**
  369. * @description 设置内容
  370. */
  371. _set(nodes, append) {
  372. 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 + ')')
  373. },
  374. /**
  375. * @description 接收到 web-view 消息
  376. */
  377. _onMessage(e) {
  378. const message = e.detail.data[0]
  379. switch (message.action) {
  380. // web-view 初始化完毕
  381. case 'onJSBridgeReady':
  382. this._ready = true
  383. if (this.nodes) {
  384. this._set(this.nodes)
  385. }
  386. break
  387. // 内容 dom 加载完毕
  388. case 'onLoad':
  389. this.height = message.height
  390. this._hook('onLoad')
  391. this.$emit('load')
  392. break
  393. // 所有图片加载完毕
  394. case 'onReady':
  395. this.getRect().then(res => {
  396. this.$emit('ready', res)
  397. }).catch(() => {
  398. this.$emit('ready', {})
  399. })
  400. break
  401. // 总高度发生变化
  402. case 'onHeightChange':
  403. this.height = message.height
  404. break
  405. // 图片点击
  406. case 'onImgTap':
  407. this.$emit('imgTap', message.attrs)
  408. if (this.previewImg) {
  409. uni.previewImage({
  410. current: parseInt(message.attrs.i),
  411. urls: this.imgList
  412. })
  413. }
  414. break
  415. // 链接点击
  416. case 'onLinkTap': {
  417. const href = message.attrs.href
  418. this.$emit('linkTap', message.attrs)
  419. if (href) {
  420. // 锚点跳转
  421. if (href[0] === '#') {
  422. if (this.useAnchor) {
  423. dom.scrollToElement(this.$refs.web, {
  424. offset: message.offset
  425. })
  426. }
  427. } else if (href.includes('://')) {
  428. // 打开外链
  429. if (this.copyLink) {
  430. plus.runtime.openWeb(href)
  431. }
  432. } else {
  433. uni.navigateTo({
  434. url: href,
  435. fail() {
  436. uni.switchTab({
  437. url: href
  438. })
  439. }
  440. })
  441. }
  442. }
  443. break
  444. }
  445. case 'onPlay':
  446. this.$emit('play')
  447. break
  448. // 获取到锚点的偏移量
  449. case 'getOffset':
  450. if (typeof message.offset === 'number') {
  451. dom.scrollToElement(this.$refs.web, {
  452. offset: message.offset + this._navigateTo.offset
  453. })
  454. this._navigateTo.resolve()
  455. } else {
  456. this._navigateTo.reject(Error('Label not found'))
  457. }
  458. break
  459. // 点击
  460. case 'onClick':
  461. this.$emit('tap')
  462. this.$emit('click')
  463. break
  464. // 出错
  465. case 'onError':
  466. this.$emit('error', {
  467. source: message.source,
  468. attrs: message.attrs
  469. })
  470. }
  471. }
  472. // #endif
  473. }
  474. }
  475. </script>
  476. <style>
  477. /* #ifndef APP-PLUS-NVUE */
  478. /* 根节点样式 */
  479. ._root {
  480. padding: 1px 0;
  481. overflow-x: auto;
  482. overflow-y: hidden;
  483. -webkit-overflow-scrolling: touch;
  484. }
  485. /* 长按复制 */
  486. ._select {
  487. user-select: text;
  488. }
  489. /* #endif */
  490. </style>