su-parse.vue 13 KB

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