79 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2024-05-09 22:32:21 -07:00
"use client";
2024-04-28 01:33:28 -04:00
2024-05-09 22:32:21 -07:00
import { validateName } from "@/lib/utils";
import Image from "next/image";
import { useEffect, useRef } from "react";
import { Socket } from "socket.io-client";
2024-04-28 01:33:28 -04:00
export default function New({
2024-04-29 00:50:25 -04:00
socket,
2024-04-28 01:33:28 -04:00
type,
stopEditing,
2024-04-29 00:50:25 -04:00
addNew,
2024-04-28 01:33:28 -04:00
}: {
2024-05-09 22:32:21 -07:00
socket: Socket;
type: "file" | "folder";
stopEditing: () => void;
addNew: (name: string, type: "file" | "folder") => void;
2024-04-28 01:33:28 -04:00
}) {
2024-05-09 22:32:21 -07:00
const inputRef = useRef<HTMLInputElement>(null);
2024-04-28 01:33:28 -04:00
2024-05-11 18:03:42 -07:00
function createNew() {
2024-05-09 22:32:21 -07:00
const name = inputRef.current?.value;
2024-04-29 00:50:25 -04:00
2024-05-05 12:55:34 -07:00
if (name) {
2024-05-09 22:32:21 -07:00
const valid = validateName(name, "", type);
2024-05-05 12:55:34 -07:00
if (valid.status) {
if (type === "file") {
2024-05-09 22:32:21 -07:00
socket.emit(
"createFile",
name,
({ success }: { success: boolean }) => {
if (success) {
addNew(name, type);
}
}
);
2024-05-11 18:03:42 -07:00
} else {
socket.emit("createFolder", name, () => {
addNew(name, type);
});
2024-05-05 12:55:34 -07:00
}
2024-04-29 00:50:25 -04:00
}
}
2024-05-09 22:32:21 -07:00
stopEditing();
2024-05-11 18:03:42 -07:00
}
2024-04-28 01:33:28 -04:00
useEffect(() => {
2024-05-09 22:32:21 -07:00
inputRef.current?.focus();
}, []);
2024-04-28 01:33:28 -04:00
return (
<div className="w-full flex items-center h-7 px-1 hover:bg-secondary rounded-sm cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring">
<Image
src={
type === "file"
? "/icons/default_file.svg"
: "/icons/default_folder.svg"
}
alt="File Icon"
width={18}
height={18}
className="mr-2"
/>
<form
onSubmit={(e) => {
2024-05-09 22:32:21 -07:00
e.preventDefault();
createNew();
2024-04-28 01:33:28 -04:00
}}
>
<input
ref={inputRef}
className={`bg-transparent transition-all focus-visible:outline-none focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-ring rounded-sm w-full`}
2024-04-29 00:50:25 -04:00
onBlur={() => createNew()}
2024-04-28 01:33:28 -04:00
/>
</form>
</div>
2024-05-09 22:32:21 -07:00
);
2024-04-28 01:33:28 -04:00
}