Skip to content

Commit

Permalink
create, rename, move file and folder
Browse files Browse the repository at this point in the history
  • Loading branch information
rahulyadav-57 committed Aug 29, 2024
1 parent c61fb64 commit b902cf4
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 76 deletions.
4 changes: 2 additions & 2 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ module.exports = {
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extra-non-null-assertion": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-for-in-array": "error",
"no-implied-eval": "off",
"@typescript-eslint/no-implied-eval": "error",
Expand All @@ -71,7 +71,7 @@ module.exports = {
"@typescript-eslint/no-loss-of-precision": "error",
"@typescript-eslint/no-meaningless-void-operator": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/no-misused-promises": "off",
"@typescript-eslint/no-mixed-enums": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error",
Expand Down
16 changes: 9 additions & 7 deletions src/components/workspace/WorkSpace/WorkSpace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ import s from './WorkSpace.module.scss';

const WorkSpace: FC = () => {
const workspaceAction = useWorkspaceActions();
const { clearLog } = useLogActivity();
const { clearLog, createLog } = useLogActivity();

const router = useRouter();
const [activeMenu, setActiveMenu] = useState<WorkSpaceMenu>('code');
Expand All @@ -41,15 +41,17 @@ const WorkSpace: FC = () => {
const [contract, setContract] = useState<any>('');

const { tab } = router.query;
const { activeProject } = useProjects();
const { activeProject, newFileFolder } = useProjects();

const activeFile = workspaceAction.activeFile(activeProject as string);

const commitItemCreation = (type: string, name: string) => {
console.log('commitItemCreation', type, name);
// workspaceAction
// .createNewItem('', name, type, projectId as string)
// .catch(() => {});
const commitItemCreation = async (type: Tree['type'], name: string) => {
if (!name) return;
try {
await newFileFolder(name, type);
} catch (error) {
createLog((error as Error).message, 'error');
}
};

const createSandbox = async (force: boolean = false) => {
Expand Down
31 changes: 18 additions & 13 deletions src/components/workspace/tree/FileTree/FileTree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,45 +9,50 @@ import {
import { FC } from 'react';
import { DndProvider } from 'react-dnd';
import s from './FileTree.module.scss';
import TreeNode from './TreeNode';
import TreeNode, { TreeNodeData } from './TreeNode';

interface Props {
projectId: string;
}

const FileTree: FC<Props> = ({ projectId }) => {
const { projectFiles } = useProjects();
const { activeProject, projectFiles, moveItem } = useProjects();

const getProjectFiles = (): NodeModel[] => {
return [...projectFiles].map((item) => {
if (!activeProject) return [];
return projectFiles.map((item) => {
return {
id: item.path,
parent: item.parent ?? 0,
id: `${activeProject}/${item.path}`,
parent: item.parent ? `${activeProject}/${item.parent}` : activeProject,
droppable: item.type === 'directory',
text: item.name,
data: {
path: item.path,
},
};
});
};

const handleDrop = (_: unknown, _options: DropOptions) => {
// workspaceAction.moveFile(
// options.dragSourceId as string,
// options.dropTargetId as string,
// projectId,
// );
const handleDrop = async (_: unknown, options: DropOptions) => {
await moveItem(
options.dragSourceId as string,
options.dropTargetId as string,
);
};

if (!activeProject) return null;

return (
<div className={s.root}>
<DndProvider backend={MultiBackend} options={getBackendOptions()}>
<Tree
tree={getProjectFiles()}
rootId={0}
rootId={activeProject}
onDrop={handleDrop}
render={(node, { depth, isOpen, onToggle }) => (
<TreeNode
projectId={projectId as string}
node={node}
node={node as NodeModel<TreeNodeData>}
depth={depth}
isOpen={isOpen}
onToggle={onToggle}
Expand Down
73 changes: 47 additions & 26 deletions src/components/workspace/tree/FileTree/TreeNode.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { useLogActivity } from '@/hooks/logActivity.hooks';
import { useProjects } from '@/hooks/projectV2.hooks';
import { useWorkspaceActions } from '@/hooks/workspace.hooks';
import { Project, Tree } from '@/interfaces/workspace.interface';
import { fileTypeFromFileName } from '@/utility/utils';
Expand All @@ -10,13 +12,17 @@ import ItemAction, { actionsTypes } from './ItemActions';
import TreePlaceholderInput from './TreePlaceholderInput';

interface Props {
node: NodeModel;
node: NodeModel<TreeNodeData>;
depth: number;
isOpen: boolean;
onToggle: (id: NodeModel['id']) => void;
projectId: Project['id'];
}

export interface TreeNodeData {
path: string;
}

const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
const { droppable } = node;
const indent = (depth + 1) * 15;
Expand All @@ -27,13 +33,15 @@ const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
const router = useRouter();
const { id: projectId } = router.query;

const { openFile, renameItem, deleteItem, createNewItem, isProjectEditable } =
useWorkspaceActions();
const { openFile, isProjectEditable } = useWorkspaceActions();
const { deleteProjectFile, renameProjectFile, newFileFolder } = useProjects();
const { createLog } = useLogActivity();

const disallowedFile = [
'message.cell.ts',
'stateInit.cell.ts',
'test.spec.js',
'setting.json',
];

const handleClick = (e: React.MouseEvent) => {
Expand All @@ -51,19 +59,32 @@ const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
setIsEditing(true);
};

const commitEditing = (name: string) => {
renameItem(node.id as string, name, projectId as string);
reset();
const commitEditing = async (name: string) => {
try {
await renameProjectFile(node.data?.path as string, name);
reset();
} catch (error) {
createLog((error as Error).message, 'error');
}
};

const commitItemCreation = async (name: string) => {
if (!newItemAdd) return;
const path = `${node.data?.path}/${name}`;
try {
await newFileFolder(path, newItemAdd);
reset();
} catch (error) {
createLog((error as Error).message, 'error');
}
};

const commitItemCreation = (name: string) => {
createNewItem(
node.id as string,
name,
newItemAdd,
projectId as string,
).catch(() => {});
reset();
const updateItemTypeCreation = (type: Tree['type']) => {
if (!isAllowed()) return;
if (node.droppable && !isOpen) {
onToggle(node.id);
}
setNewItemAdd(type);
};

const reset = () => {
Expand All @@ -86,8 +107,14 @@ const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
return ['Edit', 'Close'];
};

const deleteItemFromNode = () => {
deleteItem(node.id as string, projectId as string);
const deleteItemFromNode = async () => {
const nodePath = node.data?.path;
if (!nodePath) {
createLog(`'${nodePath}' not found`, 'error');
return;
}

await deleteProjectFile(nodePath);
};

const isAllowed = () => {
Expand Down Expand Up @@ -133,19 +160,13 @@ const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
}}
allowedActions={getAllowedActions() as actionsTypes[]}
onNewFile={() => {
if (!isAllowed()) {
return;
}
setNewItemAdd('file');
updateItemTypeCreation('file');
}}
onNewDirectory={() => {
if (!isAllowed()) {
return;
}
setNewItemAdd('directory');
updateItemTypeCreation('directory');
}}
onDelete={() => {
deleteItemFromNode();
deleteItemFromNode().catch(() => {});
}}
/>
)}
Expand All @@ -163,7 +184,7 @@ const TreeNode: FC<Props> = ({ node, depth, isOpen, onToggle }) => {
</div>
{newItemAdd && (
<TreePlaceholderInput
style={{ paddingInlineStart: 15 * (depth + 1) }}
style={{ paddingInlineStart: 15 * (depth + 2) }}
onSubmit={commitItemCreation}
onCancel={reset}
type={newItemAdd}
Expand Down
30 changes: 5 additions & 25 deletions src/components/workspace/tree/FileTree/TreePlaceholderInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,10 @@ const TreePlaceholderInput: FC<Props> = ({
return (
<div className={rootClassName} style={style}>
{type === 'directory' ? (
<FolderEdit
style={style}
inputRef={inputRef}
defaultValue={defaultValue}
/>
<FolderEdit inputRef={inputRef} defaultValue={defaultValue} />
) : (
<FileEdit
ext={ext}
style={style}
updateExt={updateExt}
inputRef={inputRef}
defaultValue={defaultValue}
Expand All @@ -90,14 +85,9 @@ interface FolderEditProps {
style?: React.CSSProperties;
}

const FolderEdit: FC<FolderEditProps> = ({ inputRef, defaultValue, style }) => {
const FolderEdit: FC<FolderEditProps> = ({ inputRef, defaultValue }) => {
return (
<input
ref={inputRef}
className={s.treeInput}
defaultValue={defaultValue}
style={style}
/>
<input ref={inputRef} className={s.treeInput} defaultValue={defaultValue} />
);
};

Expand All @@ -109,19 +99,9 @@ interface FileEditProps {
style?: React.CSSProperties;
}

const FileEdit: FC<FileEditProps> = ({
inputRef,
updateExt,
defaultValue,
style,
}) => {
const FileEdit: FC<FileEditProps> = ({ inputRef, updateExt, defaultValue }) => {
return (
<input
ref={inputRef}
onChange={updateExt}
defaultValue={defaultValue}
style={style}
/>
<input ref={inputRef} onChange={updateExt} defaultValue={defaultValue} />
);
};

Expand Down
50 changes: 48 additions & 2 deletions src/hooks/projectV2.hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,58 @@ export const useProjects = () => {
return projectName;
};

const newFileFolder = async (path: string, type: 'file' | 'directory') => {
if (!activeProject) return;
const newPath = `${baseProjectPath}${activeProject}/${path}`;
await fileSystem.create(newPath, type);
await loadProjectFiles(activeProject);
};

const deleteProjectFile = async (path: string) => {
if (!activeProject) return;
await fileSystem.remove(`${baseProjectPath}${activeProject}/${path}`, {
recursive: true,
});
await loadProjectFiles(activeProject);
};

const moveItem = async (oldPath: string, targetPath: string) => {
if (!activeProject) return;
if (oldPath === targetPath) return;

const newPath = targetPath + '/' + oldPath.split('/').pop();

await fileSystem.rename(
`${baseProjectPath}/${oldPath}`,
`${baseProjectPath}/${newPath}`,
);
await loadProjectFiles(activeProject);
};

const renameProjectFile = async (oldPath: string, newName: string) => {
if (!activeProject) return;
const newPath = oldPath.includes('/')
? oldPath.split('/').slice(0, -1).join('/') + '/' + newName
: newName;

const success = await fileSystem.rename(
`${baseProjectPath}${activeProject}/${oldPath}`,
`${baseProjectPath}${activeProject}/${newPath}`,
);
if (!success) return;
await loadProjectFiles(activeProject);
};

return {
projects,
createProject,
projectFiles,
deleteProject,
activeProject,
createProject,
deleteProject,
newFileFolder,
deleteProjectFile,
moveItem,
renameProjectFile,
setActiveProject,
};
};
Expand Down
Loading

0 comments on commit b902cf4

Please sign in to comment.