mp-html.vue 15 KB

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