index.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { Component, reactive } from "vue";
  2. import { DrawItem } from "../components";
  3. import { installGlobalVar } from "../hook/use-global-vars";
  4. import { useStoreRaw } from "./store";
  5. import { useHistory } from "../hook/use-history";
  6. import { round } from "@/utils/shared";
  7. // 放置重复放入历史,我们把小数保留5位小数
  8. const b = 3
  9. const normalStore = (store: any) => {
  10. const norStore = Array.isArray(store) ? [...store] : {...store}
  11. for (const key in norStore) {
  12. const val = norStore[key]
  13. if (typeof val === 'number') {
  14. norStore[key] = round(val, b)
  15. } else if (typeof val === 'object') {
  16. norStore[key] = normalStore(val)
  17. } else {
  18. norStore[key] = val
  19. }
  20. }
  21. return norStore
  22. }
  23. export const useStore = installGlobalVar(() => {
  24. const history = useHistory();
  25. const store = useStoreRaw();
  26. const trackActions = [
  27. "setStore",
  28. "repStore",
  29. "addItem",
  30. "delItem",
  31. "setItem",
  32. ];
  33. store.$onAction(({ name, after, store }) => {
  34. if (!trackActions.includes(name)) return;
  35. const isInit = name === "setStore";
  36. after(() => {
  37. if (isInit) {
  38. history.setInit(JSON.stringify(store.data));
  39. } else {
  40. history.push(JSON.stringify(store.data));
  41. }
  42. });
  43. });
  44. return store;
  45. }, Symbol("store"));
  46. export type DrawStore = ReturnType<typeof useStore>
  47. export const useStoreRenderProcessors = installGlobalVar(() => {
  48. type Processor<T extends DrawItem = DrawItem> = (data: T) => Component;
  49. const processors = reactive(new Map<Processor, DrawItem["id"][]>());
  50. const store = useStore();
  51. const result = {
  52. register<T extends DrawItem>(
  53. processor: Processor<T>,
  54. ids: DrawItem["id"][] = []
  55. ) {
  56. processors.set(processor as any, ids);
  57. return reactive(ids);
  58. },
  59. itemHasRegistor(id: DrawItem["id"]) {
  60. for (const ids of processors.values()) {
  61. if (ids.includes(id)) return true;
  62. }
  63. return false;
  64. },
  65. getProcessor(id: DrawItem["id"]) {
  66. for (const [p, ids] of processors.entries()) {
  67. if (ids.includes(id)) {
  68. return p;
  69. }
  70. }
  71. },
  72. renderer(id: DrawItem["id"]) {
  73. const processor = result.getProcessor(id);
  74. const item = store.items.find((item) => item.id === id);
  75. return processor && item && processor(item);
  76. },
  77. };
  78. return result;
  79. }, Symbol("storeRenderProcessors"));