3
0

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