-
Notifications
You must be signed in to change notification settings - Fork 572
/
Copy pathGraphViewModal.tsx
377 lines (359 loc) · 13.1 KB
/
GraphViewModal.tsx
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import { Banner, Dialog, Flex, IconButtonArray, LoadingSpinner } from '@neo4j-ndl/react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { GraphType, GraphViewModalProps, OptionType, Scheme, UserCredentials } from '../../types';
import { InteractiveNvlWrapper } from '@neo4j-nvl/react';
import NVL from '@neo4j-nvl/base';
import type { Node, Relationship } from '@neo4j-nvl/base';
import { Resizable } from 're-resizable';
import {
ArrowPathIconOutline,
DragIcon,
FitToScreenIcon,
MagnifyingGlassMinusIconOutline,
MagnifyingGlassPlusIconOutline,
} from '@neo4j-ndl/react/icons';
import IconButtonWithToolTip from '../UI/IconButtonToolTip';
import { filterData, processGraphData } from '../../utils/Utils';
import { useCredentials } from '../../context/UserCredentials';
import { LegendsChip } from './LegendsChip';
import graphQueryAPI from '../../services/GraphQuery';
import {
entityGraph,
graphQuery,
graphView,
intitalGraphType,
knowledgeGraph,
lexicalGraph,
mouseEventCallbacks,
nvlOptions,
} from '../../utils/Constants';
import { useFileContext } from '../../context/UsersFiles';
// import CheckboxSelection from './CheckboxSelection';
import DropdownComponent from '../Dropdown';
const GraphViewModal: React.FunctionComponent<GraphViewModalProps> = ({
open,
inspectedName,
setGraphViewOpen,
viewPoint,
nodeValues,
relationshipValues,
processingCheck,
}) => {
const nvlRef = useRef<NVL>(null);
const [nodes, setNodes] = useState<Node[]>([]);
const [relationships, setRelationships] = useState<Relationship[]>([]);
const [graphType, setGraphType] = useState<GraphType[]>(intitalGraphType);
const [allNodes, setAllNodes] = useState<Node[]>([]);
const [allRelationships, setAllRelationships] = useState<Relationship[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [status, setStatus] = useState<'unknown' | 'success' | 'danger'>('unknown');
const [statusMessage, setStatusMessage] = useState<string>('');
const { userCredentials } = useCredentials();
const [scheme, setScheme] = useState<Scheme>({});
const { selectedRows } = useFileContext();
const [newScheme, setNewScheme] = useState<Scheme>({});
// const handleCheckboxChange = (graph: GraphType) => {
// const currentIndex = graphType.indexOf(graph);
// const newGraphSelected = [...graphType];
// if (currentIndex === -1) {
// newGraphSelected.push(graph);
// } else {
// newGraphSelected.splice(currentIndex, 1);
// }
// setGraphType(newGraphSelected);
// };
const handleZoomToFit = () => {
nvlRef.current?.fit(
allNodes.map((node) => node.id),
{}
);
};
// Destroy the component
useEffect(() => {
const timeoutId = setTimeout(() => {
handleZoomToFit();
}, 10);
return () => {
nvlRef.current?.destroy();
setGraphType(intitalGraphType);
clearTimeout(timeoutId);
setScheme({});
setNodes([]);
setRelationships([]);
setAllNodes([]);
setAllRelationships([]);
};
}, []);
// To get nodes and relations on basis of view
const fetchData = useCallback(async () => {
try {
const nodeRelationshipData =
viewPoint === 'showGraphView'
? await graphQueryAPI(
userCredentials as UserCredentials,
graphQuery,
selectedRows.map((f) => JSON.parse(f).name)
)
: await graphQueryAPI(userCredentials as UserCredentials, graphQuery, [inspectedName ?? '']);
return nodeRelationshipData;
} catch (error: any) {
console.log(error);
}
}, [viewPoint, selectedRows, graphQuery, inspectedName, userCredentials]);
// Api call to get the nodes and relations
const graphApi = () => {
fetchData()
.then((result) => {
if (result && result.data.data.nodes.length > 0) {
const neoNodes = result.data.data.nodes.map((f: Node) => f);
const neoRels = result.data.data.relationships.map((f: Relationship) => f);
const { finalNodes, finalRels, schemeVal } = processGraphData(neoNodes, neoRels);
setAllNodes(finalNodes);
setAllRelationships(finalRels);
setScheme(schemeVal);
setNodes(finalNodes);
setRelationships(finalRels);
setNewScheme(schemeVal);
setLoading(false);
} else {
setLoading(false);
setStatus('danger');
setStatusMessage(`No Nodes and Relations for the ${inspectedName} file`);
}
})
.catch((error: any) => {
setLoading(false);
setStatus('danger');
setStatusMessage(error.message);
});
};
useEffect(() => {
if (open) {
setLoading(true);
if (viewPoint === 'chatInfoView') {
const { finalNodes, finalRels, schemeVal } = processGraphData(nodeValues ?? [], relationshipValues ?? []);
setAllNodes(finalNodes);
setAllRelationships(finalRels);
setScheme(schemeVal);
setNodes(finalNodes);
setRelationships(finalRels);
setNewScheme(schemeVal);
setLoading(false);
} else {
graphApi();
}
}
}, [open]);
if (!open) {
return <></>;
}
const headerTitle =
viewPoint === 'showGraphView' || viewPoint === 'chatInfoView'
? 'Generated Graph'
: `Inspect Generated Graph from ${inspectedName}`;
const dropDownView = viewPoint !== 'chatInfoView';
const nvlCallbacks = {
onLayoutComputing(isComputing: boolean) {
if (!isComputing) {
handleZoomToFit();
}
},
};
// To handle the current zoom in function of graph
const handleZoomIn = () => {
nvlRef.current?.setZoom(nvlRef.current.getScale() * 1.3);
};
// To handle the current zoom out function of graph
const handleZoomOut = () => {
nvlRef.current?.setZoom(nvlRef.current.getScale() * 0.7);
};
// Refresh the graph with nodes and relations if file is processing
const handleRefresh = () => {
setLoading(true);
setGraphType(intitalGraphType);
graphApi();
};
// when modal closes reset all states to default
const onClose = () => {
setStatus('unknown');
setStatusMessage('');
setGraphViewOpen(false);
setScheme({});
setGraphType(intitalGraphType);
setNodes([]);
setRelationships([]);
};
// sort the legends in with Chunk and Document always the first two values
const legendCheck = Object.keys(newScheme).sort((a, b) => {
if (a === 'Document' || a === 'Chunk') {
return -1;
} else if (b === 'Document' || b === 'Chunk') {
return 1;
}
return a.localeCompare(b);
});
// setting the default dropdown values
const getDropdownDefaultValue = () => {
if (graphType.includes('Document') && graphType.includes('Chunk') && graphType.includes('Entities')) {
return knowledgeGraph;
}
if (graphType.includes('Document') && graphType.includes('Chunk')) {
return lexicalGraph;
}
if (graphType.includes('Entities')) {
return entityGraph;
}
return '';
};
// Make a function call to store the nodes and relations in their states
const initGraph = (graphType: GraphType[], finalNodes: Node[], finalRels: Relationship[], schemeVal: Scheme) => {
if (allNodes.length > 0 && allRelationships.length > 0) {
const { filteredNodes, filteredRelations, filteredScheme } = filterData(
graphType,
finalNodes,
finalRels,
schemeVal
);
setNodes(filteredNodes);
setRelationships(filteredRelations);
setNewScheme(filteredScheme);
}
};
// handle dropdown value change and call the init graph method
const handleDropdownChange = (selectedOption: OptionType | null | void) => {
if (selectedOption?.value) {
const selectedValue = selectedOption.value;
let newGraphType: GraphType[] = [];
if (selectedValue === knowledgeGraph) {
newGraphType = intitalGraphType;
} else if (selectedValue === lexicalGraph) {
newGraphType = ['Document', 'Chunk'];
} else if (selectedValue === entityGraph) {
newGraphType = ['Entities'];
}
setGraphType(newGraphType);
initGraph(newGraphType, allNodes, allRelationships, scheme);
}
};
return (
<>
<Dialog
modalProps={{
className: 'h-[90%]',
id: 'default-menu',
}}
size='unset'
open={open}
aria-labelledby='form-dialog-title'
disableCloseButton={false}
onClose={onClose}
>
<Dialog.Header id='graph-title'>
{headerTitle}
<Flex className='w-full' alignItems='center' justifyContent='flex-end' flexDirection='row'>
{/* {checkBoxView && (
<CheckboxSelection graphType={graphType} loading={loading} handleChange={handleCheckboxChange} />
)} */}
{dropDownView && (
<DropdownComponent
onSelect={handleDropdownChange}
options={graphView}
placeholder='Select Graph Type'
defaultValue={getDropdownDefaultValue()}
view='GraphView'
isDisabled={nodes.length === 0 || allNodes.length === 0}
/>
)}
</Flex>
</Dialog.Header>
<Dialog.Content className='flex flex-col n-gap-token-4 w-full grow overflow-auto border border-palette-neutral-border-weak'>
<div className='bg-white relative w-full h-full max-h-full'>
{loading ? (
<div className='my-40 flex items-center justify-center'>
<LoadingSpinner size='large' />
</div>
) : status !== 'unknown' ? (
<div className='my-40 flex items-center justify-center'>
<Banner name='graph banner' description={statusMessage} type={status} />
</div>
) : (
<>
<div className='flex' style={{ height: '100%' }}>
<div className='bg-palette-neutral-bg-default relative' style={{ width: '100%', flex: '1' }}>
<InteractiveNvlWrapper
nodes={nodes}
rels={relationships}
nvlOptions={nvlOptions}
ref={nvlRef}
mouseEventCallbacks={{ ...mouseEventCallbacks }}
interactionOptions={{
selectOnClick: true,
}}
nvlCallbacks={nvlCallbacks}
/>
<IconButtonArray orientation='vertical' floating className='absolute bottom-4 right-4'>
{viewPoint !== 'chatInfoView' && processingCheck && (
<IconButtonWithToolTip
label='Refresh'
text='Refresh graph'
onClick={handleRefresh}
placement='left'
>
<ArrowPathIconOutline />
</IconButtonWithToolTip>
)}
<IconButtonWithToolTip label='Zoomin' text='Zoom in' onClick={handleZoomIn} placement='left'>
<MagnifyingGlassPlusIconOutline />
</IconButtonWithToolTip>
<IconButtonWithToolTip label='Zoom out' text='Zoom out' onClick={handleZoomOut} placement='left'>
<MagnifyingGlassMinusIconOutline />
</IconButtonWithToolTip>
<IconButtonWithToolTip
label='Zoom to fit'
text='Zoom to fit'
onClick={handleZoomToFit}
placement='left'
>
<FitToScreenIcon />
</IconButtonWithToolTip>
</IconButtonArray>
</div>
<Resizable
defaultSize={{
width: 400,
height: '100%',
}}
minWidth={230}
maxWidth='72%'
enable={{
top: false,
right: false,
bottom: false,
left: true,
topRight: false,
bottomRight: false,
bottomLeft: false,
topLeft: false,
}}
handleComponent={{ left: <DragIcon className='absolute top-1/2 h-6 w-6' /> }}
handleClasses={{ left: 'ml-1' }}
>
<div className='legend_div'>
<h4 className='py-4 pt-3 ml-2'>Result Overview</h4>
<div className='flex gap-2 flex-wrap ml-2'>
{legendCheck.map((key, index) => (
<LegendsChip key={index} title={key} scheme={newScheme} nodes={nodes} />
))}
</div>
</div>
</Resizable>
</div>
</>
)}
</div>
</Dialog.Content>
</Dialog>
</>
);
};
export default GraphViewModal;