80 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-04-11 04:24:36 -04:00
"use client"
import Image from "next/image"
import { getIconForFile } from "vscode-icons-js"
2024-04-27 11:08:19 -04:00
import { TFile, TTab } from "./types"
import { useEffect, useRef, useState } from "react"
2024-04-26 00:10:53 -04:00
export default function SidebarFile({
data,
selectFile,
2024-04-27 14:23:09 -04:00
handleRename,
2024-04-26 00:10:53 -04:00
}: {
data: TFile
2024-04-27 11:08:19 -04:00
selectFile: (file: TTab) => void
2024-04-27 14:23:09 -04:00
handleRename: (
id: string,
newName: string,
oldName: string,
type: "file" | "folder"
) => boolean
2024-04-26 00:10:53 -04:00
}) {
const [imgSrc, setImgSrc] = useState(`/icons/${getIconForFile(data.name)}`)
2024-04-27 11:08:19 -04:00
const [editing, setEditing] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
useEffect(() => {
if (editing) {
inputRef.current?.focus()
}
}, [editing])
2024-04-11 04:24:36 -04:00
2024-04-27 14:23:09 -04:00
const renameFile = () => {
const renamed = handleRename(
data.id,
inputRef.current?.value ?? data.name,
data.name,
"file"
)
if (!renamed && inputRef.current) {
inputRef.current.value = data.name
}
setEditing(false)
}
2024-04-11 04:24:36 -04:00
return (
2024-04-26 00:10:53 -04:00
<button
2024-04-27 11:08:19 -04:00
onClick={() => selectFile({ ...data, saved: true })}
onDoubleClick={() => {
setEditing(true)
}}
2024-04-26 00:10:53 -04:00
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"
>
2024-04-11 04:24:36 -04:00
<Image
2024-04-26 00:10:53 -04:00
src={imgSrc}
2024-04-11 04:24:36 -04:00
alt="File Icon"
width={18}
height={18}
className="mr-2"
2024-04-26 00:10:53 -04:00
onError={() => setImgSrc("/icons/default_file.svg")}
2024-04-11 04:24:36 -04:00
/>
2024-04-27 11:08:19 -04:00
<form
onSubmit={(e) => {
e.preventDefault()
2024-04-27 14:23:09 -04:00
renameFile()
2024-04-27 11:08:19 -04:00
}}
>
<input
ref={inputRef}
2024-04-28 01:33:28 -04:00
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-27 11:08:19 -04:00
editing ? "" : "pointer-events-none"
}`}
disabled={!editing}
defaultValue={data.name}
2024-04-27 14:23:09 -04:00
onBlur={() => renameFile()}
2024-04-27 11:08:19 -04:00
/>
</form>
2024-04-26 00:10:53 -04:00
</button>
2024-04-11 04:24:36 -04:00
)
}