ui.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import { router, t } from "@/.cool";
  2. import type { ClConfirmAction, ClConfirmOptions, ClToastOptions } from "../types";
  3. /**
  4. * UiInstance 类型定义
  5. * - showConfirm: 显示确认弹窗的方法
  6. * - showTips: 显示提示弹窗的方法
  7. */
  8. export type UiInstance = {
  9. /**
  10. * 显示确认弹窗
  11. * @param options ClConfirmOptions 弹窗配置项
  12. */
  13. showConfirm: (options: ClConfirmOptions) => void;
  14. /**
  15. * 显示提示弹窗
  16. * @param message 提示消息
  17. * @param callback 回调函数,参数为用户操作类型
  18. */
  19. showTips: (message: string, callback: (action: ClConfirmAction) => void) => void;
  20. /**
  21. * 显示提示弹窗
  22. * @param options ClToastOptions 弹窗配置项
  23. */
  24. showToast: (options: ClToastOptions) => void;
  25. };
  26. /**
  27. * 存储每个页面对应的 UiInstance 实例
  28. * key: 当前页面路由
  29. * value: UiInstance 实例
  30. */
  31. const list = new Map<string, UiInstance>();
  32. /**
  33. * Ui 类,提供全局弹窗调用能力
  34. */
  35. class Ui {
  36. /**
  37. * 获取当前页面的 UiInstance 实例
  38. * @returns UiInstance | undefined
  39. */
  40. getInstance() {
  41. return list.get(router.path());
  42. }
  43. /**
  44. * 显示确认弹窗
  45. * @param options ClConfirmOptions 弹窗配置项
  46. */
  47. showConfirm(options: ClConfirmOptions): void {
  48. const instance = this.getInstance();
  49. if (instance != null) {
  50. instance.showConfirm(options);
  51. }
  52. }
  53. /**
  54. * 显示提示弹窗
  55. * @param message 提示消息
  56. * @param callback 回调函数
  57. */
  58. showTips(message: string, callback: (action: ClConfirmAction) => void): void {
  59. const instance = this.getInstance();
  60. if (instance != null) {
  61. instance.showTips(message, callback);
  62. }
  63. }
  64. /**
  65. * 显示提示弹窗
  66. * @param options ClToastOptions 弹窗配置项
  67. */
  68. showToast(options: ClToastOptions): void {
  69. const instance = this.getInstance();
  70. if (instance != null) {
  71. instance.showToast(options);
  72. }
  73. }
  74. /**
  75. * 显示加载中弹窗
  76. * @param title 提示内容
  77. * @param mask 是否显示蒙层
  78. */
  79. showLoading(title: string | null = null, mask: boolean | null = null): void {
  80. uni.showLoading({
  81. title: title ?? t("加载中"),
  82. mask: mask ?? true
  83. });
  84. }
  85. /**
  86. * 隐藏加载中弹窗
  87. */
  88. hideLoading(): void {
  89. uni.hideLoading();
  90. }
  91. }
  92. /**
  93. * 获取 Ui 实例(始终返回同一个 Ui 实例)
  94. * @returns Ui
  95. */
  96. const ui = new Ui();
  97. export function useUi() {
  98. return ui;
  99. }
  100. /**
  101. * 注册当前页面的 UiInstance 实例
  102. * @param instance UiInstance
  103. */
  104. export function createUi(instance: UiInstance): void {
  105. list.set(router.path(), instance);
  106. }