FileBrowser.tsx
| 1 | import "./FileBrowser.css"; |
| 2 | import type { Directory, FileListing, MediaFile } from "music-server-shared/types"; |
| 3 | import { |
| 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"; |
| 16 | import { createStore, reconcile } from "solid-js/store"; |
| 17 | import type { FlatFileListing } from "../App"; |
| 18 | import { clearDirectoryCache, getCover, listFiles, storedFilesLive } from "../offline"; |
| 19 | import type { AppOptions, PlaylistItem } from "../types"; |
| 20 | import { |
| 21 | basename, |
| 22 | compareDirFirst, |
| 23 | formatFilename, |
| 24 | joinPath, |
| 25 | LocalStorageValues, |
| 26 | persistedToggle, |
| 27 | toast, |
| 28 | } from "../utils"; |
| 29 | import { DownloadButton } from "./DownloadButton"; |
| 30 | import { LoadingScreen } from "./LoadingScreen"; |
| 31 | import { ClosedFolderSVG, DownSVG, FilterSVG, MusicSVG, RefreshSVG, UpSVG } from "./SVG"; |
| 32 | |
| 33 | interface FileBrowserProps { |
| 34 | currentDir: Accessor<string>; |
| 35 | setCurrentDir: Setter<string>; |
| 36 | playTrack: (track: PlaylistItem) => void; |
| 37 | playlist: Accessor<PlaylistItem[]>; |
| 38 | setPlaylist: Setter<PlaylistItem[]>; |
| 39 | showFileBrowser: Accessor<boolean>; |
| 40 | setShowFileBrowser: Setter<boolean>; |
| 41 | options: AppOptions; |
| 42 | isOffline: Accessor<boolean>; |
| 43 | files: InitializedResource<FlatFileListing>; |
| 44 | fetchFiles: ResourceActions<FlatFileListing>; |
| 45 | } |
| 46 | |
| 47 | export default function FileBrowser(props: FileBrowserProps) { |
| 48 | //"root" stands for the virtual top level that lists the user's roots |
| 49 | const breadcrumbs = () => ["root", ...props.currentDir().split("/").filter(Boolean)]; |
| 50 | const [loadingActions, setLoadingActions] = createSignal(0); |
| 51 | const [showActionButtons, setShowActionButtons] = persistedToggle(LocalStorageValues.fileBrowserButtons, true); |
| 52 | const [showFilter, setShowFilter] = createSignal(false); |
| 53 | const [filter, setFilter] = createSignal(""); |
| 54 | createEffect( |
| 55 | on(props.currentDir, () => { |
| 56 | setFilter(""); |
| 57 | setShowFilter(false); |
| 58 | }), |
| 59 | ); |
| 60 | createEffect( |
| 61 | on([showFilter, showActionButtons], ([showFilter, showActionButtons]) => { |
| 62 | if (!showActionButtons) setShowFilter(false); |
| 63 | if (!showFilter) setFilter(""); |
| 64 | }), |
| 65 | ); |
| 66 | const [cover, fetchCover] = createResource<string | undefined, { dir: string; offline: boolean }>( |
| 67 | () => ({ dir: props.currentDir(), offline: props.isOffline() }), |
| 68 | async (args, info) => { |
| 69 | if (info.value) URL.revokeObjectURL(info.value as string); |
| 70 | return await getCover(args.dir, props.options, false, args.offline); |
| 71 | }, |
| 72 | { initialValue: undefined }, |
| 73 | ); |
| 74 | |
| 75 | let dialogElement!: HTMLDialogElement; |
| 76 | let addAnywayButton!: HTMLButtonElement; |
| 77 | |
| 78 | function handleBreadcrumbClick(index: number) { |
| 79 | if (index === 0) { |
| 80 | props.setCurrentDir(""); |
| 81 | } else { |
| 82 | props.setCurrentDir(joinPath(...breadcrumbs().slice(1, index + 1))); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | function fileToPlaylistItem(path: string, item: MediaFile): PlaylistItem { |
| 87 | return { |
| 88 | id: crypto.randomUUID(), |
| 89 | metadata: item.metadata, |
| 90 | path: path, |
| 91 | }; |
| 92 | } |
| 93 | |
| 94 | // Recursively convert file listing to PlaylistItem array |
| 95 | function listingToPlaylistItems(basePath: string, files: FileListing): PlaylistItem[] { |
| 96 | //keep sorting same as shown in the filebrowser: directories first (by name), then files (by display name) |
| 97 | const displayNameOf = (name: string, item: Directory | MediaFile) => |
| 98 | "metadata" in item |
| 99 | ? formatFilename({ path: name, metadata: item.metadata }, props.options.filebrowserDisplay) |
| 100 | : name; |
| 101 | const sorted = Object.entries(files).sort(([aName, aItem], [bName, bItem]) => |
| 102 | compareDirFirst( |
| 103 | displayNameOf(aName, aItem), |
| 104 | !("metadata" in aItem), |
| 105 | displayNameOf(bName, bItem), |
| 106 | !("metadata" in bItem), |
| 107 | ), |
| 108 | ); |
| 109 | let result: PlaylistItem[] = []; |
| 110 | for (const [fileName, file] of sorted) { |
| 111 | const fullPath = joinPath(basePath, fileName); |
| 112 | if ("metadata" in file) { |
| 113 | // It's an audio file |
| 114 | result.push(fileToPlaylistItem(fullPath, file)); |
| 115 | } else if (Object.keys(file.files).length > 0) { |
| 116 | // It's a directory with files, recursively add its contents |
| 117 | result = [...result, ...listingToPlaylistItems(fullPath, file.files)]; |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | return result; |
| 122 | } |
| 123 | |
| 124 | function playFile(path: string, item: MediaFile) { |
| 125 | props.playTrack(fileToPlaylistItem(path, item)); |
| 126 | } |
| 127 | |
| 128 | function scrollPlaylistToBottom() { |
| 129 | setTimeout(() => { |
| 130 | const element = document.getElementById("playlist"); |
| 131 | if (!element) return; |
| 132 | element.scrollTop = element.scrollHeight; |
| 133 | }, 0); |
| 134 | } |
| 135 | |
| 136 | const addedToast = toast("", "info"); |
| 137 | addedToast.hideToast(); |
| 138 | |
| 139 | async function playFiles(fullPath: string, recursive: boolean, queue: boolean, item?: MediaFile) { |
| 140 | if (recursive) { |
| 141 | setLoadingActions(loadingActions() + 1); |
| 142 | } |
| 143 | try { |
| 144 | const oldPlaylist = queue ? props.playlist() : []; |
| 145 | const newPlaylist = item |
| 146 | ? [fileToPlaylistItem(fullPath, item)] |
| 147 | : listingToPlaylistItems(fullPath, await listFiles(fullPath, props.isOffline(), recursive)); |
| 148 | const addAction = () => { |
| 149 | if (newPlaylist.length !== 0 && oldPlaylist.length === 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 | const newPaths = new Set(newPlaylist.map((item) => item.path)); |
| 158 | if (props.options.duplicateWarning && oldPlaylist.some((oldItem) => newPaths.has(oldItem.path))) { |
| 159 | addAnywayButton.onclick = () => { |
| 160 | addAction(); |
| 161 | dialogElement.close(); |
| 162 | }; |
| 163 | dialogElement.showModal(); |
| 164 | } else { |
| 165 | addAction(); |
| 166 | } |
| 167 | } finally { |
| 168 | if (recursive) { |
| 169 | setLoadingActions(loadingActions() - 1); |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | function reloadDirectory() { |
| 175 | clearDirectoryCache(props.currentDir()).then(() => props.fetchFiles.refetch()); |
| 176 | //this call only exists to refresh the cache/db entry, the url it mints is unused |
| 177 | //(fetchCover.refetch creates the one that actually gets rendered), so revoke it |
| 178 | getCover(props.currentDir(), props.options, false, props.isOffline(), true).then((url) => { |
| 179 | if (url) URL.revokeObjectURL(url); |
| 180 | fetchCover.refetch(); |
| 181 | }); |
| 182 | } |
| 183 | |
| 184 | let filelistElement!: HTMLDivElement; |
| 185 | const scrollPositions: { part: string; pos: number }[] = []; |
| 186 | let lastDir = props.currentDir(); |
| 187 | createEffect( |
| 188 | //on props.files, because doing it on props.currentDir causes us to scroll up before the new content is being loaded |
| 189 | on(props.files, () => { |
| 190 | //don't update scroll pos if directory didn't change |
| 191 | //otherwise would cause jank when scrolling while in offline mode and synced items pop up |
| 192 | if (lastDir === props.currentDir()) return; |
| 193 | lastDir = props.currentDir(); |
| 194 | //need the timeout, otherwise we could execute the scroll before rendering finishes |
| 195 | setTimeout(() => { |
| 196 | let parts = `${props.currentDir()}`.split("/"); |
| 197 | if (props.currentDir() !== "") parts = ["", ...parts]; |
| 198 | scrollPositions.length = Math.min(parts.length, scrollPositions.length); |
| 199 | for (let index = 0; index < parts.length; index++) { |
| 200 | const part = parts[index]; |
| 201 | if (scrollPositions.length - 1 < index) { |
| 202 | scrollPositions.push({ part, pos: 0 }); |
| 203 | } else if (scrollPositions[index].part !== part) { |
| 204 | scrollPositions[index] = { part, pos: 0 }; |
| 205 | } |
| 206 | } |
| 207 | filelistElement.scrollTop = scrollPositions[scrollPositions.length - 1].pos; |
| 208 | }, 0); |
| 209 | }), |
| 210 | ); |
| 211 | |
| 212 | onMount(() => { |
| 213 | filelistElement.addEventListener("scrollend", () => { |
| 214 | if (scrollPositions.length > 0) scrollPositions[scrollPositions.length - 1].pos = filelistElement.scrollTop; |
| 215 | }); |
| 216 | }); |
| 217 | |
| 218 | function getAbsolutePathFiles() { |
| 219 | return props.files.latest.map(([name, item]) => { |
| 220 | return [joinPath(props.currentDir(), name), item] as [string, Directory | MediaFile]; |
| 221 | }); |
| 222 | } |
| 223 | |
| 224 | interface FileProxy { |
| 225 | key: string; |
| 226 | fullPath: string; |
| 227 | displayName: string; |
| 228 | file: MediaFile | Directory; |
| 229 | } |
| 230 | |
| 231 | //this proxy store allows us to diff changes correctly when the filelisting changes, only rerendering the changed items |
| 232 | //absolute paths are required here to make sure it's really the same file in the same directory |
| 233 | const [fileStore, setFileStore] = createStore<FileProxy[]>([]); |
| 234 | |
| 235 | function fileSort(a: FileProxy, b: FileProxy): number { |
| 236 | return compareDirFirst(a.displayName, !("metadata" in a.file), b.displayName, !("metadata" in b.file)); |
| 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 | : basename(value[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().toLowerCase()); |
| 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={breadcrumbs()}> |
| 301 | {(crumb, index) => ( |
| 302 | <> |
| 303 | <span title={crumb} onClick={() => handleBreadcrumbClick(index())}> |
| 304 | {crumb} |
| 305 | </span> |
| 306 | {index() < 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 | <div |
| 383 | class={(isDirectory && "directory-item") || "file-item"} |
| 384 | onClick={() => { |
| 385 | (isDirectory && props.setCurrentDir(fullPath)) || playFile(fullPath, file as MediaFile); |
| 386 | }} |
| 387 | > |
| 388 | {(isDirectory && <ClosedFolderSVG forButton={false} />) || <MusicSVG />} |
| 389 | <span>{displayName}</span> |
| 390 | <div class="download-button-wrapper"> |
| 391 | {isDirectory && !props.isOffline() && downloadedChildren[fullPath]} |
| 392 | <DownloadButton |
| 393 | fullPath={fullPath} |
| 394 | item={file} |
| 395 | fetchFiles={props.fetchFiles} |
| 396 | isOffline={props.isOffline} |
| 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 | </For> |
| 417 | </div> |
| 418 | </div> |
| 419 | <Show when={!props.options.hideCover && (cover.loading || cover())}> |
| 420 | <div class="cover"> |
| 421 | <Show when={cover.loading}> |
| 422 | <LoadingScreen /> |
| 423 | </Show> |
| 424 | <img src={cover()} alt="" /> |
| 425 | </div> |
| 426 | </Show> |
| 427 | <Show when={loadingActions() > 0}> |
| 428 | <LoadingScreen text="Loading files from subdirectories, this might take a while.." /> |
| 429 | </Show> |
| 430 | </div> |
| 431 | </> |
| 432 | ); |
| 433 | } |
| 434 |