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 } 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 return (
264 <>
265 <dialog
266 class="duplicate-warning-dialog"
267 ref={dialogElement}
268 onclick={(e) => e.target.nodeName === "DIALOG" && dialogElement.close()}
269 >
270 <div>
271 Some of the items you're trying to add already exists in your current playlist
272 <div class="buttons">
273 <button ref={addAnywayButton}>Add anyway</button>
274 <button onClick={() => dialogElement.close()}>Cancel</button>
275 </div>
276 </div>
277 </dialog>
278 <div classList={{ "file-browser": true, hidden: !props.showFileBrowser() }}>
279 <div classList={{ breadcrumb: true, "breadcrumb-nowrap": !showActionButtons() }}>
280 <For each={props.breadcrumbs()}>
281 {(crumb, index) => (
282 <>
283 <span title={crumb} onClick={() => handleBreadcrumbClick(index())}>
284 {crumb}
285 </span>
286 {index() < props.breadcrumbs().length - 1 && "/"}
287 </>
288 )}
289 </For>
290 <button
291 class="toggle-browser-actions"
292 title="Toggle filebrowser actions"
293 onclick={() => setShowActionButtons(!showActionButtons())}
294 >
295 {showActionButtons() ? <UpSVG /> : <DownSVG />}
296 </button>
297 </div>
298
299 <Show when={showActionButtons()}>
300 <div class="browser-actions">
301 <div>
302 <button
303 title="Replace playlist with all files in current directory"
304 onClick={() => playFiles(props.currentDir(), false, false)}
305 >
306 Play Directory
307 </button>
308 <button
309 title="Replace playlist with all files in current directory and all subdirectories"
310 onClick={() => playFiles(props.currentDir(), true, false)}
311 >
312 Play All
313 </button>
314 <button
315 title="Add all files in current directory to playlist"
316 onClick={() => playFiles(props.currentDir(), false, true)}
317 >
318 Queue Directory
319 </button>
320 <button
321 title="Add all files in current directory and all subdirectories to playlist"
322 onClick={() => playFiles(props.currentDir(), true, true)}
323 >
324 Queue All
325 </button>
326 </div>
327 <div class="spacer" />
328 <button title="Filter current directory" onClick={() => setShowFilter(!showFilter())}>
329 <FilterSVG />
330 </button>
331 <Show when={!props.isOffline()}>
332 <button
333 class="refresh-button"
334 title="Refresh current directory listing and cover art, refreshing the cache"
335 onClick={reloadDirectory}
336 >
337 <RefreshSVG />
338 </button>
339 </Show>
340 </div>
341 <Show when={showFilter()}>
342 <input
343 oninput={(e) => setFilter(e.target.value)}
344 onkeydown={(e) => e.key === "Escape" && setShowFilter(false)}
345 class="filter-files"
346 type="text"
347 placeholder="Filter files..."
348 />
349 </Show>
350 </Show>
351
352 <div class="file-list-wrapper">
353 <Show when={props.files.loading}>
354 <LoadingScreen />
355 </Show>
356
357 <div class="file-list" ref={filelistElement}>
358 <For each={fileStore}>
359 {({ fullPath, displayName, file }) => {
360 const isDirectory = !("metadata" in file);
361 return (
362 <>
363 <div
364 class={(isDirectory && "directory-item") || "file-item"}
365 onClick={() => {
366 (isDirectory && props.setCurrentDir(fullPath)) || playFile(fullPath, file as MediaFile);
367 }}
368 >
369 {(isDirectory && <ClosedFolderSVG forButton={false} />) || <MusicSVG />}
370 <span>{displayName}</span>
371 <div class="spacer" />
372 <DownloadButton
373 fullPath={fullPath}
374 item={file}
375 fetchFiles={props.fetchFiles}
376 isOffline={props.isOffline}
377 currentDir={props.currentDir}
378 options={props.options}
379 />
380 <button
381 title="Add to Playlist"
382 onClick={(event) => {
383 event.stopPropagation();
384 if (isDirectory) {
385 playFiles(fullPath, true, true);
386 } else {
387 playFiles(fullPath, false, true, file);
388 }
389 }}
390 >
391 Add
392 </button>
393 </div>
394 </>
395 );
396 }}
397 </For>
398 </div>
399 </div>
400 <Show when={!props.options.hideCover && (cover.loading || cover())}>
401 <div class="cover">
402 <Show when={cover.loading}>
403 <LoadingScreen />
404 </Show>
405 <img src={cover()} alt="" />
406 </div>
407 </Show>
408 <Show when={loadingActions() > 0}>
409 <LoadingScreen text="Loading files from subdirectories, this might take a while.." />
410 </Show>
411 </div>
412 </>
413 );
414}
415