Skip to content
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

fix: resolve contract import issue when no projects are created #166

Merged
merged 5 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
113 changes: 46 additions & 67 deletions src/components/project/NewProject/NewProject.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { Tooltip } from '@/components/ui';
import AppIcon, { AppIconType } from '@/components/ui/icon';
import { useFileTab } from '@/hooks';
import useCodeImport from '@/hooks/codeImport.hooks';
import { useLogActivity } from '@/hooks/logActivity.hooks';
import { baseProjectPath, useProject } from '@/hooks/projectV2.hooks';
import { useProject } from '@/hooks/projectV2.hooks';
import {
ContractLanguage,
ProjectTemplate,
Tree,
} from '@/interfaces/workspace.interface';
import { Analytics } from '@/utility/analytics';
import EventEmitter from '@/utility/eventEmitter';
import { downloadRepo } from '@/utility/gitRepoDownloader';
import { decodeBase64 } from '@/utility/utils';
import { delay } from '@/utility/utils';
import { Button, Form, Input, Modal, Radio, Upload, message } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import type { RcFile } from 'antd/lib/upload';
Expand Down Expand Up @@ -45,10 +44,11 @@ const NewProject: FC<Props> = ({
name,
}) => {
const [isActive, setIsActive] = useState(active);
const { createProject } = useProject();
const { createProject, projects } = useProject();
const [isLoading, setIsLoading] = useState(false);
const { createLog } = useLogActivity();
const { open: openTab } = useFileTab();
const [newProjectType, setNewProjectType] = useState(projectType);
const { importEncodedCode, removeImportParams } = useCodeImport();

const router = useRouter();
const {
Expand Down Expand Up @@ -91,7 +91,7 @@ const NewProject: FC<Props> = ({
try {
setIsLoading(true);

if (projectType === 'git') {
if (newProjectType === 'git') {
files = await downloadRepo(githubUrl as string);
}

Expand All @@ -108,7 +108,7 @@ const NewProject: FC<Props> = ({
Analytics.track('Create project', {
platform: 'IDE',
type: `TON - ${language}`,
sourceType: projectType,
sourceType: newProjectType,
template: values.template,
});
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Expand All @@ -127,87 +127,66 @@ const NewProject: FC<Props> = ({
}
};

const importFromCode = async (code: string) => {
try {
const defaultFileName = `main.${importLanguage}`;
if (!importLanguage || !['tact', 'func'].includes(importLanguage)) {
createLog(`Invalid language: ${importLanguage}`, 'error');
return;
}
await createProject({
name: 'temp',
language: importLanguage,
template: 'import',
file: null,
defaultFiles: [
{
id: '',
parent: null,
path: defaultFileName,
type: 'file' as const,
name: defaultFileName,
content: decodeBase64(code),
},
],
isTemporary: true,
});
const finalQueryParam = router.query;
delete finalQueryParam.code;
delete finalQueryParam.lang;
router.replace({ query: finalQueryParam }).catch(() => {});
openTab(defaultFileName, `${baseProjectPath}/temp/${defaultFileName}`);
} catch (error) {
if (error instanceof Error) {
createLog(error.message, 'error');
return;
const onRouterReady = async () => {
if (codeToImport) {
// Default to 'func' as the language if none is provided in the query parameters.
// This ensures backward compatibility for cases where the language was not included in the query params initially.
try {
await importEncodedCode(codeToImport, importLanguage ?? 'func');
} catch (error) {
if (error instanceof Error) {
createLog(error.message, 'error');
return;
}
createLog('Error in importing code', 'error');
}
return;
}
};

useEffect(() => {
if (codeToImport) {
importFromCode(codeToImport as string);
// When the IDE starts without any projects and no import URL is provided,
// or if projects already exist but the import URL is missing or the modal is inactive,
// skip setting up the New Project dialog for import.
if (
(projects.length == 0 && !importURL && !active) ||
(projects.length !== 0 && (!importURL || !active))
verytactical marked this conversation as resolved.
Show resolved Hide resolved
) {
return;
}

if (!importURL || !active) {
return;
// If there are no projects but an import URL is provided, set the project type to git
if (projects.length === 0 && importURL) {
setNewProjectType('git');
}

form.setFieldsValue({
template: 'import',
githubUrl: importURL || '',
githubUrl: importURL ?? '',
name: projectName ?? '',
language: importLanguage ?? 'func',
});
setIsActive(true);
const finalQueryParam = router.query;
delete finalQueryParam.importURL;
delete finalQueryParam.name;
router.replace({ query: finalQueryParam }).catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [importURL, projectName, form, codeToImport]);

const closeModal = () => {
setIsActive(false);
// Wait for the form to be set up before removing the import query parameters
await delay(100);
removeImportParams();
};

useEffect(() => {
EventEmitter.on('ONBOARDING_NEW_PROJECT', () => {
setIsActive(true);
});
return () => {
EventEmitter.off('ONBOARDING_NEW_PROJECT');
};
}, []);
if (!router.isReady) return;
onRouterReady();
rahulyadav-57 marked this conversation as resolved.
Show resolved Hide resolved
}, [router.isReady]);

const closeModal = () => {
setIsActive(false);
};

return (
<>
<Tooltip title={heading} placement="bottom">
<div
className={`${s.root} ${className} onboarding-new-project`}
onClick={() => {
if (projectType !== 'exampleTemplate') {
if (newProjectType !== 'exampleTemplate') {
setIsActive(true);
return;
}
Expand Down Expand Up @@ -270,7 +249,7 @@ const NewProject: FC<Props> = ({
</Form.Item>
</div>

{projectType === 'default' && (
{newProjectType === 'default' && (
<Form.Item
label="Select Template"
name="template"
Expand All @@ -280,7 +259,7 @@ const NewProject: FC<Props> = ({
</Form.Item>
)}

{projectType === 'local' && (
{newProjectType === 'local' && (
<Form.Item
label="Select contract zip file"
name="file"
Expand All @@ -303,7 +282,7 @@ const NewProject: FC<Props> = ({
</Form.Item>
)}

{projectType === 'git' && (
{newProjectType === 'git' && (
<Form.Item
label="Github Repository URL"
name="githubUrl"
Expand Down
17 changes: 3 additions & 14 deletions src/components/workspace/WorkspaceSidebar/WorkspaceSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AppData } from '@/constant/AppData';
import { useSettingAction } from '@/hooks/setting.hooks';
import { Form, Input, Popover, Select, Switch } from 'antd';
import Link from 'next/link';
import { FC, useContext, useEffect } from 'react';
import { FC, useContext } from 'react';
import s from './WorkspaceSidebar.module.scss';

export type WorkSpaceMenu = 'code' | 'build' | 'test-cases' | 'setting';
Expand All @@ -22,11 +22,7 @@ interface Props {
projectName?: string | null;
}

const WorkspaceSidebar: FC<Props> = ({
activeMenu,
onMenuClicked,
projectName,
}) => {
const WorkspaceSidebar: FC<Props> = ({ activeMenu, onMenuClicked }) => {
const {
isContractDebugEnabled,
toggleContractDebug,
Expand Down Expand Up @@ -63,12 +59,6 @@ const WorkspaceSidebar: FC<Props> = ({
},
];

useEffect(() => {
if (!projectName) {
onMenuClicked('code');
}
}, []);

const settingContent = () => (
<div>
<div className={s.settingItem}>
Expand Down Expand Up @@ -206,9 +196,8 @@ const WorkspaceSidebar: FC<Props> = ({
<div
className={`${s.action} ${
activeMenu === menu.value ? s.isActive : ''
} ${!projectName ? s.disabled : ''}`}
}`}
onClick={() => {
if (!projectName) return;
onMenuClicked(menu.value);
}}
>
Expand Down
60 changes: 60 additions & 0 deletions src/hooks/codeImport.hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { ContractLanguage } from '@/interfaces/workspace.interface';
import { decodeBase64 } from '@/utility/utils';
import { useRouter } from 'next/router';
import useFileTab from './fileTabs.hooks';
import { baseProjectPath, useProject } from './projectV2.hooks';

const useCodeImport = () => {
const router = useRouter();
const { createProject } = useProject();
const { open: openTab } = useFileTab();

const importEncodedCode = async (
code: string,
language: ContractLanguage,
) => {
const fileExtension = language === 'func' ? 'fc' : language;
const defaultFileName = `main.${fileExtension}`;

await removeImportParams();

await createProject({
name: 'temp',
language,
template: 'import',
file: null,
defaultFiles: [
{
id: '',
parent: null,
path: defaultFileName,
type: 'file' as const,
name: defaultFileName,
content: decodeBase64(code),
},
],
isTemporary: true,
});

openTab(defaultFileName, `${baseProjectPath}/temp/${defaultFileName}`);
};

const removeImportParams = async () => {
// Remove all query params related to importing code
const keysToRemove = ['code', 'lang', 'importURL', 'name'];
const finalQueryParam = Object.fromEntries(
Object.entries(router.query).filter(
([key]) => !keysToRemove.includes(key),
),
);

await router.replace({ query: finalQueryParam });
};

return {
importEncodedCode,
rahulyadav-57 marked this conversation as resolved.
Show resolved Hide resolved
removeImportParams,
};
};

export default useCodeImport;
rahulyadav-57 marked this conversation as resolved.
Show resolved Hide resolved
1 change: 0 additions & 1 deletion src/utility/eventEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import EventEmitterDefault from 'eventemitter3';
const eventEmitter = new EventEmitterDefault();

export interface EventEmitterPayloads {
ONBOARDING_NEW_PROJECT: { projectName: string };
LOG_CLEAR: undefined;
LOG: LogEntry;
ON_SPLIT_DRAG_END: { position?: number };
Expand Down
Loading