123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547 |
- import { useState, useEffect, useRef, useContext } from 'react';
- import { Typography } from '@material-ui/core';
- import { useTranslation } from 'react-i18next';
- import { rootContext, dataContext } from '@/context';
- import { DataService } from '@/http';
- import { useQuery } from '@/hooks';
- import { saveCsvAs, getColumnWidth } from '@/utils';
- import icons from '@/components/icons/Icons';
- import CustomButton from '@/components/customButton/CustomButton';
- import AttuGrid from '@/components/grid/Grid';
- import { ToolBarConfig } from '@/components/grid/Types';
- import Filter from '@/components/advancedSearch';
- import DeleteTemplate from '@/components/customDialog/DeleteDialogTemplate';
- import CustomToolBar from '@/components/grid/ToolBar';
- import InsertDialog from '@/pages/dialogs/insert/Dialog';
- import EditEntityDialog from '@/pages/dialogs/EditEntityDialog';
- import { getLabelDisplayedRows } from '@/pages/search/Utils';
- import { getQueryStyles } from './Styles';
- import {
- DYNAMIC_FIELD,
- DataTypeStringEnum,
- CONSISTENCY_LEVEL_OPTIONS,
- ConsistencyLevelEnum,
- } from '@/consts';
- import CustomSelector from '@/components/customSelector/CustomSelector';
- import EmptyDataDialog from '@/pages/dialogs/EmptyDataDialog';
- import ImportSampleDialog from '@/pages/dialogs/ImportSampleDialog';
- import { detectItemType } from '@/utils';
- import { CollectionObject, CollectionFullObject } from '@server/types';
- import StatusIcon, { LoadingType } from '@/components/status/StatusIcon';
- import CustomInput from '@/components/customInput/CustomInput';
- import CustomMultiSelector from '@/components/customSelector/CustomMultiSelector';
- export interface CollectionDataProps {
- collectionName: string;
- collections: CollectionObject[];
- }
- const CollectionData = (props: CollectionDataProps) => {
- // props
- const { collections } = props;
- const collection = collections.find(
- i => i.collection_name === props.collectionName
- ) as CollectionFullObject;
- // collection is not found or collection full object is not ready
- if (!collection || !collection.consistency_level) {
- return <StatusIcon type={LoadingType.CREATING} />;
- }
- // UI state
- const [tableLoading, setTableLoading] = useState<boolean>();
- const [selectedData, setSelectedData] = useState<any[]>([]);
- const [expression, setExpression] = useState<string>('');
- const [consistencyLevel, setConsistencyLevel] = useState<string>(
- collection.consistency_level
- );
- // collection fields, combine static and dynamic fields
- const fields = [
- ...collection.schema.fields,
- ...collection.schema.dynamicFields,
- ];
- // UI functions
- const { setDialog, handleCloseDialog, openSnackBar } =
- useContext(rootContext);
- const { fetchCollection } = useContext(dataContext);
- // icons
- const ResetIcon = icons.refresh;
- // translations
- const { t: dialogTrans } = useTranslation('dialog');
- const { t: successTrans } = useTranslation('success');
- const { t: searchTrans } = useTranslation('search');
- const { t: collectionTrans } = useTranslation('collection');
- const { t: btnTrans } = useTranslation('btn');
- const { t: commonTrans } = useTranslation();
- const gridTrans = commonTrans('grid');
- // classes
- const classes = getQueryStyles();
- // UI ref
- const filterRef = useRef();
- const inputRef = useRef<HTMLInputElement>();
- // UI event handlers
- const handleFilterReset = async () => {
- // reset advanced filter
- const currentFilter: any = filterRef.current;
- currentFilter?.getReset();
- // update UI expression
- setExpression('');
- // reset query
- reset();
- // ensure not loading
- setTableLoading(false);
- };
- const handleFilterSubmit = async (expression: string) => {
- // update UI expression
- setExpression(expression);
- // update expression
- setExpr(expression);
- };
- const handlePageChange = async (e: any, page: number) => {
- // do the query
- await query(page, consistencyLevel);
- // update page number
- setCurrentPage(page);
- };
- const onSelectChange = (value: any) => {
- setSelectedData(value);
- };
- const onDelete = async () => {
- // reset query
- reset();
- count(ConsistencyLevelEnum.Strong);
- await query(0, ConsistencyLevelEnum.Strong);
- };
- const handleDelete = async () => {
- // call delete api
- await DataService.deleteEntities(collection.collection_name, {
- expr: `${collection!.schema.primaryField.name} in [${selectedData
- .map(v =>
- collection!.schema.primaryField.data_type ===
- DataTypeStringEnum.VarChar
- ? `"${v[collection!.schema.primaryField.name]}"`
- : v[collection!.schema.primaryField.name]
- )
- .join(',')}]`,
- });
- handleCloseDialog();
- openSnackBar(successTrans('delete', { name: collectionTrans('entities') }));
- setSelectedData([]);
- await onDelete();
- };
- // Query hook
- const {
- currentPage,
- total,
- pageSize,
- expr,
- queryResult,
- setPageSize,
- setCurrentPage,
- setExpr,
- query,
- reset,
- count,
- outputFields,
- setOutputFields,
- } = useQuery({
- collection,
- consistencyLevel,
- fields,
- onQueryStart: (expr: string = '') => {
- setTableLoading(true);
- if (expr === '') {
- handleFilterReset();
- return;
- }
- },
- onQueryFinally: () => {
- setTableLoading(false);
- },
- });
- const onInsert = async (collectionName: string) => {
- await fetchCollection(collectionName);
- };
- // Toolbar settings
- const toolbarConfigs: ToolBarConfig[] = [
- {
- icon: 'uploadFile',
- type: 'button',
- btnVariant: 'text',
- btnColor: 'secondary',
- label: btnTrans('importFile'),
- tooltip: btnTrans('importFileTooltip'),
- disabled: () => selectedData?.length > 0,
- onClick: () => {
- setDialog({
- open: true,
- type: 'custom',
- params: {
- component: (
- <InsertDialog
- defaultSelectedCollection={collection.collection_name}
- // user can't select partition on collection page, so default value is ''
- defaultSelectedPartition={''}
- collections={[collection!]}
- onInsert={onInsert}
- />
- ),
- },
- });
- },
- },
- {
- type: 'button',
- btnVariant: 'text',
- onClick: () => {
- setDialog({
- open: true,
- type: 'custom',
- params: {
- component: (
- <ImportSampleDialog
- collection={collection!}
- cb={async () => {
- await onInsert(collection.collection_name);
- await onDelete();
- }}
- />
- ),
- },
- });
- },
- tooltip: btnTrans('importSampleDataTooltip'),
- label: btnTrans('importSampleData'),
- icon: 'add',
- // tooltip: collectionTrans('deleteTooltip'),
- disabled: () => selectedData?.length > 0,
- },
- {
- icon: 'deleteOutline',
- type: 'button',
- btnVariant: 'text',
- onClick: () => {
- setDialog({
- open: true,
- type: 'custom',
- params: {
- component: (
- <EmptyDataDialog
- cb={async () => {
- openSnackBar(
- successTrans('empty', {
- name: collectionTrans('collection'),
- })
- );
- await onDelete();
- }}
- collection={collection!}
- />
- ),
- },
- });
- },
- label: btnTrans('empty'),
- tooltip: btnTrans('emptyTooltip'),
- disabled: () => selectedData?.length > 0 || total == 0,
- },
- {
- type: 'button',
- btnVariant: 'text',
- onClick: () => {
- setDialog({
- open: true,
- type: 'custom',
- params: {
- component: (
- <EditEntityDialog
- data={selectedData[0]}
- collection={collection!}
- />
- ),
- },
- });
- },
- label: btnTrans('edit'),
- icon: 'edit',
- tooltip: btnTrans('editEntityTooltip'),
- disabledTooltip: btnTrans('editEntityDisabledTooltip'),
- disabled: () => selectedData?.length !== 1,
- hideOnDisable() {
- return selectedData?.length === 0;
- },
- },
- {
- type: 'button',
- btnVariant: 'text',
- onClick: () => {
- saveCsvAs(selectedData, `${collection.collection_name}.query.csv`);
- },
- label: btnTrans('export'),
- icon: 'download',
- tooltip: btnTrans('exportTooltip'),
- disabledTooltip: btnTrans('downloadDisabledTooltip'),
- disabled: () => !selectedData?.length,
- },
- {
- type: 'button',
- btnVariant: 'text',
- onClick: async () => {
- let json = JSON.stringify(selectedData);
- try {
- await navigator.clipboard.writeText(json);
- alert(`${selectedData.length} rows copied to clipboard`);
- } catch (err) {
- console.error('Failed to copy text: ', err);
- }
- },
- label: btnTrans('copyJson'),
- icon: 'copy',
- tooltip: btnTrans('copyJsonTooltip'),
- disabledTooltip: btnTrans('downloadDisabledTooltip'),
- disabled: () => !selectedData?.length,
- },
- {
- type: 'button',
- btnVariant: 'text',
- onClick: () => {
- setDialog({
- open: true,
- type: 'custom',
- params: {
- component: (
- <DeleteTemplate
- label={btnTrans('drop')}
- title={dialogTrans('deleteTitle', {
- type: collectionTrans('entities'),
- })}
- text={collectionTrans('deleteDataWarning')}
- handleDelete={handleDelete}
- />
- ),
- },
- });
- },
- label: btnTrans('delete'),
- icon: 'delete',
- tooltip: btnTrans('deleteTooltip'),
- disabledTooltip: collectionTrans('deleteDisabledTooltip'),
- disabled: () => selectedData.length === 0,
- },
- ];
- useEffect(() => {
- if (inputRef.current) {
- inputRef.current.focus();
- }
- }, []);
- return (
- <div className={classes.root}>
- {collection && (
- <>
- <CustomToolBar toolbarConfigs={toolbarConfigs} hideOnDisable={true} />
- <div className={classes.toolbar}>
- <div className="left">
- <CustomInput
- type="text"
- textConfig={{
- label: expression
- ? collectionTrans('queryExpression')
- : collectionTrans('exprPlaceHolder'),
- key: 'advFilter',
- className: 'textarea',
- onChange: (value: string) => {
- setExpression(value);
- },
- value: expression,
- disabled: !collection.loaded,
- variant: 'filled',
- required: false,
- InputLabelProps: { shrink: true },
- InputProps: {
- endAdornment: (
- <Filter
- title={''}
- showTitle={false}
- fields={collection.schema.scalarFields}
- filterDisabled={!collection.loaded}
- onSubmit={handleFilterSubmit}
- showTooltip={false}
- />
- ),
- },
- onKeyDown: (e: any) => {
- if (e.key === 'Enter') {
- // reset page
- setCurrentPage(0);
- if (expr !== expression) {
- setExpr(expression);
- } else {
- // ensure query
- query();
- }
- e.preventDefault();
- }
- },
- }}
- checkValid={() => true}
- />
- <CustomSelector
- options={CONSISTENCY_LEVEL_OPTIONS}
- value={consistencyLevel}
- label={collectionTrans('consistency')}
- wrapperClass={classes.selector}
- disabled={!collection.loaded}
- variant="filled"
- onChange={(e: { target: { value: unknown } }) => {
- const consistency = e.target.value as string;
- setConsistencyLevel(consistency);
- }}
- />
- </div>
- <div className="right">
- <CustomMultiSelector
- className={classes.outputs}
- options={fields.map(f => {
- return {
- label:
- f.name === DYNAMIC_FIELD
- ? searchTrans('dynamicFields')
- : f.name,
- value: f.name,
- };
- })}
- values={outputFields}
- renderValue={selected => (
- <span>{`${(selected as string[]).length} ${
- gridTrans[
- (selected as string[]).length > 1 ? 'fields' : 'field'
- ]
- }`}</span>
- )}
- label={searchTrans('outputFields')}
- wrapperClass="selector"
- variant="filled"
- onChange={(e: { target: { value: unknown } }) => {
- // add value to output fields if not exist, remove if exist
- const newOutputFields = [...outputFields];
- const values = e.target.value as string[];
- const newFields = values.filter(
- v => !newOutputFields.includes(v as string)
- );
- const removeFields = newOutputFields.filter(
- v => !values.includes(v as string)
- );
- newOutputFields.push(...newFields);
- removeFields.forEach(f => {
- const index = newOutputFields.indexOf(f);
- newOutputFields.splice(index, 1);
- });
- // sort output fields by schema order
- newOutputFields.sort(
- (a, b) =>
- fields.findIndex(f => f.name === a) -
- fields.findIndex(f => f.name === b)
- );
- setOutputFields(newOutputFields);
- }}
- />
- <CustomButton
- className={classes.btn}
- onClick={handleFilterReset}
- disabled={!collection.loaded}
- startIcon={<ResetIcon classes={{ root: 'icon' }} />}
- >
- {btnTrans('reset')}
- </CustomButton>
- <CustomButton
- className={classes.btn}
- variant="contained"
- onClick={() => {
- setCurrentPage(0);
- if (expr !== expression) {
- setExpr(expression);
- } else {
- // ensure query
- query();
- }
- }}
- disabled={!collection.loaded}
- >
- {btnTrans('query')}
- </CustomButton>
- </div>
- </div>
- <AttuGrid
- toolbarConfigs={[]}
- colDefinitions={outputFields.map(i => {
- return {
- id: i,
- align: 'left',
- disablePadding: false,
- needCopy: true,
- formatter(_: any, cellData: any) {
- const itemType = detectItemType(cellData);
- switch (itemType) {
- case 'json':
- case 'array':
- case 'bool':
- const res = JSON.stringify(cellData);
- return <Typography title={res}>{res}</Typography>;
- default:
- return cellData;
- }
- },
- field: i,
- getStyle: d => {
- if (!d || !d.field) {
- return {};
- }
- return {
- minWidth: getColumnWidth(d.field),
- };
- },
- label: i === DYNAMIC_FIELD ? searchTrans('dynamicFields') : i,
- };
- })}
- primaryKey={collection.schema.primaryField.name}
- openCheckBox={true}
- isLoading={tableLoading}
- rows={queryResult.data}
- rowCount={total}
- tableHeaderHeight={46}
- rowHeight={43}
- selected={selectedData}
- setSelected={onSelectChange}
- page={currentPage}
- onPageChange={handlePageChange}
- setRowsPerPage={setPageSize}
- rowsPerPage={pageSize}
- labelDisplayedRows={getLabelDisplayedRows(
- gridTrans[queryResult.data.length > 1 ? 'entities' : 'entity'],
- `(${queryResult.latency || ''} ms)`
- )}
- noData={searchTrans(
- `${collection.loaded ? 'empty' : 'collectionNotLoaded'}`
- )}
- />
- </>
- )}
- </div>
- );
- };
- export default CollectionData;
|