-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathFileSidebar.tsx
More file actions
318 lines (294 loc) · 9.46 KB
/
FileSidebar.tsx
File metadata and controls
318 lines (294 loc) · 9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import React, { useMemo, useState } from "react"
import { cn } from "@/lib/utils"
import { PanelRightOpen, Plus, Loader2 } from "lucide-react"
import { TreeView } from "@/components/ui/tree-view"
import { Input } from "@/components/ui/input"
import { transformFilesToTreeData } from "@/lib/utils/transformFilesToTreeData"
import type {
ICreateFileProps,
ICreateFileResult,
IDeleteFileProps,
IDeleteFileResult,
IRenameFileProps,
IRenameFileResult,
} from "@/hooks/useFileManagement"
import type { Package } from "fake-snippets-api/lib/db/schema"
type FileName = string
interface FileSidebarProps {
files: Record<FileName, string>
currentFile: FileName | null
onFileSelect: (filename: FileName) => void
className?: string
fileSidebarState: ReturnType<typeof useState<boolean>>
handleCreateFile: (props: ICreateFileProps) => ICreateFileResult
handleDeleteFile: (props: IDeleteFileProps) => IDeleteFileResult
handleRenameFile: (props: IRenameFileProps) => IRenameFileResult
isCreatingFile: boolean
setIsCreatingFile: React.Dispatch<React.SetStateAction<boolean>>
pkg?: Package
isLoadingFiles?: boolean
loadingProgress?: string | null
preservedDirectories: Set<string>
}
const FileSidebar: React.FC<FileSidebarProps> = ({
files,
currentFile,
onFileSelect,
className,
fileSidebarState,
handleCreateFile,
handleDeleteFile,
handleRenameFile,
isCreatingFile,
setIsCreatingFile,
pkg,
isLoadingFiles = true,
loadingProgress = null,
preservedDirectories,
}) => {
const [sidebarOpen, setSidebarOpen] = fileSidebarState
const [newFileName, setNewFileName] = useState("")
const [errorMessage, setErrorMessage] = useState("")
const [renamingFile, setRenamingFile] = useState<string | null>(null)
const [selectedFolderForCreation, setSelectedFolderForCreation] = useState<
string | null
>(null)
const [openDropdownId, setOpenDropdownId] = useState<string | null>(null)
const selectedItemId = useMemo(() => {
if (selectedFolderForCreation) return selectedFolderForCreation
return currentFile || ""
}, [currentFile, selectedFolderForCreation])
const canModifyFiles = Boolean(pkg) && !isLoadingFiles
const onFolderSelect = (folderPath: string) => {
setSelectedFolderForCreation(folderPath)
}
const treeData = transformFilesToTreeData({
files,
currentFile,
renamingFile,
handleRenameFile,
handleDeleteFile,
setRenamingFile,
onFileSelect,
onFolderSelect,
canModifyFiles,
setErrorMessage,
setSelectedFolderForCreation,
openDropdownId,
setOpenDropdownId,
preservedDirectories,
})
const getCurrentFolderPath = (): string => {
if (selectedFolderForCreation) {
return selectedFolderForCreation
}
if (!selectedItemId || selectedItemId === "") return ""
const hasLeadingSlash = selectedItemId.startsWith("/")
const normalizedPath = hasLeadingSlash
? selectedItemId.slice(1)
: selectedItemId
const pathParts = selectedItemId.split("/")
if (pathParts.length > 1) {
const folderPath = pathParts.slice(0, -1).join("/")
return hasLeadingSlash ? `/${folderPath}` : folderPath
}
return hasLeadingSlash ? "/" : "/" // Default to root slash if project is slashed
}
const constructFilePath = (fileName: string): string => {
let trimmedFileName = fileName.trim()
if (!trimmedFileName) {
return ""
}
trimmedFileName = trimmedFileName.replace(/\/+/g, "/")
const currentFolder = getCurrentFolderPath()
if (trimmedFileName.startsWith("/")) {
return trimmedFileName
}
if (!currentFolder || currentFolder === "/") {
return currentFolder === "/" ? `/${trimmedFileName}` : trimmedFileName
}
const normFolder = currentFolder.replace(/^\/|\/$/g, "")
const normFileName = trimmedFileName.replace(/^\/|\/$/g, "")
if (
normFileName === normFolder ||
normFileName.startsWith(`${normFolder}/`)
) {
const hasLeadingSlash = currentFolder.startsWith("/")
return hasLeadingSlash ? `/${normFileName}` : normFileName
}
return `${currentFolder}/${trimmedFileName}`
}
const handleCreateFileInline = () => {
const finalFileName = constructFilePath(newFileName)
if (!finalFileName) {
setErrorMessage("File name cannot be empty")
return
}
const { newFileCreated } = handleCreateFile({
newFileName: finalFileName,
onError: (error) => {
setErrorMessage(error.message)
},
})
if (newFileCreated) {
setIsCreatingFile(false)
setNewFileName("")
setErrorMessage("")
onFileSelect(finalFileName)
setSelectedFolderForCreation(null)
}
}
const handleCreateFileBlur = () => {
if (newFileName.trim() === "") {
setIsCreatingFile(false)
setNewFileName("")
setErrorMessage("")
setSelectedFolderForCreation(null)
return
}
handleCreateFileInline()
}
const toggleSidebar = () => {
setSidebarOpen(!sidebarOpen)
setErrorMessage("")
setIsCreatingFile(false)
setNewFileName("")
setSelectedFolderForCreation(null)
}
return (
<div
className={cn(
"flex-shrink-0 transition-all duration-300 border-r relative",
!sidebarOpen ? "w-0 overflow-hidden" : "w-[14rem]",
className,
)}
onClick={(e) => {
if (e.target === e.currentTarget) {
setSelectedFolderForCreation("/")
onFileSelect("")
}
}}
>
<div
className="flex items-center justify-between px-2 py-2"
onClick={(e) => {
if (e.target === e.currentTarget) {
setSelectedFolderForCreation("/")
onFileSelect("")
}
}}
>
<button
onClick={(e) => {
e.stopPropagation()
toggleSidebar()
}}
className={`text-gray-400 scale-90 transition-opacity duration-200 ${!sidebarOpen ? "opacity-0 pointer-events-none" : "opacity-100"}`}
>
<PanelRightOpen />
</button>
<div className="flex items-center gap-2" onClick={(e) => e.stopPropagation()}>
{isLoadingFiles && (
<div className="flex items-center gap-1">
<Loader2 className="w-3 h-3 animate-spin text-gray-400" />
{loadingProgress && (
<span className="text-xs text-gray-400">{loadingProgress}</span>
)}
</div>
)}
<button
onClick={() => setIsCreatingFile(true)}
className="text-gray-400 hover:text-gray-600"
aria-label="Create new file"
>
<Plus className="w-5 h-5" />
</button>
</div>
</div>
{isCreatingFile && (
<div className="p-2" onClick={(e) => e.stopPropagation()}>
<Input
autoFocus
value={newFileName}
spellCheck={false}
onChange={(e) => {
setNewFileName(e.target.value)
if (errorMessage) {
setErrorMessage("")
}
}}
onBlur={handleCreateFileBlur}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault()
handleCreateFileInline()
} else if (e.key === "Escape") {
e.preventDefault()
setIsCreatingFile(false)
setNewFileName("")
setErrorMessage("")
setSelectedFolderForCreation(null)
} else if (e.key === "Tab") {
e.preventDefault()
const currentFolder = getCurrentFolderPath()
if (currentFolder && !newFileName.includes("/")) {
const displayPath = currentFolder.startsWith("/")
? currentFolder.slice(1)
: currentFolder
setNewFileName(`${displayPath}/`)
}
}
}}
placeholder={(() => {
const currentFolder = getCurrentFolderPath()
if (!currentFolder || currentFolder === "/") {
return "Enter file name (root folder)"
}
const displayPath = currentFolder.startsWith("/")
? currentFolder.slice(1)
: currentFolder
return `Enter file name (${displayPath}/)`
})()}
className={
errorMessage ? "border-red-500 focus:border-red-500" : ""
}
/>
{errorMessage && (
<div className="text-red-500 text-xs mt-1 px-1">{errorMessage}</div>
)}
<div className="text-gray-400 text-xs mt-1 px-1">
Tip: Use / for subfolders, Tab to auto-complete current folder
</div>
</div>
)}
<div
className="flex-1 border-t h-full overflow-y-auto"
onClick={(e) => {
if (e.target === e.currentTarget) {
setSelectedFolderForCreation("/")
onFileSelect("")
}
}}
>
<TreeView
data={treeData}
setSelectedItemId={(value) => {
if (value && files[value]) {
onFileSelect(value)
} else if (!value) {
onFileSelect("")
setSelectedFolderForCreation(null)
}
}}
selectedItemId={selectedItemId}
onSelectChange={(item) => {
if (item?.onClick) {
item.onClick()
}
}}
/>
</div>
</div>
)
}
export default FileSidebar