Collections.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import { useCallback, useContext, useEffect, useState } from 'react';
  2. import { Link } from 'react-router-dom';
  3. import { useNavigationHook } from '../../hooks/Navigation';
  4. import { ALL_ROUTER_TYPES } from '../../router/Types';
  5. import MilvusGrid from '../../components/grid/Grid';
  6. import CustomToolBar from '../../components/grid/ToolBar';
  7. import { CollectionCreateParam, CollectionView, DataTypeEnum } from './Types';
  8. import { ColDefinitionsType, ToolBarConfig } from '../../components/grid/Types';
  9. import { usePaginationHook } from '../../hooks/Pagination';
  10. import icons from '../../components/icons/Icons';
  11. import EmptyCard from '../../components/cards/EmptyCard';
  12. import Status from '../../components/status/Status';
  13. import { useTranslation } from 'react-i18next';
  14. import { ChildrenStatusType, StatusEnum } from '../../components/status/Types';
  15. import { makeStyles, Theme } from '@material-ui/core';
  16. import StatusIcon from '../../components/status/StatusIcon';
  17. import CustomToolTip from '../../components/customToolTip/CustomToolTip';
  18. import { rootContext } from '../../context/Root';
  19. import CreateCollection from './Create';
  20. import DeleteTemplate from '../../components/customDialog/DeleteDialogTemplate';
  21. import { CollectionHttp } from '../../http/Collection';
  22. import {
  23. useInsertDialogHook,
  24. useLoadAndReleaseDialogHook,
  25. } from '../../hooks/Dialog';
  26. import Highlighter from 'react-highlight-words';
  27. import { parseLocationSearch } from '../../utils/Format';
  28. import InsertContainer from '../../components/insert/Container';
  29. import { PartitionData } from '../partitions/Types';
  30. import { FieldData } from '../schema/Types';
  31. import { PartitionHttp } from '../../http/Partition';
  32. const useStyles = makeStyles((theme: Theme) => ({
  33. emptyWrapper: {
  34. marginTop: theme.spacing(2),
  35. },
  36. icon: {
  37. fontSize: '20px',
  38. marginLeft: theme.spacing(0.5),
  39. },
  40. dialogContent: {
  41. lineHeight: '24px',
  42. fontSize: '16px',
  43. },
  44. link: {
  45. color: theme.palette.common.black,
  46. },
  47. highlight: {
  48. color: theme.palette.primary.main,
  49. backgroundColor: 'transparent',
  50. },
  51. }));
  52. let timer: NodeJS.Timeout | null = null;
  53. // get init search value from url
  54. const { search = '' } = parseLocationSearch(window.location.search);
  55. const Collections = () => {
  56. useNavigationHook(ALL_ROUTER_TYPES.COLLECTIONS);
  57. const { handleAction } = useLoadAndReleaseDialogHook({ type: 'collection' });
  58. const { handleInsertDialog } = useInsertDialogHook();
  59. const [collections, setCollections] = useState<CollectionView[]>([]);
  60. const [searchedCollections, setSearchedCollections] = useState<
  61. CollectionView[]
  62. >([]);
  63. const {
  64. pageSize,
  65. handlePageSize,
  66. currentPage,
  67. handleCurrentPage,
  68. total,
  69. data: collectionList,
  70. } = usePaginationHook(searchedCollections);
  71. const [loading, setLoading] = useState<boolean>(true);
  72. const [selectedCollections, setSelectedCollections] = useState<
  73. CollectionView[]
  74. >([]);
  75. const { setDialog, handleCloseDialog, openSnackBar } =
  76. useContext(rootContext);
  77. const { t: collectionTrans } = useTranslation('collection');
  78. const { t: btnTrans } = useTranslation('btn');
  79. const { t: dialogTrans } = useTranslation('dialog');
  80. const { t: successTrans } = useTranslation('success');
  81. const classes = useStyles();
  82. const LoadIcon = icons.load;
  83. const ReleaseIcon = icons.release;
  84. const InfoIcon = icons.info;
  85. /**
  86. * insert needed data:
  87. * 1. partitions: according to selected collection, always selectable
  88. * 2. schema: according to selected collection, used as editable heads options
  89. */
  90. const [insertPartitions, setInsertPartitions] = useState<PartitionData[]>([]);
  91. const [insertSchema, setInsertSchema] = useState<FieldData[]>([]);
  92. const fetchData = useCallback(async () => {
  93. try {
  94. const res = await CollectionHttp.getCollections();
  95. const statusRes = await CollectionHttp.getCollectionsIndexState();
  96. setLoading(false);
  97. const collections = res.map(v => {
  98. const indexStatus = statusRes.find(item => item._name === v._name);
  99. Object.assign(v, {
  100. nameElement: (
  101. <Link to={`/collections/${v._name}`} className={classes.link}>
  102. <Highlighter
  103. textToHighlight={v._name}
  104. searchWords={[search]}
  105. highlightClassName={classes.highlight}
  106. />
  107. </Link>
  108. ),
  109. statusElement: <Status status={v._status} />,
  110. indexCreatingElement: (
  111. <StatusIcon
  112. type={indexStatus?._indexState || ChildrenStatusType.FINISH}
  113. />
  114. ),
  115. });
  116. return v;
  117. });
  118. // filter collection if url contains search param
  119. const filteredCollections = collections.filter(collection =>
  120. collection._name.includes(search)
  121. );
  122. setCollections(collections);
  123. setSearchedCollections(filteredCollections);
  124. } catch (err) {
  125. setLoading(false);
  126. }
  127. }, [classes.link, classes.highlight]);
  128. useEffect(() => {
  129. fetchData();
  130. }, [fetchData]);
  131. const handleInsert = useCallback(async (): Promise<boolean> => {
  132. return new Promise((resolve, reject) => {});
  133. }, []);
  134. const handleInsertCollectionChange = useCallback(
  135. async (name: string) => {
  136. const selectCollection = collections.find(c => c._name === name);
  137. console.log('select collection', selectCollection);
  138. if (selectCollection) {
  139. const partitions = await PartitionHttp.getPartitions(name);
  140. console.log('----- partitions', partitions);
  141. setInsertPartitions(partitions);
  142. const schema = selectCollection._fields || [];
  143. console.log('----- schema', schema);
  144. setInsertSchema(schema);
  145. }
  146. },
  147. [collections]
  148. );
  149. const handleCreateCollection = async (param: CollectionCreateParam) => {
  150. const data: CollectionCreateParam = JSON.parse(JSON.stringify(param));
  151. const vectorType = [DataTypeEnum.BinaryVector, DataTypeEnum.FloatVector];
  152. data.fields = data.fields.map(v =>
  153. vectorType.includes(v.data_type)
  154. ? {
  155. ...v,
  156. type_params: [{ key: 'dim', value: v.dimension }],
  157. }
  158. : v
  159. );
  160. await CollectionHttp.createCollection(data);
  161. handleCloseDialog();
  162. openSnackBar(
  163. successTrans('create', { name: collectionTrans('collection') })
  164. );
  165. fetchData();
  166. };
  167. const handleRelease = async (data: CollectionView) => {
  168. const res = await CollectionHttp.releaseCollection(data._name);
  169. openSnackBar(
  170. successTrans('release', { name: collectionTrans('collection') })
  171. );
  172. fetchData();
  173. return res;
  174. };
  175. const handleLoad = async (data: CollectionView) => {
  176. const res = await CollectionHttp.loadCollection(data._name);
  177. openSnackBar(successTrans('load', { name: collectionTrans('collection') }));
  178. fetchData();
  179. return res;
  180. };
  181. const handleDelete = async () => {
  182. for (const item of selectedCollections) {
  183. await CollectionHttp.deleteCollection(item._name);
  184. }
  185. openSnackBar(
  186. successTrans('delete', { name: collectionTrans('collection') })
  187. );
  188. fetchData();
  189. handleCloseDialog();
  190. setSelectedCollections([]);
  191. };
  192. const handleSearch = (value: string) => {
  193. if (timer) {
  194. clearTimeout(timer);
  195. }
  196. // add loading manually
  197. setLoading(true);
  198. timer = setTimeout(() => {
  199. const searchWords = [value];
  200. const list = value
  201. ? collections.filter(c => c._name.includes(value))
  202. : collections;
  203. const highlightList = list.map(c => {
  204. Object.assign(c, {
  205. nameElement: (
  206. <Link to={`/collections/${c._name}`} className={classes.link}>
  207. <Highlighter
  208. textToHighlight={c._name}
  209. searchWords={searchWords}
  210. highlightClassName={classes.highlight}
  211. />
  212. </Link>
  213. ),
  214. });
  215. return c;
  216. });
  217. setLoading(false);
  218. setSearchedCollections(highlightList);
  219. }, 300);
  220. };
  221. const toolbarConfigs: ToolBarConfig[] = [
  222. {
  223. label: collectionTrans('create'),
  224. onClick: () => {
  225. setDialog({
  226. open: true,
  227. type: 'custom',
  228. params: {
  229. component: (
  230. <CreateCollection handleCreate={handleCreateCollection} />
  231. ),
  232. },
  233. });
  234. },
  235. icon: 'add',
  236. },
  237. {
  238. label: btnTrans('insert'),
  239. onClick: () => {
  240. handleInsertDialog(
  241. <InsertContainer
  242. collections={collections}
  243. defaultSelectedCollection={
  244. selectedCollections.length === 1
  245. ? selectedCollections[0]._name
  246. : ''
  247. }
  248. handleSelectedCollectionChange={handleInsertCollectionChange}
  249. partitions={insertPartitions}
  250. // user can't select partition on collection page, so default value is ''
  251. defaultSelectedPartition={''}
  252. schema={insertSchema}
  253. handleInsert={handleInsert}
  254. />
  255. );
  256. },
  257. /**
  258. * insert validation:
  259. * 1. At least 1 available collection
  260. * 2. selected collections quantity shouldn't over 1
  261. */
  262. disabled: () =>
  263. collectionList.length === 0 || selectedCollections.length > 1,
  264. btnVariant: 'outlined',
  265. },
  266. {
  267. type: 'iconBtn',
  268. onClick: () => {
  269. setDialog({
  270. open: true,
  271. type: 'custom',
  272. params: {
  273. component: (
  274. <DeleteTemplate
  275. label={btnTrans('delete')}
  276. title={dialogTrans('deleteTitle', {
  277. type: collectionTrans('collection'),
  278. })}
  279. text={collectionTrans('deleteWarning')}
  280. handleDelete={handleDelete}
  281. />
  282. ),
  283. },
  284. });
  285. },
  286. label: collectionTrans('delete'),
  287. icon: 'delete',
  288. disabled: data => data.length === 0,
  289. },
  290. {
  291. label: 'Search',
  292. icon: 'search',
  293. searchText: search,
  294. onSearch: (value: string) => {
  295. handleSearch(value);
  296. },
  297. },
  298. ];
  299. const colDefinitions: ColDefinitionsType[] = [
  300. {
  301. id: '_id',
  302. align: 'left',
  303. disablePadding: true,
  304. label: collectionTrans('id'),
  305. },
  306. {
  307. id: 'nameElement',
  308. align: 'left',
  309. disablePadding: true,
  310. sortBy: '_name',
  311. label: collectionTrans('name'),
  312. },
  313. {
  314. id: 'statusElement',
  315. align: 'left',
  316. disablePadding: false,
  317. sortBy: '_status',
  318. label: collectionTrans('status'),
  319. },
  320. {
  321. id: '_rowCount',
  322. align: 'left',
  323. disablePadding: false,
  324. label: (
  325. <span className="flex-center">
  326. {collectionTrans('rowCount')}
  327. <CustomToolTip title={collectionTrans('tooltip')}>
  328. <InfoIcon classes={{ root: classes.icon }} />
  329. </CustomToolTip>
  330. </span>
  331. ),
  332. },
  333. {
  334. id: '_desc',
  335. align: 'left',
  336. disablePadding: false,
  337. label: collectionTrans('desc'),
  338. },
  339. {
  340. id: 'indexCreatingElement',
  341. align: 'left',
  342. disablePadding: false,
  343. label: '',
  344. },
  345. {
  346. id: 'action',
  347. align: 'center',
  348. disablePadding: false,
  349. label: '',
  350. showActionCell: true,
  351. isHoverAction: true,
  352. actionBarConfigs: [
  353. {
  354. onClick: (e: React.MouseEvent, row: CollectionView) => {
  355. const cb =
  356. row._status === StatusEnum.unloaded ? handleLoad : handleRelease;
  357. handleAction(row, cb);
  358. },
  359. icon: 'load',
  360. label: 'load',
  361. showIconMethod: 'renderFn',
  362. getLabel: (row: CollectionView) =>
  363. row._status === StatusEnum.loaded ? 'release' : 'load',
  364. renderIconFn: (row: CollectionView) =>
  365. row._status === StatusEnum.loaded ? <ReleaseIcon /> : <LoadIcon />,
  366. },
  367. ],
  368. },
  369. ];
  370. const handleSelectChange = (value: any) => {
  371. setSelectedCollections(value);
  372. };
  373. const handlePageChange = (e: any, page: number) => {
  374. handleCurrentPage(page);
  375. setSelectedCollections([]);
  376. };
  377. const CollectionIcon = icons.navCollection;
  378. return (
  379. <section className="page-wrapper">
  380. {collections.length > 0 || loading ? (
  381. <MilvusGrid
  382. toolbarConfigs={toolbarConfigs}
  383. colDefinitions={colDefinitions}
  384. rows={collectionList}
  385. rowCount={total}
  386. primaryKey="_name"
  387. selected={selectedCollections}
  388. setSelected={handleSelectChange}
  389. page={currentPage}
  390. onChangePage={handlePageChange}
  391. rowsPerPage={pageSize}
  392. setRowsPerPage={handlePageSize}
  393. isLoading={loading}
  394. />
  395. ) : (
  396. <>
  397. <CustomToolBar toolbarConfigs={toolbarConfigs} />
  398. <EmptyCard
  399. wrapperClass={`page-empty-card ${classes.emptyWrapper}`}
  400. icon={<CollectionIcon />}
  401. text={collectionTrans('noData')}
  402. />
  403. </>
  404. )}
  405. </section>
  406. );
  407. };
  408. export default Collections;