-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathImageList.tsx
More file actions
619 lines (608 loc) · 19.8 KB
/
ImageList.tsx
File metadata and controls
619 lines (608 loc) · 19.8 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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import Flex from '../components/Flex';
import {
filterEmptyItem,
filterNonNullItems,
getImageFullName,
localeCompare,
preserveDotStartCase,
} from '../helper';
import {
useBackendAIImageMetaData,
useSuspendedBackendaiClient,
useUpdatableState,
} from '../hooks';
import { useHiddenColumnKeysSetting } from '../hooks/useHiddenColumnKeysSetting';
import BAITable from './BAITable';
import DoubleTag from './DoubleTag';
import ImageInstallModal from './ImageInstallModal';
import { ImageTags } from './ImageTags';
import ManageAppsModal from './ManageAppsModal';
import ManageImageResourceLimitModal from './ManageImageResourceLimitModal';
import ResourceNumber from './ResourceNumber';
import TableColumnsSettingModal from './TableColumnsSettingModal';
import TextHighlighter from './TextHighlighter';
import {
ImageListQuery,
ImageListQuery$data,
} from './__generated__/ImageListQuery.graphql';
import {
AppstoreOutlined,
ReloadOutlined,
SearchOutlined,
SettingOutlined,
VerticalAlignBottomOutlined,
} from '@ant-design/icons';
import { useToggle } from 'ahooks';
import { App, Button, Input, Tag, theme, Typography } from 'antd';
import { ColumnType } from 'antd/es/table';
import graphql from 'babel-plugin-relay/macro';
import _ from 'lodash';
import { Key, useMemo, useState, useTransition } from 'react';
import { useTranslation } from 'react-i18next';
import { useLazyLoadQuery } from 'react-relay';
export type EnvironmentImage = NonNullable<
NonNullable<ImageListQuery$data['images']>[number]
>;
const ImageList: React.FC<{ style?: React.CSSProperties }> = ({ style }) => {
const { t } = useTranslation();
const [selectedRows, setSelectedRows] = useState<EnvironmentImage[]>([]);
const [, { getBaseVersion, getBaseImages, getBaseImage, tagAlias, getTags }] =
useBackendAIImageMetaData();
const { token } = theme.useToken();
const [managingApp, setManagingApp] = useState<EnvironmentImage | null>(null);
const [managingResourceLimit, setManagingResourceLimit] =
useState<EnvironmentImage | null>(null);
const [isOpenInstallModal, setIsOpenInstallModal] = useState<boolean>(false);
const [environmentFetchKey, updateEnvironmentFetchKey] =
useUpdatableState('initial-fetch');
const [, startTransition] = useTransition();
const [installingImages, setInstallingImages] = useState<string[]>([]);
const { message } = App.useApp();
const [imageSearch, setImageSearch] = useState('');
const [visibleColumnSettingModal, { toggle: toggleColumnSettingModal }] =
useToggle();
const [isPendingRefreshTransition, startRefreshTransition] = useTransition();
const [isPendingSearchTransition, startSearchTransition] = useTransition();
const baiClient = useSuspendedBackendaiClient();
const supportExtendedImageInfo = baiClient?.supports('extended-image-info');
const { images } = useLazyLoadQuery<ImageListQuery>(
graphql`
query ImageListQuery {
images {
id
name @deprecatedSince(version: "24.12.0")
tag
registry
architecture
digest
installed
labels {
key
value
}
humanized_name
resource_limits {
key
min
max
}
namespace @since(version: "24.12.0")
base_image_name @since(version: "24.12.0")
tags @since(version: "24.12.0") {
key
value
}
version @since(version: "24.12.0")
...ManageImageResourceLimitModal_image
...ManageAppsModal_image
}
}
`,
{},
{
fetchPolicy:
environmentFetchKey === 'initial-fetch'
? 'store-and-network'
: 'network-only',
fetchKey: environmentFetchKey,
},
);
// Sort images by humanized_name to prevent the image list from jumping around when the images are updated
// TODO: after `images` query supports sort order, we should remove this line
const defaultSortedImages = useMemo(
() => _.sortBy(images, (image) => image?.humanized_name),
[images],
);
const columns: Array<ColumnType<EnvironmentImage>> = filterEmptyItem([
{
title: t('environment.Status'),
dataIndex: 'installed',
key: 'installed',
defaultSortOrder: 'descend',
sorter: (a, b) => {
return _.toNumber(a?.installed || 0) - _.toNumber(b?.installed || 0);
},
render: (text, row) =>
row?.id && installingImages.includes(row.id) ? (
<Tag color="gold">
<TextHighlighter keyword={imageSearch}>
{t('environment.Installing')}
</TextHighlighter>
</Tag>
) : row?.installed ? (
<Tag color="gold">
<TextHighlighter keyword={imageSearch}>
{t('environment.Installed')}
</TextHighlighter>
</Tag>
) : null,
},
{
title: t('environment.FullImagePath'),
key: 'fullImagePath',
render: (row) => (
<Typography.Text
copyable={{
text: getImageFullName(row) || '',
}}
>
<TextHighlighter keyword={imageSearch}>
{getImageFullName(row) || ''}
</TextHighlighter>
</Typography.Text>
),
sorter: (a, b) => localeCompare(getImageFullName(a), getImageFullName(b)),
width: token.screenXS,
},
{
title: t('environment.Registry'),
dataIndex: 'registry',
key: 'registry',
sorter: (a, b) => localeCompare(a?.registry, b?.registry),
render: (text) => (
<TextHighlighter keyword={imageSearch}>{text}</TextHighlighter>
),
},
{
title: t('environment.Architecture'),
dataIndex: 'architecture',
key: 'architecture',
sorter: (a, b) => localeCompare(a?.architecture, b?.architecture),
render: (text) => (
<TextHighlighter keyword={imageSearch}>{text}</TextHighlighter>
),
},
supportExtendedImageInfo && {
title: t('environment.Namespace'),
key: 'namespace',
dataIndex: 'namespace',
sorter: (a, b) => localeCompare(a?.namespace, b?.namespace),
render: (text) => (
<TextHighlighter keyword={imageSearch}>{text}</TextHighlighter>
),
},
supportExtendedImageInfo && {
title: t('environment.BaseImageName'),
key: 'base_image_name',
dataIndex: 'base_image_name',
sorter: (a, b) => localeCompare(a?.base_image_name, b?.base_image_name),
render: (text) => (
<TextHighlighter keyword={imageSearch}>
{tagAlias(text)}
</TextHighlighter>
),
},
supportExtendedImageInfo && {
title: t('environment.Version'),
key: 'version',
dataIndex: 'version',
sorter: (a, b) => localeCompare(a?.version, b?.version),
render: (text) => (
<TextHighlighter keyword={imageSearch}>{text}</TextHighlighter>
),
},
supportExtendedImageInfo && {
title: t('environment.Tags'),
key: 'tags',
dataIndex: 'tags',
render: (text, row) => {
return (
<Flex direction="row" align="start">
{/* TODO: replace this with AliasedImageDoubleTags after image list query with ImageNode is implemented. */}
{_.map(text, (tag: { key: string; value: string }) => {
const isCustomized = _.includes(tag.key, 'customized_');
const tagValue = isCustomized
? _.find(row?.labels, {
key: 'ai.backend.customized-image.name',
})?.value
: tag.value;
const aliasedTag = tagAlias(tag.key + tagValue);
return _.isEqual(
aliasedTag,
preserveDotStartCase(tag.key + tagValue),
) || isCustomized ? (
<DoubleTag
key={tag.key}
highlightKeyword={imageSearch}
values={[
{
label: tagAlias(tag.key),
color: isCustomized ? 'cyan' : 'blue',
},
{
label: tagValue ?? '',
color: isCustomized ? 'cyan' : 'blue',
},
]}
/>
) : (
<Tag key={tag.key} color={isCustomized ? 'cyan' : 'blue'}>
<TextHighlighter keyword={imageSearch}>
{aliasedTag}
</TextHighlighter>
</Tag>
);
})}
</Flex>
);
},
},
!supportExtendedImageInfo && {
title: t('environment.Namespace'),
key: 'name',
dataIndex: 'name',
sorter: (a, b) => localeCompare(getImageFullName(a), getImageFullName(b)),
render: (text) => (
<TextHighlighter keyword={imageSearch}>{text}</TextHighlighter>
),
},
!supportExtendedImageInfo && {
title: t('environment.Base'),
key: 'baseimage',
dataIndex: 'baseimage',
sorter: (a, b) =>
localeCompare(
getBaseImage(getImageFullName(a) || ''),
getBaseImage(getImageFullName(b) || ''),
),
render: (text, row) => (
<TextHighlighter keyword={imageSearch}>
{tagAlias(getBaseImage(getImageFullName(row) || ''))}
</TextHighlighter>
),
},
!supportExtendedImageInfo && {
title: t('environment.Version'),
key: 'baseversion',
dataIndex: 'baseversion',
sorter: (a, b) =>
localeCompare(
getBaseVersion(getImageFullName(a) || ''),
getBaseVersion(getImageFullName(b) || ''),
),
render: (text, row) => (
<TextHighlighter keyword={imageSearch}>
{getBaseVersion(getImageFullName(row) || '')}
</TextHighlighter>
),
},
!supportExtendedImageInfo && {
title: t('environment.Tags'),
key: 'tag',
dataIndex: 'tag',
sorter: (a, b) => localeCompare(a?.tag, b?.tag),
render: (text, row) => (
<ImageTags
tag={text}
labels={row.labels as Array<{ key: string; value: string }>}
highlightKeyword={imageSearch}
/>
),
},
{
title: t('environment.Digest'),
dataIndex: 'digest',
key: 'digest',
sorter: (a, b) => localeCompare(a?.digest || '', b?.digest || ''),
render: (text, row) => (
<Typography.Text ellipsis={{ tooltip: true }} style={{ maxWidth: 200 }}>
<TextHighlighter keyword={imageSearch}>{row.digest}</TextHighlighter>
</Typography.Text>
),
},
{
title: t('environment.ResourceLimit'),
dataIndex: 'resource_limits',
key: 'resource_limits',
render: (text, row) => (
<Flex direction="row" gap="xxs">
{row?.resource_limits?.map((resource_limit) => (
<ResourceNumber
key={resource_limit?.key}
type={resource_limit?.key || ''}
value={resource_limit?.min || '0'}
max={resource_limit?.max || 'Infinity'}
/>
))}
</Flex>
),
},
{
title: t('general.Control'),
key: 'control',
dataIndex: 'control',
fixed: 'right',
render: (text, row) => (
<Flex
direction="row"
align="stretch"
justify="center"
gap="xxs"
onClick={(e) => {
// To prevent the click event from selecting the row
e.stopPropagation();
}}
>
<Button
type="text"
icon={
<SettingOutlined
style={{
color: token.colorInfo,
}}
/>
}
onClick={() => setManagingResourceLimit(row)}
/>
<Button
type="text"
icon={
<AppstoreOutlined
style={{
color: token.colorInfo,
}}
/>
}
onClick={() => {
setManagingApp(row);
}}
/>
</Flex>
),
},
]);
const [hiddenColumnKeys, setHiddenColumnKeys] =
useHiddenColumnKeysSetting('ImageList');
const imageFilterValues = useMemo(() => {
return defaultSortedImages?.map((image) => {
return {
namespace: supportExtendedImageInfo ? image?.namespace : image?.name,
fullName: getImageFullName(image) || '',
digest: image?.digest || '',
// ------------ need only before 24.12.0 ------------
baseversion: getBaseVersion(getImageFullName(image) || ''),
baseimage:
image?.tag && image?.name ? getBaseImages(image.tag, image.name) : [],
tag:
getTags(
image?.tag || '',
image?.labels as Array<{ key: string; value: string }>,
) || [],
isCustomized: image?.tag
? image.tag.indexOf('customized') !== -1
: false,
// -------------------------------------------------
// ------------ need only after 24.12.0 ------------
baseImageName: supportExtendedImageInfo ? image?.base_image_name : '',
tags: supportExtendedImageInfo ? image?.tags : [],
version: supportExtendedImageInfo ? image?.version : '',
// -------------------------------------------------
};
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [defaultSortedImages]);
const filteredImageData = useMemo(() => {
if (_.isEmpty(imageSearch)) return defaultSortedImages;
const regExp = new RegExp(`${_.escapeRegExp(imageSearch)}`, 'i');
return _.filter(defaultSortedImages, (image, idx) => {
return _.some(image, (value, key) => {
if (key === 'id') return false;
if (['digest', 'architecture', 'registry'].includes(key))
return regExp.test(_.toString(value));
const curFilterValues = imageFilterValues[idx] || {};
const baseVersionMatch = regExp.test(curFilterValues.baseversion);
const baseImagesMatch = _.some(curFilterValues.baseimage, (value) =>
regExp.test(value),
);
const tagMatch = _.some(
curFilterValues.tag,
(tag) => regExp.test(tag.key) || regExp.test(tag.value),
);
const customizedMatch = curFilterValues.isCustomized
? regExp.test('customized')
: false;
const namespaceMatch = regExp.test(curFilterValues.namespace || '');
const fullNameMatch = regExp.test(curFilterValues.fullName);
const tagsMatch = _.some(
curFilterValues.tags,
(tag: { key: string; value: string }) =>
regExp.test(tag.key) || regExp.test(tag.value),
);
const versionMatch = regExp.test(curFilterValues.version || '');
const digestMatch = regExp.test(curFilterValues.digest);
return (
baseVersionMatch ||
baseImagesMatch ||
tagMatch ||
namespaceMatch ||
customizedMatch ||
fullNameMatch ||
tagsMatch ||
versionMatch ||
digestMatch
);
});
});
}, [imageSearch, imageFilterValues, defaultSortedImages]);
return (
<>
<Flex
direction="column"
align="stretch"
style={{
flex: 1,
...style,
}}
>
<Flex justify="end" style={{ padding: token.paddingSM }} gap={'xs'}>
{selectedRows.length > 0 ? (
<Typography.Text>
{t('general.NSelected', {
count: selectedRows.length,
})}
</Typography.Text>
) : null}
<Input
allowClear
prefix={<SearchOutlined />}
placeholder={t('environment.SearchImages')}
onChange={(e) => {
startSearchTransition(() => setImageSearch(e.target.value));
}}
style={{
width: 200,
}}
/>
<Button
icon={<ReloadOutlined />}
loading={isPendingRefreshTransition}
onClick={() => {
setSelectedRows([]);
startRefreshTransition(() => updateEnvironmentFetchKey());
}}
>
{t('button.Refresh')}
</Button>
<Button
icon={<VerticalAlignBottomOutlined />}
style={{ backgroundColor: token.colorPrimary, color: 'white' }}
onClick={() => {
if (selectedRows.length === 0) {
message.error(t('environment.NoImagesAreSelected'));
return;
}
if (selectedRows.some((image) => !image.installed)) {
setIsOpenInstallModal(true);
return;
}
message.error(t('environment.AlreadyInstalledImage'));
}}
>
{t('environment.Install')}
</Button>
</Flex>
<BAITable
resizable
rowKey="id"
scroll={{ x: 'max-content' }}
pagination={{
showTotal(total, range) {
return `${range[0]}-${range[1]} of ${total} items`;
},
pageSizeOptions: ['10', '20', '50'],
style: { marginRight: token.marginXS },
}}
dataSource={filterNonNullItems(filteredImageData)}
columns={_.filter(
columns,
(column) => !_.includes(hiddenColumnKeys, _.toString(column?.key)),
)}
loading={isPendingSearchTransition}
rowSelection={{
type: 'checkbox',
// hideSelectAll: true,
// columnWidth: 48,
onChange: (_, selectedRows) => {
setSelectedRows(selectedRows);
},
selectedRowKeys: selectedRows.map((row) => row.id) as Key[],
}}
onRow={(record) => ({
onClick: (e) => {
// selected or deselect row
if (selectedRows.find((row) => row.id === record.id)) {
setSelectedRows((rows) =>
rows.filter((row) => row.id !== record.id),
);
} else {
setSelectedRows((rows) => [...rows, record]);
}
},
})}
showSorterTooltip={false}
sortDirections={['descend', 'ascend', 'descend']}
/>
<Flex
justify="end"
style={{
padding: token.paddingXXS,
}}
>
<Button
type="text"
icon={<SettingOutlined />}
onClick={() => {
toggleColumnSettingModal();
}}
/>
</Flex>
</Flex>
<ManageImageResourceLimitModal
open={!!managingResourceLimit}
onRequestClose={(success) => {
setManagingResourceLimit(null);
if (success)
startTransition(() => {
updateEnvironmentFetchKey();
});
}}
imageFrgmt={managingResourceLimit}
/>
<ManageAppsModal
open={!!managingApp}
onRequestClose={(success) => {
setManagingApp(null);
if (success)
startTransition(() => {
updateEnvironmentFetchKey();
});
}}
imageFrgmt={managingApp}
/>
<ImageInstallModal
open={isOpenInstallModal}
onRequestClose={() => {
setIsOpenInstallModal(false);
}}
setInstallingImages={setInstallingImages}
selectedRows={selectedRows}
/>
<TableColumnsSettingModal
open={visibleColumnSettingModal}
onRequestClose={(values) => {
values?.selectedColumnKeys &&
setHiddenColumnKeys(
_.difference(
columns.map((column) => _.toString(column.key)),
values?.selectedColumnKeys,
),
);
toggleColumnSettingModal();
}}
columns={columns}
hiddenColumnKeys={hiddenColumnKeys}
/>
</>
);
};
export default ImageList;