mp-html.vue 14 KB

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