Playlist.tsx
| 1 | import { |
| 2 | type Accessor, |
| 3 | batch, |
| 4 | createEffect, |
| 5 | createResource, |
| 6 | createSelector, |
| 7 | createSignal, |
| 8 | on, |
| 9 | onMount, |
| 10 | type ResourceActions, |
| 11 | type Setter, |
| 12 | Show, |
| 13 | } from "solid-js"; |
| 14 | import "./Playlist.css"; |
| 15 | import type { FlatFileListing } from "../App"; |
| 16 | import { download, getCover, savePlaylist, storedFilesLive } from "../offline"; |
| 17 | import type { AppOptions, PlayerState, PlaylistItem } from "../types"; |
| 18 | import { formatFilename, formatTime, LocalStorageValues, toast } from "../utils"; |
| 19 | import { DraggableList } from "./DraggableList"; |
| 20 | import { LoadingScreen } from "./LoadingScreen"; |
| 21 | import { ClearSVG, DownloadSVG, DownSVG, DragSVG, LinkSVG, SaveSVG, SyncSVG, UpSVG } from "./SVG"; |
| 22 | |
| 23 | interface PlaylistProps { |
| 24 | playlist: Accessor<PlaylistItem[]>; |
| 25 | setPlaylist: Setter<PlaylistItem[]>; |
| 26 | playerState: PlayerState; |
| 27 | setPlayerState: Setter<PlayerState>; |
| 28 | playTrack: (item: PlaylistItem) => void; |
| 29 | playNext: () => void; |
| 30 | videoElement: (el: HTMLVideoElement) => void; |
| 31 | videoShown: Accessor<boolean>; |
| 32 | options: AppOptions; |
| 33 | fetchFiles: ResourceActions<FlatFileListing>; |
| 34 | isOffline: Accessor<boolean>; |
| 35 | } |
| 36 | |
| 37 | export default function Playlist(props: PlaylistProps) { |
| 38 | const [showActionButtons, setShowActionButtons] = createSignal(true); |
| 39 | |
| 40 | //TODO: add a way to refetch cover |
| 41 | const [cover] = createResource<string | undefined, { filePath?: string; offline: boolean }>( |
| 42 | () => ({ filePath: props.playerState.currentTrack?.path, offline: props.isOffline() }), |
| 43 | async (args, info) => { |
| 44 | if (info.value) URL.revokeObjectURL(info.value as string); |
| 45 | if (!args.filePath) return undefined; |
| 46 | return await getCover(args.filePath, props.options, false, args.offline); |
| 47 | }, |
| 48 | { initialValue: undefined }, |
| 49 | ); |
| 50 | |
| 51 | function removeFromPlaylist(id: string) { |
| 52 | const newPlaylist = props.playlist().filter((i) => i.id !== id); |
| 53 | if (id === props.playerState.currentTrack?.id && newPlaylist.length > 0) props.playNext(); |
| 54 | props.setPlaylist(newPlaylist); |
| 55 | } |
| 56 | |
| 57 | async function playlistDownload(download: boolean) { |
| 58 | try { |
| 59 | const playlist = props.playlist(); |
| 60 | const filePaths = playlist.map((item) => item.path); |
| 61 | const response = await fetch("/prepare-playlist", { |
| 62 | body: JSON.stringify(filePaths), |
| 63 | method: "POST", |
| 64 | credentials: "same-origin", |
| 65 | }); |
| 66 | if (!response.ok) throw new Error(`Generating playlist id not successful: ${await response.text()}`); |
| 67 | const id = await response.text(); |
| 68 | if (download) { |
| 69 | toast("Started playlist download", "info"); |
| 70 | const a = document.createElement("a"); |
| 71 | a.href = `/download-playlist/${id}`; |
| 72 | document.body.appendChild(a); |
| 73 | a.click(); |
| 74 | document.body.removeChild(a); |
| 75 | } else { |
| 76 | toast("Copied playlist link to clipboard", "info"); |
| 77 | const urlPath = location.href.split(/\?|#/)[0]; |
| 78 | navigator.clipboard.writeText(`${urlPath}${urlPath.endsWith("/") ? "" : "/"}download-playlist/${id}`); |
| 79 | } |
| 80 | } catch (e) { |
| 81 | toast("Playlist items download failed", "error", e); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | const [syncing, setSyncing] = createSignal(false); |
| 86 | async function syncPlaylist() { |
| 87 | if (syncing()) return; |
| 88 | setSyncing(true); |
| 89 | const progressToast = toast("Started playlist sync", "info"); |
| 90 | try { |
| 91 | const itemsToSync: PlaylistItem[] = []; |
| 92 | const playlist = props.playlist(); |
| 93 | const stored = new Set(storedFilesLive().map(String)); |
| 94 | //dedup by path (playlist items are always fresh objects, so reference dedup was a no-op) |
| 95 | const seen = new Set<string>(); |
| 96 | for (const item of playlist) { |
| 97 | if (seen.has(item.path) || stored.has(item.path)) continue; |
| 98 | seen.add(item.path); |
| 99 | itemsToSync.push(item); |
| 100 | } |
| 101 | let downloadPromises!: Promise<void>[]; |
| 102 | batch(() => { |
| 103 | downloadPromises = itemsToSync.map((item) => download(item.path, item, props.options, props.fetchFiles)); |
| 104 | }); |
| 105 | await Promise.allSettled(downloadPromises); |
| 106 | toast("Playlist sync completed", "success"); |
| 107 | } finally { |
| 108 | progressToast.hideToast(); |
| 109 | setSyncing(false); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | let dialogElement!: HTMLDialogElement; |
| 114 | let playlistNameInput!: HTMLInputElement; |
| 115 | let allowOverwriteCheckbox!: HTMLInputElement; |
| 116 | |
| 117 | async function save() { |
| 118 | try { |
| 119 | if (!playlistNameInput.reportValidity()) return; |
| 120 | await savePlaylist({ name: playlistNameInput.value, items: props.playlist() }, allowOverwriteCheckbox.checked); |
| 121 | closeDialog(); |
| 122 | } catch (e) { |
| 123 | if (e instanceof Error && e.name === "ConstraintError") { |
| 124 | toast("Playlist with this name already exists", "error"); |
| 125 | } else { |
| 126 | toast("Saving playlist failed", "error", e); |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | function closeDialog() { |
| 132 | dialogElement.close(); |
| 133 | playlistNameInput.value = ""; |
| 134 | allowOverwriteCheckbox.checked = false; |
| 135 | } |
| 136 | |
| 137 | const [syncedCount, setSyncedCount] = createSignal(0); |
| 138 | createEffect( |
| 139 | on([props.playlist, storedFilesLive], ([playlist, storedFiles]) => { |
| 140 | const stored = new Set(storedFiles.map(String)); |
| 141 | setSyncedCount(playlist.filter((item) => stored.has(item.path)).length); |
| 142 | }), |
| 143 | ); |
| 144 | onMount(() => { |
| 145 | const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons); |
| 146 | if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true"); |
| 147 | createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString())); |
| 148 | }); |
| 149 | |
| 150 | return ( |
| 151 | <div class="playlist-container"> |
| 152 | <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}> |
| 153 | <div> |
| 154 | <input ref={playlistNameInput} required type="text" placeholder="Playlist name" /> |
| 155 | <div class="save-buttons"> |
| 156 | <label for="overwrite-checkbox">allow overwrite</label> |
| 157 | <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" /> |
| 158 | <button onClick={save}>Save</button> |
| 159 | <button onClick={closeDialog}>Cancel</button> |
| 160 | </div> |
| 161 | </div> |
| 162 | </dialog> |
| 163 | |
| 164 | <div class="playlist-header"> |
| 165 | <div class="playlist-header-title"> |
| 166 | <span> |
| 167 | Playlist ({props.playlist().length} tracks, {syncedCount()} synced) |
| 168 | </span> |
| 169 | <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}> |
| 170 | {showActionButtons() ? <UpSVG /> : <DownSVG />} |
| 171 | </button> |
| 172 | </div> |
| 173 | <Show when={showActionButtons()}> |
| 174 | <div class="button-container"> |
| 175 | <button title="Save playlist" onClick={() => dialogElement.showModal()}> |
| 176 | <SaveSVG /> |
| 177 | </button> |
| 178 | <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}> |
| 179 | <SyncSVG /> |
| 180 | </button> |
| 181 | <button |
| 182 | title="Copies and 1-hour valid link for the same action as the download button" |
| 183 | onClick={() => playlistDownload(false)} |
| 184 | > |
| 185 | <LinkSVG /> |
| 186 | </button> |
| 187 | <button |
| 188 | title="Download all files in the playlist in their original format as a .tar file, or without archive if it contains just a single item" |
| 189 | onClick={() => playlistDownload(true)} |
| 190 | > |
| 191 | <DownloadSVG /> |
| 192 | </button> |
| 193 | <button title="Clear Playlist" onClick={() => props.setPlaylist([])}> |
| 194 | <ClearSVG /> |
| 195 | </button> |
| 196 | </div> |
| 197 | </Show> |
| 198 | </div> |
| 199 | |
| 200 | <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist"> |
| 201 | {(item, _, { dragHandlers, isDragging, dropPosition }) => { |
| 202 | const isActive = createSelector( |
| 203 | () => props.playerState.currentTrack?.id, |
| 204 | (itemId, currentId) => currentId === itemId, |
| 205 | ); |
| 206 | return ( |
| 207 | <div |
| 208 | classList={{ |
| 209 | "playlist-item": true, |
| 210 | "draggable-item": true, |
| 211 | active: isActive(item.id), |
| 212 | "drop-target-top-border": dropPosition() === "before", |
| 213 | "drop-target-bottom-border": dropPosition() === "after", |
| 214 | }} |
| 215 | style={{ opacity: isDragging() ? 0.5 : 1 }} |
| 216 | onClick={() => props.playTrack(item)} |
| 217 | title={item.path} |
| 218 | > |
| 219 | <div class="playlist-drag-btn" {...dragHandlers}> |
| 220 | <DragSVG /> |
| 221 | </div> |
| 222 | <span>{formatFilename(item, props.options.playlistDisplay)}</span> |
| 223 | <div class="spacer" /> |
| 224 | {formatTime(item.metadata.duration)} |
| 225 | <button |
| 226 | title="Remove from playlist" |
| 227 | onClick={(e) => { |
| 228 | e.stopPropagation(); |
| 229 | removeFromPlaylist(item.id); |
| 230 | }} |
| 231 | > |
| 232 | <ClearSVG /> |
| 233 | </button> |
| 234 | </div> |
| 235 | ); |
| 236 | }} |
| 237 | </DraggableList> |
| 238 | |
| 239 | <div |
| 240 | class="cover" |
| 241 | style={{ |
| 242 | display: |
| 243 | props.videoShown() || (!props.options.hidePlaylistCover && (cover.loading || cover())) ? undefined : "none", |
| 244 | }} |
| 245 | > |
| 246 | <Show when={!props.videoShown()}> |
| 247 | <Show when={cover.loading}> |
| 248 | <LoadingScreen /> |
| 249 | </Show> |
| 250 | <img src={cover()} alt="" /> |
| 251 | </Show> |
| 252 | <video ref={props.videoElement} preload="auto" /> |
| 253 | </div> |
| 254 | </div> |
| 255 | ); |
| 256 | } |
| 257 |