Plugin Directory

Changeset 3799705


Ignore:
Timestamp:
11/13/2026 05:19:56 AM (3 days ago)
Author:
sonaar
Message:

Release Sonaar MP3 Audio Player Cloud 1.0.2: responsive playlists, preview readiness, batched uploads and checkmark fix

Location:
sonaar-mp3-audio-player-cloud
Files:
2 added
20 edited
1 copied

Legend:

Unmodified
Added
Removed
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/editor.js

    r3799592 r3799705  
    211211        if (!alive.current || new URL(value.url).origin !== config.origin) throw Error();
    212212        setConnectionUrl(popup ? '' : value.url); if (popup) popup.location = value.url;
    213         var started = Date.now();
     213        var started = Date.now(), checking = false;
    214214        clearInterval(connectPoll.current);
    215215        connectPoll.current = setInterval(function () {
    216216          if (Date.now() - started > 10 * 60 * 1000) { clearInterval(connectPoll.current); setBusy(false); return; }
     217          if (checking) return;
     218          checking = true;
    217219          request('status', 'GET', { postId: postId }).then(function (value) {
    218220            if (!alive.current) return;
    … …  
    222224            }
    223225            clearInterval(connectPoll.current); setConnected(true); setBusy(false); setConnectionUrl('');
    224           }).catch(function () {});
     226          }).catch(function () {}).finally(function () { checking = false; });
    225227        }, 2000);
    226228      }).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  
    155155    "sharedPlaylistHelp": "Changes here update this player everywhere it is used.",
    156156    "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…"
    158159  },
    159160  "fr": {
    … …  
    312313    "sharedPlaylistHelp": "Les modifications ici mettent à jour ce lecteur partout où il est utilisé.",
    313314    "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…"
    315317  },
    316318  "es": {
    … …  
    469471    "sharedPlaylistHelp": "Los cambios aquí actualizan este reproductor en todos los lugares donde se utiliza.",
    470472    "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…"
    472475  },
    473476  "de": {
    … …  
    626629    "sharedPlaylistHelp": "Änderungen hier aktualisieren diesen Player überall, wo er verwendet wird.",
    627630    "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…"
    629633  },
    630634  "ja": {
    … …  
    783787    "sharedPlaylistHelp": "ここでの変更は、このプレーヤーが使用されているすべての場所に反映されます。",
    784788    "dynamicPlaylistHelp": "このプレーヤーはコレクションまたは自動ソースを使用しています。「プレーヤーを編集」から音声を管理してください。",
    785     "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。"
     789    "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。",
     790    "savingPlaylist": "プレイリストを保存中…"
    786791  },
    787792  "pt": {
    … …  
    940945    "sharedPlaylistHelp": "As alterações aqui atualizam este player em todos os locais onde é usado.",
    941946    "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…"
    943949  },
    944950  "ru": {
    … …  
    10971103    "sharedPlaylistHelp": "Изменения здесь обновляют этот плеер везде, где он используется.",
    10981104    "dynamicPlaylistHelp": "Этот плеер использует коллекцию или автоматический источник. Чтобы управлять аудио, выберите «Редактировать плеер».",
    1099     "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице."
     1105    "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице.",
     1106    "savingPlaylist": "Сохранение плейлиста…"
    11001107  },
    11011108  "it": {
    … …  
    12541261    "sharedPlaylistHelp": "Le modifiche qui aggiornano questo lettore ovunque venga utilizzato.",
    12551262    "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…"
    12571265  },
    12581266  "nl": {
    … …  
    14111419    "sharedPlaylistHelp": "Wijzigingen hier werken deze speler overal bij waar hij wordt gebruikt.",
    14121420    "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…"
    14141423  },
    14151424  "pl": {
    … …  
    15681577    "sharedPlaylistHelp": "Zmiany w tym miejscu aktualizują ten odtwarzacz wszędzie, gdzie jest używany.",
    15691578    "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…"
    15711581  }
    15721582}
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/page-song.css

    r3799592 r3799705  
    359359.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; }
    360360.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; }
    361364.sonaar-song-modal .is-selected .sonaar-audio-check { background:#fff; color:#6041d8; border-color:#fff; }
    362365.sonaar-song-modal .sonaar-song-result:not(.is-selected):hover .sonaar-audio-check { border-color:#6041d8; background:#eee9fc; }
    363366.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; }
    364368@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); } }
    365369.sonaar-song-panel-title {
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/page-song.js

    r3799592 r3799705  
    1448614486  }
    1448714487
     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
    1448814534  // wordpress/sonaar-mp3-audio-player-cloud/source/page-song.ts
    1448914535  var config = window.sonaarPageSong;
    … …  
    1453214578    const api = (method, body) => requestApi(method, body, playerId, postId, context);
    1453314579    const latest = wp.element.useRef(null);
     14580    const dataVersion = wp.element.useRef(0);
    1453414581    const saveLock = wp.element.useRef("sonaar-audio-" + Math.random().toString(36).slice(2));
    1453514582    const updateData = (next) => {
     14583      dataVersion.current++;
    1453614584      latest.current = next;
    1453714585      setData(next);
    … …  
    1454014588    };
    1454114589    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 };
    1454214596    const reportError = (error2) => {
    1454314597      const expired = isConnectionError(error2);
    … …  
    1457514629    wp.element.useEffect(() => {
    1457614630      let alive = true;
     14631      const version = dataVersion.current;
    1457714632      api("GET").then((v) => {
    14578         if (alive) updateData(v);
     14633        if (alive && version === dataVersion.current) updateData(v);
    1457914634      }).catch((e) => {
    1458014635        if (alive) reportError(e);
    … …  
    1458514640    }, [playerId, postId, context, refreshRevision]);
    1458614641    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;
    1458814692      const prevent = (e) => {
    1458914693        e.preventDefault();
    … …  
    1460914713        }
    1461014714      };
    14611     }, [busy]);
     14715    }, [saving]);
    1461214716    async function run(job) {
    1461314717      if (pending.current) return;
    … …  
    1462914733      setPlaying("");
    1463014734    };
     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    };
    1463114753    const choose = async (ids) => {
    1463214754      if (ids.length > 100) throw new Error("selection_limit");
     14755      const session = selectionSession.current;
     14756      if (!session?.active) return;
    1463314757      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);
    1464714765    };
     14766    const currentSelection = () => selectionSession.current?.desired ?? trackIds;
    1464814767    async function listen(id) {
    1464914768      if (playing === id) {
    … …  
    1466814787    }
    1466914788    async function upload(selected) {
    14670       if (!selected.length) return;
     14789      if (!selected.length || savingSelection) return;
    1467114790      if (selected.length + trackIds.length > 100) {
    1467214791        setError(c.selectionLimit);
    … …  
    1467514794      await run(async () => {
    1467614795        let next = [...trackIds];
     14796        let added = false;
    1467714797        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          }
    1471514841        }
    1471614842      });
    1471714843    }
    1471814844    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);
    1472014846    const songs = data?.cloud.tracks || [];
    1472114847    const shownIds = dragOrder || trackIds;
    … …  
    1473614862    };
    1473714863    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      }
    1475114870    };
    1475214871    const grip = (id) => h(
    … …  
    1487714996        "aria-label": c.removeSong + " " + (songs.find((s) => s.id === id)?.title || ""),
    1487814997        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        }
    1488015001      },
    1488115002      h(
    … …  
    1489515016    const design = data?.cloud.players.find((p) => p.id === data.settings.playerId);
    1489615017    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(
    1489815019      wp.components.Button,
    14899       { variant: primary ? "primary" : "secondary", disabled: busy, onClick: callback },
     15020      { variant: primary ? "primary" : "secondary", disabled, onClick: callback },
    1490015021      iconPath && h(
    1490115022        "svg",
    … …  
    1494715068    return h(
    1494815069      "div",
    14949       { className: "sonaar-song-panel", "aria-busy": busy },
     15070      { className: "sonaar-song-panel", "aria-busy": saving },
    1495015071      editingAudio && h(window.SonaarCloudEditor.Studio, {
    1495115072        action: "audio",
    … …  
    1502015141            onDrop: (e) => {
    1502115142              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 || []));
    1502315144            }
    1502415145          },
    … …  
    1506515186                      label: c.editAudio,
    1506615187                      showTooltip: true,
     15188                      disabled: saving,
    1506715189                      onClick: () => {
    1506815190                        audio.current?.pause();
    … …  
    1509315215              true,
    1509415216              "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 : "")
    1509615219          ),
    1509715220          h("input", {
    … …  
    1515815281              () => file.current.click(),
    1515915282              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
    1516115285            )
    1516215286          )
    … …  
    1517915303                  variant: "tertiary",
    1518015304                  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                  },
    1518615309                  "aria-pressed": trackIds.includes(s.id)
    1518715310                },
    … …  
    1519915322                    "svg",
    1520015323                    { 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" })
    1520215325                  )
    1520315326                )
    … …  
    1521315336          { className: "sonaar-picker-footer" },
    1521415337          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 : ""),
    1521515339          button(
    1521615340            c.close,
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/assets/player.js

    r3799592 r3799705  
    99    var origin;
    1010    try { origin = new URL(frame.src).origin; } catch (_error) { return function () {}; }
    11     var timer;
     11    var timer, ready = false;
    1212    function fail() {
    1313      clearTimeout(timer);
    … …  
    1515    }
    1616    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      }
    2024      requestSize();
    2125    }
    … …  
    2529    function receive(event) {
    2630      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;
    2832      if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) return;
    2933      clearTimeout(timer);
     34      ready = true;
    3035      if (options.onReady) options.onReady();
    3136      if (options.autoHeight === false) return;
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/block/block.json

    r3799603 r3799705  
    33  "apiVersion": 3,
    44  "name": "sonaar-cloud/player",
    5   "version": "1.0.1",
     5  "version": "1.0.2",
    66  "title": "Sonaar MP3 Audio Player Cloud",
    77  "category": "media",
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/includes/class-page-song.php

    r3799592 r3799705  
    8585        public static function request( $request ) {
    8686                $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                }
    87102                $cloud = Plugin::cloud( 'page-player', 'GET' );
    88103                if ( is_wp_error( $cloud ) ) { return $cloud; }
    … …  
    91106                        $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 ) );
    92107                } else {
    93                         $body = $request->get_json_params(); $action = $body['action'] ?? '';
    94108                        if ( 'assign' === $action ) {
    95109                                $token = $body['token'] ?? ''; $decoded = self::decode( $token, $id );
    … …  
    102116                                }
    103117                                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 );
    108118                        }
    109119                        $track = $body['trackId'] ?? null;
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/readme.txt

    r3799603 r3799705  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 1.0.1
     7Stable tag: 1.0.2
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    157157== Changelog ==
    158158
     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
    159166= 1.0.1 - November 12, 2026 =
    160167* 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  
    33 * Plugin Name: Sonaar MP3 Audio Player Cloud
    44 * Description: Create and embed Sonaar Cloud audio players with Gutenberg, Elementor or a shortcode.
    5  * Version: 1.0.1
     5 * Version: 1.0.2
    66 * Requires at least: 6.5
    77 * Requires PHP: 8.1
  • sonaar-mp3-audio-player-cloud/tags/1.0.2/source/page-song.ts

    r3799592 r3799705  
    11import { importSelectedTracks } from '../../../lib/audio-import';
     2import { selectionSaveQueue } from './selection-save-queue';
    23declare global {
    34  interface Window {
    … …  
    6162  const api = (method: string, body?: any) => requestApi(method, body, playerId, postId, context);
    6263  const latest = wp.element.useRef(null);
     64  const dataVersion = wp.element.useRef(0);
    6365  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(''); };
    6567  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 };
    6674  const reportError = (error: any) => {
    6775    const expired = isConnectionError(error);
    … …  
    101109  wp.element.useEffect(() => {
    102110    let alive = true;
     111    const version = dataVersion.current;
    103112    api('GET')
    104113      .then((v) => {
    105         if (alive) updateData(v);
     114        if (alive && version === dataVersion.current) updateData(v);
    106115      })
    107116      .catch((e) => {
    … …  
    113122  }, [playerId, postId, context, refreshRevision]);
    114123  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;
    116168    const prevent = (e: BeforeUnloadEvent) => {
    117169      e.preventDefault();
    … …  
    137189      }
    138190    };
    139   }, [busy]);
     191  }, [saving]);
    140192  async function run(job: () => Promise<void>) {
    141193    if (pending.current) return;
    … …  
    157209    setPlaying('');
    158210  };
    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 }> => {
    162212    if (playerId) {
    163213      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) } } };
    168219    }
    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 };
    170222    if (context === 'elementor') {
    171223      // Page assignments belong to the preview page, never to the widget's design.
    172224      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 };
    176229  };
     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;
    177244  async function listen(id: string) {
    178245    if (playing === id) {
    … …  
    197264  }
    198265  async function upload(selected: File[]) {
    199     if (!selected.length) return;
     266    if (!selected.length || savingSelection) return;
    200267    if (selected.length + trackIds.length > 100) {
    201268      setError(c.selectionLimit);
    … …  
    204271    await run(async () => {
    205272      let next = [...trackIds];
     273      let added = false;
    206274      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;
    240312        }
    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); }
    244317      }
    245318    });
    246319  }
    247320  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);
    249322  const songs: any[] = data?.cloud.tracks || [];
    250323  const shownIds: string[] = dragOrder || trackIds;
    … …  
    265338  };
    266339  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. */ }
    280343  };
    281344  const grip = (id: string) =>
    … …  
    414477        'aria-label': c.removeSong + ' ' + (songs.find((s) => s.id === id)?.title || ''),
    415478        disabled: busy,
    416         onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))),
     479        onClick: () => { void choose(currentSelection().filter((t) => t !== id)).catch(reportError); },
    417480      },
    418481      h(
    … …  
    432495  const design = data?.cloud.players.find((p: any) => p.id === data.settings.playerId);
    433496  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) =>
    435498    h(
    436499      wp.components.Button,
    437       { variant: primary ? 'primary' : 'secondary', disabled: busy, onClick: callback },
     500      { variant: primary ? 'primary' : 'secondary', disabled, onClick: callback },
    438501      iconPath &&
    439502        h(
    … …  
    494557  return h(
    495558    'div',
    496     { className: 'sonaar-song-panel', 'aria-busy': busy },
     559    { className: 'sonaar-song-panel', 'aria-busy': saving },
    497560    editingAudio && h(window.SonaarCloudEditor.Studio, {
    498561      action: 'audio', trackId: editingAudio, postId: data?.postId || postId,
    … …  
    563626            onDrop: (e: DragEvent) => {
    564627              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 || []));
    566629            },
    567630          },
    … …  
    609672                        className: 'sonaar-edit-audio', icon: 'edit',
    610673                        label: c.editAudio, showTooltip: true,
     674                        disabled: saving,
    611675                        onClick: () => { audio.current?.pause(); setPlaying(''); setEditingAudio(id); },
    612676                      }),
    … …  
    635699              'M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3',
    636700            ),
     701            h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''),
    637702          ),
    638703          h('input', {
    … …  
    698763              true,
    699764              'M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5',
     765              saving,
    700766            ),
    701767          )),
    … …  
    722788                    variant: 'tertiary',
    723789                    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                    },
    732794                    'aria-pressed': trackIds.includes(s.id),
    733795                  },
    … …  
    741803                  h('span', { className: 'sonaar-audio-check', 'aria-hidden': true },
    742804                    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' }),
    744806                    ),
    745807                  ),
    … …  
    757819          { className: 'sonaar-picker-footer' },
    758820          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 : ''),
    759822          button(
    760823            c.close,
  • sonaar-mp3-audio-player-cloud/trunk/assets/editor.js

    r3799592 r3799705  
    211211        if (!alive.current || new URL(value.url).origin !== config.origin) throw Error();
    212212        setConnectionUrl(popup ? '' : value.url); if (popup) popup.location = value.url;
    213         var started = Date.now();
     213        var started = Date.now(), checking = false;
    214214        clearInterval(connectPoll.current);
    215215        connectPoll.current = setInterval(function () {
    216216          if (Date.now() - started > 10 * 60 * 1000) { clearInterval(connectPoll.current); setBusy(false); return; }
     217          if (checking) return;
     218          checking = true;
    217219          request('status', 'GET', { postId: postId }).then(function (value) {
    218220            if (!alive.current) return;
    … …  
    222224            }
    223225            clearInterval(connectPoll.current); setConnected(true); setBusy(false); setConnectionUrl('');
    224           }).catch(function () {});
     226          }).catch(function () {}).finally(function () { checking = false; });
    225227        }, 2000);
    226228      }).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  
    155155    "sharedPlaylistHelp": "Changes here update this player everywhere it is used.",
    156156    "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…"
    158159  },
    159160  "fr": {
    … …  
    312313    "sharedPlaylistHelp": "Les modifications ici mettent à jour ce lecteur partout où il est utilisé.",
    313314    "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…"
    315317  },
    316318  "es": {
    … …  
    469471    "sharedPlaylistHelp": "Los cambios aquí actualizan este reproductor en todos los lugares donde se utiliza.",
    470472    "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…"
    472475  },
    473476  "de": {
    … …  
    626629    "sharedPlaylistHelp": "Änderungen hier aktualisieren diesen Player überall, wo er verwendet wird.",
    627630    "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…"
    629633  },
    630634  "ja": {
    … …  
    783787    "sharedPlaylistHelp": "ここでの変更は、このプレーヤーが使用されているすべての場所に反映されます。",
    784788    "dynamicPlaylistHelp": "このプレーヤーはコレクションまたは自動ソースを使用しています。「プレーヤーを編集」から音声を管理してください。",
    785     "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。"
     789    "pagePlaylistHelp": "ここでの変更は、このページに割り当てられた音声にすぐに保存されます。",
     790    "savingPlaylist": "プレイリストを保存中…"
    786791  },
    787792  "pt": {
    … …  
    940945    "sharedPlaylistHelp": "As alterações aqui atualizam este player em todos os locais onde é usado.",
    941946    "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…"
    943949  },
    944950  "ru": {
    … …  
    10971103    "sharedPlaylistHelp": "Изменения здесь обновляют этот плеер везде, где он используется.",
    10981104    "dynamicPlaylistHelp": "Этот плеер использует коллекцию или автоматический источник. Чтобы управлять аудио, выберите «Редактировать плеер».",
    1099     "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице."
     1105    "pagePlaylistHelp": "Изменения сразу сохраняются в аудиозаписях, назначенных этой странице.",
     1106    "savingPlaylist": "Сохранение плейлиста…"
    11001107  },
    11011108  "it": {
    … …  
    12541261    "sharedPlaylistHelp": "Le modifiche qui aggiornano questo lettore ovunque venga utilizzato.",
    12551262    "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…"
    12571265  },
    12581266  "nl": {
    … …  
    14111419    "sharedPlaylistHelp": "Wijzigingen hier werken deze speler overal bij waar hij wordt gebruikt.",
    14121420    "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…"
    14141423  },
    14151424  "pl": {
    … …  
    15681577    "sharedPlaylistHelp": "Zmiany w tym miejscu aktualizują ten odtwarzacz wszędzie, gdzie jest używany.",
    15691578    "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…"
    15711581  }
    15721582}
  • sonaar-mp3-audio-player-cloud/trunk/assets/page-song.css

    r3799592 r3799705  
    359359.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; }
    360360.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; }
    361364.sonaar-song-modal .is-selected .sonaar-audio-check { background:#fff; color:#6041d8; border-color:#fff; }
    362365.sonaar-song-modal .sonaar-song-result:not(.is-selected):hover .sonaar-audio-check { border-color:#6041d8; background:#eee9fc; }
    363366.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; }
    364368@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); } }
    365369.sonaar-song-panel-title {
  • sonaar-mp3-audio-player-cloud/trunk/assets/page-song.js

    r3799592 r3799705  
    1448614486  }
    1448714487
     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
    1448814534  // wordpress/sonaar-mp3-audio-player-cloud/source/page-song.ts
    1448914535  var config = window.sonaarPageSong;
    … …  
    1453214578    const api = (method, body) => requestApi(method, body, playerId, postId, context);
    1453314579    const latest = wp.element.useRef(null);
     14580    const dataVersion = wp.element.useRef(0);
    1453414581    const saveLock = wp.element.useRef("sonaar-audio-" + Math.random().toString(36).slice(2));
    1453514582    const updateData = (next) => {
     14583      dataVersion.current++;
    1453614584      latest.current = next;
    1453714585      setData(next);
    … …  
    1454014588    };
    1454114589    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 };
    1454214596    const reportError = (error2) => {
    1454314597      const expired = isConnectionError(error2);
    … …  
    1457514629    wp.element.useEffect(() => {
    1457614630      let alive = true;
     14631      const version = dataVersion.current;
    1457714632      api("GET").then((v) => {
    14578         if (alive) updateData(v);
     14633        if (alive && version === dataVersion.current) updateData(v);
    1457914634      }).catch((e) => {
    1458014635        if (alive) reportError(e);
    … …  
    1458514640    }, [playerId, postId, context, refreshRevision]);
    1458614641    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;
    1458814692      const prevent = (e) => {
    1458914693        e.preventDefault();
    … …  
    1460914713        }
    1461014714      };
    14611     }, [busy]);
     14715    }, [saving]);
    1461214716    async function run(job) {
    1461314717      if (pending.current) return;
    … …  
    1462914733      setPlaying("");
    1463014734    };
     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    };
    1463114753    const choose = async (ids) => {
    1463214754      if (ids.length > 100) throw new Error("selection_limit");
     14755      const session = selectionSession.current;
     14756      if (!session?.active) return;
    1463314757      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);
    1464714765    };
     14766    const currentSelection = () => selectionSession.current?.desired ?? trackIds;
    1464814767    async function listen(id) {
    1464914768      if (playing === id) {
    … …  
    1466814787    }
    1466914788    async function upload(selected) {
    14670       if (!selected.length) return;
     14789      if (!selected.length || savingSelection) return;
    1467114790      if (selected.length + trackIds.length > 100) {
    1467214791        setError(c.selectionLimit);
    … …  
    1467514794      await run(async () => {
    1467614795        let next = [...trackIds];
     14796        let added = false;
    1467714797        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          }
    1471514841        }
    1471614842      });
    1471714843    }
    1471814844    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);
    1472014846    const songs = data?.cloud.tracks || [];
    1472114847    const shownIds = dragOrder || trackIds;
    … …  
    1473614862    };
    1473714863    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      }
    1475114870    };
    1475214871    const grip = (id) => h(
    … …  
    1487714996        "aria-label": c.removeSong + " " + (songs.find((s) => s.id === id)?.title || ""),
    1487814997        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        }
    1488015001      },
    1488115002      h(
    … …  
    1489515016    const design = data?.cloud.players.find((p) => p.id === data.settings.playerId);
    1489615017    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(
    1489815019      wp.components.Button,
    14899       { variant: primary ? "primary" : "secondary", disabled: busy, onClick: callback },
     15020      { variant: primary ? "primary" : "secondary", disabled, onClick: callback },
    1490015021      iconPath && h(
    1490115022        "svg",
    … …  
    1494715068    return h(
    1494815069      "div",
    14949       { className: "sonaar-song-panel", "aria-busy": busy },
     15070      { className: "sonaar-song-panel", "aria-busy": saving },
    1495015071      editingAudio && h(window.SonaarCloudEditor.Studio, {
    1495115072        action: "audio",
    … …  
    1502015141            onDrop: (e) => {
    1502115142              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 || []));
    1502315144            }
    1502415145          },
    … …  
    1506515186                      label: c.editAudio,
    1506615187                      showTooltip: true,
     15188                      disabled: saving,
    1506715189                      onClick: () => {
    1506815190                        audio.current?.pause();
    … …  
    1509315215              true,
    1509415216              "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 : "")
    1509615219          ),
    1509715220          h("input", {
    … …  
    1515815281              () => file.current.click(),
    1515915282              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
    1516115285            )
    1516215286          )
    … …  
    1517915303                  variant: "tertiary",
    1518015304                  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                  },
    1518615309                  "aria-pressed": trackIds.includes(s.id)
    1518715310                },
    … …  
    1519915322                    "svg",
    1520015323                    { 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" })
    1520215325                  )
    1520315326                )
    … …  
    1521315336          { className: "sonaar-picker-footer" },
    1521415337          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 : ""),
    1521515339          button(
    1521615340            c.close,
  • sonaar-mp3-audio-player-cloud/trunk/assets/player.js

    r3799592 r3799705  
    99    var origin;
    1010    try { origin = new URL(frame.src).origin; } catch (_error) { return function () {}; }
    11     var timer;
     11    var timer, ready = false;
    1212    function fail() {
    1313      clearTimeout(timer);
    … …  
    1515    }
    1616    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      }
    2024      requestSize();
    2125    }
    … …  
    2529    function receive(event) {
    2630      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;
    2832      if (typeof data.height !== 'number' || !Number.isFinite(data.height) || data.height <= 0) return;
    2933      clearTimeout(timer);
     34      ready = true;
    3035      if (options.onReady) options.onReady();
    3136      if (options.autoHeight === false) return;
  • sonaar-mp3-audio-player-cloud/trunk/block/block.json

    r3799603 r3799705  
    33  "apiVersion": 3,
    44  "name": "sonaar-cloud/player",
    5   "version": "1.0.1",
     5  "version": "1.0.2",
    66  "title": "Sonaar MP3 Audio Player Cloud",
    77  "category": "media",
  • sonaar-mp3-audio-player-cloud/trunk/includes/class-page-song.php

    r3799592 r3799705  
    8585        public static function request( $request ) {
    8686                $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                }
    87102                $cloud = Plugin::cloud( 'page-player', 'GET' );
    88103                if ( is_wp_error( $cloud ) ) { return $cloud; }
    … …  
    91106                        $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 ) );
    92107                } else {
    93                         $body = $request->get_json_params(); $action = $body['action'] ?? '';
    94108                        if ( 'assign' === $action ) {
    95109                                $token = $body['token'] ?? ''; $decoded = self::decode( $token, $id );
    … …  
    102116                                }
    103117                                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 );
    108118                        }
    109119                        $track = $body['trackId'] ?? null;
  • sonaar-mp3-audio-player-cloud/trunk/readme.txt

    r3799603 r3799705  
    55Tested up to: 7.1
    66Requires PHP: 8.1
    7 Stable tag: 1.0.1
     7Stable tag: 1.0.2
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    157157== Changelog ==
    158158
     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
    159166= 1.0.1 - November 12, 2026 =
    160167* 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  
    33 * Plugin Name: Sonaar MP3 Audio Player Cloud
    44 * Description: Create and embed Sonaar Cloud audio players with Gutenberg, Elementor or a shortcode.
    5  * Version: 1.0.1
     5 * Version: 1.0.2
    66 * Requires at least: 6.5
    77 * Requires PHP: 8.1
  • sonaar-mp3-audio-player-cloud/trunk/source/page-song.ts

    r3799592 r3799705  
    11import { importSelectedTracks } from '../../../lib/audio-import';
     2import { selectionSaveQueue } from './selection-save-queue';
    23declare global {
    34  interface Window {
    … …  
    6162  const api = (method: string, body?: any) => requestApi(method, body, playerId, postId, context);
    6263  const latest = wp.element.useRef(null);
     64  const dataVersion = wp.element.useRef(0);
    6365  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(''); };
    6567  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 };
    6674  const reportError = (error: any) => {
    6775    const expired = isConnectionError(error);
    … …  
    101109  wp.element.useEffect(() => {
    102110    let alive = true;
     111    const version = dataVersion.current;
    103112    api('GET')
    104113      .then((v) => {
    105         if (alive) updateData(v);
     114        if (alive && version === dataVersion.current) updateData(v);
    106115      })
    107116      .catch((e) => {
    … …  
    113122  }, [playerId, postId, context, refreshRevision]);
    114123  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;
    116168    const prevent = (e: BeforeUnloadEvent) => {
    117169      e.preventDefault();
    … …  
    137189      }
    138190    };
    139   }, [busy]);
     191  }, [saving]);
    140192  async function run(job: () => Promise<void>) {
    141193    if (pending.current) return;
    … …  
    157209    setPlaying('');
    158210  };
    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 }> => {
    162212    if (playerId) {
    163213      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) } } };
    168219    }
    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 };
    170222    if (context === 'elementor') {
    171223      // Page assignments belong to the preview page, never to the widget's design.
    172224      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 };
    176229  };
     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;
    177244  async function listen(id: string) {
    178245    if (playing === id) {
    … …  
    197264  }
    198265  async function upload(selected: File[]) {
    199     if (!selected.length) return;
     266    if (!selected.length || savingSelection) return;
    200267    if (selected.length + trackIds.length > 100) {
    201268      setError(c.selectionLimit);
    … …  
    204271    await run(async () => {
    205272      let next = [...trackIds];
     273      let added = false;
    206274      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;
    240312        }
    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); }
    244317      }
    245318    });
    246319  }
    247320  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);
    249322  const songs: any[] = data?.cloud.tracks || [];
    250323  const shownIds: string[] = dragOrder || trackIds;
    … …  
    265338  };
    266339  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. */ }
    280343  };
    281344  const grip = (id: string) =>
    … …  
    414477        'aria-label': c.removeSong + ' ' + (songs.find((s) => s.id === id)?.title || ''),
    415478        disabled: busy,
    416         onClick: () => void run(() => choose(trackIds.filter((t) => t !== id))),
     479        onClick: () => { void choose(currentSelection().filter((t) => t !== id)).catch(reportError); },
    417480      },
    418481      h(
    … …  
    432495  const design = data?.cloud.players.find((p: any) => p.id === data.settings.playerId);
    433496  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) =>
    435498    h(
    436499      wp.components.Button,
    437       { variant: primary ? 'primary' : 'secondary', disabled: busy, onClick: callback },
     500      { variant: primary ? 'primary' : 'secondary', disabled, onClick: callback },
    438501      iconPath &&
    439502        h(
    … …  
    494557  return h(
    495558    'div',
    496     { className: 'sonaar-song-panel', 'aria-busy': busy },
     559    { className: 'sonaar-song-panel', 'aria-busy': saving },
    497560    editingAudio && h(window.SonaarCloudEditor.Studio, {
    498561      action: 'audio', trackId: editingAudio, postId: data?.postId || postId,
    … …  
    563626            onDrop: (e: DragEvent) => {
    564627              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 || []));
    566629            },
    567630          },
    … …  
    609672                        className: 'sonaar-edit-audio', icon: 'edit',
    610673                        label: c.editAudio, showTooltip: true,
     674                        disabled: saving,
    611675                        onClick: () => { audio.current?.pause(); setPlaying(''); setEditingAudio(id); },
    612676                      }),
    … …  
    635699              'M4 6h10M4 11h10M4 16h5M18 16V3l4 2M18 16a3 3 0 1 1-3-3h3',
    636700            ),
     701            h('span', { className: 'sonaar-selection-saving', role: 'status', 'aria-live': 'polite' }, savingSelection ? c.savingPlaylist : ''),
    637702          ),
    638703          h('input', {
    … …  
    698763              true,
    699764              'M12 16V3m-5 5 5-5 5 5M4 16v5h16v-5',
     765              saving,
    700766            ),
    701767          )),
    … …  
    722788                    variant: 'tertiary',
    723789                    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                    },
    732794                    'aria-pressed': trackIds.includes(s.id),
    733795                  },
    … …  
    741803                  h('span', { className: 'sonaar-audio-check', 'aria-hidden': true },
    742804                    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' }),
    744806                    ),
    745807                  ),
    … …  
    757819          { className: 'sonaar-picker-footer' },
    758820          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 : ''),
    759822          button(
    760823            c.close,
Note: See TracChangeset for help on using the changeset viewer.