Playlist.tsx
⎇
Raw
1import {
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";
14import "./Playlist.css";
15import type { FlatFileListing } from "../App";
16import { download, getCover, savePlaylist, storedFilesLive } from "../offline";
17import type { AppOptions, PlayerState, PlaylistItem } from "../types";
18import { formatFilename, formatTime, handleUnauthorized, LocalStorageValues, toast } from "../utils";
19import { DraggableList } from "./DraggableList";
20import { LoadingScreen } from "./LoadingScreen";
21import { ClearSVG, DownloadSVG, DownSVG, DragSVG, LinkSVG, SaveSVG, SyncSVG, UpSVG } from "./SVG";
22
23interface 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
37export 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 //the server validates the body against a JSON array schema, which only applies when
66 //the content type says it is JSON (a bare string body arrives as text/plain)
67 headers: { "content-type": "application/json" },
68 });
69 if (handleUnauthorized(response)) return;
70 if (!response.ok) throw new Error(`Generating playlist id not successful: ${await response.text()}`);
71 const id = await response.text();
72 if (download) {
73 toast("Started playlist download", "info");
74 const a = document.createElement("a");
75 a.href = `/download-playlist/${id}`;
76 document.body.appendChild(a);
77 a.click();
78 document.body.removeChild(a);
79 } else {
80 toast("Copied playlist link to clipboard", "info");
81 const urlPath = location.href.split(/\?|#/)[0];
82 navigator.clipboard.writeText(`${urlPath}${urlPath.endsWith("/") ? "" : "/"}download-playlist/${id}`);
83 }
84 } catch (e) {
85 toast("Playlist items download failed", "error", e);
86 }
87 }
88
89 const [syncing, setSyncing] = createSignal(false);
90 async function syncPlaylist() {
91 if (syncing()) return;
92 setSyncing(true);
93 const progressToast = toast("Started playlist sync", "info");
94 try {
95 const itemsToSync: PlaylistItem[] = [];
96 const playlist = props.playlist();
97 const stored = new Set(storedFilesLive().map(String));
98 //dedup by path (playlist items are always fresh objects, so reference dedup was a no-op)
99 const seen = new Set<string>();
100 for (const item of playlist) {
101 if (seen.has(item.path) || stored.has(item.path)) continue;
102 seen.add(item.path);
103 itemsToSync.push(item);
104 }
105 let downloadPromises!: Promise<void>[];
106 batch(() => {
107 downloadPromises = itemsToSync.map((item) => download(item.path, item, props.options, props.fetchFiles));
108 });
109 await Promise.allSettled(downloadPromises);
110 toast("Playlist sync completed", "success");
111 } finally {
112 progressToast.hideToast();
113 setSyncing(false);
114 }
115 }
116
117 let dialogElement!: HTMLDialogElement;
118 let playlistNameInput!: HTMLInputElement;
119 let allowOverwriteCheckbox!: HTMLInputElement;
120
121 async function save() {
122 try {
123 if (!playlistNameInput.reportValidity()) return;
124 await savePlaylist({ name: playlistNameInput.value, items: props.playlist() }, allowOverwriteCheckbox.checked);
125 closeDialog();
126 } catch (e) {
127 if (e instanceof Error && e.name === "ConstraintError") {
128 toast("Playlist with this name already exists", "error");
129 } else {
130 toast("Saving playlist failed", "error", e);
131 }
132 }
133 }
134
135 function closeDialog() {
136 dialogElement.close();
137 playlistNameInput.value = "";
138 allowOverwriteCheckbox.checked = false;
139 }
140
141 const [syncedCount, setSyncedCount] = createSignal(0);
142 createEffect(
143 on([props.playlist, storedFilesLive], ([playlist, storedFiles]) => {
144 const stored = new Set(storedFiles.map(String));
145 setSyncedCount(playlist.filter((item) => stored.has(item.path)).length);
146 }),
147 );
148 onMount(() => {
149 const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons);
150 if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true");
151 createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString()));
152 });
153
154 return (
155 <div class="playlist-container">
156 <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}>
157 <div>
158 <input ref={playlistNameInput} required type="text" placeholder="Playlist name" />
159 <div class="save-buttons">
160 <label for="overwrite-checkbox">allow overwrite</label>
161 <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" />
162 <button onClick={save}>Save</button>
163 <button onClick={closeDialog}>Cancel</button>
164 </div>
165 </div>
166 </dialog>
167
168 <div class="playlist-header">
169 <div class="playlist-header-title">
170 <span>
171 Playlist ({props.playlist().length} tracks, {syncedCount()} synced)
172 </span>
173 <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}>
174 {showActionButtons() ? <UpSVG /> : <DownSVG />}
175 </button>
176 </div>
177 <Show when={showActionButtons()}>
178 <div class="button-container">
179 <button title="Save playlist" onClick={() => dialogElement.showModal()}>
180 <SaveSVG />
181 </button>
182 <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}>
183 <SyncSVG />
184 </button>
185 <button
186 title="Copies and 1-hour valid link for the same action as the download button"
187 onClick={() => playlistDownload(false)}
188 >
189 <LinkSVG />
190 </button>
191 <button
192 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"
193 onClick={() => playlistDownload(true)}
194 >
195 <DownloadSVG />
196 </button>
197 <button title="Clear Playlist" onClick={() => props.setPlaylist([])}>
198 <ClearSVG />
199 </button>
200 </div>
201 </Show>
202 </div>
203
204 <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist">
205 {(item, _, { dragHandlers, isDragging, dropPosition }) => {
206 const isActive = createSelector(
207 () => props.playerState.currentTrack?.id,
208 (itemId, currentId) => currentId === itemId,
209 );
210 return (
211 <div
212 classList={{
213 "playlist-item": true,
214 "draggable-item": true,
215 active: isActive(item.id),
216 "drop-target-top-border": dropPosition() === "before",
217 "drop-target-bottom-border": dropPosition() === "after",
218 }}
219 style={{ opacity: isDragging() ? 0.5 : 1 }}
220 onClick={() => props.playTrack(item)}
221 title={item.path}
222 >
223 <div class="playlist-drag-btn" {...dragHandlers}>
224 <DragSVG />
225 </div>
226 <span>{formatFilename(item, props.options.playlistDisplay)}</span>
227 <div class="spacer" />
228 {formatTime(item.metadata.duration)}
229 <button
230 title="Remove from playlist"
231 onClick={(e) => {
232 e.stopPropagation();
233 removeFromPlaylist(item.id);
234 }}
235 >
236 <ClearSVG />
237 </button>
238 </div>
239 );
240 }}
241 </DraggableList>
242
243 <div
244 class="cover"
245 style={{
246 display:
247 props.videoShown() || (!props.options.hidePlaylistCover && (cover.loading || cover())) ? undefined : "none",
248 }}
249 >
250 <Show when={!props.videoShown()}>
251 <Show when={cover.loading}>
252 <LoadingScreen />
253 </Show>
254 <img src={cover()} alt="" />
255 </Show>
256 <video ref={props.videoElement} preload="auto" playsinline />
257 </div>
258 </div>
259 );
260}
261