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