Playlist.tsx
⎇
Raw
1import {
2 createSelector,
3 type Accessor,
4 type Setter,
5 createSignal,
6 type ResourceActions,
7 createEffect,
8 onMount,
9 Show,
10 on,
11 batch,
12 createResource,
13} from "solid-js";
14import "./Playlist.css";
15import type { PlayerState, PlaylistItem, AppOptions } from "../types";
16import { formatFilename, formatTime, LocalStorageValues, toast } from "../utils";
17import { ClearSVG, DownloadSVG, DownSVG, DragSVG, LinkSVG, SaveSVG, SyncSVG, UpSVG } from "./SVG";
18import { savePlaylist, download, storedFilesLive, getCover } from "../offline";
19import { DraggableList } from "./DraggableList";
20import type { FlatFileListing } from "../App";
21import { LoadingScreen } from "./LoadingScreen";
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, fetchCover] = 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 let videoElement!: HTMLVideoElement;
145 onMount(() => {
146 const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons);
147 if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true");
148 createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString()));
149 });
150
151 return (
152 <div class="playlist-container">
153 <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}>
154 <div>
155 <input ref={playlistNameInput} required type="text" placeholder="Playlist name" />
156 <div class="save-buttons">
157 <label for="overwrite-checkbox">allow overwrite</label>
158 <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" />
159 <button onClick={save}>Save</button>
160 <button onClick={closeDialog}>Cancel</button>
161 </div>
162 </div>
163 </dialog>
164
165 <div class="playlist-header">
166 <div class="playlist-header-title">
167 <span>
168 Playlist ({props.playlist().length} tracks, {syncedCount()} synced)
169 </span>
170 <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}>
171 {showActionButtons() ? <UpSVG /> : <DownSVG />}
172 </button>
173 </div>
174 <Show when={showActionButtons()}>
175 <div class="button-container">
176 <button title="Save playlist" onClick={() => dialogElement.showModal()}>
177 <SaveSVG />
178 </button>
179 <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}>
180 <SyncSVG />
181 </button>
182 <button
183 title="Copies and 1-hour valid link for the same action as the download button"
184 onClick={() => playlistDownload(false)}
185 >
186 <LinkSVG />
187 </button>
188 <button
189 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"
190 onClick={() => playlistDownload(true)}
191 >
192 <DownloadSVG />
193 </button>
194 <button title="Clear Playlist" onClick={() => props.setPlaylist([])}>
195 <ClearSVG />
196 </button>
197 </div>
198 </Show>
199 </div>
200
201 <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist">
202 {(item, _, { dragHandlers, isDragging, dropPosition }) => {
203 const isActive = createSelector(
204 () => props.playerState.currentTrack?.id,
205 (itemId, currentId) => currentId === itemId,
206 );
207 return (
208 <div
209 classList={{
210 "playlist-item": true,
211 "draggable-item": true,
212 active: isActive(item.id),
213 "drop-target-top-border": dropPosition() === "before",
214 "drop-target-bottom-border": dropPosition() === "after",
215 }}
216 style={{ opacity: isDragging() ? 0.5 : 1 }}
217 onClick={() => props.playTrack(item)}
218 title={item.path}
219 >
220 <div class="playlist-drag-btn" {...dragHandlers}>
221 <DragSVG />
222 </div>
223 <span>{formatFilename(item, props.options.playlistDisplay)}</span>
224 <div class="spacer" />
225 {formatTime(item.metadata.duration)}
226 <button
227 title="Remove from playlist"
228 onClick={(e) => {
229 e.stopPropagation();
230 removeFromPlaylist(item.id);
231 }}
232 >
233 <ClearSVG />
234 </button>
235 </div>
236 );
237 }}
238 </DraggableList>
239
240 <div
241 class="cover"
242 style={{
243 display:
244 props.videoShown() || (!props.options.hidePlaylistCover && (cover.loading || cover())) ? undefined : "none",
245 }}
246 >
247 <Show when={!props.videoShown()}>
248 <Show when={cover.loading}>
249 <LoadingScreen />
250 </Show>
251 <img src={cover()} alt="" />
252 </Show>
253 <video ref={props.videoElement} preload="auto" />
254 </div>
255 </div>
256 );
257}
258