diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a002f8f..4ca097e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,8 +38,7 @@ jobs: - name: Linux system libraries if: runner.os == 'Linux' run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libasound2-dev libdbus-1-dev \ + sudo apt-get update && sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libasound2-dev libdbus-1-dev \ libssl-dev libayatana-appindicator3-dev librsvg2-dev libsoup-3.0-dev ffmpeg - name: ffmpeg (test fixtures) @@ -86,7 +85,16 @@ jobs: npx playwright install --with-deps chromium - name: Test working-directory: ui-tests + env: + PM_SCREENSHOTS: ${{ runner.temp }}/pm-screenshots run: npm test + - name: Upload UI screenshots + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ui-screenshots + path: ${{ runner.temp }}/pm-screenshots + if-no-files-found: ignore bundle: name: Bundle (${{ matrix.name }}) @@ -105,8 +113,7 @@ jobs: - name: Linux system libraries if: runner.os == 'Linux' run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libasound2-dev libdbus-1-dev \ + sudo apt-get update && sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev libasound2-dev libdbus-1-dev \ libssl-dev libayatana-appindicator3-dev librsvg2-dev libsoup-3.0-dev - name: macOS targets diff --git a/ui-tests/mini-gesture-policy.test.js b/ui-tests/mini-gesture-policy.test.js new file mode 100644 index 0000000..9af1355 --- /dev/null +++ b/ui-tests/mini-gesture-policy.test.js @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { gestureAction, isMiniGestureTarget } from "../ui/js/mobile/mini-gesture-policy.js"; + +test("an upward cover gesture opens the full player", () => { + assert.equal(gestureAction({ x: 3, y: -70 }, { x: 3, y: -70 }), "open"); + const cover = { classList: { contains: name => name === "cover-button" } }; + const target = { closest: () => cover }; + assert.equal(isMiniGestureTarget(target), true); +}); + +test("horizontal swipes keep their transport meaning", () => { + assert.equal(gestureAction({ x: -90, y: 2 }, { x: -90, y: 2 }), "next"); + assert.equal(gestureAction({ x: 90, y: 2 }, { x: 90, y: 2 }), "previous"); +}); + +test("play, next and links do not become gesture starters", () => { + const button = { classList: { contains: () => false } }; + const target = { closest: () => button }; + assert.equal(isMiniGestureTarget(target), false); +}); + +test("short and downward movements have no action and need no click suppression", () => { + assert.equal(gestureAction({ x: 5, y: 10 }, { x: 5, y: 10 }), null); + assert.equal(gestureAction({ x: 2, y: 70 }, { x: 2, y: 70 }), null); +}); diff --git a/ui-tests/mix-playback.test.js b/ui-tests/mix-playback.test.js new file mode 100644 index 0000000..12b38f0 --- /dev/null +++ b/ui-tests/mix-playback.test.js @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { loadMixTracks, mixOptionsRejected } from "../ui/js/mix-playback.js"; + +const mix = { id: "artist-mix", options: '{"curator":"anya"}' }; + +test("a rejected tuned mix retries untuned and continues with the working options", async () => { + const calls = []; + const tracks = [{ track_id: 1 }]; + const result = await loadMixTracks(mix, async (id, options) => { + calls.push({ id, options }); + if (options) throw { kind: "vk", message: "VK error 8: bad request" }; + return tracks; + }); + assert.deepEqual(result, { tracks, options: null }); + assert.deepEqual(calls, [ + { id: "artist-mix", options: mix.options }, + { id: "artist-mix", options: null }, + ]); +}); + +test("an empty tuned response also falls back to the plain mix", async () => { + const tracks = [{ track_id: 2 }]; + const result = await loadMixTracks(mix, async (_id, options) => options ? [] : tracks); + assert.deepEqual(result, { tracks, options: null }); +}); + +test("network and service failures are not hidden by a second request", async () => { + const failure = { kind: "offline", message: "No internet connection." }; + let calls = 0; + await assert.rejects(loadMixTracks(mix, async () => { calls += 1; throw failure; }), error => error === failure); + assert.equal(calls, 1); + assert.equal(mixOptionsRejected(failure), false); +}); + +test("an accepted tuned mix keeps its options for radio continuation", async () => { + const tracks = [{ track_id: 3 }]; + const result = await loadMixTracks(mix, async () => tracks); + assert.deepEqual(result, { tracks, options: mix.options }); +}); diff --git a/ui-tests/mix-shelf-regressions.test.js b/ui-tests/mix-shelf-regressions.test.js new file mode 100644 index 0000000..00a2db7 --- /dev/null +++ b/ui-tests/mix-shelf-regressions.test.js @@ -0,0 +1,25 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { openApp } from "./harness.js"; + +test("a catalog mix rejected by VK starts untuned and keeps that continuation", async () => { + const app = await openApp({ config: { signedIn: true, platform: "android", catalogMixes: true }, phone: "small" }); + try { + const { page } = app; + await page.locator(".mix-tile").nth(1).waitFor(); + await page.evaluate(() => { + const invoke = window.__TAURI__.core.invoke; + window.__TAURI__.core.invoke = (command, args) => { + if (command === "stream_mix" && args.options) throw { kind: "vk", message: "VK error 8: bad request" }; + return invoke(command, args); + }; + }); + await page.locator(".mix-tile").nth(1).click(); + await page.waitForFunction(() => window.__mock.calls.some(call => call.command === "play_radio")); + const calls = await page.evaluate(() => window.__mock.calls.filter(call => call.command === "stream_mix").map(call => call.args.options)); + assert.deepEqual(calls, ['{"mood":["calm"]}', null]); + assert.equal(await page.evaluate(() => window.__mock.last("play_radio").args.source.options), null); + if (process.env.PM_SCREENSHOTS) await page.screenshot({ path: `${process.env.PM_SCREENSHOTS}/mix-untuned-playing.png` }); + assert.deepEqual(app.problems, []); + } finally { await app.close(); } +}); diff --git a/ui-tests/package.json b/ui-tests/package.json index 572be16..bd67b8a 100644 --- a/ui-tests/package.json +++ b/ui-tests/package.json @@ -3,7 +3,7 @@ "private": true, "type": "module", "scripts": { - "test": "node --test --test-concurrency=1 catalogue-gate.test.js polish.test.js ui.test.js network.test.js features.test.js phone.test.js parity.test.js share-links.test.js radio-snapshot.test.js saved-lyrics.test.js download-details.test.js player-regressions.test.js lyrics-copy.test.js performance.test.js ios-phone-parity.test.js audio-export-lyrics.test.js screen-audit.test.js updates.test.js artwork.test.js interface-regressions.test.js html-entities.test.js track-filter.test.js state-regressions.test.js security-regressions.test.js local-audio.test.js local-audio-actions.test.js queue-transport.test.js" + "test": "node --test --test-concurrency=1 catalogue-gate.test.js polish.test.js ui.test.js network.test.js features.test.js phone.test.js parity.test.js share-links.test.js radio-snapshot.test.js saved-lyrics.test.js download-details.test.js player-regressions.test.js lyrics-copy.test.js performance.test.js ios-phone-parity.test.js audio-export-lyrics.test.js screen-audit.test.js updates.test.js artwork.test.js interface-regressions.test.js html-entities.test.js track-filter.test.js state-regressions.test.js security-regressions.test.js local-audio.test.js local-audio-actions.test.js queue-transport.test.js seek-gate.test.js mix-playback.test.js mini-gesture-policy.test.js player-seek-regressions.test.js mix-shelf-regressions.test.js" }, "devDependencies": { "playwright": "1.64.1" diff --git a/ui-tests/player-seek-regressions.test.js b/ui-tests/player-seek-regressions.test.js new file mode 100644 index 0000000..a2aa50a --- /dev/null +++ b/ui-tests/player-seek-regressions.test.js @@ -0,0 +1,87 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { openApp } from "./harness.js"; + +const config = { signedIn: true, platform: "android", catalogMixes: true }; + +async function startTrack(page) { + await page.locator(".stage-cta").click(); + await page.locator(".player:not(.is-empty)").waitFor(); +} + +test("the scrubber does not flash the pre-seek position while the command is pending", async () => { + const app = await openApp({ config, phone: "small" }); + try { + const { page } = app; + await startTrack(page); + await page.locator(".player .now").click(); + const lane = page.locator(".np .np-seek input"); + await lane.waitFor(); + await page.waitForTimeout(400); + await page.evaluate(() => { + const invoke = window.__TAURI__.core.invoke; + window.__TAURI__.core.invoke = (command, args) => { + if (command === "seek") return new Promise(resolve => { + window.__finishSeek = () => { + window.__mock.state.player.position = args.seconds; + window.__mock.emitState(); + resolve(); + }; + }); + return invoke(command, args); + }; + }); + const box = await lane.boundingBox(); + const max = Number(await lane.getAttribute("max")); + await page.touchscreen.tap(box.x + box.width * 0.75, box.y + box.height / 2); + await page.waitForFunction(() => !!window.__finishSeek); + await page.evaluate(() => { + window.__mock.state.player.position = 0; + window.__mock.emitState(); + }); + assert.ok(Math.abs(Number(await lane.inputValue()) - max * 0.75) <= max * 0.03); + await page.evaluate(() => window.__finishSeek()); + await page.waitForFunction(() => Math.abs(window.__mock.state.player.position - window.__mock.last("seek").args.seconds) < 0.01); + if (process.env.PM_SCREENSHOTS) await page.screenshot({ path: `${process.env.PM_SCREENSHOTS}/phone-seek-confirmed.png` }); + assert.deepEqual(app.problems, []); + } finally { await app.close(); } +}); + +test("the compact player timeline keeps advancing while its slider has focus", async () => { + const app = await openApp({ config }); + try { + const { page } = app; + await page.locator(".main .row").first().dblclick(); + const slider = page.locator(".mini-player input[type=range]"); + await slider.focus(); + await page.evaluate(() => { + window.__mock.state.player.duration = 300; + window.__mock.state.player.position = 42; + window.__mock.emitState(); + }); + assert.equal(Number(await slider.inputValue()), 42); + assert.equal(await page.locator(".mini-time").textContent(), "0:42"); + assert.deepEqual(app.problems, []); + } finally { await app.close(); } +}); + +test("an upward swipe that starts on the mini player cover opens Now Playing", async () => { + const app = await openApp({ config, phone: "small" }); + try { + const { page } = app; + await startTrack(page); + const box = await page.locator(".player .cover-button").boundingBox(); + const x = box.x + box.width / 2; + const y = box.y + box.height / 2; + const cdp = await page.context().newCDPSession(page); + try { + await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y, id: 1 }] }); + for (let i = 1; i <= 5; i += 1) { + await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x, y: y - i * 16, id: 1 }] }); + } + await cdp.send("Input.dispatchTouchEvent", { type: "touchEnd", touchPoints: [] }); + } finally { await cdp.detach(); } + await page.locator(".np:not([hidden])").waitFor(); + assert.deepEqual(app.problems, []); + } finally { await app.close(); } +}); diff --git a/ui-tests/seek-gate.test.js b/ui-tests/seek-gate.test.js new file mode 100644 index 0000000..672c16d --- /dev/null +++ b/ui-tests/seek-gate.test.js @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createSeekGate } from "../ui/js/seek-gate.js"; + +test("an old state packet cannot replace the requested position", async () => { + const gate = createSeekGate(() => {}); + gate.preview(); + assert.equal(gate.shouldRender(10), false); + await gate.commit(90, async () => {}); + assert.equal(gate.shouldRender(10), false); + assert.equal(gate.shouldRender(90), true); + assert.equal(gate.shouldRender(91), true); +}); + +test("an invoke acknowledgement alone does not release the scrubber", async () => { + const gate = createSeekGate(() => {}); + await gate.commit(75, async () => {}); + assert.equal(gate.shouldRender(4), false); +}); + +test("a failed or unanswered seek returns to the real position after the timeout", async () => { + let notified = 0; + const gate = createSeekGate(() => { notified += 1; }, { timeout: 5 }); + await gate.commit(80, async () => { throw new Error("seek failed"); }).catch(() => {}); + assert.equal(gate.shouldRender(8), false); + await new Promise(resolve => setTimeout(resolve, 15)); + assert.equal(gate.shouldRender(8), true); + assert.ok(notified >= 1); +}); + +test("an older request cannot clear a newer gesture", async () => { + const gate = createSeekGate(() => {}); + let finish; + const first = gate.commit(30, () => new Promise(resolve => { finish = resolve; })); + gate.preview(); + finish(); + await first; + assert.equal(gate.shouldRender(12), false); +}); + +test("changing tracks cancels the pending position", async () => { + const gate = createSeekGate(() => {}); + await gate.commit(80, async () => {}); + gate.track("7_2"); + assert.equal(gate.shouldRender(0), true); +}); diff --git a/ui/js/mini-player.js b/ui/js/mini-player.js index 15acfdb..898ce7b 100644 --- a/ui/js/mini-player.js +++ b/ui/js/mini-player.js @@ -8,6 +8,7 @@ import { artBox } from "./ui-parts.js"; import { setWindowMode } from "./window-mode.js"; import { toast } from "./toast.js"; import { errorText } from "./i18n.js"; +import { createSeekGate } from "./seek-gate.js"; export function createMiniPlayer(onLike) { const safe = (fn) => () => Promise.resolve() @@ -32,6 +33,7 @@ export function createMiniPlayer(onLike) { const previous = button(ft("Предыдущий"), "prev", () => api.previous()); const next = button(ft("Следующий"), "next", () => api.next()); const like = button(ft("Избранное"), "heart", () => onLike(store.player.track)); + const seekGate = createSeekGate(() => render()); const seek = h("input", { type: "range", min: 0, @@ -39,7 +41,11 @@ export function createMiniPlayer(onLike) { step: 0.1, value: 0, "aria-label": ft("Позиция воспроизведения"), - onchange: (event) => safe(() => api.seek(Number(event.target.value)))(), + oninput: () => { seekGate.preview(); time.textContent = formatTime(Number(seek.value)); }, + onchange: (event) => { + const value = Number(event.target.value); + safe(() => seekGate.commit(value, () => api.seek(value)))(); + }, }); const time = h("span", { class: "mini-time" }); const element = h( @@ -68,6 +74,7 @@ export function createMiniPlayer(onLike) { function render() { const p = store.player; const key = p.track ? `${p.track.owner_id}_${p.track.track_id}` : null; + seekGate.track(key); if (key !== previousKey) { previousKey = key; art.replaceChildren(artBox(p.track?.artwork_url)); @@ -91,9 +98,13 @@ export function createMiniPlayer(onLike) { like.setAttribute("aria-pressed", String(liked)); like.hidden = isLocalTrack(p.track); like.disabled = !p.track || isLocalTrack(p.track); - seek.max = String(p.duration || 1); - if (document.activeElement !== seek) seek.value = String(p.position || 0); - time.textContent = formatTime(p.position); + const duration = Math.max(0, p.duration || 0); + const position = Math.min(Math.max(0, p.position || 0), duration); + seek.max = String(duration || 1); + if (seekGate.shouldRender(p.position)) { + seek.value = String(position); + time.textContent = formatTime(position); + } } subscribe("player", render); subscribe("likes", render); diff --git a/ui/js/mix-playback.js b/ui/js/mix-playback.js new file mode 100644 index 0000000..8ec21cc --- /dev/null +++ b/ui/js/mix-playback.js @@ -0,0 +1,23 @@ +// VK rejects some undocumented mix_options shapes with error 8. Match the iOS +// client: retry the tile untuned and use the working options for continuation. +export function mixOptionsRejected(error) { + const message = String(error?.message ?? error ?? ""); + return error?.kind === "invalid" || (error?.kind === "vk" && /error\s+8|bad request/i.test(message)); +} + +export async function loadMixTracks(mix, stream) { + let options = mix.options ?? null; + let tracks; + try { + tracks = await stream(mix.id, options); + } catch (error) { + if (!options || !mixOptionsRejected(error)) throw error; + tracks = await stream(mix.id, null); + options = null; + } + if (!tracks.length && options) { + tracks = await stream(mix.id, null); + options = null; + } + return { tracks, options }; +} diff --git a/ui/js/mobile/mini-gesture-policy.js b/ui/js/mobile/mini-gesture-policy.js new file mode 100644 index 0000000..226b7a8 --- /dev/null +++ b/ui/js/mobile/mini-gesture-policy.js @@ -0,0 +1,26 @@ +const MIN_DISTANCE = 18; +const HORIZONTAL = 58; +const VERTICAL = 42; +const DOMINANCE = 1.2; + +/** The iOS policy: "next" | "previous" | "open" | null for a drag. */ +export function gestureAction(translation, predicted) { + const settled = Math.hypot(translation.x, translation.y); + const heading = Math.hypot(predicted.x, predicted.y); + const t = heading > settled ? predicted : translation; + const horizontal = Math.abs(t.x); + const vertical = Math.abs(t.y); + if (Math.max(horizontal, vertical) < MIN_DISTANCE) return null; + if (vertical >= horizontal * DOMINANCE) return t.y <= -VERTICAL ? "open" : null; + if (horizontal >= vertical * DOMINANCE) { + if (t.x <= -HORIZONTAL) return "next"; + if (t.x >= HORIZONTAL) return "previous"; + } + return null; +} + +/** Cover swipes are allowed; transport and other native controls keep their taps. */ +export function isMiniGestureTarget(target) { + const control = target?.closest?.("button, input, a, [role=button]"); + return !control || control.classList.contains("cover-button"); +} diff --git a/ui/js/mobile/mini-gestures.js b/ui/js/mobile/mini-gestures.js index b37e3ef..7067458 100644 --- a/ui/js/mobile/mini-gestures.js +++ b/ui/js/mobile/mini-gestures.js @@ -6,31 +6,14 @@ import { motionOk } from "../motion.js"; import { haptic, isPhone } from "./layout.js"; +import { gestureAction, isMiniGestureTarget } from "./mini-gesture-policy.js"; + +export { gestureAction } from "./mini-gesture-policy.js"; -const MIN_DISTANCE = 18; -const HORIZONTAL = 58; -const VERTICAL = 42; -const DOMINANCE = 1.2; const PARALLAX_X = 0.12; const PARALLAX_Y = 0.08; const PREDICT_MS = 160; -/** The iOS policy: "next" | "previous" | "open" | null for a drag. */ -export function gestureAction(translation, predicted) { - const settled = Math.hypot(translation.x, translation.y); - const heading = Math.hypot(predicted.x, predicted.y); - const t = heading > settled ? predicted : translation; - const horizontal = Math.abs(t.x); - const vertical = Math.abs(t.y); - if (Math.max(horizontal, vertical) < MIN_DISTANCE) return null; - if (vertical >= horizontal * DOMINANCE) return t.y <= -VERTICAL ? "open" : null; - if (horizontal >= vertical * DOMINANCE) { - if (t.x <= -HORIZONTAL) return "next"; - if (t.x >= HORIZONTAL) return "previous"; - } - return null; -} - export function attachMiniGestures(element, { onNext, onPrevious, onOpen }) { let drag = null; let suppressClick = false; @@ -38,9 +21,9 @@ export function attachMiniGestures(element, { onNext, onPrevious, onOpen }) { element.addEventListener("pointerdown", (event) => { if (!isPhone() || (event.pointerType === "mouse" && event.button !== 0)) return; suppressClick = false; - // A finger can move slightly while pressing Pause/Next. Capturing that - // pointer on the card would retarget the button's click to its parent. - if (event.target.closest?.("button, input, a, [role=button]")) return; + // Transport buttons keep their taps. The cover also accepts swipes: it is + // the largest natural place to start the upward gesture on a phone. + if (!isMiniGestureTarget(event.target)) return; drag = { id: event.pointerId, x: event.clientX, y: event.clientY, samples: [{ x: event.clientX, y: event.clientY, t: performance.now() }], moved: false }; }); element.addEventListener("pointermove", (event) => { @@ -75,9 +58,10 @@ export function attachMiniGestures(element, { onNext, onPrevious, onOpen }) { x: translation.x + ((last.x - first.x) / span) * PREDICT_MS, y: translation.y + ((last.y - first.y) / span) * PREDICT_MS, }; - suppressClick = true; const action = gestureAction(translation, predicted); + // A small unrecognised movement must not eat the next genuine tap. if (!action) return; + suppressClick = true; haptic(8); if (action === "next") onNext(); else if (action === "previous") onPrevious(); @@ -85,7 +69,7 @@ export function attachMiniGestures(element, { onNext, onPrevious, onOpen }) { } element.addEventListener("pointerup", (event) => finish(event, false)); element.addEventListener("pointercancel", (event) => finish(event, true)); - // A swipe is not a tap. + // A recognised swipe is not a tap. element.addEventListener("click", (event) => { if (suppressClick && event.detail > 0) { suppressClick = false; diff --git a/ui/js/now-playing.js b/ui/js/now-playing.js index 1cd84f0..a489bf9 100644 --- a/ui/js/now-playing.js +++ b/ui/js/now-playing.js @@ -17,6 +17,7 @@ import { artBox, bindRange, syncRange } from "./ui-parts.js"; import { isPhone, isAndroid, onLayoutChange } from "./mobile/layout.js"; import {attachArtworkGestures} from "./mobile/artwork-gestures.js"; import { attachSheetDrag } from "./mobile/np-sheet.js"; +import { createSeekGate } from "./seek-gate.js"; const IDLE_MS = 3000; const QUEUE_ROWS = 100; @@ -48,7 +49,7 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) let returnFocus = null; let queueOpen = false; let userChoseMode = MODES.includes(settings.visualizer); - let dragging = false; + const seekGate = createSeekGate(() => render(store.player)); // A track without a cover: a note glyph the styles may show (the default design does; the classic look keeps // the cover area empty and centres the title instead). const placeholderArt = () => h("div", { class: "np-placeholder", "aria-hidden": "true" }, icon("note", 72)); @@ -112,9 +113,9 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) const total = h("span", { text: remaining(0) }); const seek = h("input", { type: "range", min: "0", max: "0", step: "1", value: "0", "aria-label": t("seek"), - oninput: () => { dragging = true; elapsed.textContent = formatTime(Number(seek.value)); total.textContent = remaining(Number(seek.max) - Number(seek.value)); }, + oninput: () => { seekGate.preview(); elapsed.textContent = formatTime(Number(seek.value)); total.textContent = remaining(Number(seek.max) - Number(seek.value)); }, // Keyboard and mouse changes; touch commits its own seek (below) and must not seek twice. - onchange: () => { if (seekTouch !== null || performance.now() - seekTouchEnded < 600) return; playbackAction(() => api.seek(Number(seek.value))); dragging = false; lyrics.snap(Number(seek.value)); }, + onchange: () => { if (seekTouch !== null || performance.now() - seekTouchEnded < 600) return; const value = Number(seek.value); lyrics.snap(value); seekGate.commit(value, () => playbackAction(() => api.seek(value))); }, }); bindRange(seek); // Touch seeking is handled here rather than by the native range: on Android System WebViews a tap or a drag @@ -138,8 +139,8 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) seek.addEventListener("pointerdown", (event) => { if (event.pointerType === "mouse" || seek.disabled) return; event.preventDefault(); + seekGate.preview(); seekTouch = event.pointerId; - dragging = true; try { seek.setPointerCapture(event.pointerId); } catch { /* the pointer may already be gone */ } showSeek(seekValueAt(event.clientX)); }); @@ -152,12 +153,15 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) if (event.pointerId !== seekTouch) return; seekTouch = null; seekTouchEnded = performance.now(); - dragging = false; - if (!commit) return; + if (!commit) { + seekGate.cancel(); + render(store.player); + return; + } const value = seekValueAt(event.clientX); showSeek(value); - playbackAction(() => api.seek(value)); lyrics.snap(value); + seekGate.commit(value, () => playbackAction(() => api.seek(value))); }; seek.addEventListener("pointerup", (event) => endSeekTouch(event, true)); seek.addEventListener("pointercancel", (event) => endSeekTouch(event, false)); @@ -407,6 +411,8 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) function render(player) { renderVolume(player); const track = player.track; + const currentSeekKey = track ? `${track.owner_id}_${track.track_id}` : null; + seekGate.track(currentSeekKey); const titleText = track ? track.title : t("nothing"); if (title.textContent !== titleText) { title.textContent = titleText; title.title = titleText; } const artistText = track ? track.artist : ""; @@ -449,11 +455,12 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) quickMore.disabled = !track; const duration = Math.max(0, player.duration || 0); + const position = Math.min(Math.max(0, player.position || 0), duration); seek.max = String(Math.max(duration, 1)); - if (!dragging) { - seek.value = String(Math.min(player.position || 0, duration || 0)); - elapsed.textContent = formatTime(player.position || 0); - total.textContent = remaining(duration - (player.position || 0)); + if (seekGate.shouldRender(player.position)) { + seek.value = String(position); + elapsed.textContent = formatTime(position); + total.textContent = remaining(duration - position); } syncRange(seek); seek.disabled = !track; @@ -576,6 +583,8 @@ export function createNowPlaying({ settings, onSettingsChange, onLike, onMenu }) function close() { if (!open) return; open = false; + seekGate.cancel(); + seekTouch = null; clearTimeout(idleTimer); element.classList.remove("idle"); visualizer.stop(); diff --git a/ui/js/player-bar.js b/ui/js/player-bar.js index 3d47bee..eff74ee 100644 --- a/ui/js/player-bar.js +++ b/ui/js/player-bar.js @@ -11,10 +11,11 @@ import { artBox, bindRange, syncRange, swapArt } from "./ui-parts.js"; import { coverPalette } from "./palette.js"; import { isPhone } from "./mobile/layout.js"; import { attachMiniGestures } from "./mobile/mini-gestures.js"; +import { createSeekGate } from "./seek-gate.js"; /** Нижняя панель: что играет, транспорт, позиция и громкость. */ export function createPlayerBar({ onSettingsChange, onExpand, onLike }) { - let dragging = false; + const seekGate = createSeekGate(() => render(store.player)); let lastVolume = 1; const coverSlot = h("span", { class: "cover-slot" }, artBox(null, { size: 22 })); @@ -37,8 +38,8 @@ export function createPlayerBar({ onSettingsChange, onExpand, onLike }) { const total = h("span", { text: remaining(0) }); const seek = h("input", { class: "reveal", type: "range", min: "0", max: "0", step: "1", value: "0", "aria-label": t("seek"), - oninput: () => { dragging = true; elapsed.textContent = formatTime(Number(seek.value)); total.textContent = remaining(Number(seek.max) - Number(seek.value)); }, - onchange: () => { playbackAction(() => api.seek(Number(seek.value))); dragging = false; }, + oninput: () => { seekGate.preview(); elapsed.textContent = formatTime(Number(seek.value)); total.textContent = remaining(Number(seek.max) - Number(seek.value)); }, + onchange: () => seekGate.commit(Number(seek.value), () => playbackAction(() => api.seek(Number(seek.value)))), }); bindRange(seek); const buffering = h("div", { class: "buffering", hidden: true, role: "status", text: t("buffering") }); @@ -123,6 +124,8 @@ export function createPlayerBar({ onSettingsChange, onExpand, onLike }) { function render(player) { const track = player.track; + const currentSeekKey = track ? `${track.owner_id}_${track.track_id}` : null; + seekGate.track(currentSeekKey); const titleText=track ? track.title : t("nothing"); if(title.textContent!==titleText) title.textContent=titleText; const artistText=track ? track.artist : ""; @@ -164,11 +167,12 @@ export function createPlayerBar({ onSettingsChange, onExpand, onLike }) { } const duration = Math.max(0, player.duration || 0); + const position = Math.min(Math.max(0, player.position || 0), duration); seek.max = String(Math.max(duration, 1)); - if (!dragging) { - seek.value = String(Math.min(player.position || 0, duration || 0)); - elapsed.textContent = formatTime(player.position || 0); - total.textContent = remaining(duration - (player.position || 0)); + if (seekGate.shouldRender(player.position)) { + seek.value = String(position); + elapsed.textContent = formatTime(position); + total.textContent = remaining(duration - position); } syncRange(seek); seek.disabled = !track; diff --git a/ui/js/seek-gate.js b/ui/js/seek-gate.js new file mode 100644 index 0000000..68e2016 --- /dev/null +++ b/ui/js/seek-gate.js @@ -0,0 +1,70 @@ +// Keeps the user's scrubber value until the engine confirms it. A resolved invoke +// alone is not confirmation: its state event can still arrive after older packets. +export function createSeekGate(notify, { tolerance = 1.1, timeout = 1200 } = {}) { + let generation = 0; + let trackKey = null; + let pending = null; + let dragging = false; + let timer = null; + + function clearTimer() { + if (timer !== null) clearTimeout(timer); + timer = null; + } + + function settle() { + generation += 1; + clearTimer(); + pending = null; + dragging = false; + notify(); + } + + function cancel() { + generation += 1; + clearTimer(); + pending = null; + dragging = false; + } + + return { + preview() { + generation += 1; + clearTimer(); + pending = null; + dragging = true; + }, + track(key) { + if (key === trackKey) return; + trackKey = key; + cancel(); + }, + cancel, + async commit(value, run) { + const mine = ++generation; + clearTimer(); + pending = { value, at: performance.now() }; + dragging = true; + try { return await run(); } + finally { + if (mine === generation) { + pending.at = performance.now(); + timer = setTimeout(settle, timeout); + notify(); + } + } + }, + shouldRender(position, now = performance.now()) { + if (!pending) return !dragging; + if (Math.abs(Math.max(0, position || 0) - pending.value) <= tolerance) { + settle(); + return true; + } + if (now - pending.at >= timeout) { + settle(); + return true; + } + return false; + }, + }; +} diff --git a/ui/js/shelves.js b/ui/js/shelves.js index ad284fb..201bb46 100644 --- a/ui/js/shelves.js +++ b/ui/js/shelves.js @@ -10,6 +10,7 @@ import { openAlbum } from "./navigation.js"; import { errorText, t } from "./i18n.js"; import { icon } from "./icons.js"; import { mixName, mixColors, mixKey } from "./selena.js"; +import { loadMixTracks } from "./mix-playback.js"; import { paintStatus } from "./ui-parts.js"; /** Устойчивое семейство цветов для каждого микса, чтобы карточка выглядела одинаково между визитами. */ @@ -43,11 +44,11 @@ export function createMixShelf({ play, toast, heading = t("fy.catalog") }) { button.disabled = true; paintStatus(status, t("fy.mixLoading", { title: mix.title }), { extra: "inline" }); try { - const tracks = await api.streamMix(mix.id, mix.options); + const { tracks, options } = await loadMixTracks(mix, (id, mixOptions) => api.streamMix(id, mixOptions)); if (!tracks.length) throw new Error(t("fy.noCatalog")); // Обычный личный поток — то же радио, что и вкладка «Мой микс». - const personal = mix.id === "common" && !mix.options; - play(tracks, 0, { shuffle: false, radio: personal ? { kind: "personal", options: null } : { kind: "catalog", mix_id: mix.id, options: mix.options ?? null } }); + const personal = mix.id === "common" && !options; + await play(tracks, 0, { shuffle: false, radio: personal ? { kind: "personal", options: null } : { kind: "catalog", mix_id: mix.id, options } }); paintStatus(status, ""); } catch (error) { paintStatus(status, errorText(error), { error: true, extra: "inline" });