mp-html.vue 12 KB

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