mp-html.vue 12 KB

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