mp-html.vue 14 KB

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