page.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { config } from "@/config";
  2. import { router } from "../router";
  3. import { getPx, isH5, isHarmony } from "../utils";
  4. import { ctx } from "../ctx";
  5. class Page {
  6. scrolls: Map<string, ((top: number) => void)[]> = new Map();
  7. path() {
  8. return router.path();
  9. }
  10. /**
  11. * 触发滚动事件
  12. * @param top 滚动距离
  13. */
  14. triggerScroll(top: number) {
  15. const callbacks = this.scrolls.get(this.path()) ?? [];
  16. callbacks.forEach((cb) => {
  17. cb(top);
  18. });
  19. }
  20. /**
  21. * 注册滚动事件回调
  22. * @param callback 回调函数
  23. */
  24. onPageScroll(callback: (top: number) => void) {
  25. const callbacks = this.scrolls.get(this.path()) ?? [];
  26. callbacks.push(callback);
  27. this.scrolls.set(this.path(), callbacks);
  28. }
  29. /**
  30. * 是否需要计算 tabBar 高度
  31. * @returns boolean
  32. */
  33. hasCustomTabBar() {
  34. if (router.isTabPage()) {
  35. if (isHarmony()) {
  36. return false;
  37. }
  38. return config.isCustomTabBar || isH5();
  39. }
  40. return false;
  41. }
  42. /**
  43. * 是否存在自定义 topbar
  44. * @returns boolean
  45. */
  46. hasCustomTopbar() {
  47. return router.route()?.isCustomNavbar ?? false;
  48. }
  49. /**
  50. * 获取 tabBar 高度
  51. * @returns tabBar 高度
  52. */
  53. getTabBarHeight() {
  54. let h = ctx.tabBar.height == null ? 50 : getPx(ctx.tabBar.height!);
  55. if (this.hasCustomTabBar()) {
  56. h += this.getSafeAreaHeight("bottom");
  57. }
  58. return h;
  59. }
  60. /**
  61. * 获取安全区域高度
  62. * @param type 类型
  63. * @returns 安全区域高度
  64. */
  65. getSafeAreaHeight(type: "top" | "bottom") {
  66. const { safeAreaInsets } = uni.getWindowInfo();
  67. let h: number;
  68. if (type == "top") {
  69. h = safeAreaInsets.top;
  70. } else {
  71. h = safeAreaInsets.bottom;
  72. // #ifdef APP-ANDROID
  73. if (h == 0) {
  74. h = 16;
  75. }
  76. // #endif
  77. }
  78. return h;
  79. }
  80. }
  81. export const page = new Page();
  82. export function usePage(): Page {
  83. return page;
  84. }