forked from redhat-developer/gitops-console-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplicationSetList.tsx
More file actions
511 lines (472 loc) · 14.5 KB
/
ApplicationSetList.tsx
File metadata and controls
511 lines (472 loc) · 14.5 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import TechPreviewBadge from 'src/components/import/badges/TechPreviewBadge';
import {
K8sResourceCommon,
ListPageBody,
ListPageCreate,
ListPageFilter,
ListPageHeader,
ResourceLink,
RowFilter,
useK8sWatchResource,
useListPageFilter,
} from '@openshift-console/dynamic-plugin-sdk';
import { ErrorState } from '@patternfly/react-component-groups';
import { EmptyState, EmptyStateBody } from '@patternfly/react-core';
import { DataViewTh, DataViewTr } from '@patternfly/react-data-view/dist/dynamic/DataViewTable';
import { CubesIcon } from '@patternfly/react-icons';
import { Tbody, Td, ThProps, Tr } from '@patternfly/react-table';
import { useApplicationSetActionsProvider } from '../../hooks/useApplicationSetActionsProvider';
import { ApplicationSetKind, ApplicationSetModel } from '../../models/ApplicationSetModel';
import ActionsDropdown from '../../utils/components/ActionDropDown/ActionDropDown';
// Import status icons for consistency with ApplicationList
import {
HealthDegradedIcon,
HealthHealthyIcon,
HealthUnknownIcon,
} from '../../utils/components/Icons/Icons';
import { ApplicationSetStatus } from '../../utils/constants';
import { getAppSetGeneratorCount, getAppSetStatus } from '../../utils/gitops';
import { modelToGroupVersionKind, modelToRef } from '../../utils/utils';
import {
ShowOperandsInAllNamespacesRadioGroup,
useShowOperandsInAllNamespaces,
} from './AllNamespaces';
import { GitOpsDataViewTable, useGitOpsDataViewSort } from './DataView';
const formatCreationTimestamp = (timestamp: string): string => {
if (!timestamp) return '-';
const date = new Date(timestamp);
const now = new Date();
const diffInMinutes = (now.getTime() - date.getTime()) / (1000 * 60);
if (diffInMinutes < 60) {
return `${Math.floor(diffInMinutes)}m ago`;
} else if (diffInMinutes < 60 * 24) {
const hours = Math.floor(diffInMinutes / 60);
const minutes = Math.floor(diffInMinutes % 60);
return minutes > 0 ? `${hours}h ${minutes}m ago` : `${hours}h ago`;
} else if (diffInMinutes < 60 * 24 * 7) {
const days = Math.floor(diffInMinutes / (60 * 24));
return `${days}d ago`;
} else {
return date.toLocaleDateString();
}
};
// Helper function to get generated applications count
const getGeneratedAppsCount = (
appSet: ApplicationSetKind,
applications: any[],
appsLoaded: boolean,
): number => {
if (!applications || !appsLoaded) return 0;
return applications.filter((app: any) => {
if (!app.metadata?.ownerReferences) return false;
return app.metadata.ownerReferences.some(
(owner: any) => owner.kind === 'ApplicationSet' && owner.name === appSet.metadata.name,
);
}).length;
};
const ApplicationSetStatusFragment: React.FC<{ status: string }> = ({ status }) => {
let targetIcon: React.ReactNode;
switch (status) {
case ApplicationSetStatus.HEALTHY:
targetIcon = <HealthHealthyIcon />;
break;
case ApplicationSetStatus.ERROR:
targetIcon = <HealthDegradedIcon />;
break;
default:
targetIcon = <HealthUnknownIcon />;
}
return (
<span>
{targetIcon} {status}
</span>
);
};
interface ApplicationSetProps {
namespace: string;
hideNameLabelFilters?: boolean;
showTitle?: boolean;
}
const ApplicationSetList: React.FC<ApplicationSetProps> = ({
namespace,
hideNameLabelFilters,
showTitle,
}) => {
const [showOperandsInAllNamespaces] = useShowOperandsInAllNamespaces();
const listAllNamespaces =
location.pathname?.includes('openshift-gitops-operator') && showOperandsInAllNamespaces;
if (listAllNamespaces) {
namespace = null;
}
const [applicationSets, loaded, loadError] = useK8sWatchResource<K8sResourceCommon[]>({
isList: true,
groupVersionKind: {
group: 'argoproj.io',
kind: 'ApplicationSet',
version: 'v1alpha1',
},
namespaced: !listAllNamespaces,
namespace,
});
// Watch Applications to count generated apps
const [applications, appsLoaded] = useK8sWatchResource<K8sResourceCommon[]>({
isList: true,
groupVersionKind: {
group: 'argoproj.io',
kind: 'Application',
version: 'v1alpha1',
},
namespaced: true,
namespace,
});
const { t } = useTranslation('plugin__gitops-plugin');
const columnSortConfig = React.useMemo(
() =>
[
'name',
...(!listAllNamespaces || !namespace ? ['namespace'] : []),
'status',
'generated-apps',
'generators',
'created-at',
'actions',
].map((key) => ({ key })),
[listAllNamespaces, namespace],
);
const { searchParams, sortBy, direction, getSortParams } =
useGitOpsDataViewSort(columnSortConfig);
// Get search query from URL parameters
const searchQuery = searchParams.get('q') || '';
const columnsDV = useColumnsDV(namespace, getSortParams);
const sortedApplicationSets = React.useMemo(() => {
return sortData(
applicationSets as ApplicationSetKind[],
sortBy,
direction,
applications,
appsLoaded,
);
}, [applicationSets, sortBy, direction, applications, appsLoaded]);
const filters = getFilters(t);
const [data, filteredData, onFilterChange] = useListPageFilter(sortedApplicationSets, filters);
// Filter by search query if present (after other filters)
const filteredBySearch = React.useMemo(() => {
if (!searchQuery) return filteredData;
return filteredData.filter((appSet) => {
const labels = appSet.metadata?.labels || {};
// Check if any label matches the search query
return Object.entries(labels).some(([key, value]) => {
const labelSelector = `${key}=${value}`;
return labelSelector.includes(searchQuery) || key.includes(searchQuery);
});
});
}, [filteredData, searchQuery]);
const rows = useApplicationSetRowsDV(filteredBySearch, namespace, applications, appsLoaded);
// Check if there are ApplicationSets initially (before search)
const hasApplicationSets = React.useMemo(() => {
return sortedApplicationSets.length > 0;
}, [sortedApplicationSets]);
const getEmptyStateBody = () => {
if (searchQuery) {
return (
<>
{t('No Argo CD ApplicationSets match the label filter')}{' '}
<strong>"{searchQuery}"</strong>.
<br />
{t('Try removing the filter or selecting a different label to see more ApplicationSets.')}
</>
);
}
return namespace
? t('There are no Argo CD ApplicationSets in this project.')
: t('There are no Argo CD ApplicationSets in all projects.');
};
const empty = (
<Tbody>
<Tr key="loading" ouiaId="table-tr-loading">
<Td colSpan={columnsDV.length}>
<EmptyState
headingLevel="h4"
icon={CubesIcon}
titleText={
searchQuery
? t('No matching Argo CD ApplicationSets')
: t('No Argo CD ApplicationSets')
}
>
<EmptyStateBody>{getEmptyStateBody()}</EmptyStateBody>
</EmptyState>
</Td>
</Tr>
</Tbody>
);
const error = loadError && (
<Tbody>
<Tr key="loading" ouiaId={'table-tr-loading'}>
<Td colSpan={columnsDV.length}>
<ErrorState
titleText={t('Unable to load data')}
bodyText={t(
'There was an error retrieving applicationsets. Check your connection and reload the page.',
)}
/>
</Td>
</Tr>
</Tbody>
);
const isEmptyState = !loadError && filteredBySearch.length === 0;
return (
<div>
{showTitle == undefined && (
<ListPageHeader
title={t('ApplicationSets')}
badge={
location.pathname?.includes('openshift-gitops-operator') ? null : (
<TechPreviewBadge
tooltipContent={t(
'This list page is under tech preview, but not necessarily the resources it represents',
)}
/>
)
}
helpText={
location.pathname?.includes('openshift-gitops-operator') ? (
<ShowOperandsInAllNamespacesRadioGroup />
) : null
}
hideFavoriteButton={false}
>
<ListPageCreate groupVersionKind={modelToRef(ApplicationSetModel)}>
{t('Create ApplicationSet')}
</ListPageCreate>
</ListPageHeader>
)}
<ListPageBody>
{!hideNameLabelFilters && hasApplicationSets && (
<ListPageFilter
data={data}
loaded={loaded}
rowFilters={filters}
onFilterChange={onFilterChange}
/>
)}
<GitOpsDataViewTable
rows={rows}
columns={columnsDV}
isEmpty={isEmptyState}
emptyState={empty}
isError={!!loadError}
errorState={error}
/>
</ListPageBody>
</div>
);
};
const ApplicationSetActionsCell: React.FC<{ appSet: ApplicationSetKind }> = ({ appSet }) => {
const [actions] = useApplicationSetActionsProvider(appSet);
return (
<div style={{ textAlign: 'right' }}>
<ActionsDropdown actions={actions} id="gitops-applicationset-actions" isKebabToggle={true} />
</div>
);
};
const useApplicationSetRowsDV = (
applicationSetsList,
namespace,
applications,
appsLoaded,
): DataViewTr[] => {
const rows: DataViewTr[] = [];
applicationSetsList.forEach((appSet: ApplicationSetKind, index: number) => {
rows.push([
{
cell: (
<div>
<ResourceLink
groupVersionKind={modelToGroupVersionKind(ApplicationSetModel)}
name={appSet.metadata.name}
namespace={appSet.metadata.namespace}
inline={true}
/>
</div>
),
id: appSet.metadata?.name,
dataLabel: 'Name',
},
...(!namespace
? [
{
cell: <ResourceLink kind="Namespace" name={appSet.metadata.namespace} />,
id: appSet.metadata.namespace,
dataLabel: 'Namespace',
},
]
: []),
{
id: getAppSetStatus(appSet),
cell: <ApplicationSetStatusFragment status={getAppSetStatus(appSet)} />,
},
{
id: 'generated-apps-' + index,
cell: <div>{getGeneratedAppsCount(appSet, applications, appsLoaded).toString()}</div>,
},
{
id: 'generators-' + index,
cell: <div>{getAppSetGeneratorCount(appSet).toString()}</div>,
},
{
id: 'created-at-' + index,
cell: <div>{formatCreationTimestamp(appSet.metadata.creationTimestamp)}</div>,
},
{
id: 'actions-' + index,
cell: <ApplicationSetActionsCell appSet={appSet} />,
props: { style: { paddingTop: 8, paddingRight: 0, paddingLeft: 0, width: 10 } },
},
]);
});
return rows;
};
const useColumnsDV = (
namespace: string,
getSortParams: (columnIndex: number) => ThProps['sort'],
): DataViewTh[] => {
const i: number = namespace ? 0 : 1;
const { t } = useTranslation('plugin__gitops-plugin');
const columns: DataViewTh[] = [
{
cell: t('Name'),
props: {
'aria-label': 'name',
className: 'pf-m-width-25',
sort: getSortParams(0),
},
},
...(!namespace
? [
{
cell: t('Namespace'),
props: {
'aria-label': 'namespace',
className: 'pf-m-width-15',
sort: getSortParams(1),
},
},
]
: []),
{
cell: t('Health Status'),
props: {
'aria-label': 'health status',
className: 'pf-m-width-15',
sort: getSortParams(1 + i),
},
},
{
cell: t('Generated Apps'),
props: {
'aria-label': 'generated apps',
className: 'pf-m-width-15',
sort: getSortParams(2 + i),
},
},
{
cell: t('Generators'),
props: {
'aria-label': 'generators',
className: 'pf-m-width-15',
sort: getSortParams(3 + i),
},
},
{
cell: t('Created At'),
props: {
'aria-label': 'created at',
className: 'pf-m-width-15',
sort: getSortParams(4 + i),
},
},
{
cell: '',
props: { 'aria-label': 'actions' },
},
];
return columns;
};
const getFilters = (t: (key: string) => string): RowFilter[] => [
{
filterGroupName: t('Health Status'),
type: 'application-set-status',
reducer: (applicationSet) => getAppSetStatus(applicationSet),
filter: (input, applicationSet) => {
if (input.selected?.length && applicationSet) {
return input.selected.includes(getAppSetStatus(applicationSet));
} else {
return true;
}
},
items: [
{ id: ApplicationSetStatus.HEALTHY, title: ApplicationSetStatus.HEALTHY },
{ id: ApplicationSetStatus.ERROR, title: ApplicationSetStatus.ERROR },
{ id: ApplicationSetStatus.UNKNOWN, title: ApplicationSetStatus.UNKNOWN },
],
},
];
export const sortData = (
data: ApplicationSetKind[],
sortBy: string | undefined,
direction: 'asc' | 'desc' | undefined,
applications: any[] = [],
appsLoaded = false,
) => {
if (!sortBy || !direction) return data;
return [...data].sort((a, b) => {
let aValue: any, bValue: any;
switch (sortBy) {
case 'name':
aValue = a.metadata?.name || '';
bValue = b.metadata?.name || '';
break;
case 'namespace':
aValue = a.metadata?.namespace || '';
bValue = b.metadata?.namespace || '';
break;
case 'status':
aValue = getAppSetStatus(a);
bValue = getAppSetStatus(b);
break;
case 'generated-apps':
aValue = getGeneratedAppsCount(a, applications, appsLoaded);
bValue = getGeneratedAppsCount(b, applications, appsLoaded);
break;
case 'generators':
aValue = getAppSetGeneratorCount(a);
bValue = getAppSetGeneratorCount(b);
break;
case 'created-at':
aValue = new Date(a.metadata?.creationTimestamp || 0).getTime();
bValue = new Date(b.metadata?.creationTimestamp || 0).getTime();
break;
default:
return 0;
}
if (direction === 'asc') {
if (aValue < bValue) {
return -1;
} else if (aValue > bValue) {
return 1;
}
return 0;
} else {
if (aValue > bValue) {
return -1;
} else if (aValue < bValue) {
return 1;
}
return 0;
}
});
};
export default ApplicationSetList;