ui.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { router } 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. * 获取 Ui 实例(始终返回同一个 Ui 实例)
  77. * @returns Ui
  78. */
  79. const ui = new Ui();
  80. export function useUi() {
  81. return ui;
  82. }
  83. /**
  84. * 注册当前页面的 UiInstance 实例
  85. * @param instance UiInstance
  86. */
  87. export function createUi(instance: UiInstance): void {
  88. list.set(router.path(), instance);
  89. }