File size: 10,394 Bytes
b0798af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"use client";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import {
  Search,
  Plus,
  Music2,
  ArrowUpRight,
  Heart,
  LayoutGrid,
  List,
  Folder,
} from "lucide-react";
import { api, apiRequest, Track, Playlist, token } from "@/lib/api/apiClient";
import Artwork from "./Artwork";
import BackupStatus from "./BackupStatus";
import TrackList from "./TrackList";
import { usePlayerStore } from "@/lib/store/playerStore";
export default function Collection() {
  const [tracks, setTracks] = useState<Track[]>([]),
    [playlists, setPlaylists] = useState<Playlist[]>([]),
    [tab, setTab] = useState("songs"),
    [query, setQuery] = useState(""),
    [sort, setSort] = useState("recent"),
    [grid, setGrid] = useState(false),
    [error, setError] = useState(""),
    [loading, setLoading] = useState(true),
    [create, setCreate] = useState(false),
    [name, setName] = useState(""),
    [saving, setSaving] = useState(false),
    [syncing, setSyncing] = useState(false);
  const load = () => {
    setLoading(true);
    api
      .getTracks()
      .then(setTracks)
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
    if (token())
      api
        .playlists()
        .then(setPlaylists)
        .catch((e) => setError(e.message));
  };
  useEffect(() => {
    const refresh = () => {
      api
        .getTracks()
        .then(setTracks)
        .catch((e) => setError(e.message))
        .finally(() => setLoading(false));
      if (token())
        api
          .playlists()
          .then(setPlaylists)
          .catch((e) => setError(e.message));
    };
    refresh();
    window.addEventListener("library-updated", refresh);
    return () => window.removeEventListener("library-updated", refresh);
  }, []);
  const filtered = useMemo(
    () =>
      tracks
        .filter(
          (t) =>
            (tab !== "liked" || t.liked) &&
            (tab !== "uploads" || t.source === "upload") &&
            `${t.title} ${t.artist_name} ${t.album_title}`
              .toLowerCase()
              .includes(query.toLowerCase()),
        )
        .sort((a, b) =>
          sort === "title"
            ? a.title.localeCompare(b.title)
            : sort === "artist"
              ? a.artist_name.localeCompare(b.artist_name)
              : String(b.created_at).localeCompare(String(a.created_at)),
        ),
    [tracks, tab, query, sort],
  );
  return (
    <div className="page-enter">
      <div className="page-title-row">
        <div>
          <span className="eyebrow">A SOUND OF YOUR OWN</span>
          <h1>
            Your collection<span className="title-period">.</span>
          </h1>
          <p>{tracks.length} songs. Every one has a place.</p>
        </div>
        <Link className="button" href="/uploads">
          <Plus size={17} /> Import music
        </Link>
      </div>
      <div className="collection-toolbar">
        <span className="muted">
          Your uploads and connected dataset, together.
        </span>
        <button
          className="button small secondary"
          disabled={syncing}
          onClick={async () => {
            setSyncing(true);
            setError("");
            try {
              await apiRequest("/library/refresh", { method: "POST" });
              load();
              window.dispatchEvent(new Event("library-updated"));
            } catch (e) {
              setError((e as Error).message);
            } finally {
              setSyncing(false);
            }
          }}
        >
          {syncing ? "Refreshing…" : "Refresh dataset"}
        </button>
      </div>
      <div className="tabs">
        {[
          ["songs", "All songs"],
          ["liked", "Favorites"],
          ["uploads", "Your uploads"],
          ["playlists", "Playlists"],
        ].map(([id, label]) => (
          <button
            key={id}
            className={tab === id ? "active" : ""}
            onClick={() => setTab(id)}
          >
            {id === "liked" && <Heart size={14} />} {label}
          </button>
        ))}
      </div>
      {error && (
        <div className="notice error" role="alert">
          {error}
          <button onClick={load}>Retry</button>
        </div>
      )}
      {tab !== "playlists" && (
        <div className="backup-legend" aria-label="Cloud backup symbols">
          <BackupStatus status="replicated" showLabel />
          <BackupStatus status="pending" showLabel />
          <BackupStatus status="failed" showLabel />
        </div>
      )}
      {tab === "playlists" ? (
        <>
          <div className="collection-toolbar">
            <span className="muted">Made by you, for any moment.</span>
            <button
              className="button secondary small"
              onClick={() => setCreate(true)}
            >
              <Plus size={15} /> New playlist
            </button>
          </div>
          <div className="album-grid">
            {playlists.map((p) => (
              <Link
                className="album-card"
                href={"/playlist/" + p.id}
                key={p.id}
              >
                <Artwork id={p.id} />
                <h3>{p.title}</h3>
                <p>{p.track_ids.length} songs</p>
              </Link>
            ))}
          </div>
          {!playlists.length && (
            <div className="empty-state">
              <Folder />
              <h3>Every mood deserves a playlist</h3>
              <p>Collect the songs that belong together.</p>
              <button
                className="button secondary"
                onClick={() => setCreate(true)}
              >
                Create a playlist
              </button>
            </div>
          )}
        </>
      ) : (
        <>
          <div className="collection-toolbar">
            <label className="search-field">
              <Search size={16} />
              <input
                placeholder="Find something in your collection"
                aria-label="Filter collection"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
              />
            </label>
            <div className="toolbar-actions">
              <select
                aria-label="Sort songs"
                value={sort}
                onChange={(e) => setSort(e.target.value)}
              >
                <option value="recent">Recently added</option>
                <option value="title">Song title</option>
                <option value="artist">Artist</option>
              </select>
              <button
                className="icon-button"
                aria-label={grid ? "Switch to list" : "Switch to artwork grid"}
                onClick={() => setGrid(!grid)}
              >
                {grid ? <List size={18} /> : <LayoutGrid size={18} />}
              </button>
            </div>
          </div>
          {loading ? (
            <div className="loading-block">
              <span className="spinner" /> Opening your collection…
            </div>
          ) : filtered.length ? (
            grid ? (
              <div className="album-grid">
                {filtered.map((t) => (
                  <button
                    className="album-card"
                    key={t.id}
                    onClick={() => usePlayerStore.getState().start(t, filtered)}
                  >
                    <Artwork
                      hasArtwork={t.has_artwork}
                      id={t.id}
                      title={t.title}
                    />
                    <h3 className="song-title">
                      <span>{t.title}</span>
                      <BackupStatus id={t.id} status={t.backup_status} />
                    </h3>
                    <p>{t.artist_name}</p>
                  </button>
                ))}
              </div>
            ) : (
              <TrackList tracks={filtered} onChange={load} />
            )
          ) : (
            <div className="empty-state">
              <Music2 />
              <h3>
                {query
                  ? "Nothing here just yet"
                  : tab === "liked"
                    ? "Keep your favorites close"
                    : "A little space for your songs"}
              </h3>
              <p>
                {query
                  ? "Try another title or artist."
                  : tab === "liked"
                    ? "Tap the heart beside any song to find it here."
                    : "Import music to make this collection your own."}
              </p>
              <Link className="text-link" href="/uploads">
                Import music <ArrowUpRight size={16} />
              </Link>
            </div>
          )}
        </>
      )}
      {create && (
        <div className="modal-backdrop">
          <form
            className="modal-card"
            role="dialog"
            aria-modal="true"
            aria-label="Create playlist"
            onSubmit={async (e) => {
              e.preventDefault();
              setSaving(true);
              try {
                await api.createPlaylist(name);
                setCreate(false);
                setName("");
                load();
              } catch (e) {
                setError((e as Error).message);
                setCreate(false);
              } finally {
                setSaving(false);
              }
            }}
          >
            <button
              type="button"
              className="close-button"
              aria-label="Close"
              onClick={() => setCreate(false)}
            >
              ×
            </button>
            <span className="eyebrow">COLLECT A FEELING</span>
            <h2>Name your playlist</h2>
            <label className="field">
              Playlist name
              <input
                required
                autoFocus
                maxLength={100}
                placeholder="Sunday, unhurried"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
            </label>
            <button className="button" disabled={saving || !name.trim()}>
              {saving ? "Creating…" : "Create playlist"}
            </button>
          </form>
        </div>
      )}
    </div>
  );
}