FileBrowser.tsx
⎇
Raw
1import "./FileBrowser.css";
2import type { Directory, FileListing, MediaFile } from "music-server-shared/types";
3import {
4 type Accessor,
5 createEffect,
6 createResource,
7 createSignal,
8 For,
9 type InitializedResource,
10 on,
11 onMount,
12 type ResourceActions,
13 type Setter,
14 Show,
15} from "solid-js";
16import { createStore, reconcile } from "solid-js/store";
17import type { FlatFileListing } from "../App";
18import { clearDirectoryCache, getCover, listFiles, storedFilesLive } from "../offline";
19import type { AppOptions, PlaylistItem } from "../types";
20import { formatFilename, generateUUID, joinPath, LocalStorageValues, toast } from "../utils";
21import { DownloadButton } from "./DownloadButton";
22import { LoadingScreen } from "./LoadingScreen";
23import { ClosedFolderSVG, DownSVG, FilterSVG, MusicSVG, RefreshSVG, UpSVG } from "./SVG";
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 const newPaths = new Set(newPlaylist.map((item) => item.path));
160 if (props.options.duplicateWarning && oldPlaylist.some((oldItem) => newPaths.has(oldItem.path))) {
161 addAnywayButton.onclick = () => {
162 addAction();
163 dialogElement.close();
164 };
165 dialogElement.showModal();
166 } else {
167 addAction();
168 }
169 } finally {
170 if (recursive) {
171 setLoadingActions(loadingActions() - 1);
172 }
173 }
174 }
175
176 function reloadDirectory() {
177 clearDirectoryCache(props.currentDir()).then(() => props.fetchFiles.refetch());
178 getCover(props.currentDir(), props.options, false, props.isOffline(), true).then(() => fetchCover.refetch());
179 }
180
181 let filelistElement!: HTMLDivElement;
182 const scrollPositions: { part: string; pos: number }[] = [];
183 let lastDir = props.currentDir();
184 createEffect(
185 //on props.files, because doing it on props.currentDir causes us to scroll up before the new content is being loaded
186 on(props.files, () => {
187 //don't update scroll pos if directory didn't change
188 //otherwise would cause jank when scrolling while in offline mode and synced items pop up
189 if (lastDir === props.currentDir()) return;
190 lastDir = props.currentDir();
191 //need the timeout, otherwise we could execute the scroll before rendering finishes
192 setTimeout(() => {
193 let parts = `${props.currentDir()}`.split("/");
194 if (props.currentDir() !== "") parts = ["", ...parts];
195 scrollPositions.length = Math.min(parts.length, scrollPositions.length);
196 for (let index = 0; index < parts.length; index++) {
197 const part = parts[index];
198 if (scrollPositions.length - 1 < index) {
199 scrollPositions.push({ part, pos: 0 });
200 } else if (scrollPositions[index].part !== part) {
201 scrollPositions[index] = { part, pos: 0 };
202 }
203 }
204 filelistElement.scrollTop = scrollPositions[scrollPositions.length - 1].pos;
205 }, 0);
206 }),
207 );
208
209 onMount(() => {
210 const savedFileBrowserButtons = localStorage.getItem(LocalStorageValues.fileBrowserButtons);
211 if (savedFileBrowserButtons !== null) setShowActionButtons(savedFileBrowserButtons === "true");
212 createEffect(() => localStorage.setItem(LocalStorageValues.fileBrowserButtons, showActionButtons().toString()));
213
214 filelistElement.addEventListener("scrollend", () => {
215 if (scrollPositions.length > 0) scrollPositions[scrollPositions.length - 1].pos = filelistElement.scrollTop;
216 });
217 });
218
219 function getAbsolutePathFiles() {
220 return props.files.latest.map(([name, item]) => {
221 return [joinPath(props.currentDir(), name), item] as [string, Directory | MediaFile];
222 });
223 }
224
225 interface FileProxy {
226 key: string;
227 fullPath: string;
228 displayName: string;
229 file: MediaFile | Directory;
230 }
231
232 //this proxy store allows us to diff changes correctly when the filelisting changes, only rerendering the changed items
233 //absolute paths are required here to make sure it's really the same file in the same directory
234 const [fileStore, setFileStore] = createStore<FileProxy[]>([]);
235
236 function fileSort(a: FileProxy, b: FileProxy): number {
237 //sort directories first
238 if ("metadata" in b.file && !("metadata" in a.file)) return -1;
239 if ("metadata" in a.file && !("metadata" in b.file)) return 1;
240 return a.displayName.localeCompare(b.displayName, undefined, { numeric: true });
241 }
242
243 createEffect(() => {
244 setFileStore(
245 reconcile(
246 getAbsolutePathFiles()
247 .map((value) => {
248 const fullPath = value[0];
249 const displayName =
250 "metadata" in value[1]
251 ? formatFilename({ path: value[0], metadata: value[1].metadata }, props.options.filebrowserDisplay)
252 : value[0].split("/").toReversed()[0];
253 return {
254 key: fullPath + displayName,
255 fullPath,
256 displayName,
257 file: value[1],
258 };
259 })
260 .filter((item) => {
261 return item.displayName.toLowerCase().includes(filter());
262 })
263 .sort(fileSort),
264 { key: "key" },
265 ),
266 );
267 });
268
269 const [downloadedChildren, setDownloadedChildren] = createStore<Record<string, number>>({});
270 createEffect(() => {
271 const storedFiles = storedFilesLive();
272 const newChildren: Record<string, number> = {};
273
274 for (const storedFile of storedFiles) {
275 const pathParts = storedFile.toString().split("/");
276 // Update all parent directories in the path
277 for (let i = 1; i <= pathParts.length; i++) {
278 const parentPath = pathParts.slice(0, i).join("/");
279 if (parentPath) {
280 newChildren[parentPath] = (newChildren[parentPath] || 0) + 1;
281 }
282 }
283 }
284 setDownloadedChildren(reconcile(newChildren));
285 });
286
287 return (
288 <>
289 <dialog
290 class="duplicate-warning-dialog"
291 ref={dialogElement}
292 onclick={(e) => e.target.nodeName === "DIALOG" && dialogElement.close()}
293 >
294 <div>
295 Some of the items you're trying to add already exists in your current playlist
296 <div class="buttons">
297 <button ref={addAnywayButton}>Add anyway</button>
298 <button onClick={() => dialogElement.close()}>Cancel</button>
299 </div>
300 </div>
301 </dialog>
302 <div classList={{ "file-browser": true, hidden: !props.showFileBrowser() }}>
303 <div classList={{ breadcrumb: true, "breadcrumb-nowrap": !showActionButtons() }}>
304 <For each={props.breadcrumbs()}>
305 {(crumb, index) => (
306 <>
307 <span title={crumb} onClick={() => handleBreadcrumbClick(index())}>
308 {crumb}
309 </span>
310 {index() < props.breadcrumbs().length - 1 && "/"}
311 </>
312 )}
313 </For>
314 <button
315 class="toggle-browser-actions"
316 title="Toggle filebrowser actions"
317 onclick={() => setShowActionButtons(!showActionButtons())}
318 >
319 {showActionButtons() ? <UpSVG /> : <DownSVG />}
320 </button>
321 </div>
322
323 <Show when={showActionButtons()}>
324 <div class="browser-actions">
325 <div>
326 <button
327 title="Replace playlist with all files in current directory"
328 onClick={() => playFiles(props.currentDir(), false, false)}
329 >
330 Play Directory
331 </button>
332 <button
333 title="Replace playlist with all files in current directory and all subdirectories"
334 onClick={() => playFiles(props.currentDir(), true, false)}
335 >
336 Play All
337 </button>
338 <button
339 title="Add all files in current directory to playlist"
340 onClick={() => playFiles(props.currentDir(), false, true)}
341 >
342 Queue Directory
343 </button>
344 <button
345 title="Add all files in current directory and all subdirectories to playlist"
346 onClick={() => playFiles(props.currentDir(), true, true)}
347 >
348 Queue All
349 </button>
350 </div>
351 <div class="spacer" />
352 <button title="Filter current directory" onClick={() => setShowFilter(!showFilter())}>
353 <FilterSVG />
354 </button>
355 <Show when={!props.isOffline()}>
356 <button
357 class="refresh-button"
358 title="Refresh current directory listing and cover art, refreshing the cache"
359 onClick={reloadDirectory}
360 >
361 <RefreshSVG />
362 </button>
363 </Show>
364 </div>
365 <Show when={showFilter()}>
366 <input
367 oninput={(e) => setFilter(e.target.value)}
368 onkeydown={(e) => e.key === "Escape" && setShowFilter(false)}
369 class="filter-files"
370 type="text"
371 placeholder="Filter files..."
372 />
373 </Show>
374 </Show>
375
376 <div class="file-list-wrapper">
377 <Show when={props.files.loading}>
378 <LoadingScreen />
379 </Show>
380
381 <div class="file-list" ref={filelistElement}>
382 <For each={fileStore}>
383 {({ fullPath, displayName, file }) => {
384 const isDirectory = !("metadata" in file);
385 return (
386 <div
387 class={(isDirectory && "directory-item") || "file-item"}
388 onClick={() => {
389 (isDirectory && props.setCurrentDir(fullPath)) || playFile(fullPath, file as MediaFile);
390 }}
391 >
392 {(isDirectory && <ClosedFolderSVG forButton={false} />) || <MusicSVG />}
393 <span>{displayName}</span>
394 <div class="download-button-wrapper">
395 {isDirectory && !props.isOffline() && downloadedChildren[fullPath]}
396 <DownloadButton
397 fullPath={fullPath}
398 item={file}
399 fetchFiles={props.fetchFiles}
400 isOffline={props.isOffline}
401 currentDir={props.currentDir}
402 options={props.options}
403 />
404 </div>
405 <button
406 title="Add to Playlist"
407 onClick={(event) => {
408 event.stopPropagation();
409 if (isDirectory) {
410 playFiles(fullPath, true, true);
411 } else {
412 playFiles(fullPath, false, true, file);
413 }
414 }}
415 >
416 Add
417 </button>
418 </div>
419 );
420 }}
421 </For>
422 </div>
423 </div>
424 <Show when={!props.options.hideCover && (cover.loading || cover())}>
425 <div class="cover">
426 <Show when={cover.loading}>
427 <LoadingScreen />
428 </Show>
429 <img src={cover()} alt="" />
430 </div>
431 </Show>
432 <Show when={loadingActions() > 0}>
433 <LoadingScreen text="Loading files from subdirectories, this might take a while.." />
434 </Show>
435 </div>
436 </>
437 );
438}
439