useConfig.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { ReactZoomPanPinchRef } from "react-zoom-pan-pinch";
  2. import { CanvasDirection } from "reaflow";
  3. import { defaultJson } from "src/constants/data";
  4. import create from "zustand";
  5. interface ConfigActions {
  6. setJson: (json: string) => void;
  7. setConfig: (key: keyof Config, value: unknown) => void;
  8. getJson: () => string;
  9. zoomIn: () => void;
  10. zoomOut: () => void;
  11. centerView: () => void;
  12. }
  13. const initialStates = {
  14. json: defaultJson,
  15. cursorMode: "move" as "move" | "navigation",
  16. layout: "RIGHT" as CanvasDirection,
  17. expand: true,
  18. hideEditor: false,
  19. performanceMode: true,
  20. disableLoading: false,
  21. zoomPanPinch: undefined as ReactZoomPanPinchRef | undefined,
  22. };
  23. export type Config = typeof initialStates;
  24. const useConfig = create<Config & ConfigActions>()((set, get) => ({
  25. ...initialStates,
  26. getJson: () => get().json,
  27. setJson: (json: string) => set({ json }),
  28. zoomIn: () => {
  29. const zoomPanPinch = get().zoomPanPinch;
  30. if (zoomPanPinch) {
  31. zoomPanPinch.setTransform(
  32. zoomPanPinch?.state.positionX,
  33. zoomPanPinch?.state.positionY,
  34. zoomPanPinch?.state.scale + 0.4
  35. );
  36. }
  37. },
  38. zoomOut: () => {
  39. const zoomPanPinch = get().zoomPanPinch;
  40. if (zoomPanPinch) {
  41. zoomPanPinch.setTransform(
  42. zoomPanPinch?.state.positionX,
  43. zoomPanPinch?.state.positionY,
  44. zoomPanPinch?.state.scale - 0.4
  45. );
  46. }
  47. },
  48. centerView: () => {
  49. const zoomPanPinch = get().zoomPanPinch;
  50. const canvas = document.querySelector(".jsoncrack-canvas") as HTMLElement;
  51. if (zoomPanPinch && canvas) zoomPanPinch.zoomToElement(canvas);
  52. },
  53. setConfig: (setting: keyof Config, value: unknown) => set({ [setting]: value }),
  54. }));
  55. export default useConfig;