Skip to content

feat: add creating directory through context menu in navigation tree #958

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jul 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/Errors/ResponseError/ResponseError.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export const ResponseError = ({
statusText = error;
}
if (error && typeof error === 'object') {
if ('statusText' in error && typeof error.statusText === 'string') {
if ('data' in error && typeof error.data === 'string') {
statusText = error.data;
} else if ('statusText' in error && typeof error.statusText === 'string') {
statusText = error.statusText;
} else if ('message' in error && typeof error.message === 'string') {
statusText = error.message;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.ydb-schema-create-directory-dialog {
&__label {
display: flex;
flex-direction: column;

margin-bottom: 8px;
}
&__description {
color: var(--g-color-text-secondary);
}
&__input-wrapper {
min-height: 48px;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import React from 'react';

import {Dialog, TextInput} from '@gravity-ui/uikit';

import {ResponseError} from '../../../../components/Errors/ResponseError';
import {schemaApi} from '../../../../store/reducers/schema/schema';
import {cn} from '../../../../utils/cn';
import i18n from '../../i18n';

import './CreateDirectoryDialog.scss';

const b = cn('ydb-schema-create-directory-dialog');

const relativePathInputId = 'relativePath';

interface SchemaTreeProps {
open: boolean;
onClose: VoidFunction;
parentPath: string;
onSuccess: (value: string) => void;
}

function validateRelativePath(value: string) {
if (value && /\s/.test(value)) {
return i18n('schema.tree.dialog.whitespace');
}
return '';
}

export function CreateDirectoryDialog({open, onClose, parentPath, onSuccess}: SchemaTreeProps) {
const [validationError, setValidationError] = React.useState('');
const [relativePath, setRelativePath] = React.useState('');
const [create, response] = schemaApi.useCreateDirectoryMutation();

const resetErrors = () => {
setValidationError('');
response.reset();
};

const handleUpdate = (updated: string) => {
setRelativePath(updated);
resetErrors();
};

const handleClose = () => {
onClose();
setRelativePath('');
resetErrors();
};

const handleSubmit = () => {
const path = `${parentPath}/${relativePath}`;
create({
database: parentPath,
path,
})
.unwrap()
.then(() => {
handleClose();
onSuccess(relativePath);
});
};

return (
<Dialog open={open} onClose={handleClose} size="s">
<Dialog.Header caption={i18n('schema.tree.dialog.header')} />
<form
onSubmit={(e) => {
e.preventDefault();
const validationError = validateRelativePath(relativePath);
setValidationError(validationError);
if (!validationError) {
handleSubmit();
}
}}
>
<Dialog.Body>
<label htmlFor={relativePathInputId} className={b('label')}>
<span className={b('description')}>
{i18n('schema.tree.dialog.description')}
</span>
{`${parentPath}/`}
</label>
<div className={b('input-wrapper')}>
<TextInput
placeholder={i18n('schema.tree.dialog.placeholder')}
value={relativePath}
onUpdate={handleUpdate}
autoFocus
hasClear
autoComplete={false}
disabled={response.isLoading}
validationState={validationError ? 'invalid' : undefined}
id={relativePathInputId}
errorMessage={validationError}
/>
</div>
{response.isError && (
<ResponseError
error={response.error}
defaultMessage={i18n('schema.tree.dialog.invalid')}
/>
)}
</Dialog.Body>
<Dialog.Footer
loading={response.isLoading}
textButtonApply={i18n('schema.tree.dialog.buttonApply')}
textButtonCancel={i18n('schema.tree.dialog.buttonCancel')}
onClickButtonCancel={handleClose}
propsButtonApply={{type: 'submit'}}
/>
</form>
</Dialog>
);
}
73 changes: 51 additions & 22 deletions src/containers/Tenant/Schema/SchemaTree/SchemaTree.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// todo: tableTree is very smart, so it is impossible to update it without re-render
// It is need change NavigationTree to dump component and pass props from parent component
// In this case we can store state of tree - uploaded entities, opened nodes, selected entity and so on
import React from 'react';

import {NavigationTree} from 'ydb-ui-components';
Expand All @@ -8,6 +11,7 @@ import {useQueryModes, useTypedDispatch} from '../../../../utils/hooks';
import {isChildlessPathType, mapPathTypeToNavigationTreeType} from '../../utils/schema';
import {getActions} from '../../utils/schemaActions';
import {getControls} from '../../utils/schemaControls';
import {CreateDirectoryDialog} from '../CreateDirectoryDialog/CreateDirectoryDialog';

interface SchemaTreeProps {
rootPath: string;
Expand All @@ -19,10 +23,12 @@ interface SchemaTreeProps {

export function SchemaTree(props: SchemaTreeProps) {
const {rootPath, rootName, rootType, currentPath, onActivePathUpdate} = props;

const dispatch = useTypedDispatch();

const [_, setQueryMode] = useQueryModes();
const [createDirectoryOpen, setCreateDirectoryOpen] = React.useState(false);
const [parentPath, setParentPath] = React.useState('');
const [schemaTreeKey, setSchemaTreeKey] = React.useState('');

const fetchPath = async (path: string) => {
const promise = dispatch(
Expand All @@ -49,34 +55,57 @@ export function SchemaTree(props: SchemaTreeProps) {

return childItems;
};

React.useEffect(() => {
// if the cached path is not in the current tree, show root
if (!currentPath?.startsWith(rootPath)) {
onActivePathUpdate(rootPath);
}
}, [currentPath, onActivePathUpdate, rootPath]);

const handleSuccessSubmit = (relativePath: string) => {
const newPath = `${parentPath}/${relativePath}`;
onActivePathUpdate(newPath);
setSchemaTreeKey(newPath);
};

const handleCloseDialog = () => {
setCreateDirectoryOpen(false);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here. I would set some loading state to dialog Apply buttons and close dialog on request success. If request fails we may show an error inside the dialog's body.

};

const handleOpenCreateDirectoryDialog = (value: string) => {
setParentPath(value);
setCreateDirectoryOpen(true);
};
return (
<NavigationTree
rootState={{
path: rootPath,
name: rootName,
type: mapPathTypeToNavigationTreeType(rootType),
collapsed: false,
}}
fetchPath={fetchPath}
getActions={getActions(dispatch, {
setActivePath: onActivePathUpdate,
setQueryMode,
})}
renderAdditionalNodeElements={getControls(dispatch, {
setActivePath: onActivePathUpdate,
})}
activePath={currentPath}
onActivePathUpdate={onActivePathUpdate}
cache={false}
virtualize
/>
<React.Fragment>
<CreateDirectoryDialog
onClose={handleCloseDialog}
open={createDirectoryOpen}
parentPath={parentPath}
onSuccess={handleSuccessSubmit}
/>
<NavigationTree
key={schemaTreeKey}
rootState={{
path: rootPath,
name: rootName,
type: mapPathTypeToNavigationTreeType(rootType),
collapsed: false,
}}
fetchPath={fetchPath}
getActions={getActions(dispatch, {
setActivePath: onActivePathUpdate,
setQueryMode,
showCreateDirectoryDialog: handleOpenCreateDirectoryDialog,
})}
renderAdditionalNodeElements={getControls(dispatch, {
setActivePath: onActivePathUpdate,
})}
activePath={currentPath}
onActivePathUpdate={onActivePathUpdate}
cache={false}
virtualize
/>
</React.Fragment>
);
}
10 changes: 9 additions & 1 deletion src/containers/Tenant/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,13 @@
"actions.selectQuery": "Select query...",
"actions.upsertQuery": "Upsert query...",
"actions.alterReplication": "Alter async replicaton...",
"actions.dropReplication": "Drop async replicaton..."
"actions.dropReplication": "Drop async replicaton...",
"actions.createDirectory": "Create directory",
"schema.tree.dialog.placeholder": "Relative path",
"schema.tree.dialog.invalid": "Invalid path",
"schema.tree.dialog.whitespace": "Whitespace is not allowed",
"schema.tree.dialog.header": "Create directory",
"schema.tree.dialog.description": "Inside",
"schema.tree.dialog.buttonCancel": "Cancel",
"schema.tree.dialog.buttonApply": "Create"
}
7 changes: 6 additions & 1 deletion src/containers/Tenant/utils/schemaActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ import {
interface ActionsAdditionalEffects {
setQueryMode: (mode: QueryMode) => void;
setActivePath: (path: string) => void;
showCreateDirectoryDialog: (path: string) => void;
}

const bindActions = (
path: string,
dispatch: React.Dispatch<any>,
additionalEffects: ActionsAdditionalEffects,
) => {
const {setActivePath, setQueryMode} = additionalEffects;
const {setActivePath, setQueryMode, showCreateDirectoryDialog} = additionalEffects;

const inputQuery = (tmpl: (path: string) => string, mode?: QueryMode) => () => {
if (mode) {
Expand All @@ -50,6 +51,9 @@ const bindActions = (
};

return {
createDirectory: () => {
showCreateDirectoryDialog(path);
},
createTable: inputQuery(createTableTemplate, 'script'),
createColumnTable: inputQuery(createColumnTableTemplate, 'script'),
createAsyncReplication: inputQuery(createAsyncReplicationTemplate, 'script'),
Expand Down Expand Up @@ -95,6 +99,7 @@ export const getActions =

const DIR_SET: ActionsSet = [
[copyItem],
[{text: i18n('actions.createDirectory'), action: actions.createDirectory}],
[
{text: i18n('actions.createTable'), action: actions.createTable},
{text: i18n('actions.createColumnTable'), action: actions.createColumnTable},
Expand Down
14 changes: 14 additions & 0 deletions src/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,20 @@ export class YdbEmbeddedAPI extends AxiosWrapper {
requestConfig: {signal},
});
}

createSchemaDirectory(database: string, path: string, {signal}: {signal?: AbortSignal} = {}) {
return this.post<{test: string}>(
this.getPath('/scheme/directory'),
{},
{
database,
path,
},
{
requestConfig: {signal},
},
);
}
}

export class YdbWebVersionAPI extends YdbEmbeddedAPI {
Expand Down
10 changes: 10 additions & 0 deletions src/store/reducers/schema/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ export default schema;

export const schemaApi = api.injectEndpoints({
endpoints: (builder) => ({
createDirectory: builder.mutation<unknown, {database: string; path: string}>({
queryFn: async ({database, path}, {signal}) => {
try {
const data = await window.api.createSchemaDirectory(database, path, {signal});
return {data};
} catch (error) {
return {error};
}
},
}),
getSchema: builder.query<TEvDescribeSchemeResult & {partial?: boolean}, {path: string}>({
queryFn: async ({path}, {signal}) => {
try {
Expand Down
Loading