Changeset 3799705
- Timestamp:
- 11/13/2026 05:19:56 AM (3 days ago)
- Location:
- sonaar-mp3-audio-player-cloud
- Files:
-
- 2 added
- 20 edited
- 1 copied
-
tags/1.0.2 (copied) (copied from sonaar-mp3-audio-player-cloud/trunk )
-
tags/1.0.2/assets/editor.js (modified) (2 diffs)
-
tags/1.0.2/assets/page-player-copy.json (modified) (10 diffs)
-
tags/1.0.2/assets/page-song.css (modified) (1 diff)
-
tags/1.0.2/assets/page-song.js (modified) (20 diffs)
-
tags/1.0.2/assets/player.js (modified) (3 diffs)
-
tags/1.0.2/block/block.json (modified) (1 diff)
-
tags/1.0.2/includes/class-page-song.php (modified) (3 diffs)
-
tags/1.0.2/readme.txt (modified) (2 diffs)
-
tags/1.0.2/sonaar-mp3-audio-player-cloud.php (modified) (1 diff)
-
tags/1.0.2/source/page-song.ts (modified) (19 diffs)
-
tags/1.0.2/source/selection-save-queue.ts (added)
-
trunk/assets/editor.js (modified) (2 diffs)
-
trunk/assets/page-player-copy.json (modified) (10 diffs)
-
trunk/assets/page-song.css (modified) (1 diff)
-
trunk/assets/page-song.js (modified) (20 diffs)
-
trunk/assets/player.js (modified) (3 diffs)
-
trunk/block/block.json (modified) (1 diff)
-
trunk/includes/class-page-song.php (modified) (3 diffs)
-
trunk/readme.txt (modified) (2 diffs)
-
trunk/sonaar-mp3-audio-player-cloud.php (modified) (1 diff)
-
trunk/source/page-song.ts (modified) (19 diffs)
-
trunk/source/selection-save-queue.ts (added)
Legend:
- Unmodified
- Added
- Removed
-
sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/editor.js
r3799592 r3799705 211 211 if (!alive.current || new URL(value.url).origin !== config.origin) throw Error(); 212 212 setConnectionUrl(popup ? '' : value.url); if (popup) popup.location = value.url; 213 var started = Date.now() ;213 var started = Date.now(), checking = false; 214 214 clearInterval(connectPoll.current); 215 215 connectPoll.current = setInterval(function () { 216 216 if (Date.now() - started > 10 * 60 * 1000) { clearInterval(connectPoll.current); setBusy(false); return; } 217 if (checking) return; 218 checking = true; 217 219 request('status', 'GET', { postId: postId }).then(function (value) { 218 220 if (!alive.current) return; … … 222 224 } 223 225 clearInterval(connectPoll.current); setConnected(true); setBusy(false); setConnectionUrl(''); 224 }).catch(function () {}) ;226 }).catch(function () {}).finally(function () { checking = false; }); 225 227 }, 2000); 226 228 }).catch(function () { if (popup) popup.close(); setBusy(false); setError(__('Studio could not complete this request. Keep this window open and try again.', 'sonaar-mp3-audio-player-cloud')); }); -
sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/page-player-copy.json
r3799592 r3799705 155 155 "sharedPlaylistHelp": "Changes here update this player everywhere it is used.", 156 156 "dynamicPlaylistHelp": "This player uses a collection or automatic source. Use Edit player to manage its audio.", 157 "pagePlaylistHelp": "Changes here are saved immediately to the audio assigned to this page." 157 "pagePlaylistHelp": "Changes here are saved immediately to the audio assigned to this page.", 158 "savingPlaylist": "Saving playlist…" 158 159 }, 159 160 "fr": { … … 312 313 "sharedPlaylistHelp": "Les modifications ici mettent à jour ce lecteur partout où il est utilisé.", 313 314 "dynamicPlaylistHelp": "Ce lecteur utilise une collection ou une source automatique. Utilisez Modifier le lecteur pour gérer son audio.", 314 "pagePlaylistHelp": "Les modifications sont immédiatement enregistrées dans la sélection audio de cette page." 315 "pagePlaylistHelp": "Les modifications sont immédiatement enregistrées dans la sélection audio de cette page.", 316 "savingPlaylist": "Enregistrement de la playlist…" 315 317 }, 316 318 "es": { … … 469 471 "sharedPlaylistHelp": "Los cambios aquí actualizan este reproductor en todos los lugares donde se utiliza.", 470 472 "dynamicPlaylistHelp": "Este reproductor usa una colección o una fuente automática. Usa Editar reproductor para gestionar su audio.", 471 "pagePlaylistHelp": "Los cambios se guardan de inmediato en el audio asignado a esta página." 473 "pagePlaylistHelp": "Los cambios se guardan de inmediato en el audio asignado a esta página.", 474 "savingPlaylist": "Guardando lista de reproducción…" 472 475 }, 473 476 "de": { … … 626 629 "sharedPlaylistHelp": "Änderungen hier aktualisieren diesen Player überall, wo er verwendet wird.", 627 630 "dynamicPlaylistHelp": "Dieser Player verwendet eine Sammlung oder eine automatische Quelle. Verwalte seine Audiodateien über Player bearbeiten.", 628 "pagePlaylistHelp": "Änderungen werden sofort für die dieser Seite zugewiesenen Audiodateien gespeichert." 631 "pagePlaylistHelp": "Änderungen werden sofort für die dieser Seite zugewiesenen Audiodateien gespeichert.", 632 "savingPlaylist": "Wiedergabeliste wird gespeichert…" 629 633 }, 630 634 "ja": { … … 783 787 "sharedPlaylistHelp": "ここでの変更は、このプレーヤーが使用されているすべての場所に反映されます。", 784 788 "dynamicPlaylistHelp": "このプレーヤーはコレクションまたは自動ソースを使用しています。「プレーヤーを編集」から音声を管理してください。", 785 "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。" 789 "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。", 790 "savingPlaylist": "プレイリストを保存中…" 786 791 }, 787 792 "pt": { … … 940 945 "sharedPlaylistHelp": "As alterações aqui atualizam este player em todos os locais onde é usado.", 941 946 "dynamicPlaylistHelp": "Este player usa uma coleção ou uma fonte automática. Use Editar player para gerenciar o áudio.", 942 "pagePlaylistHelp": "As alterações são salvas imediatamente no áudio atribuído a esta página." 947 "pagePlaylistHelp": "As alterações são salvas imediatamente no áudio atribuído a esta página.", 948 "savingPlaylist": "Salvando a lista de reprodução…" 943 949 }, 944 950 "ru": { … … 1097 1103 "sharedPlaylistHelp": "Изменения здесь обновляют этот плеер везде, где он используется.", 1098 1104 "dynamicPlaylistHelp": "Этот плеер использует коллекцию или автоматический источник. Чтобы управлять аудио, выберите «Редактировать плеер».", 1099 "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице." 1105 "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице.", 1106 "savingPlaylist": "Сохранение плейлиста…" 1100 1107 }, 1101 1108 "it": { … … 1254 1261 "sharedPlaylistHelp": "Le modifiche qui aggiornano questo lettore ovunque venga utilizzato.", 1255 1262 "dynamicPlaylistHelp": "Questo lettore usa una raccolta o una sorgente automatica. Usa Modifica lettore per gestire il suo audio.", 1256 "pagePlaylistHelp": "Le modifiche vengono salvate subito nell’audio assegnato a questa pagina." 1263 "pagePlaylistHelp": "Le modifiche vengono salvate subito nell’audio assegnato a questa pagina.", 1264 "savingPlaylist": "Salvataggio della playlist…" 1257 1265 }, 1258 1266 "nl": { … … 1411 1419 "sharedPlaylistHelp": "Wijzigingen hier werken deze speler overal bij waar hij wordt gebruikt.", 1412 1420 "dynamicPlaylistHelp": "Deze speler gebruikt een verzameling of automatische bron. Gebruik Speler bewerken om de audio te beheren.", 1413 "pagePlaylistHelp": "Wijzigingen worden direct opgeslagen in de audio die aan deze pagina is toegewezen." 1421 "pagePlaylistHelp": "Wijzigingen worden direct opgeslagen in de audio die aan deze pagina is toegewezen.", 1422 "savingPlaylist": "Afspeellijst opslaan…" 1414 1423 }, 1415 1424 "pl": { … … 1568 1577 "sharedPlaylistHelp": "Zmiany w tym miejscu aktualizują ten odtwarzacz wszędzie, gdzie jest używany.", 1569 1578 "dynamicPlaylistHelp": "Ten odtwarzacz korzysta z kolekcji lub automatycznego źródła. Użyj opcji Edytuj odtwarzacz, aby zarządzać dźwiękiem.", 1570 "pagePlaylistHelp": "Zmiany są natychmiast zapisywane w nagraniach przypisanych do tej strony." 1579 "pagePlaylistHelp": "Zmiany są natychmiast zapisywane w nagraniach przypisanych do tej strony.", 1580 "savingPlaylist": "Zapisywanie listy odtwarzania…" 1571 1581 } 1572 1582 } -
sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/page-song.css
r3799592 r3799705 359 359 .sonaar-song-modal .sonaar-audio-check { flex:0 0 28px; display:flex; align-items:center; justify-content:center; box-sizing:border-box; width:28px; height:28px; padding:0; border:1px solid #d9d3e5; border-radius:8px; background:#f7f6fa; color:#6041d8; line-height:1; } 360 360 .sonaar-song-modal .sonaar-audio-check svg { display:block; flex:none; width:16px; height:16px; margin:0; } 361 /* WordPress button styles fill SVGs by default; these icons use open strokes. */ 362 .sonaar-song-modal .sonaar-audio-check svg, 363 .sonaar-song-modal .sonaar-audio-check svg path { fill:none; } 361 364 .sonaar-song-modal .is-selected .sonaar-audio-check { background:#fff; color:#6041d8; border-color:#fff; } 362 365 .sonaar-song-modal .sonaar-song-result:not(.is-selected):hover .sonaar-audio-check { border-color:#6041d8; background:#eee9fc; } 363 366 .sonaar-picker-footer { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:18px 0 0; background:#fff; border-top:1px solid #e9e6ee; font-size:13px; color:#77717e; } 367 .sonaar-selection-saving { align-self:center; font-size:12px; line-height:1.4; color:inherit; } 364 368 @media(max-width:600px) { .sonaar-library-toolbar { flex-direction:column; align-items:stretch; gap:8px; } .sonaar-library-upload .components-button { width:100%; justify-content:center; } .sonaar-song-modal { max-height:calc(100dvh - 24px); height:calc(100dvh - 24px); } } 365 369 .sonaar-song-panel-title { -
sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/page-song.js
r3799592 r3799705 14486 14486 } 14487 14487 14488 // wordpress/sonaar-mp3-audio-player-cloud/source/selection-save-queue.ts 14489 function selectionSaveQueue(options) { 14490 let wanted = null; 14491 let running = null; 14492 let disposed = false; 14493 async function drain() { 14494 let changed = false, failure; 14495 options.pending(true); 14496 try { 14497 while (wanted && !disposed) { 14498 const next = wanted; 14499 wanted = null; 14500 try { 14501 await options.save(next); 14502 changed = true; 14503 failure = void 0; 14504 } catch (error) { 14505 wanted = null; 14506 failure = error; 14507 if (!disposed) await options.failed(error); 14508 } 14509 } 14510 } finally { 14511 if (!disposed) { 14512 options.pending(false); 14513 options.settled(changed); 14514 } 14515 } 14516 if (failure) throw failure; 14517 } 14518 return { 14519 enqueue(ids) { 14520 if (disposed) return Promise.resolve(); 14521 wanted = [...ids]; 14522 if (!running) running = drain().finally(() => { 14523 running = null; 14524 }); 14525 return running; 14526 }, 14527 dispose() { 14528 disposed = true; 14529 wanted = null; 14530 } 14531 }; 14532 } 14533 14488 14534 // wordpress/sonaar-mp3-audio-player-cloud/source/page-song.ts 14489 14535 var config = window.sonaarPageSong; … … 14532 14578 const api = (method, body) => requestApi(method, body, playerId, postId, context); 14533 14579 const latest = wp.element.useRef(null); 14580 const dataVersion = wp.element.useRef(0); 14534 14581 const saveLock = wp.element.useRef("sonaar-audio-" + Math.random().toString(36).slice(2)); 14535 14582 const updateData = (next) => { 14583 dataVersion.current++; 14536 14584 latest.current = next; 14537 14585 setData(next); … … 14540 14588 }; 14541 14589 const [needsConnection, setNeedsConnection] = wp.element.useState(false); 14590 const [savingSelection, setSavingSelection] = wp.element.useState(false); 14591 const [optimisticSelection, setOptimisticSelection] = wp.element.useState(null); 14592 const selectionKey = playerId + ":" + postId + ":" + context; 14593 const selectionSession = wp.element.useRef(null); 14594 const callbacks = wp.element.useRef({ onChange, onRefresh }); 14595 callbacks.current = { onChange, onRefresh }; 14542 14596 const reportError = (error2) => { 14543 14597 const expired = isConnectionError(error2); … … 14575 14629 wp.element.useEffect(() => { 14576 14630 let alive = true; 14631 const version = dataVersion.current; 14577 14632 api("GET").then((v) => { 14578 if (alive ) updateData(v);14633 if (alive && version === dataVersion.current) updateData(v); 14579 14634 }).catch((e) => { 14580 14635 if (alive) reportError(e); … … 14585 14640 }, [playerId, postId, context, refreshRevision]); 14586 14641 wp.element.useEffect(() => { 14587 if (!busy) return; 14642 const session = { active: true, saving: false, confirmed: [], desired: null, edit: 0, queue: null }; 14643 selectionSession.current = session; 14644 setOptimisticSelection(null); 14645 setSavingSelection(false); 14646 session.queue = selectionSaveQueue({ 14647 save: async (ids) => { 14648 const result = await persistSelection(ids, session); 14649 if (!session.active) return; 14650 session.confirmed = result.ids; 14651 if (result.data) updateData(result.data); 14652 if (result.token) callbacks.current.onChange?.(result.token); 14653 }, 14654 pending: (saving2) => { 14655 session.saving = saving2; 14656 if (session.active) setSavingSelection(saving2); 14657 }, 14658 failed: async (error2) => { 14659 if (!session.active) return; 14660 reportError(error2); 14661 const edit = session.edit; 14662 session.desired = [...session.confirmed]; 14663 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 14664 try { 14665 const fresh = await api("GET"); 14666 if (!session.active) return; 14667 updateData(fresh); 14668 if (playerId) session.confirmed = fresh.cloud.players.find((p) => p.id === playerId)?.trackIds || []; 14669 if (edit === session.edit) { 14670 session.desired = [...session.confirmed]; 14671 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 14672 } 14673 } catch { 14674 } 14675 if (session.active) reportError(error2); 14676 }, 14677 settled: (changed) => { 14678 if (!session.active) return; 14679 session.desired = null; 14680 setOptimisticSelection(null); 14681 if (changed) callbacks.current.onRefresh?.(); 14682 } 14683 }); 14684 return () => { 14685 session.active = false; 14686 session.queue?.dispose(); 14687 }; 14688 }, [playerId, postId, context]); 14689 const saving = busy || savingSelection; 14690 wp.element.useEffect(() => { 14691 if (!saving) return; 14588 14692 const prevent = (e) => { 14589 14693 e.preventDefault(); … … 14609 14713 } 14610 14714 }; 14611 }, [ busy]);14715 }, [saving]); 14612 14716 async function run(job) { 14613 14717 if (pending.current) return; … … 14629 14733 setPlaying(""); 14630 14734 }; 14735 const persistSelection = async (ids, session) => { 14736 if (playerId) { 14737 const player = latest.current?.cloud.players.find((p) => p.id === playerId); 14738 const result = await api("POST", { action: "playlist", playerId, trackIds: ids, revision: player?.revision }); 14739 if (!session.active) return { ids }; 14740 if (!result.player || !Number.isFinite(result.player.updatedAt)) throw new Error("request_failed"); 14741 const next = latest.current; 14742 return { ids: result.player.trackIds || [], data: { ...next, cloud: { ...next.cloud, players: next.cloud.players.map((p) => p.id === playerId ? { ...p, trackIds: result.player.trackIds || [], revision: result.player.updatedAt } : p) } } }; 14743 } 14744 const prepared = await api("POST", { action: "prepare", trackId: ids.join(",") }); 14745 if (!session.active) return { ids }; 14746 if (context === "elementor") { 14747 await api("POST", { action: "assign", token: prepared.token, previous: latest.current?.selection }); 14748 if (!session.active) return { ids }; 14749 return { ids, data: { ...latest.current, selection: prepared.token, trackId: ids.join(","), settings: { ...latest.current.settings, pageAudio: prepared.pageAudio } } }; 14750 } 14751 return { ids, token: prepared.token }; 14752 }; 14631 14753 const choose = async (ids) => { 14632 14754 if (ids.length > 100) throw new Error("selection_limit"); 14755 const session = selectionSession.current; 14756 if (!session?.active) return; 14633 14757 stop(); 14634 if (playerId) { 14635 const player = latest.current?.cloud.players.find((p) => p.id === playerId); 14636 await api("POST", { action: "playlist", playerId, trackIds: [...new Set(ids)], revision: player?.revision }); 14637 await reload(); 14638 onRefresh?.(); 14639 return; 14640 } 14641 const prepared = await api("POST", { action: "prepare", trackId: [...new Set(ids)].join(",") }); 14642 if (context === "elementor") { 14643 await api("POST", { action: "assign", token: prepared.token, previous: latest.current?.selection }); 14644 await reload(); 14645 onRefresh?.(); 14646 } else onChange?.(prepared.token); 14758 setError(""); 14759 if (!session.saving) session.confirmed = [...trackIds]; 14760 const next = [...new Set(ids)]; 14761 session.desired = next; 14762 session.edit++; 14763 setOptimisticSelection({ key: selectionKey, ids: next }); 14764 return session.queue.enqueue(next); 14647 14765 }; 14766 const currentSelection = () => selectionSession.current?.desired ?? trackIds; 14648 14767 async function listen(id) { 14649 14768 if (playing === id) { … … 14668 14787 } 14669 14788 async function upload(selected) { 14670 if (!selected.length ) return;14789 if (!selected.length || savingSelection) return; 14671 14790 if (selected.length + trackIds.length > 100) { 14672 14791 setError(c.selectionLimit); … … 14675 14794 await run(async () => { 14676 14795 let next = [...trackIds]; 14796 let added = false; 14677 14797 setQuery(""); 14678 for (const [index, input] of selected.entries()) { 14679 if (input.size > config.uploadLimit) throw new Error("upload_size"); 14680 setStatus(message("uploading", { n: index + 1, total: selected.length, name: input.name })); 14681 let track; 14682 await importSelectedTracks( 14683 [input], 14684 async (blob, _progress, processed) => { 14685 const response = await fetch(config.rest + "/upload?postId=" + postId, { 14686 method: "POST", 14687 credentials: "same-origin", 14688 headers: { 14689 "X-WP-Nonce": config.nonce, 14690 "Content-Type": "application/octet-stream", 14691 "X-Sonaar-Audio-Name": encodeURIComponent(blob.name) 14692 }, 14693 body: blob 14694 }); 14695 const result2 = await response.json(); 14696 if (!response.ok) throw new Error(result2.code); 14697 if (result2.duration) processed?.(result2.duration); 14698 return result2.url; 14699 }, 14700 (t) => { 14701 track = t; 14702 } 14703 ); 14704 if (!track) throw new Error("upload_type"); 14705 let result; 14706 try { 14707 result = await api("POST", { action: "add-track", track }); 14708 } catch (e) { 14709 if (e.message !== "revision_conflict") throw e; 14710 result = await api("POST", { action: "add-track", track }); 14711 } 14712 await reload(); 14713 next = [.../* @__PURE__ */ new Set([...next, result.track.id])]; 14714 await choose(next); 14798 try { 14799 for (const [index, input] of selected.entries()) { 14800 if (input.size > config.uploadLimit) throw new Error("upload_size"); 14801 setStatus(message("uploading", { n: index + 1, total: selected.length, name: input.name })); 14802 let track; 14803 await importSelectedTracks( 14804 [input], 14805 async (blob, _progress, processed) => { 14806 const response = await fetch(config.rest + "/upload?postId=" + postId, { 14807 method: "POST", 14808 credentials: "same-origin", 14809 headers: { 14810 "X-WP-Nonce": config.nonce, 14811 "Content-Type": "application/octet-stream", 14812 "X-Sonaar-Audio-Name": encodeURIComponent(blob.name) 14813 }, 14814 body: blob 14815 }); 14816 const result2 = await response.json(); 14817 if (!response.ok) throw new Error(result2.code); 14818 if (result2.duration) processed?.(result2.duration); 14819 return result2.url; 14820 }, 14821 (t) => { 14822 track = t; 14823 } 14824 ); 14825 if (!track) throw new Error("upload_type"); 14826 let result; 14827 try { 14828 result = await api("POST", { action: "add-track", track }); 14829 } catch (e) { 14830 if (e.message !== "revision_conflict") throw e; 14831 result = await api("POST", { action: "add-track", track }); 14832 } 14833 next = [.../* @__PURE__ */ new Set([...next, result.track.id])]; 14834 added = true; 14835 } 14836 } finally { 14837 if (added) { 14838 await reload(); 14839 await choose(next); 14840 } 14715 14841 } 14716 14842 }); 14717 14843 } 14718 14844 const selectedPlayer = data?.cloud.players.find((p) => p.id === playerId); 14719 const trackIds = playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? "").split(",").filter(Boolean);14845 const trackIds = optimisticSelection?.key === selectionKey ? optimisticSelection.ids : playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? "").split(",").filter(Boolean); 14720 14846 const songs = data?.cloud.tracks || []; 14721 14847 const shownIds = dragOrder || trackIds; … … 14736 14862 }; 14737 14863 const commitOrder = async (next, id) => { 14738 await run(async () => { 14739 try { 14740 await choose(next); 14741 setAnnouncement( 14742 message("trackMoved", { 14743 name: songs.find((s) => s.id === id)?.title || c.songs, 14744 n: next.indexOf(id) + 1 14745 }) 14746 ); 14747 } finally { 14748 cancelDrag(); 14749 } 14750 }); 14864 cancelDrag(); 14865 setAnnouncement(message("trackMoved", { name: songs.find((s) => s.id === id)?.title || c.songs, n: next.indexOf(id) + 1 })); 14866 try { 14867 await choose(next); 14868 } catch { 14869 } 14751 14870 }; 14752 14871 const grip = (id) => h( … … 14877 14996 "aria-label": c.removeSong + " " + (songs.find((s) => s.id === id)?.title || ""), 14878 14997 disabled: busy, 14879 onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))) 14998 onClick: () => { 14999 void choose(currentSelection().filter((t) => t !== id)).catch(reportError); 15000 } 14880 15001 }, 14881 15002 h( … … 14895 15016 const design = data?.cloud.players.find((p) => p.id === data.settings.playerId); 14896 15017 const configured = playerId ? !!selectedPlayer?.playlistEditable : !!design || !!data?.settings.widgetDesign; 14897 const button = (text, callback, primary = false, iconPath ) => h(15018 const button = (text, callback, primary = false, iconPath, disabled = busy) => h( 14898 15019 wp.components.Button, 14899 { variant: primary ? "primary" : "secondary", disabled : busy, onClick: callback },15020 { variant: primary ? "primary" : "secondary", disabled, onClick: callback }, 14900 15021 iconPath && h( 14901 15022 "svg", … … 14947 15068 return h( 14948 15069 "div", 14949 { className: "sonaar-song-panel", "aria-busy": busy},15070 { className: "sonaar-song-panel", "aria-busy": saving }, 14950 15071 editingAudio && h(window.SonaarCloudEditor.Studio, { 14951 15072 action: "audio", … … 15020 15141 onDrop: (e) => { 15021 15142 e.preventDefault(); 15022 if (config.canUpload && ! busy) void upload(Array.from(e.dataTransfer?.files || []));15143 if (config.canUpload && !saving) void upload(Array.from(e.dataTransfer?.files || [])); 15023 15144 } 15024 15145 }, … … 15065 15186 label: c.editAudio, 15066 15187 showTooltip: true, 15188 disabled: saving, 15067 15189 onClick: () => { 15068 15190 audio.current?.pause(); … … 15093 15215 true, 15094 15216 "M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3" 15095 ) 15217 ), 15218 h("span", { className: "sonaar-selection-saving", role: "status", "aria-live": "polite" }, savingSelection ? c.savingPlaylist : "") 15096 15219 ), 15097 15220 h("input", { … … 15158 15281 () => file.current.click(), 15159 15282 true, 15160 "M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5" 15283 "M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5", 15284 saving 15161 15285 ) 15162 15286 ) … … 15179 15303 variant: "tertiary", 15180 15304 disabled: busy, 15181 onClick: () => void run( 15182 () => choose( 15183 trackIds.includes(s.id) ? trackIds.filter((id) => id !== s.id) : [...trackIds, s.id] 15184 ) 15185 ), 15305 onClick: () => { 15306 const ids = currentSelection(); 15307 void choose(ids.includes(s.id) ? ids.filter((id) => id !== s.id) : [...ids, s.id]).catch(reportError); 15308 }, 15186 15309 "aria-pressed": trackIds.includes(s.id) 15187 15310 }, … … 15199 15322 "svg", 15200 15323 { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.25, strokeLinecap: "round", strokeLinejoin: "round", focusable: false }, 15201 h("path", { d: trackIds.includes(s.id) ? "M5 12l4 4L19 6" : "M12 5v14M5 12h14" })15324 h("path", { fill: "none", d: trackIds.includes(s.id) ? "M5 12l4 4L19 6" : "M12 5v14M5 12h14" }) 15202 15325 ) 15203 15326 ) … … 15213 15336 { className: "sonaar-picker-footer" }, 15214 15337 h("span", { role: "status", "aria-live": "polite" }, message("selectedCount", { n: trackIds.length })), 15338 h("span", { className: "sonaar-selection-saving", role: "status", "aria-live": "polite" }, savingSelection ? c.savingPlaylist : ""), 15215 15339 button( 15216 15340 c.close, -
sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/player.js
r3799592 r3799705 9 9 var origin; 10 10 try { origin = new URL(frame.src).origin; } catch (_error) { return function () {}; } 11 var timer ;11 var timer, ready = false; 12 12 function fail() { 13 13 clearTimeout(timer); … … 15 15 } 16 16 function loading() { 17 if (options.onLoading) options.onLoading(); 18 clearTimeout(timer); 19 if (options.onError) timer = setTimeout(fail, 15000); 17 // First paint can arrive before the document's load event or hydration. 18 // Do not hide a confirmed, rendered player again when load fires later. 19 if (!ready) { 20 if (options.onLoading) options.onLoading(); 21 clearTimeout(timer); 22 if (options.onError) timer = setTimeout(fail, 15000); 23 } 20 24 requestSize(); 21 25 } … … 25 29 function receive(event) { 26 30 var data = event.data; 27 if (event.origin !== origin || event.source !== frame.contentWindow || !data || data.type !== 'sonaar:resize') return;31 if (event.origin !== origin || event.source !== frame.contentWindow || !data || (data.type !== 'sonaar:resize' && data.type !== 'sonaar:rendered')) return; 28 32 if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) return; 29 33 clearTimeout(timer); 34 ready = true; 30 35 if (options.onReady) options.onReady(); 31 36 if (options.autoHeight === false) return; -
sonaar-mp3-audio-player-cloud/tags/1.0.2/block/block.json
r3799603 r3799705 3 3 "apiVersion": 3, 4 4 "name": "sonaar-cloud/player", 5 "version": "1.0. 1",5 "version": "1.0.2", 6 6 "title": "Sonaar MP3 Audio Player Cloud", 7 7 "category": "media", -
sonaar-mp3-audio-player-cloud/tags/1.0.2/includes/class-page-song.php
r3799592 r3799705 85 85 public static function request( $request ) { 86 86 $id = self::request_post_id( $request ); $settings = Page_Players::settings( get_post_type( $id ) ); 87 $body = 'POST' === $request->get_method() ? $request->get_json_params() : array(); 88 $action = $body['action'] ?? ''; 89 if ( in_array( $action, array( 'listen', 'add-track', 'playlist' ), true ) ) { 90 if ( 'add-track' === $action && ! current_user_can( 'upload_files' ) ) { return new \WP_Error( 'forbidden', '', array( 'status' => 403 ) ); } 91 if ( ! $request->get_param( 'playerId' ) && ! empty( $settings['scope'] ) ) { 92 // Page-bound setups still require their original workspace. Shared 93 // player edits are authorized directly by Cloud's player ownership check. 94 $cloud = Plugin::cloud( 'page-player', 'GET' ); 95 if ( is_wp_error( $cloud ) ) { return $cloud; } 96 if ( $settings['scope'] !== $cloud['scope'] ) { return new \WP_Error( 'different_account', '', array( 'status' => 409 ) ); } 97 } 98 // The authenticated Cloud mutation checks workspace ownership, track IDs 99 // and revisions itself. Avoid fetching the entire catalog first. 100 unset( $body['postId'] ); return Plugin::cloud( 'page-player', 'POST', $body ); 101 } 87 102 $cloud = Plugin::cloud( 'page-player', 'GET' ); 88 103 if ( is_wp_error( $cloud ) ) { return $cloud; } … … 91 106 $value = array( 'postId' => $id, 'selection' => get_post_meta( $id, self::META, true ), 'cloud' => $cloud, 'settings' => array_intersect_key( $settings, array_flip( array( 'playerId', 'placement', 'scope', 'widgetDesign', 'pageAudio' ) ) ), 'trackId' => self::track( $id, $settings ) ); 92 107 } else { 93 $body = $request->get_json_params(); $action = $body['action'] ?? '';94 108 if ( 'assign' === $action ) { 95 109 $token = $body['token'] ?? ''; $decoded = self::decode( $token, $id ); … … 102 116 } 103 117 return array( 'trackId' => $decoded['trackId'] ); 104 }105 if ( in_array( $action, array( 'listen', 'add-track', 'playlist' ), true ) ) {106 if ( 'add-track' === $action && ! current_user_can( 'upload_files' ) ) { return new \WP_Error( 'forbidden', '', array( 'status' => 403 ) ); }107 unset( $body['postId'] ); return Plugin::cloud( 'page-player', 'POST', $body );108 118 } 109 119 $track = $body['trackId'] ?? null; -
sonaar-mp3-audio-player-cloud/tags/1.0.2/readme.txt
r3799603 r3799705 5 5 Tested up to: 7.1 6 6 Requires PHP: 8.1 7 Stable tag: 1.0. 17 Stable tag: 1.0.2 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html … … 157 157 == Changelog == 158 158 159 = 1.0.2 - November 13, 2026 = 160 * Improved playlist selection and drag-and-drop responsiveness with background saves and fewer library requests. 161 * Improved player preview readiness and prevented late loading events from hiding an already rendered player. 162 * Reduced repeated library refreshes and playlist saves when uploading multiple audio files. 163 * Prevented overlapping account connection checks on slow networks. 164 * Fixed the selected-track checkmark appearance in the audio picker. 165 159 166 = 1.0.1 - November 12, 2026 = 160 167 * Fixed the first-install screen to offer account connection without showing a request failure. Genuine service errors remain visible. -
sonaar-mp3-audio-player-cloud/tags/1.0.2/sonaar-mp3-audio-player-cloud.php
r3799603 r3799705 3 3 * Plugin Name: Sonaar MP3 Audio Player Cloud 4 4 * Description: Create and embed Sonaar Cloud audio players with Gutenberg, Elementor or a shortcode. 5 * Version: 1.0. 15 * Version: 1.0.2 6 6 * Requires at least: 6.5 7 7 * Requires PHP: 8.1 -
sonaar-mp3-audio-player-cloud/tags/1.0.2/source/page-song.ts
r3799592 r3799705 1 1 import { importSelectedTracks } from '../../../lib/audio-import'; 2 import { selectionSaveQueue } from './selection-save-queue'; 2 3 declare global { 3 4 interface Window { … … 61 62 const api = (method: string, body?: any) => requestApi(method, body, playerId, postId, context); 62 63 const latest = wp.element.useRef(null); 64 const dataVersion = wp.element.useRef(0); 63 65 const saveLock = wp.element.useRef('sonaar-audio-' + Math.random().toString(36).slice(2)); 64 const updateData = (next: any) => { latest.current = next; setData(next); setNeedsConnection(false); setError(''); };66 const updateData = (next: any) => { dataVersion.current++; latest.current = next; setData(next); setNeedsConnection(false); setError(''); }; 65 67 const [needsConnection, setNeedsConnection] = wp.element.useState(false); 68 const [savingSelection, setSavingSelection] = wp.element.useState(false); 69 const [optimisticSelection, setOptimisticSelection] = wp.element.useState(null); 70 const selectionKey = playerId + ':' + postId + ':' + context; 71 const selectionSession = wp.element.useRef(null); 72 const callbacks = wp.element.useRef({ onChange, onRefresh }); 73 callbacks.current = { onChange, onRefresh }; 66 74 const reportError = (error: any) => { 67 75 const expired = isConnectionError(error); … … 101 109 wp.element.useEffect(() => { 102 110 let alive = true; 111 const version = dataVersion.current; 103 112 api('GET') 104 113 .then((v) => { 105 if (alive ) updateData(v);114 if (alive && version === dataVersion.current) updateData(v); 106 115 }) 107 116 .catch((e) => { … … 113 122 }, [playerId, postId, context, refreshRevision]); 114 123 wp.element.useEffect(() => { 115 if (!busy) return; 124 const session = { active: true, saving: false, confirmed: [] as string[], desired: null as string[] | null, edit: 0, queue: null as ReturnType<typeof selectionSaveQueue> | null }; 125 selectionSession.current = session; 126 setOptimisticSelection(null); 127 setSavingSelection(false); 128 session.queue = selectionSaveQueue({ 129 save: async (ids) => { 130 const result = await persistSelection(ids, session); 131 if (!session.active) return; 132 session.confirmed = result.ids; 133 if (result.data) updateData(result.data); 134 if (result.token) callbacks.current.onChange?.(result.token); 135 }, 136 pending: (saving) => { session.saving = saving; if (session.active) setSavingSelection(saving); }, 137 failed: async (error) => { 138 if (!session.active) return; 139 reportError(error); 140 const edit = session.edit; 141 session.desired = [...session.confirmed]; 142 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 143 // Read fresh revisions only after an error, never after every click. 144 try { 145 const fresh = await api('GET'); 146 if (!session.active) return; 147 updateData(fresh); 148 if (playerId) session.confirmed = fresh.cloud.players.find((p: any) => p.id === playerId)?.trackIds || []; 149 if (edit === session.edit) { 150 session.desired = [...session.confirmed]; 151 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 152 } 153 } catch { /* Keep the confirmed selection and the original error visible. */ } 154 if (session.active) reportError(error); 155 }, 156 settled: (changed) => { 157 if (!session.active) return; 158 session.desired = null; 159 setOptimisticSelection(null); 160 if (changed) callbacks.current.onRefresh?.(); 161 }, 162 }); 163 return () => { session.active = false; session.queue?.dispose(); }; 164 }, [playerId, postId, context]); 165 const saving = busy || savingSelection; 166 wp.element.useEffect(() => { 167 if (!saving) return; 116 168 const prevent = (e: BeforeUnloadEvent) => { 117 169 e.preventDefault(); … … 137 189 } 138 190 }; 139 }, [ busy]);191 }, [saving]); 140 192 async function run(job: () => Promise<void>) { 141 193 if (pending.current) return; … … 157 209 setPlaying(''); 158 210 }; 159 const choose = async (ids: string[]) => { 160 if (ids.length > 100) throw new Error('selection_limit'); 161 stop(); 211 const persistSelection = async (ids: string[], session: { active: boolean }): Promise<{ ids: string[]; data?: any; token?: string }> => { 162 212 if (playerId) { 163 213 const player = latest.current?.cloud.players.find((p: any) => p.id === playerId); 164 await api('POST', { action: 'playlist', playerId, trackIds: [...new Set(ids)], revision: player?.revision }); 165 await reload(); 166 onRefresh?.(); 167 return; 214 const result = await api('POST', { action: 'playlist', playerId, trackIds: ids, revision: player?.revision }); 215 if (!session.active) return { ids }; 216 if (!result.player || !Number.isFinite(result.player.updatedAt)) throw new Error('request_failed'); 217 const next = latest.current; 218 return { ids: result.player.trackIds || [], data: { ...next, cloud: { ...next.cloud, players: next.cloud.players.map((p: any) => p.id === playerId ? { ...p, trackIds: result.player.trackIds || [], revision: result.player.updatedAt } : p) } } }; 168 219 } 169 const prepared = await api('POST', { action: 'prepare', trackId: [...new Set(ids)].join(',') }); 220 const prepared = await api('POST', { action: 'prepare', trackId: ids.join(',') }); 221 if (!session.active) return { ids }; 170 222 if (context === 'elementor') { 171 223 // Page assignments belong to the preview page, never to the widget's design. 172 224 await api('POST', { action: 'assign', token: prepared.token, previous: latest.current?.selection }); 173 await reload(); 174 onRefresh?.(); 175 } else onChange?.(prepared.token); 225 if (!session.active) return { ids }; 226 return { ids, data: { ...latest.current, selection: prepared.token, trackId: ids.join(','), settings: { ...latest.current.settings, pageAudio: prepared.pageAudio } } }; 227 } 228 return { ids, token: prepared.token }; 176 229 }; 230 const choose = async (ids: string[]) => { 231 if (ids.length > 100) throw new Error('selection_limit'); 232 const session = selectionSession.current; 233 if (!session?.active) return; 234 stop(); 235 setError(''); 236 if (!session.saving) session.confirmed = [...trackIds]; 237 const next = [...new Set(ids)]; 238 session.desired = next; 239 session.edit++; 240 setOptimisticSelection({ key: selectionKey, ids: next }); 241 return session.queue.enqueue(next); 242 }; 243 const currentSelection = (): string[] => selectionSession.current?.desired ?? trackIds; 177 244 async function listen(id: string) { 178 245 if (playing === id) { … … 197 264 } 198 265 async function upload(selected: File[]) { 199 if (!selected.length ) return;266 if (!selected.length || savingSelection) return; 200 267 if (selected.length + trackIds.length > 100) { 201 268 setError(c.selectionLimit); … … 204 271 await run(async () => { 205 272 let next = [...trackIds]; 273 let added = false; 206 274 setQuery(''); 207 for (const [index, input] of selected.entries()) { 208 if (input.size > config.uploadLimit) throw new Error('upload_size'); 209 setStatus(message('uploading', { n: index + 1, total: selected.length, name: input.name })); 210 let track: any; 211 await importSelectedTracks( 212 [input], 213 async (blob, _progress, processed) => { 214 const response = await fetch(config.rest + '/upload?postId=' + postId, { 215 method: 'POST', 216 credentials: 'same-origin', 217 headers: { 218 'X-WP-Nonce': config.nonce, 219 'Content-Type': 'application/octet-stream', 220 'X-Sonaar-Audio-Name': encodeURIComponent(blob.name), 221 }, 222 body: blob, 223 }); 224 const result = await response.json(); 225 if (!response.ok) throw new Error(result.code); 226 if (result.duration) processed?.(result.duration); 227 return result.url; 228 }, 229 (t) => { 230 track = t; 231 }, 232 ); 233 if (!track) throw new Error('upload_type'); 234 let result; 235 try { 236 result = await api('POST', { action: 'add-track', track }); 237 } catch (e: any) { 238 if (e.message !== 'revision_conflict') throw e; 239 result = await api('POST', { action: 'add-track', track }); 275 try { 276 for (const [index, input] of selected.entries()) { 277 if (input.size > config.uploadLimit) throw new Error('upload_size'); 278 setStatus(message('uploading', { n: index + 1, total: selected.length, name: input.name })); 279 let track: any; 280 await importSelectedTracks( 281 [input], 282 async (blob, _progress, processed) => { 283 const response = await fetch(config.rest + '/upload?postId=' + postId, { 284 method: 'POST', 285 credentials: 'same-origin', 286 headers: { 287 'X-WP-Nonce': config.nonce, 288 'Content-Type': 'application/octet-stream', 289 'X-Sonaar-Audio-Name': encodeURIComponent(blob.name), 290 }, 291 body: blob, 292 }); 293 const result = await response.json(); 294 if (!response.ok) throw new Error(result.code); 295 if (result.duration) processed?.(result.duration); 296 return result.url; 297 }, 298 (t) => { 299 track = t; 300 }, 301 ); 302 if (!track) throw new Error('upload_type'); 303 let result; 304 try { 305 result = await api('POST', { action: 'add-track', track }); 306 } catch (e: any) { 307 if (e.message !== 'revision_conflict') throw e; 308 result = await api('POST', { action: 'add-track', track }); 309 } 310 next = [...new Set([...next, result.track.id])]; 311 added = true; 240 312 } 241 await reload(); 242 next = [...new Set([...next, result.track.id])]; 243 await choose(next); 313 } finally { 314 // Refresh signed artwork/usage and assign the completed uploads once per 315 // batch. Preserve successful files even if a later upload fails. 316 if (added) { await reload(); await choose(next); } 244 317 } 245 318 }); 246 319 } 247 320 const selectedPlayer = data?.cloud.players.find((p: any) => p.id === playerId); 248 const trackIds: string[] = playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? '').split(',').filter(Boolean);321 const trackIds: string[] = optimisticSelection?.key === selectionKey ? optimisticSelection.ids : playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? '').split(',').filter(Boolean); 249 322 const songs: any[] = data?.cloud.tracks || []; 250 323 const shownIds: string[] = dragOrder || trackIds; … … 265 338 }; 266 339 const commitOrder = async (next: string[], id: string) => { 267 await run(async () => { 268 try { 269 await choose(next); 270 setAnnouncement( 271 message('trackMoved', { 272 name: songs.find((s) => s.id === id)?.title || c.songs, 273 n: next.indexOf(id) + 1, 274 }), 275 ); 276 } finally { 277 cancelDrag(); 278 } 279 }); 340 cancelDrag(); 341 setAnnouncement(message('trackMoved', { name: songs.find((s) => s.id === id)?.title || c.songs, n: next.indexOf(id) + 1 })); 342 try { await choose(next); } catch { /* The save queue displays errors and restores confirmed order. */ } 280 343 }; 281 344 const grip = (id: string) => … … 414 477 'aria-label': c.removeSong + ' ' + (songs.find((s) => s.id === id)?.title || ''), 415 478 disabled: busy, 416 onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))),479 onClick: () => { void choose(currentSelection().filter((t) => t !== id)).catch(reportError); }, 417 480 }, 418 481 h( … … 432 495 const design = data?.cloud.players.find((p: any) => p.id === data.settings.playerId); 433 496 const configured = playerId ? !!selectedPlayer?.playlistEditable : !!design || !!data?.settings.widgetDesign; 434 const button = (text: string, callback: () => void, primary = false, iconPath?: string ) =>497 const button = (text: string, callback: () => void, primary = false, iconPath?: string, disabled = busy) => 435 498 h( 436 499 wp.components.Button, 437 { variant: primary ? 'primary' : 'secondary', disabled : busy, onClick: callback },500 { variant: primary ? 'primary' : 'secondary', disabled, onClick: callback }, 438 501 iconPath && 439 502 h( … … 494 557 return h( 495 558 'div', 496 { className: 'sonaar-song-panel', 'aria-busy': busy},559 { className: 'sonaar-song-panel', 'aria-busy': saving }, 497 560 editingAudio && h(window.SonaarCloudEditor.Studio, { 498 561 action: 'audio', trackId: editingAudio, postId: data?.postId || postId, … … 563 626 onDrop: (e: DragEvent) => { 564 627 e.preventDefault(); 565 if (config.canUpload && ! busy) void upload(Array.from(e.dataTransfer?.files || []));628 if (config.canUpload && !saving) void upload(Array.from(e.dataTransfer?.files || [])); 566 629 }, 567 630 }, … … 609 672 className: 'sonaar-edit-audio', icon: 'edit', 610 673 label: c.editAudio, showTooltip: true, 674 disabled: saving, 611 675 onClick: () => { audio.current?.pause(); setPlaying(''); setEditingAudio(id); }, 612 676 }), … … 635 699 'M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3', 636 700 ), 701 h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''), 637 702 ), 638 703 h('input', { … … 698 763 true, 699 764 'M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5', 765 saving, 700 766 ), 701 767 )), … … 722 788 variant: 'tertiary', 723 789 disabled: busy, 724 onClick: () => 725 void run(() => 726 choose( 727 trackIds.includes(s.id) 728 ? trackIds.filter((id) => id !== s.id) 729 : [...trackIds, s.id], 730 ), 731 ), 790 onClick: () => { 791 const ids = currentSelection(); 792 void choose(ids.includes(s.id) ? ids.filter((id) => id !== s.id) : [...ids, s.id]).catch(reportError); 793 }, 732 794 'aria-pressed': trackIds.includes(s.id), 733 795 }, … … 741 803 h('span', { className: 'sonaar-audio-check', 'aria-hidden': true }, 742 804 h('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.25, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: false }, 743 h('path', { d: trackIds.includes(s.id) ? 'M5 12l4 4L19 6' : 'M12 5v14M5 12h14' }),805 h('path', { fill: 'none', d: trackIds.includes(s.id) ? 'M5 12l4 4L19 6' : 'M12 5v14M5 12h14' }), 744 806 ), 745 807 ), … … 757 819 { className: 'sonaar-picker-footer' }, 758 820 h('span', { role: 'status', 'aria-live': 'polite' }, message('selectedCount', { n: trackIds.length })), 821 h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''), 759 822 button( 760 823 c.close, -
sonaar-mp3-audio-player-cloud/trunk/assets/editor.js
r3799592 r3799705 211 211 if (!alive.current || new URL(value.url).origin !== config.origin) throw Error(); 212 212 setConnectionUrl(popup ? '' : value.url); if (popup) popup.location = value.url; 213 var started = Date.now() ;213 var started = Date.now(), checking = false; 214 214 clearInterval(connectPoll.current); 215 215 connectPoll.current = setInterval(function () { 216 216 if (Date.now() - started > 10 * 60 * 1000) { clearInterval(connectPoll.current); setBusy(false); return; } 217 if (checking) return; 218 checking = true; 217 219 request('status', 'GET', { postId: postId }).then(function (value) { 218 220 if (!alive.current) return; … … 222 224 } 223 225 clearInterval(connectPoll.current); setConnected(true); setBusy(false); setConnectionUrl(''); 224 }).catch(function () {}) ;226 }).catch(function () {}).finally(function () { checking = false; }); 225 227 }, 2000); 226 228 }).catch(function () { if (popup) popup.close(); setBusy(false); setError(__('Studio could not complete this request. Keep this window open and try again.', 'sonaar-mp3-audio-player-cloud')); }); -
sonaar-mp3-audio-player-cloud/trunk/assets/page-player-copy.json
r3799592 r3799705 155 155 "sharedPlaylistHelp": "Changes here update this player everywhere it is used.", 156 156 "dynamicPlaylistHelp": "This player uses a collection or automatic source. Use Edit player to manage its audio.", 157 "pagePlaylistHelp": "Changes here are saved immediately to the audio assigned to this page." 157 "pagePlaylistHelp": "Changes here are saved immediately to the audio assigned to this page.", 158 "savingPlaylist": "Saving playlist…" 158 159 }, 159 160 "fr": { … … 312 313 "sharedPlaylistHelp": "Les modifications ici mettent à jour ce lecteur partout où il est utilisé.", 313 314 "dynamicPlaylistHelp": "Ce lecteur utilise une collection ou une source automatique. Utilisez Modifier le lecteur pour gérer son audio.", 314 "pagePlaylistHelp": "Les modifications sont immédiatement enregistrées dans la sélection audio de cette page." 315 "pagePlaylistHelp": "Les modifications sont immédiatement enregistrées dans la sélection audio de cette page.", 316 "savingPlaylist": "Enregistrement de la playlist…" 315 317 }, 316 318 "es": { … … 469 471 "sharedPlaylistHelp": "Los cambios aquí actualizan este reproductor en todos los lugares donde se utiliza.", 470 472 "dynamicPlaylistHelp": "Este reproductor usa una colección o una fuente automática. Usa Editar reproductor para gestionar su audio.", 471 "pagePlaylistHelp": "Los cambios se guardan de inmediato en el audio asignado a esta página." 473 "pagePlaylistHelp": "Los cambios se guardan de inmediato en el audio asignado a esta página.", 474 "savingPlaylist": "Guardando lista de reproducción…" 472 475 }, 473 476 "de": { … … 626 629 "sharedPlaylistHelp": "Änderungen hier aktualisieren diesen Player überall, wo er verwendet wird.", 627 630 "dynamicPlaylistHelp": "Dieser Player verwendet eine Sammlung oder eine automatische Quelle. Verwalte seine Audiodateien über Player bearbeiten.", 628 "pagePlaylistHelp": "Änderungen werden sofort für die dieser Seite zugewiesenen Audiodateien gespeichert." 631 "pagePlaylistHelp": "Änderungen werden sofort für die dieser Seite zugewiesenen Audiodateien gespeichert.", 632 "savingPlaylist": "Wiedergabeliste wird gespeichert…" 629 633 }, 630 634 "ja": { … … 783 787 "sharedPlaylistHelp": "ここでの変更は、このプレーヤーが使用されているすべての場所に反映されます。", 784 788 "dynamicPlaylistHelp": "このプレーヤーはコレクションまたは自動ソースを使用しています。「プレーヤーを編集」から音声を管理してください。", 785 "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。" 789 "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。", 790 "savingPlaylist": "プレイリストを保存中…" 786 791 }, 787 792 "pt": { … … 940 945 "sharedPlaylistHelp": "As alterações aqui atualizam este player em todos os locais onde é usado.", 941 946 "dynamicPlaylistHelp": "Este player usa uma coleção ou uma fonte automática. Use Editar player para gerenciar o áudio.", 942 "pagePlaylistHelp": "As alterações são salvas imediatamente no áudio atribuído a esta página." 947 "pagePlaylistHelp": "As alterações são salvas imediatamente no áudio atribuído a esta página.", 948 "savingPlaylist": "Salvando a lista de reprodução…" 943 949 }, 944 950 "ru": { … … 1097 1103 "sharedPlaylistHelp": "Изменения здесь обновляют этот плеер везде, где он используется.", 1098 1104 "dynamicPlaylistHelp": "Этот плеер использует коллекцию или автоматический источник. Чтобы управлять аудио, выберите «Редактировать плеер».", 1099 "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице." 1105 "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице.", 1106 "savingPlaylist": "Сохранение плейлиста…" 1100 1107 }, 1101 1108 "it": { … … 1254 1261 "sharedPlaylistHelp": "Le modifiche qui aggiornano questo lettore ovunque venga utilizzato.", 1255 1262 "dynamicPlaylistHelp": "Questo lettore usa una raccolta o una sorgente automatica. Usa Modifica lettore per gestire il suo audio.", 1256 "pagePlaylistHelp": "Le modifiche vengono salvate subito nell’audio assegnato a questa pagina." 1263 "pagePlaylistHelp": "Le modifiche vengono salvate subito nell’audio assegnato a questa pagina.", 1264 "savingPlaylist": "Salvataggio della playlist…" 1257 1265 }, 1258 1266 "nl": { … … 1411 1419 "sharedPlaylistHelp": "Wijzigingen hier werken deze speler overal bij waar hij wordt gebruikt.", 1412 1420 "dynamicPlaylistHelp": "Deze speler gebruikt een verzameling of automatische bron. Gebruik Speler bewerken om de audio te beheren.", 1413 "pagePlaylistHelp": "Wijzigingen worden direct opgeslagen in de audio die aan deze pagina is toegewezen." 1421 "pagePlaylistHelp": "Wijzigingen worden direct opgeslagen in de audio die aan deze pagina is toegewezen.", 1422 "savingPlaylist": "Afspeellijst opslaan…" 1414 1423 }, 1415 1424 "pl": { … … 1568 1577 "sharedPlaylistHelp": "Zmiany w tym miejscu aktualizują ten odtwarzacz wszędzie, gdzie jest używany.", 1569 1578 "dynamicPlaylistHelp": "Ten odtwarzacz korzysta z kolekcji lub automatycznego źródła. Użyj opcji Edytuj odtwarzacz, aby zarządzać dźwiękiem.", 1570 "pagePlaylistHelp": "Zmiany są natychmiast zapisywane w nagraniach przypisanych do tej strony." 1579 "pagePlaylistHelp": "Zmiany są natychmiast zapisywane w nagraniach przypisanych do tej strony.", 1580 "savingPlaylist": "Zapisywanie listy odtwarzania…" 1571 1581 } 1572 1582 } -
sonaar-mp3-audio-player-cloud/trunk/assets/page-song.css
r3799592 r3799705 359 359 .sonaar-song-modal .sonaar-audio-check { flex:0 0 28px; display:flex; align-items:center; justify-content:center; box-sizing:border-box; width:28px; height:28px; padding:0; border:1px solid #d9d3e5; border-radius:8px; background:#f7f6fa; color:#6041d8; line-height:1; } 360 360 .sonaar-song-modal .sonaar-audio-check svg { display:block; flex:none; width:16px; height:16px; margin:0; } 361 /* WordPress button styles fill SVGs by default; these icons use open strokes. */ 362 .sonaar-song-modal .sonaar-audio-check svg, 363 .sonaar-song-modal .sonaar-audio-check svg path { fill:none; } 361 364 .sonaar-song-modal .is-selected .sonaar-audio-check { background:#fff; color:#6041d8; border-color:#fff; } 362 365 .sonaar-song-modal .sonaar-song-result:not(.is-selected):hover .sonaar-audio-check { border-color:#6041d8; background:#eee9fc; } 363 366 .sonaar-picker-footer { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:18px 0 0; background:#fff; border-top:1px solid #e9e6ee; font-size:13px; color:#77717e; } 367 .sonaar-selection-saving { align-self:center; font-size:12px; line-height:1.4; color:inherit; } 364 368 @media(max-width:600px) { .sonaar-library-toolbar { flex-direction:column; align-items:stretch; gap:8px; } .sonaar-library-upload .components-button { width:100%; justify-content:center; } .sonaar-song-modal { max-height:calc(100dvh - 24px); height:calc(100dvh - 24px); } } 365 369 .sonaar-song-panel-title { -
sonaar-mp3-audio-player-cloud/trunk/assets/page-song.js
r3799592 r3799705 14486 14486 } 14487 14487 14488 // wordpress/sonaar-mp3-audio-player-cloud/source/selection-save-queue.ts 14489 function selectionSaveQueue(options) { 14490 let wanted = null; 14491 let running = null; 14492 let disposed = false; 14493 async function drain() { 14494 let changed = false, failure; 14495 options.pending(true); 14496 try { 14497 while (wanted && !disposed) { 14498 const next = wanted; 14499 wanted = null; 14500 try { 14501 await options.save(next); 14502 changed = true; 14503 failure = void 0; 14504 } catch (error) { 14505 wanted = null; 14506 failure = error; 14507 if (!disposed) await options.failed(error); 14508 } 14509 } 14510 } finally { 14511 if (!disposed) { 14512 options.pending(false); 14513 options.settled(changed); 14514 } 14515 } 14516 if (failure) throw failure; 14517 } 14518 return { 14519 enqueue(ids) { 14520 if (disposed) return Promise.resolve(); 14521 wanted = [...ids]; 14522 if (!running) running = drain().finally(() => { 14523 running = null; 14524 }); 14525 return running; 14526 }, 14527 dispose() { 14528 disposed = true; 14529 wanted = null; 14530 } 14531 }; 14532 } 14533 14488 14534 // wordpress/sonaar-mp3-audio-player-cloud/source/page-song.ts 14489 14535 var config = window.sonaarPageSong; … … 14532 14578 const api = (method, body) => requestApi(method, body, playerId, postId, context); 14533 14579 const latest = wp.element.useRef(null); 14580 const dataVersion = wp.element.useRef(0); 14534 14581 const saveLock = wp.element.useRef("sonaar-audio-" + Math.random().toString(36).slice(2)); 14535 14582 const updateData = (next) => { 14583 dataVersion.current++; 14536 14584 latest.current = next; 14537 14585 setData(next); … … 14540 14588 }; 14541 14589 const [needsConnection, setNeedsConnection] = wp.element.useState(false); 14590 const [savingSelection, setSavingSelection] = wp.element.useState(false); 14591 const [optimisticSelection, setOptimisticSelection] = wp.element.useState(null); 14592 const selectionKey = playerId + ":" + postId + ":" + context; 14593 const selectionSession = wp.element.useRef(null); 14594 const callbacks = wp.element.useRef({ onChange, onRefresh }); 14595 callbacks.current = { onChange, onRefresh }; 14542 14596 const reportError = (error2) => { 14543 14597 const expired = isConnectionError(error2); … … 14575 14629 wp.element.useEffect(() => { 14576 14630 let alive = true; 14631 const version = dataVersion.current; 14577 14632 api("GET").then((v) => { 14578 if (alive ) updateData(v);14633 if (alive && version === dataVersion.current) updateData(v); 14579 14634 }).catch((e) => { 14580 14635 if (alive) reportError(e); … … 14585 14640 }, [playerId, postId, context, refreshRevision]); 14586 14641 wp.element.useEffect(() => { 14587 if (!busy) return; 14642 const session = { active: true, saving: false, confirmed: [], desired: null, edit: 0, queue: null }; 14643 selectionSession.current = session; 14644 setOptimisticSelection(null); 14645 setSavingSelection(false); 14646 session.queue = selectionSaveQueue({ 14647 save: async (ids) => { 14648 const result = await persistSelection(ids, session); 14649 if (!session.active) return; 14650 session.confirmed = result.ids; 14651 if (result.data) updateData(result.data); 14652 if (result.token) callbacks.current.onChange?.(result.token); 14653 }, 14654 pending: (saving2) => { 14655 session.saving = saving2; 14656 if (session.active) setSavingSelection(saving2); 14657 }, 14658 failed: async (error2) => { 14659 if (!session.active) return; 14660 reportError(error2); 14661 const edit = session.edit; 14662 session.desired = [...session.confirmed]; 14663 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 14664 try { 14665 const fresh = await api("GET"); 14666 if (!session.active) return; 14667 updateData(fresh); 14668 if (playerId) session.confirmed = fresh.cloud.players.find((p) => p.id === playerId)?.trackIds || []; 14669 if (edit === session.edit) { 14670 session.desired = [...session.confirmed]; 14671 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 14672 } 14673 } catch { 14674 } 14675 if (session.active) reportError(error2); 14676 }, 14677 settled: (changed) => { 14678 if (!session.active) return; 14679 session.desired = null; 14680 setOptimisticSelection(null); 14681 if (changed) callbacks.current.onRefresh?.(); 14682 } 14683 }); 14684 return () => { 14685 session.active = false; 14686 session.queue?.dispose(); 14687 }; 14688 }, [playerId, postId, context]); 14689 const saving = busy || savingSelection; 14690 wp.element.useEffect(() => { 14691 if (!saving) return; 14588 14692 const prevent = (e) => { 14589 14693 e.preventDefault(); … … 14609 14713 } 14610 14714 }; 14611 }, [ busy]);14715 }, [saving]); 14612 14716 async function run(job) { 14613 14717 if (pending.current) return; … … 14629 14733 setPlaying(""); 14630 14734 }; 14735 const persistSelection = async (ids, session) => { 14736 if (playerId) { 14737 const player = latest.current?.cloud.players.find((p) => p.id === playerId); 14738 const result = await api("POST", { action: "playlist", playerId, trackIds: ids, revision: player?.revision }); 14739 if (!session.active) return { ids }; 14740 if (!result.player || !Number.isFinite(result.player.updatedAt)) throw new Error("request_failed"); 14741 const next = latest.current; 14742 return { ids: result.player.trackIds || [], data: { ...next, cloud: { ...next.cloud, players: next.cloud.players.map((p) => p.id === playerId ? { ...p, trackIds: result.player.trackIds || [], revision: result.player.updatedAt } : p) } } }; 14743 } 14744 const prepared = await api("POST", { action: "prepare", trackId: ids.join(",") }); 14745 if (!session.active) return { ids }; 14746 if (context === "elementor") { 14747 await api("POST", { action: "assign", token: prepared.token, previous: latest.current?.selection }); 14748 if (!session.active) return { ids }; 14749 return { ids, data: { ...latest.current, selection: prepared.token, trackId: ids.join(","), settings: { ...latest.current.settings, pageAudio: prepared.pageAudio } } }; 14750 } 14751 return { ids, token: prepared.token }; 14752 }; 14631 14753 const choose = async (ids) => { 14632 14754 if (ids.length > 100) throw new Error("selection_limit"); 14755 const session = selectionSession.current; 14756 if (!session?.active) return; 14633 14757 stop(); 14634 if (playerId) { 14635 const player = latest.current?.cloud.players.find((p) => p.id === playerId); 14636 await api("POST", { action: "playlist", playerId, trackIds: [...new Set(ids)], revision: player?.revision }); 14637 await reload(); 14638 onRefresh?.(); 14639 return; 14640 } 14641 const prepared = await api("POST", { action: "prepare", trackId: [...new Set(ids)].join(",") }); 14642 if (context === "elementor") { 14643 await api("POST", { action: "assign", token: prepared.token, previous: latest.current?.selection }); 14644 await reload(); 14645 onRefresh?.(); 14646 } else onChange?.(prepared.token); 14758 setError(""); 14759 if (!session.saving) session.confirmed = [...trackIds]; 14760 const next = [...new Set(ids)]; 14761 session.desired = next; 14762 session.edit++; 14763 setOptimisticSelection({ key: selectionKey, ids: next }); 14764 return session.queue.enqueue(next); 14647 14765 }; 14766 const currentSelection = () => selectionSession.current?.desired ?? trackIds; 14648 14767 async function listen(id) { 14649 14768 if (playing === id) { … … 14668 14787 } 14669 14788 async function upload(selected) { 14670 if (!selected.length ) return;14789 if (!selected.length || savingSelection) return; 14671 14790 if (selected.length + trackIds.length > 100) { 14672 14791 setError(c.selectionLimit); … … 14675 14794 await run(async () => { 14676 14795 let next = [...trackIds]; 14796 let added = false; 14677 14797 setQuery(""); 14678 for (const [index, input] of selected.entries()) { 14679 if (input.size > config.uploadLimit) throw new Error("upload_size"); 14680 setStatus(message("uploading", { n: index + 1, total: selected.length, name: input.name })); 14681 let track; 14682 await importSelectedTracks( 14683 [input], 14684 async (blob, _progress, processed) => { 14685 const response = await fetch(config.rest + "/upload?postId=" + postId, { 14686 method: "POST", 14687 credentials: "same-origin", 14688 headers: { 14689 "X-WP-Nonce": config.nonce, 14690 "Content-Type": "application/octet-stream", 14691 "X-Sonaar-Audio-Name": encodeURIComponent(blob.name) 14692 }, 14693 body: blob 14694 }); 14695 const result2 = await response.json(); 14696 if (!response.ok) throw new Error(result2.code); 14697 if (result2.duration) processed?.(result2.duration); 14698 return result2.url; 14699 }, 14700 (t) => { 14701 track = t; 14702 } 14703 ); 14704 if (!track) throw new Error("upload_type"); 14705 let result; 14706 try { 14707 result = await api("POST", { action: "add-track", track }); 14708 } catch (e) { 14709 if (e.message !== "revision_conflict") throw e; 14710 result = await api("POST", { action: "add-track", track }); 14711 } 14712 await reload(); 14713 next = [.../* @__PURE__ */ new Set([...next, result.track.id])]; 14714 await choose(next); 14798 try { 14799 for (const [index, input] of selected.entries()) { 14800 if (input.size > config.uploadLimit) throw new Error("upload_size"); 14801 setStatus(message("uploading", { n: index + 1, total: selected.length, name: input.name })); 14802 let track; 14803 await importSelectedTracks( 14804 [input], 14805 async (blob, _progress, processed) => { 14806 const response = await fetch(config.rest + "/upload?postId=" + postId, { 14807 method: "POST", 14808 credentials: "same-origin", 14809 headers: { 14810 "X-WP-Nonce": config.nonce, 14811 "Content-Type": "application/octet-stream", 14812 "X-Sonaar-Audio-Name": encodeURIComponent(blob.name) 14813 }, 14814 body: blob 14815 }); 14816 const result2 = await response.json(); 14817 if (!response.ok) throw new Error(result2.code); 14818 if (result2.duration) processed?.(result2.duration); 14819 return result2.url; 14820 }, 14821 (t) => { 14822 track = t; 14823 } 14824 ); 14825 if (!track) throw new Error("upload_type"); 14826 let result; 14827 try { 14828 result = await api("POST", { action: "add-track", track }); 14829 } catch (e) { 14830 if (e.message !== "revision_conflict") throw e; 14831 result = await api("POST", { action: "add-track", track }); 14832 } 14833 next = [.../* @__PURE__ */ new Set([...next, result.track.id])]; 14834 added = true; 14835 } 14836 } finally { 14837 if (added) { 14838 await reload(); 14839 await choose(next); 14840 } 14715 14841 } 14716 14842 }); 14717 14843 } 14718 14844 const selectedPlayer = data?.cloud.players.find((p) => p.id === playerId); 14719 const trackIds = playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? "").split(",").filter(Boolean);14845 const trackIds = optimisticSelection?.key === selectionKey ? optimisticSelection.ids : playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? "").split(",").filter(Boolean); 14720 14846 const songs = data?.cloud.tracks || []; 14721 14847 const shownIds = dragOrder || trackIds; … … 14736 14862 }; 14737 14863 const commitOrder = async (next, id) => { 14738 await run(async () => { 14739 try { 14740 await choose(next); 14741 setAnnouncement( 14742 message("trackMoved", { 14743 name: songs.find((s) => s.id === id)?.title || c.songs, 14744 n: next.indexOf(id) + 1 14745 }) 14746 ); 14747 } finally { 14748 cancelDrag(); 14749 } 14750 }); 14864 cancelDrag(); 14865 setAnnouncement(message("trackMoved", { name: songs.find((s) => s.id === id)?.title || c.songs, n: next.indexOf(id) + 1 })); 14866 try { 14867 await choose(next); 14868 } catch { 14869 } 14751 14870 }; 14752 14871 const grip = (id) => h( … … 14877 14996 "aria-label": c.removeSong + " " + (songs.find((s) => s.id === id)?.title || ""), 14878 14997 disabled: busy, 14879 onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))) 14998 onClick: () => { 14999 void choose(currentSelection().filter((t) => t !== id)).catch(reportError); 15000 } 14880 15001 }, 14881 15002 h( … … 14895 15016 const design = data?.cloud.players.find((p) => p.id === data.settings.playerId); 14896 15017 const configured = playerId ? !!selectedPlayer?.playlistEditable : !!design || !!data?.settings.widgetDesign; 14897 const button = (text, callback, primary = false, iconPath ) => h(15018 const button = (text, callback, primary = false, iconPath, disabled = busy) => h( 14898 15019 wp.components.Button, 14899 { variant: primary ? "primary" : "secondary", disabled : busy, onClick: callback },15020 { variant: primary ? "primary" : "secondary", disabled, onClick: callback }, 14900 15021 iconPath && h( 14901 15022 "svg", … … 14947 15068 return h( 14948 15069 "div", 14949 { className: "sonaar-song-panel", "aria-busy": busy},15070 { className: "sonaar-song-panel", "aria-busy": saving }, 14950 15071 editingAudio && h(window.SonaarCloudEditor.Studio, { 14951 15072 action: "audio", … … 15020 15141 onDrop: (e) => { 15021 15142 e.preventDefault(); 15022 if (config.canUpload && ! busy) void upload(Array.from(e.dataTransfer?.files || []));15143 if (config.canUpload && !saving) void upload(Array.from(e.dataTransfer?.files || [])); 15023 15144 } 15024 15145 }, … … 15065 15186 label: c.editAudio, 15066 15187 showTooltip: true, 15188 disabled: saving, 15067 15189 onClick: () => { 15068 15190 audio.current?.pause(); … … 15093 15215 true, 15094 15216 "M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3" 15095 ) 15217 ), 15218 h("span", { className: "sonaar-selection-saving", role: "status", "aria-live": "polite" }, savingSelection ? c.savingPlaylist : "") 15096 15219 ), 15097 15220 h("input", { … … 15158 15281 () => file.current.click(), 15159 15282 true, 15160 "M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5" 15283 "M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5", 15284 saving 15161 15285 ) 15162 15286 ) … … 15179 15303 variant: "tertiary", 15180 15304 disabled: busy, 15181 onClick: () => void run( 15182 () => choose( 15183 trackIds.includes(s.id) ? trackIds.filter((id) => id !== s.id) : [...trackIds, s.id] 15184 ) 15185 ), 15305 onClick: () => { 15306 const ids = currentSelection(); 15307 void choose(ids.includes(s.id) ? ids.filter((id) => id !== s.id) : [...ids, s.id]).catch(reportError); 15308 }, 15186 15309 "aria-pressed": trackIds.includes(s.id) 15187 15310 }, … … 15199 15322 "svg", 15200 15323 { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.25, strokeLinecap: "round", strokeLinejoin: "round", focusable: false }, 15201 h("path", { d: trackIds.includes(s.id) ? "M5 12l4 4L19 6" : "M12 5v14M5 12h14" })15324 h("path", { fill: "none", d: trackIds.includes(s.id) ? "M5 12l4 4L19 6" : "M12 5v14M5 12h14" }) 15202 15325 ) 15203 15326 ) … … 15213 15336 { className: "sonaar-picker-footer" }, 15214 15337 h("span", { role: "status", "aria-live": "polite" }, message("selectedCount", { n: trackIds.length })), 15338 h("span", { className: "sonaar-selection-saving", role: "status", "aria-live": "polite" }, savingSelection ? c.savingPlaylist : ""), 15215 15339 button( 15216 15340 c.close, -
sonaar-mp3-audio-player-cloud/trunk/assets/player.js
r3799592 r3799705 9 9 var origin; 10 10 try { origin = new URL(frame.src).origin; } catch (_error) { return function () {}; } 11 var timer ;11 var timer, ready = false; 12 12 function fail() { 13 13 clearTimeout(timer); … … 15 15 } 16 16 function loading() { 17 if (options.onLoading) options.onLoading(); 18 clearTimeout(timer); 19 if (options.onError) timer = setTimeout(fail, 15000); 17 // First paint can arrive before the document's load event or hydration. 18 // Do not hide a confirmed, rendered player again when load fires later. 19 if (!ready) { 20 if (options.onLoading) options.onLoading(); 21 clearTimeout(timer); 22 if (options.onError) timer = setTimeout(fail, 15000); 23 } 20 24 requestSize(); 21 25 } … … 25 29 function receive(event) { 26 30 var data = event.data; 27 if (event.origin !== origin || event.source !== frame.contentWindow || !data || data.type !== 'sonaar:resize') return;31 if (event.origin !== origin || event.source !== frame.contentWindow || !data || (data.type !== 'sonaar:resize' && data.type !== 'sonaar:rendered')) return; 28 32 if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) return; 29 33 clearTimeout(timer); 34 ready = true; 30 35 if (options.onReady) options.onReady(); 31 36 if (options.autoHeight === false) return; -
sonaar-mp3-audio-player-cloud/trunk/block/block.json
r3799603 r3799705 3 3 "apiVersion": 3, 4 4 "name": "sonaar-cloud/player", 5 "version": "1.0. 1",5 "version": "1.0.2", 6 6 "title": "Sonaar MP3 Audio Player Cloud", 7 7 "category": "media", -
sonaar-mp3-audio-player-cloud/trunk/includes/class-page-song.php
r3799592 r3799705 85 85 public static function request( $request ) { 86 86 $id = self::request_post_id( $request ); $settings = Page_Players::settings( get_post_type( $id ) ); 87 $body = 'POST' === $request->get_method() ? $request->get_json_params() : array(); 88 $action = $body['action'] ?? ''; 89 if ( in_array( $action, array( 'listen', 'add-track', 'playlist' ), true ) ) { 90 if ( 'add-track' === $action && ! current_user_can( 'upload_files' ) ) { return new \WP_Error( 'forbidden', '', array( 'status' => 403 ) ); } 91 if ( ! $request->get_param( 'playerId' ) && ! empty( $settings['scope'] ) ) { 92 // Page-bound setups still require their original workspace. Shared 93 // player edits are authorized directly by Cloud's player ownership check. 94 $cloud = Plugin::cloud( 'page-player', 'GET' ); 95 if ( is_wp_error( $cloud ) ) { return $cloud; } 96 if ( $settings['scope'] !== $cloud['scope'] ) { return new \WP_Error( 'different_account', '', array( 'status' => 409 ) ); } 97 } 98 // The authenticated Cloud mutation checks workspace ownership, track IDs 99 // and revisions itself. Avoid fetching the entire catalog first. 100 unset( $body['postId'] ); return Plugin::cloud( 'page-player', 'POST', $body ); 101 } 87 102 $cloud = Plugin::cloud( 'page-player', 'GET' ); 88 103 if ( is_wp_error( $cloud ) ) { return $cloud; } … … 91 106 $value = array( 'postId' => $id, 'selection' => get_post_meta( $id, self::META, true ), 'cloud' => $cloud, 'settings' => array_intersect_key( $settings, array_flip( array( 'playerId', 'placement', 'scope', 'widgetDesign', 'pageAudio' ) ) ), 'trackId' => self::track( $id, $settings ) ); 92 107 } else { 93 $body = $request->get_json_params(); $action = $body['action'] ?? '';94 108 if ( 'assign' === $action ) { 95 109 $token = $body['token'] ?? ''; $decoded = self::decode( $token, $id ); … … 102 116 } 103 117 return array( 'trackId' => $decoded['trackId'] ); 104 }105 if ( in_array( $action, array( 'listen', 'add-track', 'playlist' ), true ) ) {106 if ( 'add-track' === $action && ! current_user_can( 'upload_files' ) ) { return new \WP_Error( 'forbidden', '', array( 'status' => 403 ) ); }107 unset( $body['postId'] ); return Plugin::cloud( 'page-player', 'POST', $body );108 118 } 109 119 $track = $body['trackId'] ?? null; -
sonaar-mp3-audio-player-cloud/trunk/readme.txt
r3799603 r3799705 5 5 Tested up to: 7.1 6 6 Requires PHP: 8.1 7 Stable tag: 1.0. 17 Stable tag: 1.0.2 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html … … 157 157 == Changelog == 158 158 159 = 1.0.2 - November 13, 2026 = 160 * Improved playlist selection and drag-and-drop responsiveness with background saves and fewer library requests. 161 * Improved player preview readiness and prevented late loading events from hiding an already rendered player. 162 * Reduced repeated library refreshes and playlist saves when uploading multiple audio files. 163 * Prevented overlapping account connection checks on slow networks. 164 * Fixed the selected-track checkmark appearance in the audio picker. 165 159 166 = 1.0.1 - November 12, 2026 = 160 167 * Fixed the first-install screen to offer account connection without showing a request failure. Genuine service errors remain visible. -
sonaar-mp3-audio-player-cloud/trunk/sonaar-mp3-audio-player-cloud.php
r3799603 r3799705 3 3 * Plugin Name: Sonaar MP3 Audio Player Cloud 4 4 * Description: Create and embed Sonaar Cloud audio players with Gutenberg, Elementor or a shortcode. 5 * Version: 1.0. 15 * Version: 1.0.2 6 6 * Requires at least: 6.5 7 7 * Requires PHP: 8.1 -
sonaar-mp3-audio-player-cloud/trunk/source/page-song.ts
r3799592 r3799705 1 1 import { importSelectedTracks } from '../../../lib/audio-import'; 2 import { selectionSaveQueue } from './selection-save-queue'; 2 3 declare global { 3 4 interface Window { … … 61 62 const api = (method: string, body?: any) => requestApi(method, body, playerId, postId, context); 62 63 const latest = wp.element.useRef(null); 64 const dataVersion = wp.element.useRef(0); 63 65 const saveLock = wp.element.useRef('sonaar-audio-' + Math.random().toString(36).slice(2)); 64 const updateData = (next: any) => { latest.current = next; setData(next); setNeedsConnection(false); setError(''); };66 const updateData = (next: any) => { dataVersion.current++; latest.current = next; setData(next); setNeedsConnection(false); setError(''); }; 65 67 const [needsConnection, setNeedsConnection] = wp.element.useState(false); 68 const [savingSelection, setSavingSelection] = wp.element.useState(false); 69 const [optimisticSelection, setOptimisticSelection] = wp.element.useState(null); 70 const selectionKey = playerId + ':' + postId + ':' + context; 71 const selectionSession = wp.element.useRef(null); 72 const callbacks = wp.element.useRef({ onChange, onRefresh }); 73 callbacks.current = { onChange, onRefresh }; 66 74 const reportError = (error: any) => { 67 75 const expired = isConnectionError(error); … … 101 109 wp.element.useEffect(() => { 102 110 let alive = true; 111 const version = dataVersion.current; 103 112 api('GET') 104 113 .then((v) => { 105 if (alive ) updateData(v);114 if (alive && version === dataVersion.current) updateData(v); 106 115 }) 107 116 .catch((e) => { … … 113 122 }, [playerId, postId, context, refreshRevision]); 114 123 wp.element.useEffect(() => { 115 if (!busy) return; 124 const session = { active: true, saving: false, confirmed: [] as string[], desired: null as string[] | null, edit: 0, queue: null as ReturnType<typeof selectionSaveQueue> | null }; 125 selectionSession.current = session; 126 setOptimisticSelection(null); 127 setSavingSelection(false); 128 session.queue = selectionSaveQueue({ 129 save: async (ids) => { 130 const result = await persistSelection(ids, session); 131 if (!session.active) return; 132 session.confirmed = result.ids; 133 if (result.data) updateData(result.data); 134 if (result.token) callbacks.current.onChange?.(result.token); 135 }, 136 pending: (saving) => { session.saving = saving; if (session.active) setSavingSelection(saving); }, 137 failed: async (error) => { 138 if (!session.active) return; 139 reportError(error); 140 const edit = session.edit; 141 session.desired = [...session.confirmed]; 142 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 143 // Read fresh revisions only after an error, never after every click. 144 try { 145 const fresh = await api('GET'); 146 if (!session.active) return; 147 updateData(fresh); 148 if (playerId) session.confirmed = fresh.cloud.players.find((p: any) => p.id === playerId)?.trackIds || []; 149 if (edit === session.edit) { 150 session.desired = [...session.confirmed]; 151 setOptimisticSelection({ key: selectionKey, ids: session.confirmed }); 152 } 153 } catch { /* Keep the confirmed selection and the original error visible. */ } 154 if (session.active) reportError(error); 155 }, 156 settled: (changed) => { 157 if (!session.active) return; 158 session.desired = null; 159 setOptimisticSelection(null); 160 if (changed) callbacks.current.onRefresh?.(); 161 }, 162 }); 163 return () => { session.active = false; session.queue?.dispose(); }; 164 }, [playerId, postId, context]); 165 const saving = busy || savingSelection; 166 wp.element.useEffect(() => { 167 if (!saving) return; 116 168 const prevent = (e: BeforeUnloadEvent) => { 117 169 e.preventDefault(); … … 137 189 } 138 190 }; 139 }, [ busy]);191 }, [saving]); 140 192 async function run(job: () => Promise<void>) { 141 193 if (pending.current) return; … … 157 209 setPlaying(''); 158 210 }; 159 const choose = async (ids: string[]) => { 160 if (ids.length > 100) throw new Error('selection_limit'); 161 stop(); 211 const persistSelection = async (ids: string[], session: { active: boolean }): Promise<{ ids: string[]; data?: any; token?: string }> => { 162 212 if (playerId) { 163 213 const player = latest.current?.cloud.players.find((p: any) => p.id === playerId); 164 await api('POST', { action: 'playlist', playerId, trackIds: [...new Set(ids)], revision: player?.revision }); 165 await reload(); 166 onRefresh?.(); 167 return; 214 const result = await api('POST', { action: 'playlist', playerId, trackIds: ids, revision: player?.revision }); 215 if (!session.active) return { ids }; 216 if (!result.player || !Number.isFinite(result.player.updatedAt)) throw new Error('request_failed'); 217 const next = latest.current; 218 return { ids: result.player.trackIds || [], data: { ...next, cloud: { ...next.cloud, players: next.cloud.players.map((p: any) => p.id === playerId ? { ...p, trackIds: result.player.trackIds || [], revision: result.player.updatedAt } : p) } } }; 168 219 } 169 const prepared = await api('POST', { action: 'prepare', trackId: [...new Set(ids)].join(',') }); 220 const prepared = await api('POST', { action: 'prepare', trackId: ids.join(',') }); 221 if (!session.active) return { ids }; 170 222 if (context === 'elementor') { 171 223 // Page assignments belong to the preview page, never to the widget's design. 172 224 await api('POST', { action: 'assign', token: prepared.token, previous: latest.current?.selection }); 173 await reload(); 174 onRefresh?.(); 175 } else onChange?.(prepared.token); 225 if (!session.active) return { ids }; 226 return { ids, data: { ...latest.current, selection: prepared.token, trackId: ids.join(','), settings: { ...latest.current.settings, pageAudio: prepared.pageAudio } } }; 227 } 228 return { ids, token: prepared.token }; 176 229 }; 230 const choose = async (ids: string[]) => { 231 if (ids.length > 100) throw new Error('selection_limit'); 232 const session = selectionSession.current; 233 if (!session?.active) return; 234 stop(); 235 setError(''); 236 if (!session.saving) session.confirmed = [...trackIds]; 237 const next = [...new Set(ids)]; 238 session.desired = next; 239 session.edit++; 240 setOptimisticSelection({ key: selectionKey, ids: next }); 241 return session.queue.enqueue(next); 242 }; 243 const currentSelection = (): string[] => selectionSession.current?.desired ?? trackIds; 177 244 async function listen(id: string) { 178 245 if (playing === id) { … … 197 264 } 198 265 async function upload(selected: File[]) { 199 if (!selected.length ) return;266 if (!selected.length || savingSelection) return; 200 267 if (selected.length + trackIds.length > 100) { 201 268 setError(c.selectionLimit); … … 204 271 await run(async () => { 205 272 let next = [...trackIds]; 273 let added = false; 206 274 setQuery(''); 207 for (const [index, input] of selected.entries()) { 208 if (input.size > config.uploadLimit) throw new Error('upload_size'); 209 setStatus(message('uploading', { n: index + 1, total: selected.length, name: input.name })); 210 let track: any; 211 await importSelectedTracks( 212 [input], 213 async (blob, _progress, processed) => { 214 const response = await fetch(config.rest + '/upload?postId=' + postId, { 215 method: 'POST', 216 credentials: 'same-origin', 217 headers: { 218 'X-WP-Nonce': config.nonce, 219 'Content-Type': 'application/octet-stream', 220 'X-Sonaar-Audio-Name': encodeURIComponent(blob.name), 221 }, 222 body: blob, 223 }); 224 const result = await response.json(); 225 if (!response.ok) throw new Error(result.code); 226 if (result.duration) processed?.(result.duration); 227 return result.url; 228 }, 229 (t) => { 230 track = t; 231 }, 232 ); 233 if (!track) throw new Error('upload_type'); 234 let result; 235 try { 236 result = await api('POST', { action: 'add-track', track }); 237 } catch (e: any) { 238 if (e.message !== 'revision_conflict') throw e; 239 result = await api('POST', { action: 'add-track', track }); 275 try { 276 for (const [index, input] of selected.entries()) { 277 if (input.size > config.uploadLimit) throw new Error('upload_size'); 278 setStatus(message('uploading', { n: index + 1, total: selected.length, name: input.name })); 279 let track: any; 280 await importSelectedTracks( 281 [input], 282 async (blob, _progress, processed) => { 283 const response = await fetch(config.rest + '/upload?postId=' + postId, { 284 method: 'POST', 285 credentials: 'same-origin', 286 headers: { 287 'X-WP-Nonce': config.nonce, 288 'Content-Type': 'application/octet-stream', 289 'X-Sonaar-Audio-Name': encodeURIComponent(blob.name), 290 }, 291 body: blob, 292 }); 293 const result = await response.json(); 294 if (!response.ok) throw new Error(result.code); 295 if (result.duration) processed?.(result.duration); 296 return result.url; 297 }, 298 (t) => { 299 track = t; 300 }, 301 ); 302 if (!track) throw new Error('upload_type'); 303 let result; 304 try { 305 result = await api('POST', { action: 'add-track', track }); 306 } catch (e: any) { 307 if (e.message !== 'revision_conflict') throw e; 308 result = await api('POST', { action: 'add-track', track }); 309 } 310 next = [...new Set([...next, result.track.id])]; 311 added = true; 240 312 } 241 await reload(); 242 next = [...new Set([...next, result.track.id])]; 243 await choose(next); 313 } finally { 314 // Refresh signed artwork/usage and assign the completed uploads once per 315 // batch. Preserve successful files even if a later upload fails. 316 if (added) { await reload(); await choose(next); } 244 317 } 245 318 }); 246 319 } 247 320 const selectedPlayer = data?.cloud.players.find((p: any) => p.id === playerId); 248 const trackIds: string[] = playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? '').split(',').filter(Boolean);321 const trackIds: string[] = optimisticSelection?.key === selectionKey ? optimisticSelection.ids : playerId ? selectedPlayer?.trackIds || [] : (chosenToken(value) ?? data?.trackId ?? '').split(',').filter(Boolean); 249 322 const songs: any[] = data?.cloud.tracks || []; 250 323 const shownIds: string[] = dragOrder || trackIds; … … 265 338 }; 266 339 const commitOrder = async (next: string[], id: string) => { 267 await run(async () => { 268 try { 269 await choose(next); 270 setAnnouncement( 271 message('trackMoved', { 272 name: songs.find((s) => s.id === id)?.title || c.songs, 273 n: next.indexOf(id) + 1, 274 }), 275 ); 276 } finally { 277 cancelDrag(); 278 } 279 }); 340 cancelDrag(); 341 setAnnouncement(message('trackMoved', { name: songs.find((s) => s.id === id)?.title || c.songs, n: next.indexOf(id) + 1 })); 342 try { await choose(next); } catch { /* The save queue displays errors and restores confirmed order. */ } 280 343 }; 281 344 const grip = (id: string) => … … 414 477 'aria-label': c.removeSong + ' ' + (songs.find((s) => s.id === id)?.title || ''), 415 478 disabled: busy, 416 onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))),479 onClick: () => { void choose(currentSelection().filter((t) => t !== id)).catch(reportError); }, 417 480 }, 418 481 h( … … 432 495 const design = data?.cloud.players.find((p: any) => p.id === data.settings.playerId); 433 496 const configured = playerId ? !!selectedPlayer?.playlistEditable : !!design || !!data?.settings.widgetDesign; 434 const button = (text: string, callback: () => void, primary = false, iconPath?: string ) =>497 const button = (text: string, callback: () => void, primary = false, iconPath?: string, disabled = busy) => 435 498 h( 436 499 wp.components.Button, 437 { variant: primary ? 'primary' : 'secondary', disabled : busy, onClick: callback },500 { variant: primary ? 'primary' : 'secondary', disabled, onClick: callback }, 438 501 iconPath && 439 502 h( … … 494 557 return h( 495 558 'div', 496 { className: 'sonaar-song-panel', 'aria-busy': busy},559 { className: 'sonaar-song-panel', 'aria-busy': saving }, 497 560 editingAudio && h(window.SonaarCloudEditor.Studio, { 498 561 action: 'audio', trackId: editingAudio, postId: data?.postId || postId, … … 563 626 onDrop: (e: DragEvent) => { 564 627 e.preventDefault(); 565 if (config.canUpload && ! busy) void upload(Array.from(e.dataTransfer?.files || []));628 if (config.canUpload && !saving) void upload(Array.from(e.dataTransfer?.files || [])); 566 629 }, 567 630 }, … … 609 672 className: 'sonaar-edit-audio', icon: 'edit', 610 673 label: c.editAudio, showTooltip: true, 674 disabled: saving, 611 675 onClick: () => { audio.current?.pause(); setPlaying(''); setEditingAudio(id); }, 612 676 }), … … 635 699 'M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3', 636 700 ), 701 h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''), 637 702 ), 638 703 h('input', { … … 698 763 true, 699 764 'M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5', 765 saving, 700 766 ), 701 767 )), … … 722 788 variant: 'tertiary', 723 789 disabled: busy, 724 onClick: () => 725 void run(() => 726 choose( 727 trackIds.includes(s.id) 728 ? trackIds.filter((id) => id !== s.id) 729 : [...trackIds, s.id], 730 ), 731 ), 790 onClick: () => { 791 const ids = currentSelection(); 792 void choose(ids.includes(s.id) ? ids.filter((id) => id !== s.id) : [...ids, s.id]).catch(reportError); 793 }, 732 794 'aria-pressed': trackIds.includes(s.id), 733 795 }, … … 741 803 h('span', { className: 'sonaar-audio-check', 'aria-hidden': true }, 742 804 h('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2.25, strokeLinecap: 'round', strokeLinejoin: 'round', focusable: false }, 743 h('path', { d: trackIds.includes(s.id) ? 'M5 12l4 4L19 6' : 'M12 5v14M5 12h14' }),805 h('path', { fill: 'none', d: trackIds.includes(s.id) ? 'M5 12l4 4L19 6' : 'M12 5v14M5 12h14' }), 744 806 ), 745 807 ), … … 757 819 { className: 'sonaar-picker-footer' }, 758 820 h('span', { role: 'status', 'aria-live': 'polite' }, message('selectedCount', { n: trackIds.length })), 821 h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''), 759 822 button( 760 823 c.close,
Note:
See TracChangeset
for help on using the changeset viewer.