mp-html.vue 15 KB

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