-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
217 lines (193 loc) · 7.58 KB
/
script.js
File metadata and controls
217 lines (193 loc) · 7.58 KB
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
let accessToken = null;
let trackOffset = 0;
let playlistOffset = 0;
let currentQuery = '';
/* ── AUTH ── */
function toggleTokenVis() {
const inp = document.getElementById('tokenInput');
const icon = document.getElementById('eye-icon');
if (inp.type === 'password') {
inp.type = 'text';
icon.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/><line x1="1" y1="1" x2="23" y2="23"/>';
icon.setAttribute('stroke', 'currentColor');
} else {
inp.type = 'password';
icon.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>';
}
}
async function handleConnect() {
const val = document.getElementById('tokenInput').value.trim();
const err = document.getElementById('authError');
err.textContent = '';
if (!val) {
err.textContent = 'Please paste your token.';
return;
}
// Quick validation — attempt a lightweight API call
try {
const res = await fetch('https://api.spotify.com/v1/search?q=test&type=track&limit=1', {
headers: { Authorization: `Bearer ${val}` }
});
if (res.status === 401) {
err.textContent = 'Token invalid or expired. Please get a fresh one.';
return;
}
if (!res.ok) {
err.textContent = `Spotify returned ${res.status}. Try again.`;
return;
}
} catch (e) {
err.textContent = 'Network error. Check your connection.';
return;
}
accessToken = val;
document.getElementById('auth-screen').style.display = 'none';
document.getElementById('app-screen').style.display = 'block';
document.getElementById('searchQuery').focus();
}
function logout() {
accessToken = null;
document.getElementById('tokenInput').value = '';
document.getElementById('authError').textContent = '';
document.getElementById('app-screen').style.display = 'none';
document.getElementById('auth-screen').style.display = 'flex';
document.getElementById('results-area').innerHTML = `
<div class="empty-state">
<div class="big-icon">🎵</div>
<h3>Search for anything</h3>
<p>Tracks, artists, playlists — type above to explore</p>
</div>`;
}
/* ── SEARCH ── */
function searchSpotify() {
const query = document.getElementById('searchQuery').value.trim();
if (!query) return;
currentQuery = query;
trackOffset = 0;
playlistOffset = 0;
document.getElementById('error-banner').classList.add('hidden');
document.getElementById('results-area').innerHTML = `
<div class="spinner-wrap"><div class="spinner"></div><span>Searching…</span></div>`;
Promise.all([
fetchTracks(query, 0, 6),
fetchPlaylists(query, 0, 4)
])
.then(([tracksData, playlistsData]) => renderResults(tracksData, playlistsData))
.catch(showError);
}
async function fetchTracks(query, offset, limit) {
const res = await fetch(
`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=track&offset=${offset}&limit=${limit}`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
if (res.status === 401) { logout(); throw new Error('Token expired. Please reconnect.'); }
if (!res.ok) throw new Error(`Spotify error ${res.status}`);
return res.json();
}
async function fetchPlaylists(query, offset, limit) {
const res = await fetch(
`https://api.spotify.com/v1/search?q=${encodeURIComponent(query)}&type=playlist&offset=${offset}&limit=${limit}`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
if (res.status === 401) { logout(); throw new Error('Token expired. Please reconnect.'); }
if (!res.ok) throw new Error(`Spotify error ${res.status}`);
return res.json();
}
function renderResults(tracksData, playlistsData) {
const tracks = tracksData.tracks?.items || [];
const playlists = playlistsData.playlists?.items || [];
const hasMore = {
tracks: !!tracksData.tracks?.next,
playlists: !!playlistsData.playlists?.next
};
trackOffset = 6;
playlistOffset = 4;
if (tracks.length === 0 && playlists.length === 0) {
document.getElementById('results-area').innerHTML = `
<div class="empty-state">
<div class="big-icon">🔍</div>
<h3>No results found</h3>
<p>Try a different search term</p>
</div>`;
return;
}
document.getElementById('results-area').innerHTML = `
<div class="results-grid">
<div class="result-section" id="tracks-section">
<h2>Tracks <span class="count">${tracks.length}${hasMore.tracks ? '+' : ''}</span></h2>
<div class="items-list" id="trackResults"></div>
<button class="load-more ${hasMore.tracks ? '' : 'hidden'}" id="loadMoreTracks" onclick="loadMore('tracks')">Load more tracks</button>
</div>
<div class="result-section" id="playlists-section">
<h2>Playlists <span class="count">${playlists.length}${hasMore.playlists ? '+' : ''}</span></h2>
<div class="items-list" id="playlistResults"></div>
<button class="load-more ${hasMore.playlists ? '' : 'hidden'}" id="loadMorePlaylists" onclick="loadMore('playlists')">Load more playlists</button>
</div>
</div>`;
appendTracks(tracks);
appendPlaylists(playlists);
}
function appendTracks(tracks) {
const container = document.getElementById('trackResults');
tracks.forEach(track => {
const wrap = document.createElement('div');
wrap.className = 'embed-wrap';
const iframe = document.createElement('iframe');
iframe.src = `https://open.spotify.com/embed/track/${track.id}?utm_source=generator&theme=0`;
iframe.height = '80';
iframe.allow = 'autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture';
iframe.loading = 'lazy';
wrap.appendChild(iframe);
container.appendChild(wrap);
});
}
function appendPlaylists(playlists) {
const container = document.getElementById('playlistResults');
playlists.filter(p => p && p.id).forEach(playlist => {
const wrap = document.createElement('div');
wrap.className = 'embed-wrap';
const iframe = document.createElement('iframe');
iframe.src = `https://open.spotify.com/embed/playlist/${playlist.id}?utm_source=generator&theme=0`;
iframe.height = '232';
iframe.allow = 'autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture';
iframe.loading = 'lazy';
wrap.appendChild(iframe);
container.appendChild(wrap);
});
}
async function loadMore(type) {
const btnId = type === 'tracks' ? 'loadMoreTracks' : 'loadMorePlaylists';
const btn = document.getElementById(btnId);
btn.textContent = 'Loading…';
btn.disabled = true;
try {
if (type === 'tracks') {
const data = await fetchTracks(currentQuery, trackOffset, 3);
appendTracks(data.tracks.items);
trackOffset += 3;
if (!data.tracks.next) btn.classList.add('hidden');
} else {
const data = await fetchPlaylists(currentQuery, playlistOffset, 3);
appendPlaylists(data.playlists.items);
playlistOffset += 3;
if (!data.playlists.next) btn.classList.add('hidden');
}
} catch (e) {
showError(e);
} finally {
btn.textContent = type === 'tracks' ? 'Load more tracks' : 'Load more playlists';
btn.disabled = false;
}
}
function showError(e) {
const banner = document.getElementById('error-banner');
if (!banner) return;
banner.textContent = '⚠️ ' + (e.message || 'Something went wrong.');
banner.classList.remove('hidden');
}
/* ── INIT ── */
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('tokenInput').addEventListener('keydown', e => {
if (e.key === 'Enter') handleConnect();
});
});