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("Started playlist sync", "info");
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 } finally {
89 progressToast.hideToast();
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([props.playlist, storedFilesLive], async ([playlist, storedFiles]) => {
121 setSyncedCount(playlist.filter((item) => storedFiles.includes(item.path)).length);
122 }),
123 );
124 onMount(() => {
125 const savedPlaylistButtons = localStorage.getItem(LocalStorageValues.playlistButtons);
126 if (savedPlaylistButtons !== null) setShowActionButtons(savedPlaylistButtons === "true");
127 createEffect(() => localStorage.setItem(LocalStorageValues.playlistButtons, showActionButtons().toString()));
128 });
129
130 return (
131 <div class="playlist-container">
132 <dialog class="save-dialog" ref={dialogElement} onclick={(e) => e.target.nodeName === "DIALOG" && closeDialog()}>
133 <div>
134 <input ref={playlistNameInput} required type="text" placeholder="Playlist name" />
135 <div class="save-buttons">
136 <label for="overwrite-checkbox">allow overwrite</label>
137 <input ref={allowOverwriteCheckbox} id="overwrite-checkbox" type="checkbox" />
138 <button onClick={save}>Save</button>
139 <button onClick={closeDialog}>Cancel</button>
140 </div>
141 </div>
142 </dialog>
143
144 <div class="playlist-header">
145 <div class="playlist-header-title">
146 <span>
147 Playlist ({props.playlist().length} tracks, {syncedCount()} synced)
148 </span>
149 <button title="Toggle playlist actions" onclick={() => setShowActionButtons(!showActionButtons())}>
150 {showActionButtons() ? <UpSVG /> : <DownSVG />}
151 </button>
152 </div>
153 <Show when={showActionButtons()}>
154 <div class="button-container">
155 <button title="Save playlist" onClick={() => dialogElement.showModal()}>
156 <SaveSVG />
157 </button>
158 <button title="Sync all unsynced files in playlist" onClick={syncPlaylist} disabled={syncing()}>
159 <SyncSVG />
160 </button>
161 <button
162 title="Copies and 1-hour valid link for the same action as the download button"
163 onClick={() => playlistDownload(false)}
164 >
165 <LinkSVG />
166 </button>
167 <button
168 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"
169 onClick={() => playlistDownload(true)}
170 >
171 <DownloadSVG />
172 </button>
173 <button title="Clear Playlist" onClick={() => props.setPlaylist([])}>
174 <ClearSVG />
175 </button>
176 </div>
177 </Show>
178 </div>
179
180 <DraggableList<PlaylistItem> items={props.playlist} setItems={props.setPlaylist} id="playlist">
181 {(item, _, { dragHandlers, isDragging, dropPosition }) => {
182 const isActive = createSelector(
183 () => props.playerState.currentTrack?.id,
184 (itemId, currentId) => currentId === itemId,
185 );
186 return (
187 <div
188 classList={{
189 "playlist-item": true,
190 "draggable-item": true,
191 active: isActive(item.id),
192 "drop-target-top-border": dropPosition() === "before",
193 "drop-target-bottom-border": dropPosition() === "after",
194 }}
195 style={{ opacity: isDragging() ? 0.5 : 1 }}
196 onClick={() => props.playTrack(item)}
197 title={item.path}
198 >
199 <div class="playlist-drag-btn" {...dragHandlers}>
200 <DragSVG />
201 </div>
202 <span>{getItemName(item)}</span>
203 <div class="spacer" />
204 {formatTime(item.metadata.duration)}
205 <button
206 title="Remove from playlist"
207 onClick={(e) => {
208 e.stopPropagation();
209 removeFromPlaylist(item.id);
210 }}
211 >
212 <ClearSVG />
213 </button>
214 </div>
215 );
216 }}
217 </DraggableList>
218 </div>
219 );
220}
221