forked from AykutSarac/jsoncrack.com
-
Notifications
You must be signed in to change notification settings - Fork 338
Expand file tree
/
Copy pathuseGraph.ts
More file actions
167 lines (153 loc) · 5.32 KB
/
useGraph.ts
File metadata and controls
167 lines (153 loc) · 5.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import type { ViewPort } from "react-zoomable-ui/dist/ViewPort";
import type { CanvasDirection } from "reaflow/dist/layout/elkLayout";
import { create } from "zustand";
import { toast } from "react-hot-toast";
import { SUPPORTED_LIMIT } from "../../../../../constants/graph";
import useJson from "../../../../../store/useJson";
import type { EdgeData, NodeData } from "../../../../../types/graph";
import { parser } from "../lib/jsonParser";
export interface Graph {
viewPort: ViewPort | null;
direction: CanvasDirection;
loading: boolean;
fullscreen: boolean;
nodes: NodeData[];
edges: EdgeData[];
selectedNode: NodeData | null;
path: string;
aboveSupportedLimit: boolean;
}
const initialStates: Graph = {
viewPort: null,
direction: "RIGHT",
loading: true,
fullscreen: false,
nodes: [],
edges: [],
selectedNode: null,
path: "",
aboveSupportedLimit: false,
};
interface GraphActions {
setGraph: (json?: string, options?: Partial<Graph>[]) => void;
setLoading: (loading: boolean) => void;
setDirection: (direction: CanvasDirection) => void;
setViewPort: (ref: ViewPort) => void;
setSelectedNode: (nodeData: NodeData) => void;
focusFirstNode: () => void;
toggleFullscreen: (value: boolean) => void;
zoomIn: () => void;
zoomOut: () => void;
centerView: () => void;
clearGraph: () => void;
setZoomFactor: (zoomFactor: number) => void;
updateNode: (updatedNode: NodeData) => Promise<void>;
}
const useGraph = create<Graph & GraphActions>((set, get) => ({
...initialStates,
clearGraph: () => set({ nodes: [], edges: [], loading: false }),
setSelectedNode: nodeData => set({ selectedNode: nodeData }),
setGraph: (data, options) => {
const { nodes, edges } = parser(data ?? useJson.getState().json);
if (nodes.length > SUPPORTED_LIMIT) {
return set({
aboveSupportedLimit: true,
...options,
loading: false,
});
}
set({
nodes,
edges,
aboveSupportedLimit: false,
...options,
});
},
setDirection: (direction = "RIGHT") => {
set({ direction });
setTimeout(() => get().centerView(), 200);
},
setLoading: loading => set({ loading }),
focusFirstNode: () => {
const rootNode = document.querySelector("g[id$='node-1']");
get().viewPort?.camera?.centerFitElementIntoView(rootNode as HTMLElement, {
elementExtraMarginForZoom: 100,
});
},
setZoomFactor: zoomFactor => {
const viewPort = get().viewPort;
viewPort?.camera?.recenter(viewPort.centerX, viewPort.centerY, zoomFactor);
},
zoomIn: () => {
const viewPort = get().viewPort;
viewPort?.camera?.recenter(viewPort.centerX, viewPort.centerY, viewPort.zoomFactor + 0.1);
},
zoomOut: () => {
const viewPort = get().viewPort;
viewPort?.camera?.recenter(viewPort.centerX, viewPort.centerY, viewPort.zoomFactor - 0.1);
},
centerView: () => {
const viewPort = get().viewPort;
viewPort?.updateContainerSize();
const canvas = document.querySelector(".jsoncrack-canvas") as HTMLElement | null;
if (canvas) {
viewPort?.camera?.centerFitElementIntoView(canvas);
}
},
toggleFullscreen: fullscreen => set({ fullscreen }),
setViewPort: viewPort => set({ viewPort }),
updateNode: async updatedNode => {
try {
// Get the current JSON
const currentJson = JSON.parse(useJson.getState().json);
// Update the JSON at the node's path
let current = currentJson;
const path = updatedNode.path || [];
// Navigate to the parent object
for (let i = 0; i < path.length - 1; i++) {
current = current[path[i]];
}
// Update the value
if (path.length > 0) {
const lastKey = path[path.length - 1];
if (updatedNode.text.length === 1 && !updatedNode.text[0].key) {
// Single value node
const value = updatedNode.text[0].value;
// Convert string values to their proper types
const parsedValue =
updatedNode.text[0].type === 'number' ? Number(value) :
updatedNode.text[0].type === 'boolean' ? value === 'true' :
updatedNode.text[0].type === 'null' ? null :
value;
current[lastKey] = parsedValue;
} else {
// Object node
const obj = {};
updatedNode.text.forEach(row => {
if (row.type !== "array" && row.type !== "object" && row.key) {
const value = row.value;
// Convert string values to their proper types
const parsedValue =
row.type === 'number' ? Number(value) :
row.type === 'boolean' ? value === 'true' :
row.type === 'null' ? null :
value;
obj[row.key] = parsedValue;
}
});
current[lastKey] = obj;
}
}
// Update the store with the new JSON and trigger updates
const newJsonString = JSON.stringify(currentJson, null, 2);
useJson.getState().setJson(newJsonString);
// Update the text editor contents
const useFileStore = (await import('../../../../../store/useFile')).default;
useFileStore.getState().setContents({ contents: newJsonString });
} catch (error) {
console.error('Error updating JSON:', error);
toast.error('Failed to update the visualization');
}
},
}));
export default useGraph;