mp-html.vue 12 KB

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