page.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * 获取 tabBar 高度
  44. * @returns tabBar 高度
  45. */
  46. getTabBarHeight() {
  47. let h = ctx.tabBar.height == null ? 50 : getPx(ctx.tabBar.height!);
  48. if (this.hasCustomTabBar()) {
  49. h += this.getSafeAreaHeight("bottom");
  50. }
  51. return h;
  52. }
  53. /**
  54. * 获取安全区域高度
  55. * @param type 类型
  56. * @returns 安全区域高度
  57. */
  58. getSafeAreaHeight(type: "top" | "bottom") {
  59. const { safeAreaInsets } = uni.getWindowInfo();
  60. let h: number;
  61. if (type == "top") {
  62. h = safeAreaInsets.top;
  63. } else {
  64. h = safeAreaInsets.bottom;
  65. // #ifdef APP-ANDROID
  66. if (h == 0) {
  67. h = 16;
  68. }
  69. // #endif
  70. }
  71. return h;
  72. }
  73. }
  74. export const page = new Page();
  75. export function usePage(): Page {
  76. return page;
  77. }