mp-html.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <template>
  2. <view id="_root" :class="(selectable?'_select ':'')+'_root'" :style="(editable?'min-height:200px;':'')+containerStyle" @tap="_containTap">
  3. <slot v-if="!nodes[0]" />
  4. <!-- #ifndef APP-PLUS-NVUE -->
  5. <node v-else :childs="nodes" :opts="[lazyLoad,loadingImg,errorImg,showImgMenu,selectable,editable,placeholder,'nodes']" 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 v-if="tooltip" class="_tooltip_contain" :style="'top:'+tooltip.top+'px'">
  11. <view class="_tooltip">
  12. <view v-for="(item, index) in tooltip.items" v-bind:key="index" class="_tooltip_item" :data-i="index" @tap="_tooltipTap">{{item}}</view>
  13. </view>
  14. </view>
  15. <view v-if="slider" class="_slider" :style="'top:'+slider.top+'px'">
  16. <slider :value="slider.value" :min="slider.min" :max="slider.max" handle-size="14" block-size="14" show-value activeColor="white" style="padding:3px" @changing="_sliderChanging" @change="_sliderChange" />
  17. </view>
  18. </view>
  19. </template>
  20. <script>
  21. /**
  22. * mp-html v2.3.2
  23. * @description 富文本组件
  24. * @tutorial https://github.com/jin-yufeng/mp-html
  25. * @property {String} container-style 容器的样式
  26. * @property {String} content 用于渲染的 html 字符串
  27. * @property {Boolean} copy-link 是否允许外部链接被点击时自动复制
  28. * @property {String} domain 主域名,用于拼接链接
  29. * @property {String} error-img 图片出错时的占位图链接
  30. * @property {Boolean} lazy-load 是否开启图片懒加载
  31. * @property {string} loading-img 图片加载过程中的占位图链接
  32. * @property {Boolean} pause-video 是否在播放一个视频时自动暂停其他视频
  33. * @property {Boolean} preview-img 是否允许图片被点击时自动预览
  34. * @property {Boolean} scroll-table 是否给每个表格添加一个滚动层使其能单独横向滚动
  35. * @property {Boolean | String} selectable 是否开启长按复制
  36. * @property {Boolean} set-title 是否将 title 标签的内容设置到页面标题
  37. * @property {Boolean} show-img-menu 是否允许图片被长按时显示菜单
  38. * @property {Object} tag-style 标签的默认样式
  39. * @property {Boolean | Number} use-anchor 是否使用锚点链接
  40. * @event {Function} load dom 结构加载完毕时触发
  41. * @event {Function} ready 所有图片加载完毕时触发
  42. * @event {Function} imgtap 图片被点击时触发
  43. * @event {Function} linktap 链接被点击时触发
  44. * @event {Function} play 音视频播放时触发
  45. * @event {Function} error 媒体加载出错时触发
  46. */
  47. // #ifndef APP-PLUS-NVUE
  48. import node from './node/node'
  49. // #endif
  50. import Parser from './parser'
  51. import editable from './editable/index.js'
  52. const plugins=[editable,]
  53. // #ifdef APP-PLUS-NVUE
  54. const dom = weex.requireModule('dom')
  55. // #endif
  56. export default {
  57. name: 'mp-html',
  58. data() {
  59. return {
  60. tooltip: null,
  61. slider: null,
  62. nodes: [],
  63. // #ifdef APP-PLUS-NVUE
  64. height: 3
  65. // #endif
  66. }
  67. },
  68. props: {
  69. editable: Boolean,
  70. placeholder: String,
  71. containerStyle: {
  72. type: String,
  73. default: ''
  74. },
  75. content: {
  76. type: String,
  77. default: ''
  78. },
  79. copyLink: {
  80. type: [Boolean, String],
  81. default: true
  82. },
  83. domain: String,
  84. errorImg: {
  85. type: String,
  86. default: ''
  87. },
  88. lazyLoad: {
  89. type: [Boolean, String],
  90. default: false
  91. },
  92. loadingImg: {
  93. type: String,
  94. default: ''
  95. },
  96. pauseVideo: {
  97. type: [Boolean, String],
  98. default: true
  99. },
  100. previewImg: {
  101. type: [Boolean, String],
  102. default: true
  103. },
  104. scrollTable: [Boolean, String],
  105. selectable: [Boolean, String],
  106. setTitle: {
  107. type: [Boolean, String],
  108. default: true
  109. },
  110. showImgMenu: {
  111. type: [Boolean, String],
  112. default: true
  113. },
  114. tagStyle: Object,
  115. useAnchor: [Boolean, Number]
  116. },
  117. // #ifdef VUE3
  118. emits: ['load', 'ready', 'imgtap', 'linktap', 'play', 'error'],
  119. // #endif
  120. // #ifndef APP-PLUS-NVUE
  121. components: {
  122. node
  123. },
  124. // #endif
  125. watch: {
  126. editable(val) {
  127. this.setContent(val ? this.content : this.getContent())
  128. if (!val)
  129. this._maskTap()
  130. },
  131. content (content) {
  132. this.setContent(content)
  133. }
  134. },
  135. created () {
  136. this.plugins = []
  137. for (let i = plugins.length; i--;) {
  138. this.plugins.push(new plugins[i](this))
  139. }
  140. },
  141. mounted () {
  142. if ((this.content || this.editable) && !this.nodes.length) {
  143. this.setContent(this.content)
  144. }
  145. },
  146. beforeDestroy () {
  147. this._hook('onDetached')
  148. clearInterval(this._timer)
  149. },
  150. methods: {
  151. _containTap() {
  152. if (!this._lock && !this.slider) {
  153. this._edit = undefined
  154. this._maskTap()
  155. }
  156. },
  157. _tooltipTap(e) {
  158. this._tooltipcb(e.currentTarget.dataset.i)
  159. this.$set(this, 'tooltip', null)
  160. },
  161. _sliderChanging(e) {
  162. this._slideringcb(e.detail.value)
  163. },
  164. _sliderChange(e) {
  165. this._slidercb(e.detail.value)
  166. },
  167. /**
  168. * @description 将锚点跳转的范围限定在一个 scroll-view 内
  169. * @param {Object} page scroll-view 所在页面的示例
  170. * @param {String} selector scroll-view 的选择器
  171. * @param {String} scrollTop scroll-view scroll-top 属性绑定的变量名
  172. */
  173. in (page, selector, scrollTop) {
  174. // #ifndef APP-PLUS-NVUE
  175. if (page && selector && scrollTop) {
  176. this._in = {
  177. page,
  178. selector,
  179. scrollTop
  180. }
  181. }
  182. // #endif
  183. },
  184. /**
  185. * @description 锚点跳转
  186. * @param {String} id 要跳转的锚点 id
  187. * @param {Number} offset 跳转位置的偏移量
  188. * @returns {Promise}
  189. */
  190. navigateTo (id, offset) {
  191. return new Promise((resolve, reject) => {
  192. if (!this.useAnchor) {
  193. reject(Error('Anchor is disabled'))
  194. return
  195. }
  196. offset = offset || parseInt(this.useAnchor) || 0
  197. // #ifdef APP-PLUS-NVUE
  198. if (!id) {
  199. dom.scrollToElement(this.$refs.web, {
  200. offset
  201. })
  202. resolve()
  203. } else {
  204. this._navigateTo = {
  205. resolve,
  206. reject,
  207. offset
  208. }
  209. this.$refs.web.evalJs('uni.postMessage({data:{action:"getOffset",offset:(document.getElementById(' + id + ')||{}).offsetTop}})')
  210. }
  211. // #endif
  212. // #ifndef APP-PLUS-NVUE
  213. let deep = ' '
  214. // #ifdef MP-WEIXIN || MP-QQ || MP-TOUTIAO
  215. deep = '>>>'
  216. // #endif
  217. const selector = uni.createSelectorQuery()
  218. // #ifndef MP-ALIPAY
  219. .in(this._in ? this._in.page : this)
  220. // #endif
  221. .select((this._in ? this._in.selector : '._root') + (id ? `${deep}#${id}` : '')).boundingClientRect()
  222. if (this._in) {
  223. selector.select(this._in.selector).scrollOffset()
  224. .select(this._in.selector).boundingClientRect()
  225. } else {
  226. // 获取 scroll-view 的位置和滚动距离
  227. selector.selectViewport().scrollOffset() // 获取窗口的滚动距离
  228. }
  229. selector.exec(res => {
  230. if (!res[0]) {
  231. reject(Error('Label not found'))
  232. return
  233. }
  234. const scrollTop = res[1].scrollTop + res[0].top - (res[2] ? res[2].top : 0) + offset
  235. if (this._in) {
  236. // scroll-view 跳转
  237. this._in.page[this._in.scrollTop] = scrollTop
  238. } else {
  239. // 页面跳转
  240. uni.pageScrollTo({
  241. scrollTop,
  242. duration: 300
  243. })
  244. }
  245. resolve()
  246. })
  247. // #endif
  248. })
  249. },
  250. /**
  251. * @description 获取文本内容
  252. * @return {String}
  253. */
  254. getText (nodes) {
  255. let text = '';
  256. (function traversal (nodes) {
  257. for (let i = 0; i < nodes.length; i++) {
  258. const node = nodes[i]
  259. if (node.type === 'text') {
  260. text += node.text.replace(/&amp;/g, '&')
  261. } else if (node.name === 'br') {
  262. text += '\n'
  263. } else {
  264. // 块级标签前后加换行
  265. 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')
  266. if (isBlock && text && text[text.length - 1] !== '\n') {
  267. text += '\n'
  268. }
  269. // 递归获取子节点的文本
  270. if (node.children) {
  271. traversal(node.children)
  272. }
  273. if (isBlock && text[text.length - 1] !== '\n') {
  274. text += '\n'
  275. } else if (node.name === 'td' || node.name === 'th') {
  276. text += '\t'
  277. }
  278. }
  279. }
  280. })(nodes || this.nodes)
  281. return text
  282. },
  283. /**
  284. * @description 获取内容大小和位置
  285. * @return {Promise}
  286. */
  287. getRect () {
  288. return new Promise((resolve, reject) => {
  289. uni.createSelectorQuery()
  290. // #ifndef MP-ALIPAY
  291. .in(this)
  292. // #endif
  293. .select('#_root').boundingClientRect().exec(res => res[0] ? resolve(res[0]) : reject(Error('Root label not found')))
  294. })
  295. },
  296. /**
  297. * @description 暂停播放媒体
  298. */
  299. pauseMedia () {
  300. for (let i = (this._videos || []).length; i--;) {
  301. this._videos[i].pause()
  302. }
  303. // #ifdef APP-PLUS
  304. const command = 'for(var e=document.getElementsByTagName("video"),i=e.length;i--;)e[i].pause()'
  305. // #ifndef APP-PLUS-NVUE
  306. let page = this.$parent
  307. while (!page.$scope) page = page.$parent
  308. page.$scope.$getAppWebview().evalJS(command)
  309. // #endif
  310. // #ifdef APP-PLUS-NVUE
  311. this.$refs.web.evalJs(command)
  312. // #endif
  313. // #endif
  314. },
  315. /**
  316. * @description 设置内容
  317. * @param {String} content html 内容
  318. * @param {Boolean} append 是否在尾部追加
  319. */
  320. setContent (content, append) {
  321. if (!append || !this.imgList) {
  322. this.imgList = []
  323. }
  324. const nodes = new Parser(this).parse(content)
  325. // #ifdef APP-PLUS-NVUE
  326. if (this._ready) {
  327. this._set(nodes, append)
  328. }
  329. // #endif
  330. this.$set(this, 'nodes', append ? (this.nodes || []).concat(nodes) : nodes)
  331. // #ifndef APP-PLUS-NVUE
  332. this._videos = []
  333. this.$nextTick(() => {
  334. this._hook('onLoad')
  335. this.$emit('load')
  336. })
  337. // 等待图片加载完毕
  338. let height
  339. clearInterval(this._timer)
  340. this._timer = setInterval(() => {
  341. this.getRect().then(rect => {
  342. // 350ms 总高度无变化就触发 ready 事件
  343. if (rect.height === height) {
  344. this.$emit('ready', rect)
  345. clearInterval(this._timer)
  346. }
  347. height = rect.height
  348. }).catch(() => { })
  349. }, 350)
  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. /* 提示条 */
  484. ._tooltip_contain {
  485. position: absolute;
  486. right: 20px;
  487. left: 20px;
  488. text-align: center;
  489. }
  490. ._tooltip {
  491. box-sizing: border-box;
  492. display: inline-block;
  493. width: auto;
  494. max-width: 100%;
  495. height: 30px;
  496. padding: 0 3px;
  497. overflow: scroll;
  498. font-size: 14px;
  499. line-height: 30px;
  500. white-space: nowrap;
  501. }
  502. ._tooltip_item {
  503. display: inline-block;
  504. width: auto;
  505. padding: 0 2vw;
  506. line-height: 30px;
  507. background-color: black;
  508. color: white;
  509. }
  510. /* 图片宽度滚动条 */
  511. ._slider {
  512. position: absolute;
  513. left: 20px;
  514. width: 220px;
  515. }
  516. ._tooltip,
  517. ._slider {
  518. background-color: black;
  519. border-radius: 3px;
  520. opacity: 0.75;
  521. }
  522. </style>