forked from kubernetes-sigs/headlamp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphView.tsx
More file actions
472 lines (427 loc) · 14.2 KB
/
Copy pathGraphView.tsx
File metadata and controls
472 lines (427 loc) · 14.2 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
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
* Copyright 2025 The Kubernetes Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import '@xyflow/react/dist/base.css';
import './GraphView.css';
import { Icon } from '@iconify/react';
import Box from '@mui/material/Box';
import Chip from '@mui/material/Chip';
import { Theme } from '@mui/material/styles';
import { styled } from '@mui/material/styles';
import ThemeProvider from '@mui/system/ThemeProvider';
import { Edge, Node, Panel, ReactFlowProvider } from '@xyflow/react';
import {
createContext,
ReactNode,
StrictMode,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';
import Namespace from '../../lib/k8s/namespace';
import K8sNode from '../../lib/k8s/node';
import { setNamespaceFilter } from '../../redux/filterSlice';
import { useTypedSelector } from '../../redux/hooks';
import { NamespacesAutocomplete } from '../common/NamespacesAutocomplete';
import { GraphNodeDetails } from './details/GraphNodeDetails';
import { filterGraph, GraphFilter } from './graph/graphFiltering';
import {
collapseGraph,
findGroupContaining,
getGraphSize,
GroupBy,
groupGraph,
} from './graph/graphGrouping';
import { applyGraphLayout } from './graph/graphLayout';
import { GraphLookup, makeGraphLookup } from './graph/graphLookup';
import { forEachNode, GraphEdge, GraphNode, GraphSource } from './graph/graphModel';
import { GraphControlButton } from './GraphControls';
import { GraphRenderer } from './GraphRenderer';
import { SelectionBreadcrumbs } from './SelectionBreadcrumbs';
import { kubeObjectRelations } from './sources/definitions/relations';
import { allSources } from './sources/definitions/sources';
import { GraphSourceManager, useSources } from './sources/GraphSources';
import { GraphSourcesView } from './sources/GraphSourcesView';
import { useGraphViewport } from './useGraphViewport';
import { useQueryParamsState } from './useQueryParamsState';
interface GraphViewContent {
setNodeSelection: (nodeId: string) => void;
nodeSelection?: string;
}
export const GraphViewContext = createContext({} as any);
export const useGraphView = () => useContext<GraphViewContent>(GraphViewContext);
interface FullGraphContent {
fullGraph: any;
lookup: GraphLookup<GraphNode, GraphEdge>;
}
export const FullGraphContext = createContext({} as any);
export const useFullGraphContext = () => useContext<FullGraphContent>(FullGraphContext);
export const useNode = (id: string) => {
const { lookup } = useFullGraphContext();
return lookup.getNode(id);
};
interface GraphViewContentProps {
/** Height of the Map */
height?: string;
/** ID of a node to select by default */
defaultNodeSelection?: string;
/**
* List of Graph Source to display
*
* See {@link GraphSource} for more information
*/
defaultSources?: GraphSource[];
/** Default filters to apply */
defaultFilters?: GraphFilter[];
}
const defaultFiltersValue: GraphFilter[] = [];
const ChipGroup = styled(Box)({
display: 'flex',
'.MuiChip-root': {
borderRadius: 0,
},
'.MuiChip-root:first-child': {
borderRadius: '16px 0 0 16px',
},
'.MuiChip-root:last-child': {
borderRadius: '0 16px 16px 0',
},
});
function GraphViewContent({
height,
defaultNodeSelection,
defaultSources = allSources,
defaultFilters = defaultFiltersValue,
}: GraphViewContentProps) {
const { t } = useTranslation();
const dispatch = useDispatch();
// List of selected namespaces
const namespaces = useTypedSelector(state => state.filter).namespaces;
// Sync namespace and URL
const [namespacesParam] = useQueryParamsState<string>('namespace', '');
useEffect(() => {
const list = namespacesParam?.split(' ') ?? [];
dispatch(setNamespaceFilter(list));
}, [namespacesParam, dispatch]);
// Filters
const [hasErrorsFilter, setHasErrorsFilter] = useState(false);
// Grouping state
const [groupBy, setGroupBy] = useQueryParamsState<GroupBy | undefined>('group', 'namespace');
// Keep track if user moved the viewport
const viewportMovedRef = useRef(false);
// ID of the selected Node, undefined means nothing is selected
const [selectedNodeId, _setSelectedNodeId] = useQueryParamsState<string | undefined>(
'node',
defaultNodeSelection
);
const setSelectedNodeId = useCallback(
(id: string | undefined) => {
if (id === 'root') {
_setSelectedNodeId(undefined);
return;
}
_setSelectedNodeId(id);
},
[_setSelectedNodeId]
);
// Expand all groups state
const [expandAll, setExpandAll] = useState(false);
// Load source data
const { nodes, edges, selectedSources, sourceData, isLoading, toggleSelection } = useSources();
// Graph with applied layout, has sizes and positions for all elements
const [layoutedGraph, setLayoutedGraph] = useState<{ nodes: Node[]; edges: Edge[] }>({
nodes: [],
edges: [],
});
// Apply filters
const filteredGraph = useMemo(() => {
const filters = [...defaultFilters];
if (hasErrorsFilter) {
filters.push({ type: 'hasErrors' });
}
if (namespaces?.size > 0) {
filters.push({ type: 'namespace', namespaces });
}
return filterGraph(nodes, edges, filters);
}, [nodes, edges, hasErrorsFilter, namespaces, defaultFilters]);
// Group the graph
const [allNamespaces] = Namespace.useList();
const [allNodes] = K8sNode.useList();
const { visibleGraph, fullGraph } = useMemo(() => {
const graph = groupGraph(filteredGraph.nodes, filteredGraph.edges, {
groupBy,
namespaces: allNamespaces ?? [],
k8sNodes: allNodes ?? [],
});
const visibleGraph = collapseGraph(graph, { selectedNodeId, expandAll });
return { visibleGraph, fullGraph: graph };
}, [filteredGraph, groupBy, selectedNodeId, expandAll, allNamespaces]);
const viewport = useGraphViewport();
useEffect(() => {
applyGraphLayout(visibleGraph, viewport.aspectRatio).then(layout => {
setLayoutedGraph(layout);
// Only fit bounds when user hasn't moved viewport manually
if (!viewportMovedRef.current) {
viewport.updateViewport({ nodes: layout.nodes });
}
});
}, [visibleGraph, viewport]);
// Reset after view change
useLayoutEffect(() => {
viewportMovedRef.current = false;
}, [selectedNodeId, groupBy, expandAll]);
const selectedGroup = useMemo(() => {
if (selectedNodeId) {
return findGroupContaining(visibleGraph, selectedNodeId, true);
}
}, [selectedNodeId, visibleGraph, findGroupContaining]);
const graphSize = getGraphSize(visibleGraph);
useEffect(() => {
if (expandAll && graphSize > 50) {
setExpandAll(false);
}
}, [graphSize]);
const contextValue = useMemo(
() => ({ nodeSelection: selectedNodeId, setNodeSelection: setSelectedNodeId }),
[selectedNodeId, setSelectedNodeId]
);
const fullGraphContext = useMemo(() => {
let nodes: GraphNode[] = [];
let edges: GraphEdge[] = [];
forEachNode(visibleGraph, node => {
if (node.nodes) {
nodes = nodes.concat(node.nodes);
}
if (node.edges) {
edges = edges.concat(node.edges);
}
});
return {
visibleGraph,
lookup: makeGraphLookup(nodes, edges),
};
}, [visibleGraph]);
const maybeSelectedNode = selectedNodeId
? fullGraphContext.lookup.getNode(selectedNodeId)
: undefined;
return (
<GraphViewContext.Provider value={contextValue}>
<FullGraphContext.Provider value={fullGraphContext}>
<Box
sx={{
position: 'relative',
height: height ?? '800px',
display: 'flex',
flexDirection: 'row',
flex: 1,
}}
>
<CustomThemeProvider>
<Box
sx={{
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
position: 'relative',
flexGrow: 1,
background: '#00000002',
}}
>
<Box
padding={2}
pb={0}
display="flex"
gap={1}
alignItems="center"
mb={1}
flexWrap="wrap"
>
<NamespacesAutocomplete />
<GraphSourcesView
sources={defaultSources}
selectedSources={selectedSources}
toggleSource={toggleSelection}
sourceData={sourceData ?? new Map()}
/>
<Box sx={{ fontSize: '14px', marginLeft: 1 }}>{t('Group By')}</Box>
<ChipGroup>
{namespaces.size !== 1 && (
<ChipToggleButton
label={t('Namespace')}
isActive={groupBy === 'namespace'}
onClick={() => setGroupBy(groupBy === 'namespace' ? undefined : 'namespace')}
/>
)}
<ChipToggleButton
label={t('Instance')}
isActive={groupBy === 'instance'}
onClick={() => setGroupBy(groupBy === 'instance' ? undefined : 'instance')}
/>
<ChipToggleButton
label={t('Node')}
isActive={groupBy === 'node'}
onClick={() => setGroupBy(groupBy === 'node' ? undefined : 'node')}
/>
</ChipGroup>
<ChipToggleButton
label={t('Status: Error or Warning')}
isActive={hasErrorsFilter}
onClick={() => setHasErrorsFilter(!hasErrorsFilter)}
/>
{graphSize < 50 && (
<ChipToggleButton
label={t('Expand All')}
isActive={expandAll}
onClick={() => setExpandAll(it => !it)}
/>
)}
</Box>
<div style={{ flexGrow: 1 }}>
<GraphRenderer
nodes={layoutedGraph.nodes}
edges={layoutedGraph.edges}
isLoading={isLoading}
onMoveStart={e => {
if (e === null) return;
viewportMovedRef.current = true;
}}
controlActions={
<>
<GraphControlButton
title={t('Fit to screen')}
onClick={() => viewport.updateViewport({ mode: 'fit' })}
>
<Icon icon="mdi:fit-to-screen" />
</GraphControlButton>
<GraphControlButton
title={t('Zoom to 100%')}
onClick={() => viewport.updateViewport({ mode: '100%' })}
>
100%
</GraphControlButton>
</>
}
>
<Panel position="top-left">
{selectedGroup && (
<SelectionBreadcrumbs
graph={fullGraph}
selectedNodeId={selectedNodeId}
onNodeClick={id => setSelectedNodeId(id)}
/>
)}
</Panel>
</GraphRenderer>
</div>
</Box>
</CustomThemeProvider>
{maybeSelectedNode && (
<GraphNodeDetails
node={maybeSelectedNode}
close={() => {
setSelectedNodeId(selectedGroup?.id ?? defaultNodeSelection);
}}
/>
)}
</Box>
</FullGraphContext.Provider>
</GraphViewContext.Provider>
);
}
function ChipToggleButton({
label,
isActive,
onClick,
}: {
label: string;
isActive?: boolean;
icon?: ReactNode;
onClick: () => void;
}): ReactNode {
return (
<Chip
label={label}
color={isActive ? 'primary' : undefined}
variant={isActive ? 'filled' : 'outlined'}
icon={isActive ? <Icon icon="mdi:check" /> : undefined}
onClick={onClick}
sx={{
lineHeight: '1',
}}
/>
);
}
function CustomThemeProvider({ children }: { children: ReactNode }) {
return (
<ThemeProvider
theme={(outer: Theme) => ({
...outer,
palette:
outer.palette.mode === 'light'
? {
...outer.palette,
primary: {
main: '#555',
contrastText: '#fff',
light: '#666',
dark: '#444',
},
}
: {
...outer.palette,
primary: {
main: '#fafafa',
contrastText: '#444',
light: '#fff',
dark: '#f0f0f0',
},
},
components: {},
})}
>
{children}
</ThemeProvider>
);
}
/**
* Renders Map of Kubernetes resources
*
* @param params - Map parameters
* @returns
*/
export function GraphView(props: GraphViewContentProps) {
const propsSources = props.defaultSources ?? allSources;
// Load plugin defined sources
const pluginGraphSources = useTypedSelector(state => state.graphView.graphSources);
const sources = useMemo(
() => [...propsSources, ...pluginGraphSources],
[propsSources, pluginGraphSources]
);
return (
<StrictMode>
<ReactFlowProvider>
<GraphSourceManager sources={sources} relations={kubeObjectRelations}>
<GraphViewContent {...props} defaultSources={sources} />
</GraphSourceManager>
</ReactFlowProvider>
</StrictMode>
);
}