CollectionData.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. import { useState, useEffect, useRef, useContext } from 'react';
  2. import { Typography } from '@material-ui/core';
  3. import { useTranslation } from 'react-i18next';
  4. import { rootContext, dataContext } from '@/context';
  5. import { DataService } from '@/http';
  6. import { useQuery } from '@/hooks';
  7. import { saveCsvAs, getColumnWidth } from '@/utils';
  8. import icons from '@/components/icons/Icons';
  9. import CustomButton from '@/components/customButton/CustomButton';
  10. import AttuGrid from '@/components/grid/Grid';
  11. import { ToolBarConfig } from '@/components/grid/Types';
  12. import Filter from '@/components/advancedSearch';
  13. import DeleteTemplate from '@/components/customDialog/DeleteDialogTemplate';
  14. import CustomToolBar from '@/components/grid/ToolBar';
  15. import InsertDialog from '@/pages/dialogs/insert/Dialog';
  16. import EditEntityDialog from '@/pages/dialogs/EditEntityDialog';
  17. import { getLabelDisplayedRows } from '@/pages/search/Utils';
  18. import { getQueryStyles } from './Styles';
  19. import {
  20. DYNAMIC_FIELD,
  21. DataTypeStringEnum,
  22. CONSISTENCY_LEVEL_OPTIONS,
  23. ConsistencyLevelEnum,
  24. } from '@/consts';
  25. import CustomSelector from '@/components/customSelector/CustomSelector';
  26. import EmptyDataDialog from '@/pages/dialogs/EmptyDataDialog';
  27. import ImportSampleDialog from '@/pages/dialogs/ImportSampleDialog';
  28. import { detectItemType } from '@/utils';
  29. import { CollectionObject, CollectionFullObject } from '@server/types';
  30. import StatusIcon, { LoadingType } from '@/components/status/StatusIcon';
  31. import CustomInput from '@/components/customInput/CustomInput';
  32. import CustomMultiSelector from '@/components/customSelector/CustomMultiSelector';
  33. export interface CollectionDataProps {
  34. collectionName: string;
  35. collections: CollectionObject[];
  36. }
  37. const CollectionData = (props: CollectionDataProps) => {
  38. // props
  39. const { collections } = props;
  40. const collection = collections.find(
  41. i => i.collection_name === props.collectionName
  42. ) as CollectionFullObject;
  43. // collection is not found or collection full object is not ready
  44. if (!collection || !collection.consistency_level) {
  45. return <StatusIcon type={LoadingType.CREATING} />;
  46. }
  47. // UI state
  48. const [tableLoading, setTableLoading] = useState<boolean>();
  49. const [selectedData, setSelectedData] = useState<any[]>([]);
  50. const [expression, setExpression] = useState<string>('');
  51. const [consistencyLevel, setConsistencyLevel] = useState<string>(
  52. collection.consistency_level
  53. );
  54. // collection fields, combine static and dynamic fields
  55. const fields = [
  56. ...collection.schema.fields,
  57. ...collection.schema.dynamicFields,
  58. ];
  59. // UI functions
  60. const { setDialog, handleCloseDialog, openSnackBar } =
  61. useContext(rootContext);
  62. const { fetchCollection } = useContext(dataContext);
  63. // icons
  64. const ResetIcon = icons.refresh;
  65. // translations
  66. const { t: dialogTrans } = useTranslation('dialog');
  67. const { t: successTrans } = useTranslation('success');
  68. const { t: searchTrans } = useTranslation('search');
  69. const { t: collectionTrans } = useTranslation('collection');
  70. const { t: btnTrans } = useTranslation('btn');
  71. const { t: commonTrans } = useTranslation();
  72. const gridTrans = commonTrans('grid');
  73. // classes
  74. const classes = getQueryStyles();
  75. // UI ref
  76. const filterRef = useRef();
  77. const inputRef = useRef<HTMLInputElement>();
  78. // UI event handlers
  79. const handleFilterReset = async () => {
  80. // reset advanced filter
  81. const currentFilter: any = filterRef.current;
  82. currentFilter?.getReset();
  83. // update UI expression
  84. setExpression('');
  85. // reset query
  86. reset();
  87. // ensure not loading
  88. setTableLoading(false);
  89. };
  90. const handleFilterSubmit = async (expression: string) => {
  91. // update UI expression
  92. setExpression(expression);
  93. // update expression
  94. setExpr(expression);
  95. };
  96. const handlePageChange = async (e: any, page: number) => {
  97. // do the query
  98. await query(page, consistencyLevel);
  99. // update page number
  100. setCurrentPage(page);
  101. };
  102. const onSelectChange = (value: any) => {
  103. setSelectedData(value);
  104. };
  105. const onDelete = async () => {
  106. // reset query
  107. reset();
  108. count(ConsistencyLevelEnum.Strong);
  109. await query(0, ConsistencyLevelEnum.Strong);
  110. };
  111. const handleDelete = async () => {
  112. // call delete api
  113. await DataService.deleteEntities(collection.collection_name, {
  114. expr: `${collection!.schema.primaryField.name} in [${selectedData
  115. .map(v =>
  116. collection!.schema.primaryField.data_type ===
  117. DataTypeStringEnum.VarChar
  118. ? `"${v[collection!.schema.primaryField.name]}"`
  119. : v[collection!.schema.primaryField.name]
  120. )
  121. .join(',')}]`,
  122. });
  123. handleCloseDialog();
  124. openSnackBar(successTrans('delete', { name: collectionTrans('entities') }));
  125. setSelectedData([]);
  126. await onDelete();
  127. };
  128. // Query hook
  129. const {
  130. currentPage,
  131. total,
  132. pageSize,
  133. expr,
  134. queryResult,
  135. setPageSize,
  136. setCurrentPage,
  137. setExpr,
  138. query,
  139. reset,
  140. count,
  141. outputFields,
  142. setOutputFields,
  143. } = useQuery({
  144. collection,
  145. consistencyLevel,
  146. fields,
  147. onQueryStart: (expr: string = '') => {
  148. setTableLoading(true);
  149. if (expr === '') {
  150. handleFilterReset();
  151. return;
  152. }
  153. },
  154. onQueryFinally: () => {
  155. setTableLoading(false);
  156. },
  157. });
  158. const onInsert = async (collectionName: string) => {
  159. await fetchCollection(collectionName);
  160. };
  161. // Toolbar settings
  162. const toolbarConfigs: ToolBarConfig[] = [
  163. {
  164. icon: 'uploadFile',
  165. type: 'button',
  166. btnVariant: 'text',
  167. btnColor: 'secondary',
  168. label: btnTrans('importFile'),
  169. tooltip: btnTrans('importFileTooltip'),
  170. disabled: () => selectedData?.length > 0,
  171. onClick: () => {
  172. setDialog({
  173. open: true,
  174. type: 'custom',
  175. params: {
  176. component: (
  177. <InsertDialog
  178. defaultSelectedCollection={collection.collection_name}
  179. // user can't select partition on collection page, so default value is ''
  180. defaultSelectedPartition={''}
  181. collections={[collection!]}
  182. onInsert={onInsert}
  183. />
  184. ),
  185. },
  186. });
  187. },
  188. },
  189. {
  190. type: 'button',
  191. btnVariant: 'text',
  192. onClick: () => {
  193. setDialog({
  194. open: true,
  195. type: 'custom',
  196. params: {
  197. component: (
  198. <ImportSampleDialog
  199. collection={collection!}
  200. cb={async () => {
  201. await onInsert(collection.collection_name);
  202. await onDelete();
  203. }}
  204. />
  205. ),
  206. },
  207. });
  208. },
  209. tooltip: btnTrans('importSampleDataTooltip'),
  210. label: btnTrans('importSampleData'),
  211. icon: 'add',
  212. // tooltip: collectionTrans('deleteTooltip'),
  213. disabled: () => selectedData?.length > 0,
  214. },
  215. {
  216. icon: 'deleteOutline',
  217. type: 'button',
  218. btnVariant: 'text',
  219. onClick: () => {
  220. setDialog({
  221. open: true,
  222. type: 'custom',
  223. params: {
  224. component: (
  225. <EmptyDataDialog
  226. cb={async () => {
  227. openSnackBar(
  228. successTrans('empty', {
  229. name: collectionTrans('collection'),
  230. })
  231. );
  232. await onDelete();
  233. }}
  234. collection={collection!}
  235. />
  236. ),
  237. },
  238. });
  239. },
  240. label: btnTrans('empty'),
  241. tooltip: btnTrans('emptyTooltip'),
  242. disabled: () => selectedData?.length > 0 || total == 0,
  243. },
  244. {
  245. type: 'button',
  246. btnVariant: 'text',
  247. onClick: () => {
  248. setDialog({
  249. open: true,
  250. type: 'custom',
  251. params: {
  252. component: (
  253. <EditEntityDialog
  254. data={selectedData[0]}
  255. collection={collection!}
  256. />
  257. ),
  258. },
  259. });
  260. },
  261. label: btnTrans('edit'),
  262. icon: 'edit',
  263. tooltip: btnTrans('editEntityTooltip'),
  264. disabledTooltip: btnTrans('editEntityDisabledTooltip'),
  265. disabled: () => selectedData?.length !== 1,
  266. hideOnDisable() {
  267. return selectedData?.length === 0;
  268. },
  269. },
  270. {
  271. type: 'button',
  272. btnVariant: 'text',
  273. onClick: () => {
  274. saveCsvAs(selectedData, `${collection.collection_name}.query.csv`);
  275. },
  276. label: btnTrans('export'),
  277. icon: 'download',
  278. tooltip: btnTrans('exportTooltip'),
  279. disabledTooltip: btnTrans('downloadDisabledTooltip'),
  280. disabled: () => !selectedData?.length,
  281. },
  282. {
  283. type: 'button',
  284. btnVariant: 'text',
  285. onClick: async () => {
  286. let json = JSON.stringify(selectedData);
  287. try {
  288. await navigator.clipboard.writeText(json);
  289. alert(`${selectedData.length} rows copied to clipboard`);
  290. } catch (err) {
  291. console.error('Failed to copy text: ', err);
  292. }
  293. },
  294. label: btnTrans('copyJson'),
  295. icon: 'copy',
  296. tooltip: btnTrans('copyJsonTooltip'),
  297. disabledTooltip: btnTrans('downloadDisabledTooltip'),
  298. disabled: () => !selectedData?.length,
  299. },
  300. {
  301. type: 'button',
  302. btnVariant: 'text',
  303. onClick: () => {
  304. setDialog({
  305. open: true,
  306. type: 'custom',
  307. params: {
  308. component: (
  309. <DeleteTemplate
  310. label={btnTrans('drop')}
  311. title={dialogTrans('deleteTitle', {
  312. type: collectionTrans('entities'),
  313. })}
  314. text={collectionTrans('deleteDataWarning')}
  315. handleDelete={handleDelete}
  316. />
  317. ),
  318. },
  319. });
  320. },
  321. label: btnTrans('delete'),
  322. icon: 'delete',
  323. tooltip: btnTrans('deleteTooltip'),
  324. disabledTooltip: collectionTrans('deleteDisabledTooltip'),
  325. disabled: () => selectedData.length === 0,
  326. },
  327. ];
  328. useEffect(() => {
  329. if (inputRef.current) {
  330. inputRef.current.focus();
  331. }
  332. }, []);
  333. return (
  334. <div className={classes.root}>
  335. {collection && (
  336. <>
  337. <CustomToolBar toolbarConfigs={toolbarConfigs} hideOnDisable={true} />
  338. <div className={classes.toolbar}>
  339. <div className="left">
  340. <CustomInput
  341. type="text"
  342. textConfig={{
  343. label: expression
  344. ? collectionTrans('queryExpression')
  345. : collectionTrans('exprPlaceHolder'),
  346. key: 'advFilter',
  347. className: 'textarea',
  348. onChange: (value: string) => {
  349. setExpression(value);
  350. },
  351. value: expression,
  352. disabled: !collection.loaded,
  353. variant: 'filled',
  354. required: false,
  355. InputLabelProps: { shrink: true },
  356. InputProps: {
  357. endAdornment: (
  358. <Filter
  359. title={''}
  360. showTitle={false}
  361. fields={collection.schema.scalarFields}
  362. filterDisabled={!collection.loaded}
  363. onSubmit={handleFilterSubmit}
  364. showTooltip={false}
  365. />
  366. ),
  367. },
  368. onKeyDown: (e: any) => {
  369. if (e.key === 'Enter') {
  370. // reset page
  371. setCurrentPage(0);
  372. if (expr !== expression) {
  373. setExpr(expression);
  374. } else {
  375. // ensure query
  376. query();
  377. }
  378. e.preventDefault();
  379. }
  380. },
  381. }}
  382. checkValid={() => true}
  383. />
  384. <CustomSelector
  385. options={CONSISTENCY_LEVEL_OPTIONS}
  386. value={consistencyLevel}
  387. label={collectionTrans('consistency')}
  388. wrapperClass={classes.selector}
  389. disabled={!collection.loaded}
  390. variant="filled"
  391. onChange={(e: { target: { value: unknown } }) => {
  392. const consistency = e.target.value as string;
  393. setConsistencyLevel(consistency);
  394. }}
  395. />
  396. </div>
  397. <div className="right">
  398. <CustomMultiSelector
  399. className={classes.outputs}
  400. options={fields.map(f => {
  401. return {
  402. label:
  403. f.name === DYNAMIC_FIELD
  404. ? searchTrans('dynamicFields')
  405. : f.name,
  406. value: f.name,
  407. };
  408. })}
  409. values={outputFields}
  410. renderValue={selected => (
  411. <span>{`${(selected as string[]).length} ${
  412. gridTrans[
  413. (selected as string[]).length > 1 ? 'fields' : 'field'
  414. ]
  415. }`}</span>
  416. )}
  417. label={searchTrans('outputFields')}
  418. wrapperClass="selector"
  419. variant="filled"
  420. onChange={(e: { target: { value: unknown } }) => {
  421. // add value to output fields if not exist, remove if exist
  422. const newOutputFields = [...outputFields];
  423. const values = e.target.value as string[];
  424. const newFields = values.filter(
  425. v => !newOutputFields.includes(v as string)
  426. );
  427. const removeFields = newOutputFields.filter(
  428. v => !values.includes(v as string)
  429. );
  430. newOutputFields.push(...newFields);
  431. removeFields.forEach(f => {
  432. const index = newOutputFields.indexOf(f);
  433. newOutputFields.splice(index, 1);
  434. });
  435. // sort output fields by schema order
  436. newOutputFields.sort(
  437. (a, b) =>
  438. fields.findIndex(f => f.name === a) -
  439. fields.findIndex(f => f.name === b)
  440. );
  441. setOutputFields(newOutputFields);
  442. }}
  443. />
  444. <CustomButton
  445. className={classes.btn}
  446. onClick={handleFilterReset}
  447. disabled={!collection.loaded}
  448. startIcon={<ResetIcon classes={{ root: 'icon' }} />}
  449. >
  450. {btnTrans('reset')}
  451. </CustomButton>
  452. <CustomButton
  453. className={classes.btn}
  454. variant="contained"
  455. onClick={() => {
  456. setCurrentPage(0);
  457. if (expr !== expression) {
  458. setExpr(expression);
  459. } else {
  460. // ensure query
  461. query();
  462. }
  463. }}
  464. disabled={!collection.loaded}
  465. >
  466. {btnTrans('query')}
  467. </CustomButton>
  468. </div>
  469. </div>
  470. <AttuGrid
  471. toolbarConfigs={[]}
  472. colDefinitions={outputFields.map(i => {
  473. return {
  474. id: i,
  475. align: 'left',
  476. disablePadding: false,
  477. needCopy: true,
  478. formatter(_: any, cellData: any) {
  479. const itemType = detectItemType(cellData);
  480. switch (itemType) {
  481. case 'json':
  482. case 'array':
  483. case 'bool':
  484. const res = JSON.stringify(cellData);
  485. return <Typography title={res}>{res}</Typography>;
  486. default:
  487. return cellData;
  488. }
  489. },
  490. field: i,
  491. getStyle: d => {
  492. if (!d || !d.field) {
  493. return {};
  494. }
  495. return {
  496. minWidth: getColumnWidth(d.field),
  497. };
  498. },
  499. label: i === DYNAMIC_FIELD ? searchTrans('dynamicFields') : i,
  500. };
  501. })}
  502. primaryKey={collection.schema.primaryField.name}
  503. openCheckBox={true}
  504. isLoading={tableLoading}
  505. rows={queryResult.data}
  506. rowCount={total}
  507. tableHeaderHeight={46}
  508. rowHeight={43}
  509. selected={selectedData}
  510. setSelected={onSelectChange}
  511. page={currentPage}
  512. onPageChange={handlePageChange}
  513. setRowsPerPage={setPageSize}
  514. rowsPerPage={pageSize}
  515. labelDisplayedRows={getLabelDisplayedRows(
  516. gridTrans[queryResult.data.length > 1 ? 'entities' : 'entity'],
  517. `(${queryResult.latency || ''} ms)`
  518. )}
  519. noData={searchTrans(
  520. `${collection.loaded ? 'empty' : 'collectionNotLoaded'}`
  521. )}
  522. />
  523. </>
  524. )}
  525. </div>
  526. );
  527. };
  528. export default CollectionData;