mp-html.vue 15 KB

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