Repository navigation
Expand file tree
/
Copy pathsidebar.js
More file actions
580 lines (507 loc) · 20.9 KB
/
Copy pathsidebar.js
File metadata and controls
580 lines (507 loc) · 20.9 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
const api = typeof browser !== 'undefined' ? browser : chrome;
const stationsNode = document.getElementById('stations');
const stopButton = document.getElementById('stop');
const statusNode = document.getElementById('status');
const nowplayingNode = document.getElementById('nowplaying');
const refreshButton = document.getElementById('refresh');
const popoutButton = document.getElementById('popout');
const versionNode = document.getElementById('version');
const params = new URLSearchParams(window.location.search);
const isPopout = params.get('mode') === 'popout';
function storageGetLocal(keys) {
if (typeof browser !== 'undefined') {
return browser.storage.local.get(keys);
}
return new Promise((resolve) => chrome.storage.local.get(keys, resolve));
}
function storageSetLocal(values) {
if (typeof browser !== 'undefined') {
return browser.storage.local.set(values);
}
return new Promise((resolve) => chrome.storage.local.set(values, resolve));
}
const changelogOverlay = document.getElementById('changelog');
const changelogBody = document.getElementById('changelog-body');
const changelogClose = document.getElementById('changelog-close');
// Changelog shown when the version badge is clicked (newest first, SemVer).
const CHANGELOG = [
{ version: '0.4.7', date: '2026-09-08', changes: ['Fini les sons superposés : la sidebar et la fenêtre détachée ne peuvent plus jouer en même temps, et « Arrêter » coupe la radio où qu’elle joue.', 'Le bouton « Rafraîchir » ne relance plus une radio que vous venez d’arrêter (ou de changer) pendant le chargement.', 'Un flux qui se termine ou se coupe n’affiche plus « en lecture » : l’interface et le badge repassent à l’arrêt.'] },
{ version: '0.4.6', date: '2026-07-30', changes: ['La zone « en lecture » affiche un état par défaut discret (« Aucune radio en lecture ») au lieu d’un espace vide.'] },
{ version: '0.4.5', date: '2026-07-30', changes: ['Plus de saut de mise en page (CLS) au lancement d’une radio : la zone « en lecture » est désormais réservée en permanence, les tuiles ne bougent plus.'] },
{ version: '0.4.4', date: '2026-07-30', changes: ['Le bouton « Rafraîchir » a maintenant un effet visible : il reconnecte le flux en cours (utile si le son se fige), re-trie la liste par écoutes et l’icône tourne le temps de l’opération.'] },
{ version: '0.4.3', date: '2026-07-30', changes: ['Le bouton « Détacher » ne crée plus de doublons : s’il existe déjà une fenêtre, un nouveau clic la ramène au premier plan.', 'La fenêtre détachée est entièrement redimensionnable : le contenu remplit toute la fenêtre et la grille ajuste ses colonnes.'] },
{ version: '0.4.2', date: '2026-07-30', changes: ['Flux France Inter, franceinfo, Europe 1, RFM et Chante France pointés directement sur leur hôte final (une redirection en moins à chaque lecture ; Chante France passe en HTTPS).'] },
{ version: '0.4.1', date: '2026-07-30', changes: ['Correctif perf : l’arrêt coupe réellement le flux (fini le téléchargement en arrière-plan et les connexions qui s’empilaient à chaque relance).', 'Icônes « Détacher » et « Rafraîchir » alignées sur le toolkit.'] },
{ version: '0.4.0', date: '2026-07-30', changes: ['Nouveau bouton « Détacher » : ouvre le lecteur dans une fenêtre séparée pour continuer l’écoute même en fermant la sidebar (la station en cours est reprise).'] },
{ version: '0.3.10', date: '2026-07-30', changes: ['Bouton « Arrêter » plus lisible (icône + libellé, contraste renforcé) et contrastes de l’en-tête ajustés (accessibilité).'] },
{ version: '0.3.9', date: '2026-07-30', changes: ['Haut de la sidebar optimisé : titre en double retiré, et le bouton d’arrêt n’apparaît plus que pendant la lecture (barre « en lecture » compacte).'] },
{ version: '0.3.8', date: '2026-07-30', changes: ['En-tête épuré : titre, description et version regroupés sur une ligne.'] },
{ version: '0.3.7', date: '2026-07-30', changes: ['Numéro de version déplacé dans l’en-tête, cliquable pour afficher les nouveautés.'] },
{ version: '0.3.6', date: '2026-07-30', changes: ['Classement par usage rétabli : les radios les plus écoutées remontent en tête.'] },
{ version: '0.3.5', date: '2026-07-30', changes: ['Bouton rafraîchir dans la barre d’outils.', 'Version affichée lue depuis le manifest.'] },
{ version: '0.3.4', date: '2026-07-30', changes: ['Manifest Firefox conforme à la validation Mozilla (AMO).'] },
{ version: '0.3.3', date: '2026-07-30', changes: ['Badge « ON » sur l’icône pendant la lecture.', 'Station en cours de lecture bien plus visible.'] },
{ version: '0.3.2', date: '2026-07-30', changes: ['Lien « Site » de nouveau visible sous chaque station.'] },
{ version: '0.3.1', date: '2026-07-30', changes: ['Correction de 4 flux : RTL, RTL2, Fun Radio, RFM.'] },
{ version: '0.3.0', date: '2026-07-26', changes: ['Lecture depuis la sidebar avec surveillance du flux.'] }
];
let audio = null;
let stations = [];
let currentStationId = null;
let status = 'stopped';
// Playback happens locally in each context: the sidebar and the detached
// window each own an <audio>. Nothing in the browser arbitrates between them,
// so the contexts elect a single owner by broadcasting every playback change
// over runtime messaging. Broadcasts only reach *live* contexts (unlike a
// record in storage, which can outlive the window that wrote it), so a closed
// pop-out can never leave a phantom "playing" state behind.
const CONTEXT_ID = 'ctx-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
let playbackOwner = null;
// Bumped by every change of playback intent (local or remote). Async work that
// wants to resume playback captures it first and gives up if it moved, so a
// slow request can never resurrect a stream the user has since stopped.
let playbackGeneration = 0;
function announcePlayback() {
sendMessage({
type: 'SIDEBAR_PLAYBACK',
ownerId: CONTEXT_ID,
status: status,
stationId: currentStationId
}).catch(() => {});
}
// Another context took over (or stopped) playback: release our own audio so
// only one stream is ever audible, and mirror its state so the tiles, the
// status line and the badge stay truthful in every window.
function adoptRemotePlayback(message) {
playbackGeneration += 1;
teardownAudio();
const stopped = !message.status || message.status === 'stopped';
playbackOwner = stopped ? null : message.ownerId;
status = stopped ? 'stopped' : message.status;
currentStationId = stopped ? null : (message.stationId || null);
renderPlaybackState();
}
if (api.runtime && api.runtime.onMessage) {
api.runtime.onMessage.addListener((message) => {
if (!message || message.ownerId === CONTEXT_ID) {
return;
}
if (message.type === 'SIDEBAR_PLAYBACK') {
adoptRemotePlayback(message);
return;
}
// A newly opened context asks who is playing; only the owner answers.
if (message.type === 'SIDEBAR_PLAYBACK_QUERY' && playbackOwner === CONTEXT_ID && status !== 'stopped') {
announcePlayback();
}
});
}
function sendMessage(message) {
if (typeof browser !== 'undefined') {
return browser.runtime.sendMessage(message);
}
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
reject(new Error(lastError.message));
return;
}
resolve(response);
});
});
}
function setStatus(message) {
statusNode.textContent = message || '';
}
// Toolbar icon badge: an "ON" chip while a station plays. Playback happens
// locally in the sidebar, so the badge is driven from here rather than the
// background service worker.
function setActionBadge(text, color) {
if (!api.action || typeof api.action.setBadgeText !== 'function') {
return;
}
try {
api.action.setBadgeText({ text: text });
api.action.setBadgeBackgroundColor({ color: color });
} catch (error) {
/* action badge API unavailable in this context */
}
}
// Fully release the current <audio> element AND abort its network request.
// pause() + removeAttribute('src') alone does NOT stop the ongoing download —
// the media element keeps buffering until load() runs its resource-reset
// algorithm. We also detach listeners so a stale element can't drive the UI.
function teardownAudio() {
if (!audio) {
return;
}
const el = audio;
audio = null;
el.onplaying = null;
el.onerror = null;
el.onended = null;
el.onpause = null;
try {
el.pause();
} catch (error) {
/* ignore */
}
el.removeAttribute('src');
el.load();
}
// Stopping is global, not local: whichever context holds the audio releases it
// when the broadcast arrives, so "Arrêter" from the sidebar also silences the
// detached window (and the other way round).
function stopAudio() {
playbackGeneration += 1;
teardownAudio();
currentStationId = null;
status = 'stopped';
playbackOwner = null;
renderPlaybackState();
announcePlayback();
}
function renderPlaybackState() {
const isActive = status === 'playing' || status === 'loading';
const station = stations.find((item) => item.id === currentStationId);
document.querySelectorAll('.station').forEach((button) => {
const active = button.dataset.stationId === currentStationId && isActive;
button.classList.toggle('is-active', active);
button.setAttribute('aria-pressed', String(active));
});
// The "now playing" bar keeps its reserved height at all times (no layout
// shift); the "stopped" state shows a discreet empty label via CSS.
nowplayingNode.setAttribute('data-state', status);
if (status === 'loading') {
setActionBadge('...', station ? station.color : '#737373');
setStatus(station ? 'Connexion à ' + station.name + '…' : 'Connexion…');
return;
}
if (status === 'playing') {
setActionBadge('ON', station ? station.color : '#2f6b2f');
setStatus(station ? station.name : '');
return;
}
if (status === 'error') {
setActionBadge('ERR', '#b3261e');
setStatus('Flux indisponible.');
return;
}
setActionBadge('', '#737373');
setStatus('Aucune radio en lecture');
}
function playStation(station) {
if (status === 'playing' && currentStationId === station.id) {
stopAudio();
return;
}
startPlayback(station);
}
// Actually (re)connect a station's stream, bypassing the play/stop toggle so it
// can also be used to reconnect the station that is already playing.
function startPlayback(station) {
playbackGeneration += 1;
teardownAudio();
currentStationId = station.id;
status = 'loading';
// Claim playback before the stream connects: the announcement makes any other
// window release its own audio right away, instead of overlapping with ours.
playbackOwner = CONTEXT_ID;
renderPlaybackState();
announcePlayback();
const el = new Audio(station.streamUrl);
audio = el;
el.preload = 'none';
let usageRecorded = false;
// All handlers are no-ops once `el` is no longer the current element, so a
// superseded stream can never drive the UI or re-trigger a stop.
el.onplaying = () => {
if (audio !== el) {
return;
}
status = 'playing';
renderPlaybackState();
announcePlayback();
// Count the play once it actually starts, so usage-based ordering reflects
// real listening. The new order applies on the next refresh/reopen rather
// than reshuffling tiles mid-playback.
if (!usageRecorded) {
usageRecorded = true;
sendMessage({ type: 'RECORD_USAGE', stationId: station.id }).catch(() => {});
}
};
el.onerror = () => {
if (audio !== el) {
return;
}
status = 'error';
renderPlaybackState();
announcePlayback();
};
// A live stream that simply ends (server closed the connection, playlist ran
// out) fires `ended` — never `error` — and a `pause` we did not trigger means
// the element stopped on its own. Both leave the UI and the badge stuck on
// "ON" unless we treat them as a stop.
el.onended = () => {
if (audio !== el) {
return;
}
stopAudio();
};
el.onpause = () => {
if (audio !== el) {
return;
}
stopAudio();
};
el.play().catch((error) => {
if (audio !== el) {
return;
}
// A fresh pop-out window may block autoplay (no user gesture yet): don't
// show a stream error, just return to a clickable state.
if (error && error.name === 'NotAllowedError') {
stopAudio();
return;
}
status = 'error';
renderPlaybackState();
});
}
function createStationCard(station) {
const card = document.createElement('div');
card.className = 'station-card';
card.style.setProperty('--station-color', station.color);
if (station.textColor) {
card.style.setProperty('--station-text', station.textColor);
}
const button = document.createElement('button');
button.className = 'station';
button.type = 'button';
button.dataset.stationId = station.id;
const mark = document.createElement('span');
mark.className = 'mark';
mark.textContent = station.mark || station.name;
mark.setAttribute('aria-hidden', 'true');
const name = document.createElement('span');
name.className = 'name';
name.textContent = station.name;
button.append(mark, name);
button.addEventListener('click', () => {
playStation(station);
});
const link = document.createElement('a');
link.className = 'site-link';
link.href = station.siteUrl;
link.target = '_blank';
link.rel = 'noreferrer noopener';
link.textContent = 'Site';
card.append(button, link);
return card;
}
function renderStations(state) {
stations = state.stations;
stationsNode.textContent = '';
stations.forEach((station) => {
stationsNode.append(createStationCard(station));
});
renderPlaybackState();
}
stopButton.addEventListener('click', () => {
stopAudio();
});
let refreshing = false;
function refreshStations() {
if (refreshing) {
return Promise.resolve();
}
refreshing = true;
refreshButton.classList.add('is-refreshing');
// Reconnect the current stream too, so refresh also recovers a stalled feed.
const replayId = (status === 'playing' || status === 'loading') && playbackOwner === CONTEXT_ID
? currentStationId
: null;
// GET_STATE is async: the user can stop, switch station or hand playback over
// to another window while it is in flight. Only replay if nothing changed the
// intent in the meantime, otherwise the refresh would undo their action.
const replayGeneration = playbackGeneration;
// Keep the spinner visible long enough to read, even though GET_STATE is instant.
const minSpin = new Promise((resolve) => setTimeout(resolve, 600));
return sendMessage({ type: 'GET_STATE' })
.then(renderStations)
.then(() => {
if (replayId && playbackGeneration === replayGeneration) {
const station = stations.find((item) => item.id === replayId);
if (station) {
startPlayback(station);
}
}
})
.catch(() => {
setStatus('Impossible de charger les stations.');
})
.then(() => minSpin)
.then(() => {
refreshing = false;
refreshButton.classList.remove('is-refreshing');
});
}
refreshButton.addEventListener('click', refreshStations);
// Pop-out: open the sidebar content in a detached window so the user can close
// the sidebar and keep listening. The current station is handed off via the URL
// and the sidebar's own audio is stopped to avoid playing twice.
function createPopoutWindow() {
const active = (status === 'playing' || status === 'loading') && currentStationId;
const handoff = active ? '&station=' + encodeURIComponent(currentStationId) : '';
const url = api.runtime.getURL('sidebar.html') + '?mode=popout' + handoff;
// Hand playback over *before* opening the window: releasing our audio after
// the new window has already connected would broadcast a stop that silences
// it. The station id travels in the URL, so nothing is lost.
stopAudio();
return storageGetLocal('popoutBounds')
.then((result) => (result && result.popoutBounds) || {})
.catch(() => ({}))
.then((bounds) => {
const opts = { url: url, type: 'popup', width: bounds.width || 380, height: bounds.height || 640 };
if (typeof bounds.left === 'number') opts.left = bounds.left;
if (typeof bounds.top === 'number') opts.top = bounds.top;
return api.windows.create(opts);
})
.then((win) => {
// Remember the window so a second click focuses it instead of stacking a
// new one; persisted so it survives the sidebar being reopened.
if (win && typeof win.id === 'number') {
storageSetLocal({ popoutWindowId: win.id });
}
});
}
function openPopout() {
storageGetLocal('popoutWindowId')
.then((result) => (result && typeof result.popoutWindowId === 'number') ? result.popoutWindowId : null)
.catch(() => null)
.then((existingId) => {
if (existingId === null || !api.windows || typeof api.windows.update !== 'function') {
return false;
}
// Bring the existing pop-out to the front; rejects if it was closed.
return api.windows.update(existingId, { focused: true }).then(() => true, () => false);
})
.then((focused) => {
if (!focused) {
return createPopoutWindow();
}
})
.catch(() => {});
}
popoutButton.addEventListener('click', openPopout);
if (isPopout) {
document.documentElement.classList.add('popout');
// No point popping out an already-detached window.
popoutButton.hidden = true;
// Remember the window size/position (debounced) to restore it next time.
let boundsTimer;
window.addEventListener('resize', () => {
clearTimeout(boundsTimer);
boundsTimer = setTimeout(() => {
storageSetLocal({
popoutBounds: {
width: window.outerWidth,
height: window.outerHeight,
left: window.screenX,
top: window.screenY
}
});
}, 600);
});
}
if (versionNode && api.runtime && typeof api.runtime.getManifest === 'function') {
versionNode.textContent = 'v' + api.runtime.getManifest().version;
}
function buildChangelog() {
const fragment = document.createDocumentFragment();
CHANGELOG.forEach((entry) => {
const item = document.createElement('section');
item.className = 'changelog-entry';
const head = document.createElement('div');
head.className = 'changelog-entry-head';
const version = document.createElement('span');
version.className = 'changelog-version';
version.textContent = 'v' + entry.version;
const date = document.createElement('span');
date.className = 'changelog-date';
date.textContent = entry.date;
head.append(version, date);
const list = document.createElement('ul');
list.className = 'changelog-list';
entry.changes.forEach((change) => {
const line = document.createElement('li');
line.textContent = change;
list.append(line);
});
item.append(head, list);
fragment.append(item);
});
changelogBody.textContent = '';
changelogBody.append(fragment);
}
function openChangelog() {
if (!changelogBody.childNodes.length) {
buildChangelog();
}
changelogOverlay.hidden = false;
versionNode.setAttribute('aria-expanded', 'true');
changelogClose.focus();
}
function closeChangelog() {
if (changelogOverlay.hidden) {
return;
}
changelogOverlay.hidden = true;
versionNode.setAttribute('aria-expanded', 'false');
versionNode.focus();
}
versionNode.addEventListener('click', openChangelog);
changelogClose.addEventListener('click', closeChangelog);
// Close on backdrop click (but not when clicking inside the dialog).
changelogOverlay.addEventListener('click', (event) => {
if (event.target === changelogOverlay) {
closeChangelog();
}
});
// Escape closes; Tab is trapped on the close button (only focusable control).
document.addEventListener('keydown', (event) => {
if (changelogOverlay.hidden) {
return;
}
if (event.key === 'Escape') {
closeChangelog();
} else if (event.key === 'Tab') {
event.preventDefault();
changelogClose.focus();
}
});
// Closing the window that holds the audio must not leave the other contexts
// showing a station that is no longer audible. Best effort: the broadcast is
// sent while the page is still alive.
window.addEventListener('pagehide', () => {
if (playbackOwner === CONTEXT_ID && status !== 'stopped') {
status = 'stopped';
currentStationId = null;
playbackOwner = null;
announcePlayback();
}
});
refreshStations().then(() => {
if (isPopout) {
const wanted = params.get('station');
const station = wanted && stations.find((item) => item.id === wanted);
if (station) {
playStation(station);
return;
}
}
// Opened while another context is already playing: adopt its state instead of
// showing an idle UI (and a badge) that contradicts the sound being heard.
sendMessage({ type: 'SIDEBAR_PLAYBACK_QUERY', ownerId: CONTEXT_ID }).catch(() => {});
});