FileBrowser.tsx
⎇
Raw
1import "./FileBrowser.css";
2import {
3 type Accessor,
4 createEffect,
5 createResource,
6 createSignal,
7 For,
8 type InitializedResource,
9 on,
10 onMount,
11 type ResourceActions,
12 type Setter,
13 Show,
14} from "solid-js";
15import type { MediaFile, FileListing, Directory } from "music-server-shared/types";
16import type { AppOptions, PlaylistItem } from "../types";
17import { formatFilename, generateUUID, joinPath, LocalStorageValues, toast } from "../utils";
18import { ClosedFolderSVG, DownSVG, FilterSVG, MusicSVG, RefreshSVG, UpSVG } from "./SVG";
19import { clearDirectoryCache, getCover, listFiles, storedFilesLive } from "../offline";
20import { DownloadButton } from "./DownloadButton";
21import { LoadingScreen } from "./LoadingScreen";
22import type { FlatFileListing } from "../App";
23import { createStore, reconcile } from "solid-js/store";
24
25interface FileBrowserProps {
26 breadcrumbs: Accessor<string[]>;
27 currentDir: Accessor<string>;
28 setCurrentDir: Setter<string>;
29 playTrack: (track: PlaylistItem) => void;
30 playlist: Accessor<PlaylistItem[]>;
31 setPlaylist: Setter<PlaylistItem[]>;
32 showFileBrowser: Accessor<boolean>;
33 setShowFileBrowser: Setter<boolean>;
34 options: AppOptions;
35 isOffline: Accessor<boolean>;
36 files: InitializedResource<FlatFileListing>;
37 fetchFiles: ResourceActions<FlatFileListing>;
38}
39
40export default function FileBrowser(props: FileBrowserProps) {
41 const [loadingActions, setLoadingActions] = createSignal(0);
42 const [showActionButtons, setShowActionButtons] = createSignal(true);
43 const [showFilter, setShowFilter] = createSignal(false);
44 const [filter, setFilter] = createSignal("");
45 createEffect(
46 on(props.currentDir, () => {
47 setFilter("");
48 setShowFilter(false);
49 }),
50 );
51 createEffect(
52 on([showFilter, showActionButtons], ([showFilter, showActionButtons]) => {
53 if (!showActionButtons) setShowFilter(false);
54 if (!showFilter) setFilter("");
55 }),
56 );
57 const [cover, fetchCover] = createResource<string | undefined, { dir: string; offline: boolean }>(
58 () => ({ dir: props.currentDir(), offline: props.isOffline() }),
59 async (args, info) => {
60 if (info.value) URL.revokeObjectURL(info.value as string);
61 return await getCover(args.dir, props.options, false, args.offline);
62 },
63 { initialValue: undefined },
64 );
65
66 let dialogElement!: HTMLDialogElement;
67 let addAnywayButton!: HTMLButtonElement;
68
69 function handleBreadcrumbClick(index: number) {
70 if (index === 0) {
71 props.setCurrentDir("");
72 } else {
73 props.setCurrentDir(joinPath(...props.breadcrumbs().slice(1, index + 1)));
74 }
75 }
76
77 function fileToPlaylistItem(path: string, item: MediaFile): PlaylistItem {
78 return {
79 id: generateUUID(),
80 metadata: item.metadata,
81 path: path,
82 };
83 }
84
85 // Recursively convert file listing to PlaylistItem array
86 function listingToPlaylistItems(basePath: string, files: FileListing): PlaylistItem[] {
87 //keep sorting same as shown in the filebrowser
88 const sorted = Array.from(files.entries()).sort((a, b) => {
89 if ("metadata" in b[1] && !("metadata" in a[1])) return -1;
90 if ("metadata" in a[1] && !("metadata" in b[1])) return 1;
91 return (
92 "files" in a[1]
93 ? a[0]
94 : formatFilename({ path: a[0], metadata: a[1].metadata }, props.options.filebrowserDisplay)
95 ).localeCompare(
96 "files" in b[1]
97 ? b[0]
98 : formatFilename({ path: b[0], metadata: b[1].metadata }, props.options.filebrowserDisplay),
99 undefined,
100 { numeric: true },
101 );
102 });
103 let result: PlaylistItem[] = [];
104 for (const [fileName, file] of sorted) {
105 const fullPath = joinPath(basePath, fileName);
106 if ("metadata" in file) {
107 // It's an audio file
108 result.push(fileToPlaylistItem(fullPath, file));
109 } else if (file.files && file.files.size > 0) {
110 // It's a directory with files, recursively add its contents
111 result = [...result, ...listingToPlaylistItems(fullPath, file.files)];
112 }
113 }
114
115 return result;
116 }
117
118 function playFile(path: string, item: MediaFile) {
119 props.playTrack(fileToPlaylistItem(path, item));
120 }
121
122 function scrollPlaylistToBottom() {
123 setTimeout(() => {
124 const element = document.getElementById("playlist");
125 if (!element) return;
126 element.scrollTop = element.scrollHeight;
127 }, 0);
128 }
129
130 const addedToast = toast("", "info");
131 addedToast.hideToast();
132
133 async function playFiles(fullPath: string, recursive: boolean, queue: boolean, item?: MediaFile) {
134 if (recursive) {
135 setLoadingActions(loadingActions() + 1);
136 }
137 try {
138 let oldLength = 0;
139 let newPlaylist: PlaylistItem[];
140 const oldPlaylist = queue ? props.playlist() : [];
141 if (item) {
142 newPlaylist = [fileToPlaylistItem(fullPath, item)];
143 } else {
144 const files = await listFiles(fullPath, props.isOffline(), recursive);
145 newPlaylist = listingToPlaylistItems(fullPath, files);
146 if (queue) {
147 oldLength = oldPlaylist.length;
148 }
149 }
150 const addAction = () => {
151 if (newPlaylist.length !== 0 && oldLength === 0) props.playTrack(newPlaylist[0]);
152 props.setPlaylist([...oldPlaylist, ...newPlaylist]);
153 addedToast.hideToast();
154 addedToast.options.text = `Added ${newPlaylist.length} tracks`;
155 addedToast.showToast();
156 if (queue) scrollPlaylistToBottom();
157 else props.setShowFileBrowser(false);
158 };
159 if (
160 props.options.duplicateWarning &&
161 oldPlaylist.some((oldItem) => newPlaylist.some((newItem) => oldItem.path === newItem.path))
162 ) {
163 addAnywayButton.onclick = () => {
164 addAction();
165 dialogElement.close();
166 };
167 dialogElement.showModal();
168 } else {
169 addAction();
170 }
171 } finally {
172 if (recursive) {
173 setLoadingActions(loadingActions() - 1);
174 }
175 }
176 }
177
178 function reloadDirectory() {
179 clearDirectoryCache(props.currentDir()).then(() => props.fetchFiles.refetch());
180 getCover(props.currentDir(), props.options, false, props.isOffline(), true).then(() => fetchCover.refetch());
181 }
182
183 let filelistElement!: HTMLDivElement;
184 const scrollPositions: { part: string; pos: number }[] = [];
185 createEffect(
186 on(props.currentDir, () => {
187 //need the timeout, otherwise we could execute the scroll before rendering finishes
188 setTimeout(() => {
189 let parts = `${props.currentDir()}`.split("/");
190 if (props.currentDir() !== "") parts = ["", ...parts];
191 scrollPositions.length = Math.min(parts.length, scrollPositions.length);
192 for (let index = 0; index < parts.length; index++) {
193 const part = parts[index];
194 if (scrollPositions.length - 1 < index) {
195 scrollPositions.push({ part, pos: 0 });
196 } else if (scrollPositions[index].part !== part) {
197 scrollPositions[index] = { part, pos: 0 };
198 }
199 }
200 filelistElement.scrollTop = scrollPositions[scrollPositions.length - 1].pos;
201 }, 0);
202 }),
203 );
204
205 onMount(() => {
206 const savedFileBrowserButtons = localStorage.getItem(LocalStorageValues.fileBrowserButtons);
207 if (savedFileBrowserButtons !== null) setShowActionButtons(savedFileBrowserButtons === "true");
208 createEffect(() => localStorage.setItem(LocalStorageValues.fileBrowserButtons, showActionButtons().toString()));
209
210 filelistElement.addEventListener("scrollend", () => {
211 scrollPositions[scrollPositions.length - 1].pos = filelistElement.scrollTop;
212 });
213 });
214
215 function getAbsolutePathFiles() {
216 return props.files.latest.map(([name, item]) => {
217 return [joinPath(props.currentDir(), name), item] as [string, Directory | MediaFile];
218 });
219 }
220
221 interface FileProxy {
222 key: string;
223 fullPath: string;
224 displayName: string;
225 file: MediaFile | Directory;
226 }
227
228 //this proxy store allows us to diff changes correctly when the filelisting changes, only rerendering the changed items
229 //absolute paths are required here to make sure it's really the same file in the same directory
230 const [fileStore, setFileStore] = createStore<FileProxy[]>([]);
231
232 function fileSort(a: FileProxy, b: FileProxy): number {
233 //sort directories first
234 if ("metadata" in b.file && !("metadata" in a.file)) return -1;
235 if ("metadata" in a.file && !("metadata" in b.file)) return 1;
236 return a.displayName.localeCompare(b.displayName, undefined, { numeric: true });
237 }
238
239 createEffect(() => {
240 setFileStore(
241 reconcile(
242 getAbsolutePathFiles()
243 .map((value) => {
244 const fullPath = value[0];
245 const displayName =
246 "metadata" in value[1]
247 ? formatFilename({ path: value[0], metadata: value[1].metadata }, props.options.filebrowserDisplay)
248 : value[0].split("/").toReversed()[0];
249 return {
250 key: fullPath + displayName,
251 fullPath,
252 displayName,
253 file: value[1],
254 };
255 })
256 .filter((item) => {
257 return item.displayName.toLowerCase().includes(filter());
258 })
259 .sort(fileSort),
260 { key: "key" },
261 ),
262 );
263 });
264
265 const [downloadedChildren, setDownloadedChildren] = createStore<Record<string, number>>({});
266 createEffect(() => {
267 const storedFiles = storedFilesLive();
268 const newChildren: Record<string, number> = {};
269
270 for (const storedFile of storedFiles) {
271 const pathParts = storedFile.toString().split("/");
272 // Update all parent directories in the path
273 for (let i = 1; i <= pathParts.length; i++) {
274 const parentPath = pathParts.slice(0, i).join("/");
275 if (parentPath) {
276 newChildren[parentPath] = (newChildren[parentPath] || 0) + 1;
277 }
278 }
279 }
280 setDownloadedChildren(reconcile(newChildren));
281 });
282
283 return (
284 <>
285 <dialog
286 class="duplicate-warning-dialog"
287 ref={dialogElement}
288 onclick={(e) => e.target.nodeName === "DIALOG" && dialogElement.close()}
289 >
290 <div>
291 Some of the items you're trying to add already exists in your current playlist
292 <div class="buttons">
293 <button ref={addAnywayButton}>Add anyway</button>
294 <button onClick={() => dialogElement.close()}>Cancel</button>
295 </div>
296 </div>
297 </dialog>
298 <div classList={{ "file-browser": true, hidden: !props.showFileBrowser() }}>
299 <div classList={{ breadcrumb: true, "breadcrumb-nowrap": !showActionButtons() }}>
300 <For each={props.breadcrumbs()}>
301 {(crumb, index) => (
302 <>
303 <span title={crumb} onClick={() => handleBreadcrumbClick(index())}>
304 {crumb}
305 </span>
306 {index() < props.breadcrumbs().length - 1 && "/"}
307 </>
308 )}
309 </For>
310 <button
311 class="toggle-browser-actions"
312 title="Toggle filebrowser actions"
313 onclick={() => setShowActionButtons(!showActionButtons())}
314 >
315 {showActionButtons() ? <UpSVG /> : <DownSVG />}
316 </button>
317 </div>
318
319 <Show when={showActionButtons()}>
320 <div class="browser-actions">
321 <div>
322 <button
323 title="Replace playlist with all files in current directory"
324 onClick={() => playFiles(props.currentDir(), false, false)}
325 >
326 Play Directory
327 </button>
328 <button
329 title="Replace playlist with all files in current directory and all subdirectories"
330 onClick={() => playFiles(props.currentDir(), true, false)}
331 >
332 Play All
333 </button>
334 <button
335 title="Add all files in current directory to playlist"
336 onClick={() => playFiles(props.currentDir(), false, true)}
337 >
338 Queue Directory
339 </button>
340 <button
341 title="Add all files in current directory and all subdirectories to playlist"
342 onClick={() => playFiles(props.currentDir(), true, true)}
343 >
344 Queue All
345 </button>
346 </div>
347 <div class="spacer" />
348 <button title="Filter current directory" onClick={() => setShowFilter(!showFilter())}>
349 <FilterSVG />
350 </button>
351 <Show when={!props.isOffline()}>
352 <button
353 class="refresh-button"
354 title="Refresh current directory listing and cover art, refreshing the cache"
355 onClick={reloadDirectory}
356 >
357 <RefreshSVG />
358 </button>
359 </Show>
360 </div>
361 <Show when={showFilter()}>
362 <input
363 oninput={(e) => setFilter(e.target.value)}
364 onkeydown={(e) => e.key === "Escape" && setShowFilter(false)}
365 class="filter-files"
366 type="text"
367 placeholder="Filter files..."
368 />
369 </Show>
370 </Show>
371
372 <div class="file-list-wrapper">
373 <Show when={props.files.loading}>
374 <LoadingScreen />
375 </Show>
376
377 <div class="file-list" ref={filelistElement}>
378 <For each={fileStore}>
379 {({ fullPath, displayName, file }) => {
380 const isDirectory = !("metadata" in file);
381 return (
382 <>
383 <div
384 class={(isDirectory && "directory-item") || "file-item"}
385 onClick={() => {
386 (isDirectory && props.setCurrentDir(fullPath)) || playFile(fullPath, file as MediaFile);
387 }}
388 >
389 {(isDirectory && <ClosedFolderSVG forButton={false} />) || <MusicSVG />}
390 <span>{displayName}</span>
391 <div class="download-button-wrapper">
392 {isDirectory && !props.isOffline() && downloadedChildren[fullPath]}
393 <DownloadButton
394 fullPath={fullPath}
395 item={file}
396 fetchFiles={props.fetchFiles}
397 isOffline={props.isOffline}
398 currentDir={props.currentDir}
399 options={props.options}
400 />
401 </div>
402 <button
403 title="Add to Playlist"
404 onClick={(event) => {
405 event.stopPropagation();
406 if (isDirectory) {
407 playFiles(fullPath, true, true);
408 } else {
409 playFiles(fullPath, false, true, file);
410 }
411 }}
412 >
413 Add
414 </button>
415 </div>
416 </>
417 );
418 }}
419 </For>
420 </div>
421 </div>
422 <Show when={!props.options.hideCover && (cover.loading || cover())}>
423 <div class="cover">
424 <Show when={cover.loading}>
425 <LoadingScreen />
426 </Show>
427 <img src={cover()} alt="" />
428 </div>
429 </Show>
430 <Show when={loadingActions() > 0}>
431 <LoadingScreen text="Loading files from subdirectories, this might take a while.." />
432 </Show>
433 </div>
434 </>
435 );
436}
437