Skip to content

Commit

Permalink
fix: update rename logic in upload section
Browse files Browse the repository at this point in the history
  • Loading branch information
harshsoni-harsh committed Jan 23, 2025
1 parent a709092 commit 98223f8
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 71 deletions.
1 change: 1 addition & 0 deletions src/app/actions/ftp/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { Client } from 'basic-ftp';

export async function connectToFTP(loc?: string) {
console.count('connecting...');
const host =
loc !== 'images' ? process.env.FTP_HOST : process.env.IMAGES_FTP_HOST;
const user =
Expand Down
2 changes: 0 additions & 2 deletions src/app/actions/ftp/getFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { connectToFTP } from './connect';

export async function GetFiles(loc: string) {
console.log('fetching...');
const client = await connectToFTP(loc);
try {
const files = await client.list();
Expand All @@ -13,7 +12,6 @@ export async function GetFiles(loc: string) {
size: file.size,
modifiedAt: file.modifiedAt,
})) ?? [];
console.dir({ filesData });
return filesData;
} catch (e) {
console.error(e);
Expand Down
109 changes: 62 additions & 47 deletions src/components/FTPComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,15 @@ export default function FTPComponent() {
const [data, setData] = useState<unknown[]>([]);
const [isUploading, setIsUploading] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isRenaming, setIsRenaming] = useState(false);
const [updatedFilename, setUpdatedFilename] = useState('');
const [loc, setLoc] = useState<'images' | 'docs'>('images');
const [editingFilename, setEditingFilename] = useState<string | null>(null); // Track which file is being edited

const toast = useToast();

// Fetch files on component mount
useEffect(() => {
async function fetchData() {
const fetchData = useCallback(async () => {
if (toast && loc) {
try {
setIsLoading(true);
const result = await GetFiles(loc);
Expand All @@ -49,45 +49,51 @@ export default function FTPComponent() {
setIsLoading(false);
}
}
fetchData();
}, [toast, loc]);

const handleUpload = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent the default form submission
setIsUploading(true);
// Fetch files on component mount
useEffect(() => {
fetchData();
}, [toast, loc, fetchData]);

const formData = new FormData(event.currentTarget); // Get form data
const file = formData.get('file') as File;
const handleUpload = useCallback(
async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent the default form submission
setIsUploading(true);

if (!file?.name) {
toast.push({
status: 'info',
title: 'Error Uploading to FTP server',
description: 'Please attach a file',
});
setIsUploading(false);
return;
}
const formData = new FormData(event.currentTarget); // Get form data
const file = formData.get('file') as File;

try {
await UploadFile({ formData, loc });
toast.push({
status: 'success',
title: 'File uploaded successfully.',
});
// Refresh the file list after upload
const result = await GetFiles(loc);
setData(result);
} catch (err: unknown) {
toast.push({
status: 'error',
title: 'Error Uploading to FTP server',
description: err as string,
});
} finally {
setIsUploading(false);
}
};
if (!file?.name) {
toast.push({
status: 'info',
title: 'Error Uploading to FTP server',
description: 'Please attach a file',
});
setIsUploading(false);
return;
}

try {
await UploadFile({ formData, loc });
toast.push({
status: 'success',
title: 'File uploaded successfully.',
});
// Refresh the file list after upload
await fetchData();
} catch (err: unknown) {
toast.push({
status: 'error',
title: 'Error Uploading to FTP server',
description: err as string,
});
} finally {
setIsUploading(false);
}
},
[loc, toast, fetchData]
);

const handleDownload = useCallback(
async (filename: string) => {
Expand Down Expand Up @@ -133,8 +139,7 @@ export default function FTPComponent() {
status: 'success',
title: `File ${filename} deleted successfully.`,
});
const result = await GetFiles(loc);
setData(result);
await fetchData();
} catch (e) {
const errorMsg = (e as { message: string })?.message || '';
toast.push({
Expand All @@ -144,13 +149,12 @@ export default function FTPComponent() {
});
}
},
[loc, toast]
[loc, toast, fetchData]
);

const handleRename = useCallback(
async (oldFilename: string) => {
if (updatedFilename === oldFilename) {
console.log('return');
setEditingFilename(null); // Reset editing state
setUpdatedFilename(''); // Clear the input field
return;
Expand All @@ -165,13 +169,13 @@ export default function FTPComponent() {
}

try {
setIsRenaming(true);
await renameFile({ oldFilename, newFilename: updatedFilename, loc });
toast.push({
status: 'success',
title: `File ${oldFilename} renamed to ${updatedFilename} successfully.`,
});
const result = await GetFiles(loc);
setData(result);
await fetchData();
setEditingFilename(null); // Reset editing state
setUpdatedFilename(''); // Clear the input field
} catch (e) {
Expand All @@ -181,9 +185,11 @@ export default function FTPComponent() {
title: 'Failed to rename file',
description: errorMsg,
});
} finally {
setIsRenaming(false);
}
},
[loc, toast, updatedFilename]
[loc, toast, updatedFilename, fetchData]
);

const columns = useMemo(
Expand Down Expand Up @@ -247,20 +253,28 @@ export default function FTPComponent() {
>
<Trash2 className="size-5" />
</button>
{editingFilename === row.original.name && (
{editingFilename == row.original.name && (
<Button
onClick={() => handleRename(row.original.name)}
size="sm"
variant="outline"
className="w-14 text-center"
>
Save
{isRenaming ? (
<div className="pb-2">
<Spinner muted />
</div>
) : (
'Save'
)}
</Button>
)}
</div>
),
},
],
[
isRenaming,
handleDownload,
handleDelete,
handleRename,
Expand All @@ -275,6 +289,7 @@ export default function FTPComponent() {
<CardTitle className="flex justify-between gap-2 flex-wrap">
<span>Files</span>
<Select
disabled={isLoading || isUploading}
value={loc}
onValueChange={(value: string) =>
setLoc(value as 'images' | 'docs')
Expand All @@ -294,7 +309,7 @@ export default function FTPComponent() {
<Input name="loc" className="hidden" value={loc} readOnly />
<Button
type="submit"
disabled={isUploading}
disabled={isUploading || isLoading}
className="flex items-center gap-2 min-w-20"
>
{isUploading ? (
Expand Down
2 changes: 1 addition & 1 deletion src/components/ReactTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const ReactTable = ({ columns, data }: ReactTableProps) => {
{table.getRowModel().rows.map((row) => (
<TableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
<TableCell key={cell.id} className="break-phrases">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
Expand Down
8 changes: 6 additions & 2 deletions src/components/react-table/HeaderSort.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,17 @@ const SortToggler = ({ type }: SortTogglerProps) => {
<ChevronUp
className={cn(
'h-3 w-3',
type === SortType.ASC ? 'text-foreground' : 'text-muted-foreground'
type === SortType.ASC
? 'text-foreground brightness-200'
: 'text-muted-foreground brightness-50'
)}
/>
<ChevronDown
className={cn(
'h-3 w-3 -mt-0.5',
type === SortType.DESC ? 'text-foreground' : 'text-muted-foreground'
type === SortType.DESC
? 'text-foreground brightness-200'
: 'text-muted-foreground brightness-50'
)}
/>
</div>
Expand Down
39 changes: 20 additions & 19 deletions src/sanity/components/creditIdInput.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { forwardRef, useEffect, useMemo } from "react";
import { PatchEvent, set, StringInputProps, unset, useFormValue } from "sanity";
import { TextInput } from "@sanity/ui";

import { forwardRef, useEffect, useMemo } from 'react';
import { PatchEvent, set, StringInputProps, unset, useFormValue } from 'sanity';
import { TextInput } from '@sanity/ui';

export function generateId(input: string) {
const cleanedInput = input.trim();
Expand All @@ -14,20 +14,27 @@ export function generateId(input: string) {
return `${prefix}${number}`;
}

return "";
return '';
}

const CreditIdInput = forwardRef<HTMLInputElement, StringInputProps>(
(props, ref) => {
const facultyName =
(useFormValue(["content", "head", "name"]) as string) ?? "";
console.log("Faculty Name:", facultyName); // Debugging
(useFormValue(['content', 'head', 'name']) as string) ?? '';

const idValue = useMemo(() => generateId(facultyName) || "default-id", [
facultyName,
]);
const idValue = useMemo(
() => generateId(facultyName) || 'default-id',
[facultyName]
);

const { schemaType, elementProps, changed, focused, renderDefault, ...filteredProps } = props;
const {
schemaType,
elementProps,
changed,
focused,
renderDefault,
...filteredProps
} = props;

const { value, onChange } = props;

Expand All @@ -41,16 +48,10 @@ const CreditIdInput = forwardRef<HTMLInputElement, StringInputProps>(
}
}, [idValue, onChange]);

return (
<TextInput
ref={ref}
readOnly
value={idValue || "Generating..."}
/>
);
return <TextInput ref={ref} readOnly value={idValue || 'Generating...'} />;
}
);

CreditIdInput.displayName = "CreditIdInput";
CreditIdInput.displayName = 'CreditIdInput';

export default CreditIdInput;

0 comments on commit 98223f8

Please sign in to comment.