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 const element = document.getElementById("playlist");
124 if (!element) return;
125 element.scrollTop = element.scrollHeight;
126 }
127
128 const addedToast = toast("", "info");
129 addedToast.hideToast();
130
131 async function playFiles(fullPath: string, recursive: boolean, queue: boolean, item?: MediaFile) {
132 if (recursive) {
133 setLoadingActions(loadingActions() + 1);
134 }
135 try {
136 let oldLength = 0;
137 let newPlaylist: PlaylistItem[];
138 const oldPlaylist = queue ? props.playlist() : [];
139 if (item) {
140 newPlaylist = [fileToPlaylistItem(fullPath, item)];
141 } else {
142 const files = await listFiles(fullPath, props.isOffline(), recursive);
143 newPlaylist = listingToPlaylistItems(fullPath, files);
144 if (queue) {
145 oldLength = oldPlaylist.length;
146 }
147 }
148 const addAction = () => {
149 if (newPlaylist.length !== 0 && oldLength === 0) props.playTrack(newPlaylist[0]);
150 props.setPlaylist([...oldPlaylist, ...newPlaylist]);
151 addedToast.hideToast();
152 addedToast.options.text = `Added ${newPlaylist.length} tracks`;
153 addedToast.showToast();
154 if (queue) scrollPlaylistToBottom();
155 else props.setShowFileBrowser(false);
156 };
157 if (
158 props.options.duplicateWarning &&
159 oldPlaylist.some((oldItem) => newPlaylist.some((newItem) => oldItem.path === newItem.path))
160 ) {
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 createEffect(
184 on(props.currentDir, () => {
185 //need the timeout, otherwise we could execute the scroll before rendering finishes
186 setTimeout(() => {
187 let parts = `${props.currentDir()}`.split("/");
188 if (props.currentDir() !== "") parts = ["", ...parts];
189 scrollPositions.length = Math.min(parts.length, scrollPositions.length);
190 for (let index = 0; index < parts.length; index++) {
191 const part = parts[index];
192 if (scrollPositions.length - 1 < index) {
193 scrollPositions.push({ part, pos: 0 });
194 } else if (scrollPositions[index].part !== part) {
195 scrollPositions[index] = { part, pos: 0 };
196 }
197 }
198 filelistElement.scrollTop = scrollPositions[scrollPositions.length - 1].pos;
199 }, 0);
200 }),
201 );
202
203 onMount(() => {
204 const savedFileBrowserButtons = localStorage.getItem(LocalStorageValues.fileBrowserButtons);
205 if (savedFileBrowserButtons !== null) setShowActionButtons(savedFileBrowserButtons === "true");
206 createEffect(() => localStorage.setItem(LocalStorageValues.fileBrowserButtons, showActionButtons().toString()));
207
208 filelistElement.addEventListener("scrollend", () => {
209 scrollPositions[scrollPositions.length - 1].pos = filelistElement.scrollTop;
210 });
211 });
212
213 function getAbsolutePathFiles() {
214 return props.files.latest.map(([name, item]) => {
215 return [joinPath(props.currentDir(), name), item] as [string, Directory | MediaFile];
216 });
217 }
218
219 interface FileProxy {
220 key: string;
221 fullPath: string;
222 displayName: string;
223 file: MediaFile | Directory;
224 }
225
226 //this proxy store allows us to diff changes correctly when the filelisting changes, only rerendering the changed items
227 //absolute paths are required here to make sure it's really the same file in the same directory
228 const [fileStore, setFileStore] = createStore<FileProxy[]>([]);
229
230 function fileSort(a: FileProxy, b: FileProxy): number {
231 //sort directories first
232 if ("metadata" in b.file && !("metadata" in a.file)) return -1;
233 if ("metadata" in a.file && !("metadata" in b.file)) return 1;
234 return a.displayName.localeCompare(b.displayName, undefined, { numeric: true });
235 }
236
237 createEffect(() => {
238 setFileStore(
239 reconcile(
240 getAbsolutePathFiles()
241 .map((value) => {
242 const fullPath = value[0];
243 const displayName =
244 "metadata" in value[1]
245 ? formatFilename({ path: value[0], metadata: value[1].metadata }, props.options.filebrowserDisplay)
246 : value[0].split("/").toReversed()[0];
247 return {
248 key: fullPath + displayName,
249 fullPath,
250 displayName,
251 file: value[1],
252 };
253 })
254 .filter((item) => {
255 return item.displayName.toLowerCase().includes(filter());
256 })
257 .sort(fileSort),
258 { key: "key" },
259 ),
260 );
261 });
262
263 const [downloadedChildren, setDownloadedChildren] = createStore<Record<string, number>>({});
264 createEffect(() => {
265 const storedFiles = storedFilesLive();
266 const newChildren: Record<string, number> = {};
267
268 for (const storedFile of storedFiles) {
269 const pathParts = storedFile.toString().split("/");
270 // Update all parent directories in the path
271 for (let i = 1; i <= pathParts.length; i++) {
272 const parentPath = pathParts.slice(0, i).join("/");
273 if (parentPath) {
274 newChildren[parentPath] = (newChildren[parentPath] || 0) + 1;
275 }
276 }
277 }
278 setDownloadedChildren(reconcile(newChildren));
279 });
280
281 return (
282 <>
283 <dialog
284 class="duplicate-warning-dialog"
285 ref={dialogElement}
286 onclick={(e) => e.target.nodeName === "DIALOG" && dialogElement.close()}
287 >
288 <div>
289 Some of the items you're trying to add already exists in your current playlist
290 <div class="buttons">
291 <button ref={addAnywayButton}>Add anyway</button>
292 <button onClick={() => dialogElement.close()}>Cancel</button>
293 </div>
294 </div>
295 </dialog>
296 <div classList={{ "file-browser": true, hidden: !props.showFileBrowser() }}>
297 <div classList={{ breadcrumb: true, "breadcrumb-nowrap": !showActionButtons() }}>
298 <For each={props.breadcrumbs()}>
299 {(crumb, index) => (
300 <>
301 <span title={crumb} onClick={() => handleBreadcrumbClick(index())}>
302 {crumb}
303 </span>
304 {index() < props.breadcrumbs().length - 1 && "/"}
305 </>
306 )}
307 </For>
308 <button
309 class="toggle-browser-actions"
310 title="Toggle filebrowser actions"
311 onclick={() => setShowActionButtons(!showActionButtons())}
312 >
313 {showActionButtons() ? <UpSVG /> : <DownSVG />}
314 </button>
315 </div>
316
317 <Show when={showActionButtons()}>
318 <div class="browser-actions">
319 <div>
320 <button
321 title="Replace playlist with all files in current directory"
322 onClick={() => playFiles(props.currentDir(), false, false)}
323 >
324 Play Directory
325 </button>
326 <button
327 title="Replace playlist with all files in current directory and all subdirectories"
328 onClick={() => playFiles(props.currentDir(), true, false)}
329 >
330 Play All
331 </button>
332 <button
333 title="Add all files in current directory to playlist"
334 onClick={() => playFiles(props.currentDir(), false, true)}
335 >
336 Queue Directory
337 </button>
338 <button
339 title="Add all files in current directory and all subdirectories to playlist"
340 onClick={() => playFiles(props.currentDir(), true, true)}
341 >
342 Queue All
343 </button>
344 </div>
345 <div class="spacer" />
346 <button title="Filter current directory" onClick={() => setShowFilter(!showFilter())}>
347 <FilterSVG />
348 </button>
349 <Show when={!props.isOffline()}>
350 <button
351 class="refresh-button"
352 title="Refresh current directory listing and cover art, refreshing the cache"
353 onClick={reloadDirectory}
354 >
355 <RefreshSVG />
356 </button>
357 </Show>
358 </div>
359 <Show when={showFilter()}>
360 <input
361 oninput={(e) => setFilter(e.target.value)}
362 onkeydown={(e) => e.key === "Escape" && setShowFilter(false)}
363 class="filter-files"
364 type="text"
365 placeholder="Filter files..."
366 />
367 </Show>
368 </Show>
369
370 <div class="file-list-wrapper">
371 <Show when={props.files.loading}>
372 <LoadingScreen />
373 </Show>
374
375 <div class="file-list" ref={filelistElement}>
376 <For each={fileStore}>
377 {({ fullPath, displayName, file }) => {
378 const isDirectory = !("metadata" in file);
379 return (
380 <>
381 <div
382 class={(isDirectory && "directory-item") || "file-item"}
383 onClick={() => {
384 (isDirectory && props.setCurrentDir(fullPath)) || playFile(fullPath, file as MediaFile);
385 }}
386 >
387 {(isDirectory && <ClosedFolderSVG forButton={false} />) || <MusicSVG />}
388 <span>{displayName}</span>
389 <div class="download-button-wrapper">
390 {isDirectory && !props.isOffline() && downloadedChildren[fullPath]}
391 <DownloadButton
392 fullPath={fullPath}
393 item={file}
394 fetchFiles={props.fetchFiles}
395 isOffline={props.isOffline}
396 currentDir={props.currentDir}
397 options={props.options}
398 />
399 </div>
400 <button
401 title="Add to Playlist"
402 onClick={(event) => {
403 event.stopPropagation();
404 if (isDirectory) {
405 playFiles(fullPath, true, true);
406 } else {
407 playFiles(fullPath, false, true, file);
408 }
409 }}
410 >
411 Add
412 </button>
413 </div>
414 </>
415 );
416 }}
417 </For>
418 </div>
419 </div>
420 <Show when={!props.options.hideCover && (cover.loading || cover())}>
421 <div class="cover">
422 <Show when={cover.loading}>
423 <LoadingScreen />
424 </Show>
425 <img src={cover()} alt="" />
426 </div>
427 </Show>
428 <Show when={loadingActions() > 0}>
429 <LoadingScreen text="Loading files from subdirectories, this might take a while.." />
430 </Show>
431 </div>
432 </>
433 );
434}
435