u-parse.vue 13 KB

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