useConfig.tsx 1.7 KB

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