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} from "solid-js";
13import "./Playlist.css";
14import { getItemName, type PlayerState, type PlaylistItem, type AppOptions } from "../types";
15import { formatTime, LocalStorageValues, toast } from "../utils";
16import { ClearSVG, DownloadSVG, DownSVG, DragSVG, LinkSVG, SaveSVG, SyncSVG, UpSVG } from "./SVG";
17import { savePlaylist, download, storedFilesLive } from "../offline";
18import { DraggableList } from "./DraggableList";
19import type { FlatFileListing } from "../App";
20
21interface PlaylistProps {
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<FlatFileListing>;
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, pos) => playlist.indexOf(item) === pos);
74 const storedFiles = storedFilesLive();
75 for (const item of unique) {
76 if (!storedFiles.includes(item.path)) itemsToSync.push(item);
77 }
78 let downloadPromises!: Promise<void>[];
79 batch(() => {
80 downloadPromises = itemsToSync.map((item) => {
81 const basePath = item.path.split("/").slice(0, -1).join("/");
82 const fileName = item.path.split("/").toReversed()[0];
83 return download(fileName, item, basePath, props.options, props.fetchFiles);
84 });
85 });
86 await Promise.allSettled(downloadPromises);
87 toast("Playlist sync completed", "success");
88 } catch (e) {
89 toast("Playlist sync failed", "error", e);
90 } finally {
91 progressToast.hideToast();
92 setSyncing(false);
93 }
94 }
95
96 let dialogElement!: HTMLDialogElement;
97 let playlistNameInput!: HTMLInputElement;
98 let allowOverwriteCheckbox!: HTMLInputElement;
99
100 async function save() {
101 try {
102 if (!playlistNameInput.reportValidity()) return;
103 await savePlaylist({ name: playlistNameInput.value, items: props.playlist() }, allowOverwriteCheckbox.checked);
104 closeDialog();
105 } catch (e) {
106 if (e instanceof Error && e.name === "ConstraintError") {
107 toast("Playlist with this name already exists", "error");
108 } else {
109 toast("Saving playlist failed", "error", e);
110 }
111 }
112 }
113
114 function closeDialog() {
115 dialogElement.close();
116 playlistNameInput.value = "";
117 allowOverwriteCheckbox.checked = false;
118 }
119
120 const [syncedCount, setSyncedCount] = createSignal(0);
121 createEffect(
122 on([props.playlist, storedFilesLive], async ([playlist, storedFiles]) => {
123 setSyncedCount(playlist.filter((item) => storedFiles.includes(item.path)).length);
124 }),
125 );
126 onMount(() => {
127 const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons);
128 if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true");
129 createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString()));
130 });
131
132 return (
133 <div class="playlist-container">
134 <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}>
135 <div>
136 <input ref={playlistNameInput} required type="text" placeholder="Playlist name" />
137 <div class="save-buttons">
138 <label for="overwrite-checkbox">allow overwrite</label>
139 <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" />
140 <button onClick={save}>Save</button>
141 <button onClick={closeDialog}>Cancel</button>
142 </div>
143 </div>
144 </dialog>
145
146 <div class="playlist-header">
147 <div class="playlist-header-title">
148 <span>
149 Playlist ({props.playlist().length} tracks, {syncedCount()} synced)
150 </span>
151 <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}>
152 {showActionButtons() ? <UpSVG /> : <DownSVG />}
153 </button>
154 </div>
155 <Show when={showActionButtons()}>
156 <div class="button-container">
157 <button title="Save playlist" onClick={() => dialogElement.showModal()}>
158 <SaveSVG />
159 </button>
160 <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}>
161 <SyncSVG />
162 </button>
163 <button
164 title="Copies and 1-hour valid link for the same action as the download button"
165 onClick={() => playlistDownload(false)}
166 >
167 <LinkSVG />
168 </button>
169 <button
170 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"
171 onClick={() => playlistDownload(true)}
172 >
173 <DownloadSVG />
174 </button>
175 <button title="Clear Playlist" onClick={() => props.setPlaylist([])}>
176 <ClearSVG />
177 </button>
178 </div>
179 </Show>
180 </div>
181
182 <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist">
183 {(item, _, { dragHandlers, isDragging, dropPosition }) => {
184 const isActive = createSelector(
185 () => props.playerState.currentTrack?.id,
186 (itemId, currentId) => currentId === itemId,
187 );
188 return (
189 <div
190 classList={{
191 "playlist-item": true,
192 "draggable-item": true,
193 active: isActive(item.id),
194 "drop-target-top-border": dropPosition() === "before",
195 "drop-target-bottom-border": dropPosition() === "after",
196 }}
197 style={{ opacity: isDragging() ? 0.5 : 1 }}
198 onClick={() => props.playTrack(item)}
199 >
200 <div class="playlist-drag-btn" {...dragHandlers}>
201 <DragSVG />
202 </div>
203 <span>{getItemName(item)}</span>
204 <div class="spacer" />
205 {formatTime(item.metadata.duration)}
206 <button
207 title={`Remove ${getItemName(item)}`}
208 onClick={(e) => {
209 e.stopPropagation();
210 removeFromPlaylist(item.id);
211 }}
212 >
213 <ClearSVG />
214 </button>
215 </div>
216 );
217 }}
218 </DraggableList>
219 </div>
220 );
221}
222