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} from "solid-js";
12import "./Playlist.css";
13import { getItemName, type PlayerState, type PlaylistItem, type AppOptions } from "../types";
14import { formatTime, LocalStorageValues, toast } from "../utils";
15import { ClearSVG, DownloadSVG, DownSVG, DragSVG, LinkSVG, SaveSVG, SyncSVG, UpSVG } from "./SVG";
16import { savePlaylist, download, downloadStatusMap, getStoredFiles } from "../offline";
17import { DraggableList } from "./DraggableList";
18import type { FileListing } from "music-server-shared/types";
19
20interface PlaylistProps {
21 currentDir: Accessor<string>;
22 playlist: Accessor<PlaylistItem[]>;
23 setPlaylist: Setter<PlaylistItem[]>;
24 playerState: PlayerState;
25 setPlayerState: Setter<PlayerState>;
26 playTrack: (item: PlaylistItem) => void;
27 playNext: () => void;
28 audioElement: HTMLAudioElement;
29 options: AppOptions;
30 fetchFiles: ResourceActions<FileListing>;
31}
32
33export default function Playlist(props: PlaylistProps) {
34 const [showActionButtons, setShowActionButtons] = createSignal(true);
35 function removeFromPlaylist(id: string) {
36 props.playNext();
37 const newPlaylist = props.playlist().filter((i) => i.id !== id);
38 props.setPlaylist(newPlaylist);
39 }
40
41 async function playlistDownload(download: boolean) {
42 try {
43 const playlist = props.playlist();
44 const filePaths = playlist.map((item) => item.path);
45 const response = await fetch("/prepare-playlist", { body: JSON.stringify(filePaths), method: "POST" });
46 if (!response.ok) throw new Error(`Generating playlist id not successful: ${await response.text()}`);
47 const id = await response.text();
48 if (download) {
49 toast("Started playlist download", "info");
50 const a = document.createElement("a");
51 a.href = `/download-playlist/${id}`;
52 document.body.appendChild(a);
53 a.click();
54 document.body.removeChild(a);
55 } else {
56 toast("Copied playlist link to clipboard", "info");
57 const urlPath = location.href.split(/\?|#/)[0];
58 navigator.clipboard.writeText(`${urlPath}${urlPath.endsWith("/") ? "" : "/"}download-playlist/${id}`);
59 }
60 } catch (e) {
61 toast("Playlist items download failed", "error", e);
62 }
63 }
64
65 const [syncing, setSyncing] = createSignal(false);
66 async function syncPlaylist() {
67 if (syncing()) return;
68 setSyncing(true);
69 const progressToast = toast("Syncing files in playlist...", "progress");
70 try {
71 const itemsToSync: PlaylistItem[] = [];
72 const playlist = props.playlist();
73 const unique = playlist.filter((item) => playlist.some((other) => item.path !== other.path));
74 const storedFiles = await getStoredFiles();
75 for (const item of unique) {
76 if (!storedFiles.includes(item.path)) itemsToSync.push(item);
77 }
78 const downloadPromises = itemsToSync.map((item) => {
79 const basePath = item.path.split("/").slice(0, -1).join("/");
80 const fileName = item.path.split("/").toReversed()[0];
81 return download(fileName, item, basePath, props.currentDir, props.options, props.fetchFiles);
82 });
83 await Promise.allSettled(downloadPromises);
84 progressToast.hideToast();
85 toast("Playlist sync completed", "success");
86 } catch (e) {
87 progressToast.hideToast();
88 toast("Playlist sync failed", "error", e);
89 } finally {
90 setSyncing(false);
91 }
92 }
93
94 let dialogElement!: HTMLDialogElement;
95 let playlistNameInput!: HTMLInputElement;
96 let allowOverwriteCheckbox!: HTMLInputElement;
97
98 async function save() {
99 try {
100 if (!playlistNameInput.reportValidity()) return;
101 await savePlaylist({ name: playlistNameInput.value, items: props.playlist() }, allowOverwriteCheckbox.checked);
102 closeDialog();
103 } catch (e) {
104 if (e instanceof Error && e.name === "ConstraintError") {
105 toast("Playlist with this name already exists", "error");
106 } else {
107 toast("Saving playlist failed", "error", e);
108 }
109 }
110 }
111
112 function closeDialog() {
113 dialogElement.close();
114 playlistNameInput.value = "";
115 allowOverwriteCheckbox.checked = false;
116 }
117
118 const [syncedCount, setSyncedCount] = createSignal(0);
119 createEffect(
120 on(
121 () => props.playlist().map((item) => downloadStatusMap[item.path]),
122 async () => {
123 const playlist = props.playlist();
124 const storedFiles = await getStoredFiles();
125 setSyncedCount(playlist.filter((item) => storedFiles.includes(item.path)).length);
126 },
127 ),
128 );
129
130 onMount(() => {
131 const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons);
132 if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true");
133 createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString()));
134 });
135
136 return (
137 <div class="playlist-container">
138 <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}>
139 <div>
140 <input ref={playlistNameInput} required type="text" placeholder="Playlist name" />
141 <div class="save-buttons">
142 <label for="overwrite-checkbox">allow overwrite</label>
143 <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" />
144 <button onClick={save}>Save</button>
145 <button onClick={closeDialog}>Cancel</button>
146 </div>
147 </div>
148 </dialog>
149
150 <div class="playlist-header">
151 <div class="playlist-header-title">
152 <span>
153 Playlist ({props.playlist().length} tracks, {syncedCount()} synced)
154 </span>
155 <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}>
156 {showActionButtons() ? <UpSVG /> : <DownSVG />}
157 </button>
158 </div>
159 <Show when={showActionButtons()}>
160 <div class="button-container">
161 <button title="Save playlist" onClick={() => dialogElement.showModal()}>
162 <SaveSVG />
163 </button>
164 <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}>
165 <SyncSVG />
166 </button>
167 <button
168 title="Copies and 1-hour valid link for the same action as the download button"
169 onClick={() => playlistDownload(false)}
170 >
171 <LinkSVG />
172 </button>
173 <button
174 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"
175 onClick={() => playlistDownload(true)}
176 >
177 <DownloadSVG />
178 </button>
179 <button title="Clear Playlist" onClick={() => props.setPlaylist([])}>
180 <ClearSVG />
181 </button>
182 </div>
183 </Show>
184 </div>
185
186 <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist">
187 {(item, _, { dragHandlers, isDragging, dropPosition }) => {
188 const isActive = createSelector(
189 () => props.playerState.currentTrack?.id,
190 (itemId, currentId) => currentId === itemId,
191 );
192 return (
193 <div
194 classList={{
195 "playlist-item": true,
196 "draggable-item": true,
197 active: isActive(item.id),
198 "drop-target-top-border": dropPosition() === "before",
199 "drop-target-bottom-border": dropPosition() === "after",
200 }}
201 style={{ opacity: isDragging() ? 0.5 : 1 }}
202 onClick={() => props.playTrack(item)}
203 >
204 <div class="playlist-drag-btn" {...dragHandlers}>
205 <DragSVG />
206 </div>
207 <span>{getItemName(item)}</span>
208 <div class="spacer" />
209 {formatTime(item.metadata.duration)}
210 <button
211 title={`Remove ${getItemName(item)}`}
212 onClick={(e) => {
213 e.stopPropagation();
214 removeFromPlaylist(item.id);
215 }}
216 >
217 <ClearSVG />
218 </button>
219 </div>
220 );
221 }}
222 </DraggableList>
223 </div>
224 );
225}
226