From 3aacb94048ae8a3eaf3e065a0aba3d737fdeaeff Mon Sep 17 00:00:00 2001 From: Elijah Kuntz Date: Mon, 2 Nov 2026 15:24:31 -0700 Subject: [PATCH 01/34] Publish the 0.1.0-beta.8 update feed Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index fd4a929..f15dea3 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,11 +1,11 @@ { + "version": "0.1.0-beta.8", + "notes": "Kaleido for Mac.\n\n- Kaleido now runs on Macs with Apple silicon (macOS 26 or later), with the same interface and features as on Windows: browsing, playback with hardware decoding, the miniplayer, downloads, server management and in-app updates. The window uses the Mac's own close, minimize and zoom buttons, which fade with the player's controls, and shortcuts use ⌘ (⌘K to search, ⌘[ to go back, ⌃⌘F for full screen).\n- HDR passthrough works on Mac too: HDR titles play in the display's extended dynamic range instead of being converted to SDR.\n- Each release now includes both the Windows and Mac versions.\n- Updates are signed with a new key, so the Windows version needs to be reinstalled once from this release; later updates install in the app as before.", + "pub_date": "2026-11-02T22:24:31.764Z", "platforms": { - "windows-x86_64": { - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVURlZleWFKRzhRNUVIUVdqU0NiSW1EdGx6RVhHMGFTeXp0MVFteFMzN0tndjZaNTk5a1FFLy80WWNqeDFiWU5VclNUYTZGajBLdnptQ2JWOHFETWhxeUV2c2JCSXg2YlFRPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNTAwMzQ0CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjdfeDY0LXNldHVwLmV4ZQl2ZXJzaW9uOjAuMS4wLWJldGEuNwp2c0ZpRjFVSUtIU1l3bWpqYUhzaGRFQTZ2TWIwZTFOZmRJRzBrSGNJUlEyWkNPV3pLWUJ4Y2Q5RWRHcjFTRDJuZFYvMzRGL0h1TzZEK1dER2d6ZVVEQT09Cg==", - "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.7/Kaleido_0.1.0-beta.7_x64-setup.exe" + "darwin-aarch64": { + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFE4NFdjWGFlNEZCRTExTTVVdkgrRTUvTXRmbVBsNE9ZVW11NXkwME1ZNkt1UzdGb3FzdW9oTWdLLzU3UWhyMSs3TTVjYXBoSTJnRysyVmR5SE4xVVFZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjU4MTgyCWZpbGU6S2FsZWlkby5hcHAudGFyLmd6CXZlcnNpb246MC4xLjAtYmV0YS44CmxXOHA2NDVPL3JDMWtuQmdhTGNDNHRZOHBwdjFmSGg5V3o1V2tRMUdDRFp4cVg2M1dFUXVIMmdNWm5VMHBaT2xZSDh6RFdSUkpUcjZQbEp4bk5PZUNnPT0K", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.8/Kaleido_0.1.0-beta.8_aarch64.app.tar.gz" } - }, - "version": "0.1.0-beta.7", - "notes": "A new startup animation and a bolder app icon.\r\n\r\n- New startup animation: a kaleidoscope of shards turns and gathers into the Kaleido mark, then the view flies through its centre into the app. If the server is slow to answer, small shards keep circling the mark instead of the animation freezing.\r\n- The app icon's mark is much larger, so it reads clearly on the taskbar and in the Start menu.", - "pub_date": "2026-11-01T02:32:55.644Z" + } } From a7aad594095fec93241709842ba609104467e927 Mon Sep 17 00:00:00 2001 From: Elijah Kuntz Date: Mon, 2 Nov 2026 15:34:56 -0700 Subject: [PATCH 02/34] Fix washed-out SDR video and missing download artwork on macOS The video layer's float framebuffer had no colour space, so macOS read gamma-encoded SDR as linear light; SDR is now tagged sRGB (HDR keeps BT.2100 PQ). Downloaded artwork is kept in dot-files, which the asset protocol's "**" scope skips on macOS unless leading dots are allowed. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/platform/macos.rs | 17 ++++++++++++----- src-tauri/tauri.conf.json | 9 ++++++--- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src-tauri/src/platform/macos.rs b/src-tauri/src/platform/macos.rs index d9334f6..4bb331f 100644 --- a/src-tauri/src/platform/macos.rs +++ b/src-tauri/src/platform/macos.rs @@ -14,8 +14,8 @@ use std::sync::Arc; use objc2::rc::Retained; use objc2::{define_class, msg_send, AllocAnyThread, DefinedClass, MainThreadMarker}; use objc2_app_kit::{NSAutoresizingMaskOptions, NSView, NSWindow, NSWindowButton, NSWindowOrderingMode}; -use objc2_core_foundation::CFTimeInterval; -use objc2_core_graphics::{kCGColorSpaceITUR_2100_PQ, CGColorSpace}; +use objc2_core_foundation::{CFRetained, CFTimeInterval}; +use objc2_core_graphics::{kCGColorSpaceITUR_2100_PQ, kCGColorSpaceSRGB, CGColorSpace}; use objc2_core_video::CVTimeStamp; use objc2_foundation::{NSNumber, NSPoint, NSRect, NSSize, NSString}; use objc2_open_gl::*; @@ -131,6 +131,10 @@ extern "C" fn on_update(wake: *mut c_void) { let _ = wake.try_send(()); } +fn srgb() -> Option> { + CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })) +} + // —— The video layer ——————————————————————————————————————————————————— struct LayerIvars { @@ -211,6 +215,9 @@ impl VideoLayer { let this = VideoLayer::alloc().set_ivars(LayerIvars { cgl, pixel_format, float, render: Mutex::new(None) }); let layer: Retained = unsafe { msg_send![super(this), init] }; layer.setAsynchronous(false); + // A float framebuffer without a colour space would be read as linear + // light, washing SDR out; mpv writes gamma-encoded SDR, as for Windows. + layer.setColorspace(srgb().as_deref()); layer.setNeedsDisplayOnBoundsChange(true); layer.setOpaque(true); layer @@ -393,7 +400,7 @@ impl VideoSurface { /// HDR passthrough: for PQ or HLG video, mpv outputs PQ (BT.2020) instead of /// tone-mapping to SDR, and the layer shows it in extended dynamic range, so - /// macOS maps it to the display's HDR headroom. SDR video uses the defaults. + /// macOS maps it to the display's HDR headroom. SDR video is shown as sRGB. pub fn on_property(&mut self, name: &str, value: &serde_json::Value) { if name != "video-params/gamma" { return; @@ -413,8 +420,8 @@ impl VideoSurface { let layer = &self.ui.layer; CATransaction::begin(); layer.setWantsExtendedDynamicRangeContent(edr); - let pq = if edr { CGColorSpace::with_name(Some(unsafe { kCGColorSpaceITUR_2100_PQ })) } else { None }; - layer.setColorspace(pq.as_deref()); + let space = if edr { CGColorSpace::with_name(Some(unsafe { kCGColorSpaceITUR_2100_PQ })) } else { srgb() }; + layer.setColorspace(space.as_deref()); CATransaction::commit(); } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 1646121..5494755 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -31,9 +31,12 @@ "csp": null, "assetProtocol": { "enable": true, - "scope": [ - "**" - ] + "scope": { + "allow": [ + "**" + ], + "requireLiteralLeadingDot": false + } } } }, From 6f92aa42cc38c11fc93002d04bf911624a701abe Mon Sep 17 00:00:00 2001 From: Elijah Kuntz Date: Mon, 2 Nov 2026 15:35:06 -0700 Subject: [PATCH 03/34] Release Kaleido Desktop 0.1.0-beta.9 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +++++++ package-lock.json | 4 ++-- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 6 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5b0671..561793e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.1.0-beta.9 + +Fixes for the Mac version. + +- Regular (SDR) video no longer looks washed out on Mac; HDR was unaffected. +- Downloaded titles show their artwork again on Mac. + ## 0.1.0-beta.8 Kaleido for Mac. diff --git a/package-lock.json b/package-lock.json index 089a180..01e5262 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "0.1.0-beta.8", + "version": "0.1.0-beta.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "0.1.0-beta.8", + "version": "0.1.0-beta.9", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index 2e8898e..17159e2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "0.1.0-beta.8", + "version": "0.1.0-beta.9", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 1356bb1..202e163 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "0.1.0-beta.8" +version = "0.1.0-beta.9" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 3bf361e..7aaed82 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "0.1.0-beta.8" +version = "0.1.0-beta.9" description = "Kaleido — a Plex client for Windows" authors = ["Elijah"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 5494755..013bdfe 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Kaleido", - "version": "0.1.0-beta.8", + "version": "0.1.0-beta.9", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", From c7b391d6b4a2d82e68257300abc2b94ff2d36554 Mon Sep 17 00:00:00 2001 From: Elijah Kuntz Date: Mon, 2 Nov 2026 15:37:41 -0700 Subject: [PATCH 04/34] Publish the 0.1.0-beta.9 update feed Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index f15dea3..ea05863 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,11 +1,11 @@ { - "version": "0.1.0-beta.8", - "notes": "Kaleido for Mac.\n\n- Kaleido now runs on Macs with Apple silicon (macOS 26 or later), with the same interface and features as on Windows: browsing, playback with hardware decoding, the miniplayer, downloads, server management and in-app updates. The window uses the Mac's own close, minimize and zoom buttons, which fade with the player's controls, and shortcuts use ⌘ (⌘K to search, ⌘[ to go back, ⌃⌘F for full screen).\n- HDR passthrough works on Mac too: HDR titles play in the display's extended dynamic range instead of being converted to SDR.\n- Each release now includes both the Windows and Mac versions.\n- Updates are signed with a new key, so the Windows version needs to be reinstalled once from this release; later updates install in the app as before.", - "pub_date": "2026-11-02T22:24:31.764Z", + "version": "0.1.0-beta.9", + "notes": "Fixes for the Mac version.\n\n- Regular (SDR) video no longer looks washed out on Mac; HDR was unaffected.\n- Downloaded titles show their artwork again on Mac.", + "pub_date": "2026-11-02T22:37:41.336Z", "platforms": { "darwin-aarch64": { - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFE4NFdjWGFlNEZCRTExTTVVdkgrRTUvTXRmbVBsNE9ZVW11NXkwME1ZNkt1UzdGb3FzdW9oTWdLLzU3UWhyMSs3TTVjYXBoSTJnRysyVmR5SE4xVVFZPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjU4MTgyCWZpbGU6S2FsZWlkby5hcHAudGFyLmd6CXZlcnNpb246MC4xLjAtYmV0YS44CmxXOHA2NDVPL3JDMWtuQmdhTGNDNHRZOHBwdjFmSGg5V3o1V2tRMUdDRFp4cVg2M1dFUXVIMmdNWm5VMHBaT2xZSDh6RFdSUkpUcjZQbEp4bk5PZUNnPT0K", - "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.8/Kaleido_0.1.0-beta.8_aarch64.app.tar.gz" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NGFHNnV2UlBzVWxvUjNObzhQQkJXd05vRzc0TVN6ZktNbnBnYXF6emZDdHpwMkFWVDE0cGF6UFMyUTgxVnVTNFFqMVdISXdjNmRETWRSZ0RzcXdFVWc4PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjU5MDQ5CWZpbGU6S2FsZWlkby5hcHAudGFyLmd6CXZlcnNpb246MC4xLjAtYmV0YS45CmhGRGRzaW5VcUhiRmJ1TFVzV2FkQ1dydVRXSWwwRmVFMFhZWWVEMERuQi96MFFqeHNRVHZOSlRkeHJoZ3gwdGdQZWpEQ2d1ZWFEbStmR3J6cHQyY0RBPT0K", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.9/Kaleido_0.1.0-beta.9_aarch64.app.tar.gz" } } } From 10103d0e77e5a5563f0998c014db21c4ac5d5245 Mon Sep 17 00:00:00 2001 From: Elijah Date: Mon, 2 Nov 2026 18:35:34 -0700 Subject: [PATCH 05/34] Add Windows to the 0.1.0-beta.9 update feed Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index ea05863..694bbbb 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,8 +1,12 @@ { "version": "0.1.0-beta.9", - "notes": "Fixes for the Mac version.\n\n- Regular (SDR) video no longer looks washed out on Mac; HDR was unaffected.\n- Downloaded titles show their artwork again on Mac.", - "pub_date": "2026-11-02T22:37:41.336Z", + "notes": "Fixes for the Mac version.\r\n\r\n- Regular (SDR) video no longer looks washed out on Mac; HDR was unaffected.\r\n- Downloaded titles show their artwork again on Mac.", + "pub_date": "2026-11-03T01:35:29.741Z", "platforms": { + "windows-x86_64": { + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NGZYWUFzbDhuNG5XNW41dU56QzZ2RjV4ZzFOanN2VTlqQTJXRDlObitYT2VYTEljZ0dVaEx2bkY3TFNrRGxtMWJVbU5Md3UrQUtjY1JQSGc2V3dnTWdNPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjY5NTc0CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjlfeDY0LXNldHVwLmV4ZQl2ZXJzaW9uOjAuMS4wLWJldGEuOQpyUnY4YWJ2NzAweHoyR3NKQ3Y3RkdhREg2MHY4SEhWSXB4MVpPY1V4WkV1TVBwL3VtNTVVU3E3aVpUSllCaXV3R09xL3BhS1JyMUYxa0V5Qk4vUHlCdz09Cg==", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.9/Kaleido_0.1.0-beta.9_x64-setup.exe" + }, "darwin-aarch64": { "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NGFHNnV2UlBzVWxvUjNObzhQQkJXd05vRzc0TVN6ZktNbnBnYXF6emZDdHpwMkFWVDE0cGF6UFMyUTgxVnVTNFFqMVdISXdjNmRETWRSZ0RzcXdFVWc4PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzNjU5MDQ5CWZpbGU6S2FsZWlkby5hcHAudGFyLmd6CXZlcnNpb246MC4xLjAtYmV0YS45CmhGRGRzaW5VcUhiRmJ1TFVzV2FkQ1dydVRXSWwwRmVFMFhZWWVEMERuQi96MFFqeHNRVHZOSlRkeHJoZ3gwdGdQZWpEQ2d1ZWFEbStmR3J6cHQyY0RBPT0K", "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.9/Kaleido_0.1.0-beta.9_aarch64.app.tar.gz" From a38db53161243fad5e694988e8cd806269d01e96 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 16:33:34 -0700 Subject: [PATCH 06/34] Release Kaleido Desktop 0.1.0-beta.10 - Player controls centred under the timeline: previous episode, back 10 s, play/pause, forward 10 s, next episode; volume and time on the left. - Previous episode button and Shift+P. - Draggable miniplayer, kept inside the window and remembered. - Fix the next-episode card's buttons and the skip button being covered by the player's title row, and skip buttons also pausing playback. - Drop the "Highly rated"/"Recommended" label from the hero and restore the gap between its logo and the details line. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 ++ README.md | 2 +- package-lock.json | 4 +- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/player/PlayerOverlay.tsx | 161 +++++++++++++++++++++++---- src/player/store.ts | 25 ++++- src/screens/discover.ts | 13 +-- src/screens/settings/AppSettings.tsx | 2 +- src/styles/app.css | 8 +- src/styles/base.css | 2 +- src/styles/player.css | 43 +++++-- src/ui/Hero.tsx | 2 - 15 files changed, 220 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 561793e..7b83c7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.1.0-beta.10 + +A redesigned player control bar, previous episode, and a movable miniplayer. + +- The player's controls are rearranged the way most media players lay them out: play/pause sits in the centre under the timeline, with 10-second skips either side and previous/next episode beyond those. Volume and the time are on the left; subtitles, settings and full screen stay on the right. +- New previous-episode button (and Shift+P) to go back an episode. For episodes both buttons always show, dimmed at the start or end of a show, so play/pause stays put. +- The miniplayer can be dragged anywhere in the window. It stays inside the window when it's resized, and remembers where you left it. +- Fixed: the Play now and Cancel buttons on the next-episode card during the credits couldn't be clicked (the player's title row covered them). The Skip intro/credits button had the same problem with tall show logos. +- Fixed: clicking Skip intro or Skip credits also paused the video. +- The featured titles at the top of Home, Movies and TV Shows no longer carry a "Highly rated" / "Recommended" label, and their logo has room above the details line instead of touching it. + ## 0.1.0-beta.9 Fixes for the Mac version. diff --git a/README.md b/README.md index 198e1d8..e0fcfb4 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ place (see [Architecture](docs/architecture.md)). Linux builds browse but don't | Enter / Space | Open / play | ↑ / ↓, wheel | Volume | | Menu or Shift+F10 | Title actions | F, double-click | Full screen | | Alt+← (⌘[) / mouse back | Back | C | Next subtitle | -| / | Focus search | Shift+N | Next episode | +| / | Focus search | Shift+P / N | Previous / next episode | | F11 (⌃⌘F) | Full screen | Esc | Exit full screen, then player | Keys in brackets are the macOS equivalents. diff --git a/package-lock.json b/package-lock.json index 01e5262..8f1a25f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "0.1.0-beta.9", + "version": "0.1.0-beta.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "0.1.0-beta.9", + "version": "0.1.0-beta.10", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index 17159e2..28e5543 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "0.1.0-beta.9", + "version": "0.1.0-beta.10", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 202e163..f013d0c 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "0.1.0-beta.9" +version = "0.1.0-beta.10" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7aaed82..dd5ffab 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "0.1.0-beta.9" +version = "0.1.0-beta.10" description = "Kaleido — a Plex client for Windows" authors = ["Elijah"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 013bdfe..abdfb41 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Kaleido", - "version": "0.1.0-beta.9", + "version": "0.1.0-beta.10", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index 7beee7d..1930c88 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; +import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react'; import { usePlayer } from './store'; import { useSession } from '../app/session'; import { useSettings, QUALITY_LABEL, UPSCALING, type Quality, type SubtitleBox, type Upscaling } from '../app/settings'; @@ -512,7 +512,14 @@ function SkipButton() { if (!marker || mode === 'off' || countdown !== null) return null; if (marker.type === 'credits' && nextUp) return null; return ( - @@ -583,18 +590,62 @@ function TitleBlock({ item }: { item: Item }) { ); } +/** Where the miniplayer was dragged to: its distance from the window's right and bottom edges. */ +type MiniPos = { x: number; y: number }; +const MINI_POS_KEY = 'kaleido.miniPosition'; +const MINI_MARGIN = 8; +let miniPos: MiniPos | null | undefined; + +function savedMiniPos(): MiniPos | null { + if (miniPos === undefined) { + try { + const p = JSON.parse(localStorage.getItem(MINI_POS_KEY) ?? 'null'); + miniPos = p && Number.isFinite(p.x) && Number.isFinite(p.y) ? p : null; + } catch { + miniPos = null; + } + } + return miniPos ?? null; +} + +/** Keeps the whole box inside the window. */ +function clampMini(el: HTMLElement, pos: MiniPos): MiniPos { + const cs = getComputedStyle(el); + const maxX = window.innerWidth - parseFloat(cs.width) - MINI_MARGIN; + const maxY = window.innerHeight - parseFloat(cs.height) - MINI_MARGIN; + return { x: Math.round(Math.max(MINI_MARGIN, Math.min(maxX, pos.x))), y: Math.round(Math.max(MINI_MARGIN, Math.min(maxY, pos.y))) }; +} + +/** The box and the page's hole for the video (base.css) both follow these. */ +function applyMiniPos(pos: MiniPos | null) { + const root = document.documentElement.style; + if (!pos) { + root.removeProperty('--mini-x'); + root.removeProperty('--mini-y'); + return; + } + root.setProperty('--mini-x', `${pos.x}px`); + root.setProperty('--mini-y', `${pos.y}px`); +} + /** - * Playing in the corner while browsing. The native video is drawn into this - * box's rectangle and the page has a matching hole (see `html.player-mini`). + * Playing in the corner while browsing, and draggable anywhere in the window. + * The native video is drawn into this box's rectangle and the page has a + * matching hole (see `html.player-mini`). */ function MiniPlayer() { const st = usePlayer(); const box = useRef(null); + const placeVideo = useRef(() => {}); useEffect(() => { const el = box.current; if (!el) return; let frame = 0; + const fit = () => { + const saved = savedMiniPos(); + applyMiniPos(saved && clampMini(el, saved)); + }; const place = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => { @@ -610,23 +661,64 @@ function MiniPlayer() { if (isNative) mpv.rect({ x: x * dpr - 1, y: y * dpr - 1, width: width * dpr + 2, height: height * dpr + 2 }).catch(() => {}); }); }; - place(); + placeVideo.current = place; + const onResize = () => { + fit(); + place(); + }; + onResize(); const ro = new ResizeObserver(place); ro.observe(el); - window.addEventListener('resize', place); + window.addEventListener('resize', onResize); return () => { cancelAnimationFrame(frame); ro.disconnect(); - window.removeEventListener('resize', place); + window.removeEventListener('resize', onResize); }; }, []); + const startDrag = (e: ReactPointerEvent) => { + const el = box.current; + if (e.button !== 0 || !el) return; + const cs = getComputedStyle(el); + const start = { px: e.clientX, py: e.clientY, x: parseFloat(cs.right), y: parseFloat(cs.bottom) }; + let dragging = false; + const move = (ev: PointerEvent) => { + const dx = ev.clientX - start.px; + const dy = ev.clientY - start.py; + if (!dragging && Math.hypot(dx, dy) < 5) return; + dragging = true; + el.classList.add('dragging'); + miniPos = clampMini(el, { x: start.x - dx, y: start.y - dy }); + applyMiniPos(miniPos); + placeVideo.current(); + }; + const up = () => { + window.removeEventListener('pointermove', move); + window.removeEventListener('pointerup', up); + window.removeEventListener('pointercancel', up); + if (!dragging) return; + el.classList.remove('dragging'); + localStorage.setItem(MINI_POS_KEY, JSON.stringify(miniPos)); + // Letting go after a drag isn't a click on the button under the pointer. + const swallow = (c: MouseEvent) => { + c.stopPropagation(); + c.preventDefault(); + }; + window.addEventListener('click', swallow, { capture: true, once: true }); + setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0); + }; + window.addEventListener('pointermove', move); + window.addEventListener('pointerup', up); + window.addEventListener('pointercancel', up); + }; + if (!st.item) return null; const item = st.item; const loading = !st.firstFrame && !st.error; const pct = st.duration ? Math.min(100, (st.position / st.duration) * 100) : 0; return ( -
st.expand()}> +
st.expand()}>
- - - {st.nextUp && ( - - )} {clock(st.position, st.duration >= 3600)} / {clock(st.duration, st.duration >= 3600)}
+
+ {/* Both episode buttons stay for episodes (dimmed at either end) so play/pause holds its place. */} + {item.type === 'episode' && ( + + )} + + + + {item.type === 'episode' && ( + + )} +
+ +
+
+ {(s.loading || s.buffering) && !s.error ? ( + + ) : s.error ? ( + Playback stopped + ) : ( + <> + + + + + )} +
+
+ {s.title} + {s.subtitle && {s.subtitle}} +
+
+ +
+
+ ); +} + +createRoot(document.getElementById('root')!).render( + + + , +); diff --git a/src/mini/mini.css b/src/mini/mini.css new file mode 100644 index 0000000..e6cc4cd --- /dev/null +++ b/src/mini/mini.css @@ -0,0 +1,32 @@ +/* The miniplayer window (mini.html): the page is transparent over the video + and the box fills the window, whose corners Windows rounds. */ +html.mini-window, +html.mini-window body, +html.mini-window #root { + height: 100%; + margin: 0; + overflow: hidden; + background: transparent; +} +html.mini-window .mini-player { + position: absolute; + inset: 0; + width: auto; + height: auto; + border-radius: 0; + box-shadow: none; + animation: none; + cursor: default; +} +html.mini-window.dragging .mini-player { + cursor: grabbing; +} +/* While dragged, the title stays and the buttons step back. */ +html.mini-window.dragging .mini-scrim, +html.mini-window.dragging .mini-caption { + opacity: 1; +} +html.mini-window.dragging .mini-top, +html.mini-window.dragging .mini-center { + opacity: 0; +} diff --git a/src/mini/types.ts b/src/mini/types.ts new file mode 100644 index 0000000..d5d21c2 --- /dev/null +++ b/src/mini/types.ts @@ -0,0 +1,17 @@ +/** What the miniplayer window shows, sent from the main window (src/player/miniWindow.ts). */ +export interface MiniState { + title: string; + subtitle: string; + paused: boolean; + ended: boolean; + position: number; + duration: number; + loading: boolean; + buffering: boolean; + error: boolean; +} + +/** Buttons and gestures in the miniplayer window, carried out by the main window's player. */ +export type MiniAction = 'ready' | 'toggle' | 'back' | 'forward' | 'expand' | 'close'; + +export const MINI_CORNER_KEY = 'kaleido.miniCorner'; diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index 1930c88..cdcba2e 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -10,6 +10,7 @@ import { win, isNative } from '../platform/native'; import { WindowControls } from '../app/TopBar'; import { navigate } from '../app/router'; import { mpv } from './engine'; +import { separateMini } from './miniWindow'; import { PREPARING_NOTICE_MS, UPSCALING_ORDER, hasFailed, readDiagnostics, requestEnhancement, tierAvailable, toggleBypass, type Diagnostics } from './enhance'; import { toast } from '../ui/overlays'; import type { Item } from '../plex/types'; @@ -887,7 +888,8 @@ export function PlayerOverlay() { }, [chromeHidden]); if (!st.open || !st.item) return null; - if (st.mini) return ; + // On Windows the miniplayer is a window of its own (miniWindow.ts). + if (st.mini) return separateMini ? null : ; const item = st.item; const loading = !st.firstFrame && !st.error; const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art; diff --git a/src/player/miniWindow.ts b/src/player/miniWindow.ts new file mode 100644 index 0000000..2f1966c --- /dev/null +++ b/src/player/miniWindow.ts @@ -0,0 +1,97 @@ +/** + * The miniplayer as a window of its own (Windows, src-tauri/src/mini.rs): the + * video moves into it, so it drags as one piece. This side keeps its page + * (src/mini/) up to date and carries out its buttons; macOS keeps the + * in-page miniplayer (PlayerOverlay). + */ +import { hostOS, invoke, isNative, listen } from '../platform/native'; +import { episodeLabel } from '../app/format'; +import { MINI_CORNER_KEY, type MiniAction, type MiniState } from '../mini/types'; +import type { Item } from '../plex/types'; + +export const separateMini = isNative && hostOS === 'windows'; + +export async function showMiniWindow() { + await invoke('mini_show', { corner: localStorage.getItem(MINI_CORNER_KEY) ?? 'br' }); +} + +/** Moves the video back to the main window; harmless when already there. */ +export async function hideMiniWindow() { + await invoke('mini_hide').catch(() => {}); +} + +interface PlayerView { + open: boolean; + mini: boolean; + item: Item | null; + paused: boolean; + ended: boolean; + position: number; + duration: number; + firstFrame: boolean; + buffering: boolean; + error: string; +} + +interface PlayerActions { + togglePause(): void; + seekBy(delta: number): void; + expand(): void; + close(): Promise; +} + +function view(st: PlayerView): MiniState { + const item = st.item; + return { + title: item ? (item.type === 'episode' ? item.grandparentTitle : item.title) : '', + subtitle: item?.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : '', + paused: st.paused, + ended: st.ended, + position: st.position, + duration: st.duration, + loading: !st.firstFrame && !st.error, + buffering: st.buffering, + error: !!st.error, + }; +} + +/** Mirrors the player into the miniplayer window and listens for its buttons. */ +export function bridgeMiniWindow(store: { getState(): PlayerView & PlayerActions; subscribe(listener: (st: PlayerView, prev: PlayerView) => void): () => void }) { + if (!separateMini) return; + let lastSent = 0; + let pending: ReturnType | null = null; + + const send = async () => { + pending = null; + lastSent = Date.now(); + const st = store.getState(); + if (!st.open) return; + const { emitTo } = await import('@tauri-apps/api/event'); + emitTo('mini', 'mini:state', view(st)).catch(() => {}); + }; + + store.subscribe((st, prev) => { + if (!st.open || !st.mini) return; + // Everything but the position goes straight away; the position a few times a second. + const a = view(st); + const b = view(prev); + const only = (Object.keys(a) as (keyof MiniState)[]).every((k) => k === 'position' || a[k] === b[k]); + if (!only || st.mini !== prev.mini) { + if (pending) clearTimeout(pending); + send(); + } else if (!pending) { + pending = setTimeout(send, Math.max(0, 250 - (Date.now() - lastSent))); + } + }); + + listen<{ type: MiniAction }>('mini:action', ({ type }) => { + const st = store.getState(); + if (type === 'ready') return send(); + if (!st.open) return; + if (type === 'toggle') st.togglePause(); + else if (type === 'back') st.seekBy(-10); + else if (type === 'forward') st.seekBy(10); + else if (type === 'expand') st.expand(); + else if (type === 'close') st.close(); + }); +} diff --git a/src/player/store.ts b/src/player/store.ts index 9efc231..8780c99 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -11,6 +11,7 @@ import { keepAwake, isNative, win } from '../platform/native'; import { mpv, type MpvEvent, type MpvTrack } from './engine'; import { toast } from '../ui/overlays'; import { stopThemeMusic } from './theme'; +import { bridgeMiniWindow, hideMiniWindow, separateMini, showMiniWindow } from './miniWindow'; export interface Track { key: string; // stable UI key @@ -700,6 +701,8 @@ export const usePlayer = create((set, get) => ({ keepAwake(false); watchPerformance(false); if (isNative) { + // From the miniplayer window, the video goes home first (and stays hidden). + if (separateMini && st.mini) await hideMiniWindow(); await mpv.command('stop').catch(() => {}); await mpv.show(false).catch(() => {}); } @@ -767,10 +770,19 @@ export const usePlayer = create((set, get) => ({ await win.setFullscreen(false).catch(() => {}); set({ fullscreen: false }); } + if (separateMini) { + // Once the page is opaque again (no video in it), the video moves into + // the miniplayer's own window (miniWindow.ts). + await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); + if (get().open && get().mini) await showMiniWindow().catch((e) => console.warn('[mini]', e)); + } }, expand() { - if (get().mini) set({ mini: false }); + if (!get().mini) return; + // The video comes back behind the still-opaque page before it turns transparent. + if (separateMini) hideMiniWindow().finally(() => set({ mini: false })); + else set({ mini: false }); }, async selectAudio(key) { @@ -854,15 +866,21 @@ export const usePlayer = create((set, get) => ({ usePlayer.subscribe((st, prev) => { if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error || st.mini !== prev.mini) { const html = document.documentElement.classList; - html.toggle('video-active', st.open && st.firstFrame && !st.error); + // With a miniplayer window, the video has left this page entirely. + html.toggle('video-active', st.open && st.firstFrame && !st.error && !(st.mini && separateMini)); html.toggle('player-open', st.open && !st.mini); html.toggle('player-mini', st.open && st.mini); } // However the miniplayer is left (expanding, playing another title, closing), // the video returns to the whole window. - if (prev.mini && !st.mini && isNative) mpv.rect(null).catch(() => {}); + if (prev.mini && !st.mini && isNative) { + if (separateMini) hideMiniWindow(); + else mpv.rect(null).catch(() => {}); + } }); +bridgeMiniWindow(usePlayer); + /** Subtitle look changes apply to the playing video straight away. */ const SUBTITLE_PREFS = ['subtitleScale', 'subtitleColor', 'subtitleEdge', 'subtitleBox', 'subtitleBold', 'subtitlePosition'] as const; useSettings.subscribe((prefs, prev) => { diff --git a/vite.config.ts b/vite.config.ts index af60ced..0ce0df4 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -34,5 +34,10 @@ export default defineConfig({ plugins: [react(), devSession()], clearScreen: false, server: { port: 1420, strictPort: true, watch: { ignored: ['**/src-tauri/**'] } }, - build: { target: 'es2022', chunkSizeWarningLimit: 1500 }, + build: { + target: 'es2022', + chunkSizeWarningLimit: 1500, + // The miniplayer window has a page of its own (src/mini/). + rollupOptions: { input: { main: path.resolve(import.meta.dirname, 'index.html'), mini: path.resolve(import.meta.dirname, 'mini.html') } }, + }, }); From 9729755dc9b355034108f886354d7ba8d4ad4abc Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 17:39:19 -0700 Subject: [PATCH 11/34] Publish the 0.1.0-beta.12 update feed (Windows) Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index 35f49ba..ab27ed0 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,11 +1,11 @@ { - "version": "0.1.0-beta.11", - "notes": "Fixes the app freezing when leaving full screen for the miniplayer, and adds local hang and crash reports.\r\n\r\n- Fixed: going back from the full-screen player to the miniplayer (or moving or resizing the miniplayer) could freeze the window — it turned see-through and \"Not Responding\" while the video kept playing. Two parts of the player were each waiting for the other when the window resized at the wrong moment.\r\n- When the window stops responding for 5 seconds, or the app crashes, Kaleido now saves a report of what each part of the app was doing in its log folder (`%LOCALAPPDATA%\\tv.kaleido.desktop\\logs`), so a rare problem can be traced the first time it happens. Reports stay on your computer.", - "pub_date": "2026-11-05T00:09:19.002Z", + "version": "0.1.0-beta.12", + "notes": "A smoother miniplayer on Windows.\r\n\r\n- The miniplayer is now a small window of its own, so dragging it moves the video and its controls together: the video keeps playing smoothly as you move it, with no flicker around its edges.\r\n- Letting go snaps it to the nearest corner of the window, or the corner you flick it towards, and it remembers that corner. It stays in place as the window moves or resizes.\r\n- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.\r\n- On Mac the miniplayer is unchanged for now.", + "pub_date": "2026-11-05T00:39:18.979Z", "platforms": { "windows-x86_64": { - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFk5cnNuVjNNaTRQQ2FSSU03TjMrOXF5NzQzV0ErR25zelB0UWJRaXlKcmtmRVlYNFg4OHB3RnBmWVBUTUw2anY4Tk9nTHNKa2c5ditEbytRZjRoS3dvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODM3MzI2CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjExX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjExCmdJQ2ZKNHN1T3hCeUxvdXVwbjhORFM4REVKMFRUVDUySHpjTEM2SVBONWN2ZjNoTi85a2hHWFA5aDdES2ZGOHJSWDNFWndwY21Uc1lKbGdtNVhZeUFRPT0K", - "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.11/Kaleido_0.1.0-beta.11_x64-setup.exe" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFZXbUR6ZDBPS0tDSWNEK1RTbkJMOGl4ZFVKUHRqWGZRbHpFU1ZuS01QM0RlU1pTRW5PN25KNFlDbUJ5dzRDS0hSRm5DQjU4ZlNsdm1ITjlXY09HMXdvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODM5MTM1CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjEyX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjEyClNZQ3RxSkMzaDZxZE1IWnJnM0xVcmt2T2VwZEQ5eWFjcTM4SThnV2M0aGxoeE5DZ0gwQ3UwcWNIYUZlVERxVDN2ZGpsamxkZlAwbHJZSWtnOGd0YUN3PT0K", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.12/Kaleido_0.1.0-beta.12_x64-setup.exe" } } } From 328a93695a5dbdbc6280a1ea734bf8fbd840aea3 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 21:57:23 -0700 Subject: [PATCH 12/34] Release Kaleido Desktop 0.1.0-beta.13 - Automatic intro/credits skip waits a configurable delay (default 5 s) with a filling "Skipping intro" button; pausing, seeking or pressing a key cancels it, and seeking into an intro never auto-skips it. - Watch-state queries refetch on window focus, and Continue Watching / next episode poll every minute while visible, so progress from other Plex apps shows up. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++ package-lock.json | 4 +- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- src/app/queries.ts | 16 +++++- src/app/settings.ts | 3 ++ src/player/PlayerOverlay.tsx | 77 +++++++++++++++++++++++++--- src/player/store.ts | 6 ++- src/screens/Home.tsx | 6 +-- src/screens/Item.tsx | 4 +- src/screens/Section.tsx | 4 +- src/screens/settings/AppSettings.tsx | 8 +++ src/styles/player.css | 18 +++++++ 15 files changed, 139 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39d2fb7..8ef98c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.1.0-beta.13 + +A gentler automatic intro skip, and home screens that keep up with your other Plex apps. + +- "Skip automatically" for intros (and credits) now waits a moment first: the Skip button reads "Skipping intro" and fills as it counts down, then skips. Pause, seek or press any key before then to keep watching; the button stays as a regular Skip intro for the rest of the intro. Click it to skip straight away. +- Choose how long it waits in Settings → Playback → Automatic skip delay (3, 5 or 10 seconds, or straight away as before). It's 5 seconds by default. +- Jumping into the middle of an intro yourself no longer skips it automatically. +- Fixed: Continue Watching, a show's next episode, and watched marks didn't update after watching something on another device (a TV, a phone) while Kaleido stayed open. They now refresh when you switch back to Kaleido, and Continue Watching also refreshes every minute while it's on screen. + ## 0.1.0-beta.12 A smoother miniplayer on Windows. diff --git a/package-lock.json b/package-lock.json index ce01497..71aea19 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "0.1.0-beta.12", + "version": "0.1.0-beta.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "0.1.0-beta.12", + "version": "0.1.0-beta.13", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index a14ba1c..758ab7c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "0.1.0-beta.12", + "version": "0.1.0-beta.13", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 8e94ec2..d21aa89 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "0.1.0-beta.12" +version = "0.1.0-beta.13" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b105989..6205fe5 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "0.1.0-beta.12" +version = "0.1.0-beta.13" description = "Kaleido — a Plex client for Windows" authors = ["Elijah"] edition = "2021" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index ba801ff..9b74fde 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Kaleido", - "version": "0.1.0-beta.12", + "version": "0.1.0-beta.13", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/app/queries.ts b/src/app/queries.ts index d8fcdd5..80e5bb9 100644 --- a/src/app/queries.ts +++ b/src/app/queries.ts @@ -15,6 +15,18 @@ export const queryClient = new QueryClient({ }, }); +/** + * Watch state changes from other Plex apps too (a TV, a phone), so the queries that show + * it refresh when Kaleido comes back into view and, for the progress rows, every minute + * while it is on screen. Polling pauses while the window is hidden or minimised. + */ +export const WATCH_STATE = { refetchOnWindowFocus: true } as const; +export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60_000 } as const; + +// React Query treats a visibility change as focus. Switching back to Kaleido from another +// app doesn't change visibility, so a window focus counts as well. +window.addEventListener('focus', () => queryClient.getQueryCache().onFocus()); + /** Every key starts with the server so switching servers never mixes caches. */ export function useKey(...parts: unknown[]) { const server = useServer(); @@ -37,9 +49,9 @@ export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null } export const useItem = (id: string | undefined, opts: Partial> = {}) => - useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts }); + useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE, ...opts }); -export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 }); +export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000, ...WATCH_STATE }); export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 }); diff --git a/src/app/settings.ts b/src/app/settings.ts index e5ced81..713e80e 100644 --- a/src/app/settings.ts +++ b/src/app/settings.ts @@ -19,6 +19,8 @@ export interface Preferences { countdownSeconds: number; skipIntro: SkipMode; skipCredits: SkipMode; + /** Seconds a "Skip automatically" marker waits, so it can be cancelled; 0 skips at once. */ + autoSkipDelay: number; watchedPercent: number; audioLanguage: string; subtitleMode: SubtitleMode; @@ -62,6 +64,7 @@ export const defaults: Preferences = { countdownSeconds: 8, skipIntro: 'button', skipCredits: 'button', + autoSkipDelay: 5, watchedPercent: 90, audioLanguage: '', subtitleMode: 'auto', diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index cdcba2e..10d2760 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -492,36 +492,97 @@ function Volume() { ); } +/** A seek that lands inside a marker this recently means the viewer chose to be there. */ +const SEEK_GRACE_MS = 1500; +const MODIFIER_KEYS = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock']); + +/** + * Skip intro / Skip credits. With "Skip automatically" the button counts down for the + * chosen delay, filling as it goes, then skips. Pausing, seeking or pressing a key + * before then keeps watching: the button stays as a plain skip for the rest of the marker. + */ function SkipButton() { const item = usePlayer((s) => s.item); const position = usePlayer((s) => s.position); const seek = usePlayer((s) => s.seek); const nextUp = usePlayer((s) => s.nextUp); const countdown = usePlayer((s) => s.countdown); + const paused = usePlayer((s) => s.paused); + const ready = usePlayer((s) => s.firstFrame); + const lastSeek = usePlayer((s) => s.lastSeek); const skipIntro = useSettings((s) => s.skipIntro); const skipCredits = useSettings((s) => s.skipCredits); - const autoSkipped = useRef(new Set()); + const delay = useSettings((s) => s.autoSkipDelay); + // Markers already skipped, or whose automatic skip was cancelled, don't count down again. + const settled = useRef(new Set()); + const [pending, setPending] = useState<{ key: string; from: number } | null>(null); const ms = position * 1000; const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000); + const key = item && marker ? `${item.id}:${marker.type}:${marker.start}` : ''; const mode = marker?.type === 'intro' ? skipIntro : skipCredits; + const auto = !!marker && mode === 'auto' && !(marker.type === 'credits' && nextUp); + const counting = pending && pending.key === key ? pending : null; + + const skip = () => { + if (!marker) return; + settled.current.add(key); + setPending(null); + seek(marker.end / 1000); + }; + const cancel = () => { + if (!pending) return; + settled.current.add(pending.key); + setPending(null); + }; + + // Start counting once an automatic marker is playing. useEffect(() => { - if (marker && mode === 'auto' && !autoSkipped.current.has(marker.id + marker.start) && !(marker.type === 'credits' && nextUp)) { - autoSkipped.current.add(marker.id + marker.start); - seek(marker.end / 1000); + if (!auto || !ready || paused || settled.current.has(key) || pending?.key === key) return; + if (Date.now() - usePlayer.getState().lastSeek < SEEK_GRACE_MS) { + settled.current.add(key); + return; } - }, [marker?.id, marker?.start, mode]); + if (delay <= 0) return skip(); + setPending({ key, from: usePlayer.getState().position }); + }, [key, auto, ready, paused, delay]); + + // Count playback time, so buffering doesn't eat into the delay. + useEffect(() => { + if (counting && position - counting.from >= delay) skip(); + else if (pending && !counting) setPending(null); + }, [position, key]); + + // Pausing or seeking means the viewer is watching. + useEffect(() => { + if (paused) cancel(); + }, [paused]); + useEffect(cancel, [lastSeek]); + + useEffect(() => { + if (!counting) return; + const onKey = (e: KeyboardEvent) => { + if (!MODIFIER_KEYS.has(e.key)) cancel(); + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, [counting]); + if (!marker || mode === 'off' || countdown !== null) return null; if (marker.type === 'credits' && nextUp) return null; + const what = marker.type === 'intro' ? 'intro' : 'credits'; + const elapsed = counting ? Math.max(0, position - counting.from) : 0; return ( ); diff --git a/src/player/store.ts b/src/player/store.ts index 8780c99..ea32564 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -50,6 +50,8 @@ interface PlayerState { paused: boolean; buffering: boolean; seeking: boolean; + /** When the last seek was asked for (Date.now()), so a pending auto-skip can step aside. */ + lastSeek: number; volume: number; muted: boolean; speed: number; @@ -541,6 +543,7 @@ export const usePlayer = create((set, get) => ({ paused: false, buffering: false, seeking: false, + lastSeek: 0, volume: 100, muted: false, speed: 1, @@ -588,6 +591,7 @@ export const usePlayer = create((set, get) => ({ error: '', terminated: false, position: (opts.offsetMs ?? 0) / 1000, + lastSeek: 0, duration: input.duration / 1000, cacheTime: 0, paused: false, @@ -724,7 +728,7 @@ export const usePlayer = create((set, get) => ({ seek(seconds) { const st = get(); const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5)); - set({ position: target, ended: false }); + set({ position: target, ended: false, lastSeek: Date.now() }); if (st.countdown !== null) { stopCountdown(); set({ countdown: null }); diff --git a/src/screens/Home.tsx b/src/screens/Home.tsx index d652522..5d61656 100644 --- a/src/screens/Home.tsx +++ b/src/screens/Home.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react'; import { useQuery } from '@tanstack/react-query'; import * as api from '../plex/api'; -import { useSections, useServerQuery } from '../app/queries'; +import { PROGRESS, WATCH_STATE, useSections, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { navigate } from '../app/router'; import { Hero } from '../ui/Hero'; @@ -14,8 +14,8 @@ export function Home() { const sections = useSections(); const video = (sections.data ?? []).filter((s) => (s.type === 'movie' || s.type === 'show') && !s.hidden); - const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s)); - const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), { staleTime: 15_000 }); + const home = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), WATCH_STATE); + const continueWatching = useServerQuery(['continue'], (s) => api.continueWatching(s), PROGRESS); // Section hubs feed the hero and the release shelves; shared with Discover. const sectionHubs = useQuery({ queryKey: [server.machineId, 'sectionHubsAll', video.map((s) => s.id).join(',')], diff --git a/src/screens/Item.tsx b/src/screens/Item.tsx index ed6879d..ebaf887 100644 --- a/src/screens/Item.tsx +++ b/src/screens/Item.tsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useState, type ReactNode } from 'react'; import * as api from '../plex/api'; import type { Item } from '../plex/types'; -import { useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; +import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; import { goBack, navigate, useRouter } from '../app/router'; @@ -401,7 +401,7 @@ function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item function ShowDetail({ item }: { item: Item }) { const seasons = useChildren(item.id); const server = useServer(); - const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), { staleTime: 15_000 }); + const next = useServerQuery(['onDeck', item.id], (s) => api.onDeckFor(s, item), PROGRESS); const nextEp = next.data; const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season'); const percent = useSettings((s) => s.watchedPercent); diff --git a/src/screens/Section.tsx b/src/screens/Section.tsx index 7fa4e76..252354a 100644 --- a/src/screens/Section.tsx +++ b/src/screens/Section.tsx @@ -1,6 +1,6 @@ import { useMemo } from 'react'; import * as api from '../plex/api'; -import { useSectionFor, useServerQuery } from '../app/queries'; +import { PROGRESS, useSectionFor, useServerQuery } from '../app/queries'; import { navigate, useRouter, type SectionKind, type SectionTab } from '../app/router'; import { useSettings } from '../app/settings'; import type { Section } from '../plex/types'; @@ -46,7 +46,7 @@ function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind function Discover({ kind, section }: { kind: SectionKind; section: Section }) { const hubs = useServerQuery(['sectionHubs', section.id], (s) => api.sectionHubs(s, section.id)); - const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), { staleTime: 15_000 }); + const cw = useServerQuery(['continue', section.id], (s) => api.continueWatching(s, section.id), PROGRESS); const seasons = useServerQuery(['recentSeasons', section.id], (s) => recentSeasons(s, section.id), { enabled: kind === 'show', staleTime: 120_000 }); const features = useMemo(() => buildFeatures(hubs.data ?? [], 7, kind === 'movie' ? 1 : 2), [hubs.data, kind]); diff --git a/src/screens/settings/AppSettings.tsx b/src/screens/settings/AppSettings.tsx index a5abd3e..5ef80b9 100644 --- a/src/screens/settings/AppSettings.tsx +++ b/src/screens/settings/AppSettings.tsx @@ -195,6 +195,14 @@ export function AppSettings({ tab }: { tab: string }) { set('autoSkipDelay', v)} + options={[0, 3, 5, 10].map((v) => ({ value: v, label: v ? `${v} seconds` : 'Skip straight away' }))} + /> + set('autoplayNext', v)} /> diff --git a/src/styles/player.css b/src/styles/player.css index df74507..8233fec 100644 --- a/src/styles/player.css +++ b/src/styles/player.css @@ -687,6 +687,24 @@ html.os-macos:not(.window-fullscreen) .player-top { background: #f3f5f4; color: #111; } +/* An automatic skip fills the button as it counts down. */ +.skip-button.counting { + overflow: hidden; +} +.skip-button.counting::before { + content: ''; + position: absolute; + inset: 0 auto 0 0; + width: var(--p, 0%); + background: rgba(255, 255, 255, 0.18); + transition: width 260ms linear; +} +.skip-button.counting:hover::before { + background: rgba(0, 0, 0, 0.1); +} +.skip-button > * { + position: relative; +} .post-play { position: absolute; right: clamp(24px, 3.5vw, 56px); From c70aeede74926be23921462ef661acc795bb5581 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 22:08:36 -0700 Subject: [PATCH 13/34] Publish the 0.1.0-beta.13 update feed (Windows) Co-Authored-By: Claude Opus 5.5 --- updates/latest.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/updates/latest.json b/updates/latest.json index ab27ed0..0dc98e9 100644 --- a/updates/latest.json +++ b/updates/latest.json @@ -1,11 +1,11 @@ { - "version": "0.1.0-beta.12", - "notes": "A smoother miniplayer on Windows.\r\n\r\n- The miniplayer is now a small window of its own, so dragging it moves the video and its controls together: the video keeps playing smoothly as you move it, with no flicker around its edges.\r\n- Letting go snaps it to the nearest corner of the window, or the corner you flick it towards, and it remembers that corner. It stays in place as the window moves or resizes.\r\n- Using its buttons no longer takes focus from the main window, so keyboard shortcuts keep working.\r\n- On Mac the miniplayer is unchanged for now.", - "pub_date": "2026-11-05T00:39:18.979Z", + "version": "0.1.0-beta.13", + "notes": "A gentler automatic intro skip, and home screens that keep up with your other Plex apps.\n\n- \"Skip automatically\" for intros (and credits) now waits a moment first: the Skip button reads \"Skipping intro\" and fills as it counts down, then skips. Pause, seek or press any key before then to keep watching; the button stays as a regular Skip intro for the rest of the intro. Click it to skip straight away.\n- Choose how long it waits in Settings → Playback → Automatic skip delay (3, 5 or 10 seconds, or straight away as before). It's 5 seconds by default.\n- Jumping into the middle of an intro yourself no longer skips it automatically.\n- Fixed: Continue Watching, a show's next episode, and watched marks didn't update after watching something on another device (a TV, a phone) while Kaleido stayed open. They now refresh when you switch back to Kaleido, and Continue Watching also refreshes every minute while it's on screen.", + "pub_date": "2026-11-05T05:08:29.690Z", "platforms": { "windows-x86_64": { - "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFZXbUR6ZDBPS0tDSWNEK1RTbkJMOGl4ZFVKUHRqWGZRbHpFU1ZuS01QM0RlU1pTRW5PN25KNFlDbUJ5dzRDS0hSRm5DQjU4ZlNsdm1ITjlXY09HMXdvPQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODM5MTM1CWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjEyX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjEyClNZQ3RxSkMzaDZxZE1IWnJnM0xVcmt2T2VwZEQ5eWFjcTM4SThnV2M0aGxoeE5DZ0gwQ3UwcWNIYUZlVERxVDN2ZGpsamxkZlAwbHJZSWtnOGd0YUN3PT0K", - "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.12/Kaleido_0.1.0-beta.12_x64-setup.exe" + "signature": "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZ25hdHVyZSBmcm9tIHRhdXJpIHNlY3JldCBrZXkKUlVST1RiNHdFVm01NFpSemIrYjVoY3M5NDZQbTI3aVB6RDhCbXpZbXl4d2dJYWUzWitlbXBNWnNOT29BZU11SzI3cVY5dXhjcHNNUmI0Ly83NXJGT3BVdHA2enBBMCtHK2d3PQp0cnVzdGVkIGNvbW1lbnQ6IHRpbWVzdGFtcDoxNzkzODU1MjkwCWZpbGU6S2FsZWlkb18wLjEuMC1iZXRhLjEzX3g2NC1zZXR1cC5leGUJdmVyc2lvbjowLjEuMC1iZXRhLjEzClg4bllva1Nib0pUOTJXQlc5VUQrRmxXUUo5R1FUWVY0UCtuV2l4K2NOaHQ4UUF0MlVBd2VnVUlpKzhQVWpHTnFUQWE0K2NrZnJtYW05ZCtDRFg5TkJ3PT0K", + "url": "https://git.elijahkuntz.com/Elijah/Kaleido-Desktop/releases/download/v0.1.0-beta.13/Kaleido_0.1.0-beta.13_x64-setup.exe" } } } From 8755d167357146501e483caaee0dad962f8777d9 Mon Sep 17 00:00:00 2001 From: Elijah Date: Wed, 4 Nov 2026 22:41:12 -0700 Subject: [PATCH 14/34] Fix playback, account, download and library bugs found in review - Clear cached library data when the account or profile behind the server connection changes, not only on Home user switches. - TitleArt falls back to the title when there is no server, so the player no longer crashes offline. - Playback keeps the server it started on: progress, watched state and transcodes never go to a server selected later, a download only reports to its own server, and switching account or server ends a stream from the old one. - Closing or replacing playback during setup can no longer start the file afterwards. - Transcodes save the chosen audio/subtitle tracks on the server before starting (and name them in the request), apply the language and subtitle preferences, and keep the current tracks across quality changes. - Offline playback saves its resume point and watched count in the download's metadata. - Download tasks take over from a previous task for the same title only after it exits, and pause/remove stay wired to the current task. - Downloads prefer a single-file version and refuse split ones instead of saving only part one. - Download artwork is named per file, so episodes in one season folder no longer overwrite or delete each other's images. - Library grids refetch loaded pages when the cache is invalidated. - Request timeouts and cancellation also cover the response body. - Hero rotation resumes after being scrolled back into view. Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/downloads.rs | 127 +++++++++++++--- src/app/queries.ts | 9 +- src/downloads/store.ts | 15 +- src/player/store.ts | 260 ++++++++++++++++++++++++++------- src/plex/client.ts | 40 +++-- src/plex/playback.ts | 4 + src/screens/LibraryBrowser.tsx | 27 ++++ src/ui/Hero.tsx | 9 +- src/ui/media.tsx | 7 +- 9 files changed, 399 insertions(+), 99 deletions(-) diff --git a/src-tauri/src/downloads.rs b/src-tauri/src/downloads.rs index 2d3490c..89c183c 100644 --- a/src-tauri/src/downloads.rs +++ b/src-tauri/src/downloads.rs @@ -5,8 +5,9 @@ //! server-relative source path; resuming after a restart asks the interface for //! a freshly signed URL. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -47,10 +48,19 @@ pub struct Item { pub speed: u64, } +/// The transfer task that currently owns a download (and its `.part` file). +struct Worker { + generation: u64, + cancel: watch::Sender, + /// Closes once the task has exited and let go of the file. + done: watch::Receiver<()>, +} + pub struct Downloads { items: Mutex>, dir: Mutex>, - cancels: Mutex>>, + workers: Mutex>, + generation: AtomicU64, permits: Arc, client: reqwest::Client, } @@ -60,7 +70,8 @@ impl Default for Downloads { Downloads { items: Mutex::new(Vec::new()), dir: Mutex::new(None), - cancels: Mutex::new(HashMap::new()), + workers: Mutex::new(HashMap::new()), + generation: AtomicU64::new(0), permits: Arc::new(Semaphore::new(MAX_ACTIVE)), client: reqwest::Client::builder() .connect_timeout(Duration::from_secs(20)) @@ -168,8 +179,11 @@ pub async fn download_start(app: AppHandle, request: StartRequest let mut meta = request.meta.clone(); if let Value::Object(map) = &mut meta { let mut local = serde_json::Map::new(); + // Episodes share their season's folder, so artwork is named after the file it + // belongs to: one episode's still never replaces another's. + let stem = file_path.file_stem().and_then(|s| s.to_str()).map(sanitize).unwrap_or_else(|| sanitize(&request.id)); for (name, url) in &request.assets { - let target = folder.join(format!(".{}.jpg", sanitize(name))); + let target = folder.join(format!(".{stem}.{}.jpg", sanitize(name))); if fetch_to(&state.client, url, &target).await.is_ok() { local.insert(name.clone(), Value::String(target.display().to_string())); } @@ -204,21 +218,48 @@ async fn fetch_to(client: &reqwest::Client, url: &str, target: &Path) -> Result< tokio::fs::write(target, bytes).await.map_err(|e| e.to_string()) } +/// Starts a transfer task for `id`, taking over from any task still running for it: +/// that one is cancelled and the new one waits for it to exit before touching the file. fn spawn(app: AppHandle, id: String, url: String) { + let state = app.state::(); + let generation = state.generation.fetch_add(1, Ordering::Relaxed); let (tx, rx) = watch::channel(false); - app.state::().cancels.lock().insert(id.clone(), tx); + let (done_tx, done_rx) = watch::channel(()); + let previous = state.workers.lock().insert(id.clone(), Worker { generation, cancel: tx, done: done_rx }); + let previous = previous.map(|w| { + let _ = w.cancel.send(true); + w.done + }); tauri::async_runtime::spawn(async move { + // Held until this task ends: whoever waits on `done` then knows the file is free. + let _done = done_tx; + let took_over = previous.is_some(); + if let Some(done) = previous { + exited(done).await; + } + let stopped = rx.clone(); + if *stopped.borrow() { + release(&app, &id, generation); + return; + } let permits = app.state::().permits.clone(); let _permit = tokio::select! { p = permits.acquire_owned() => p, - _ = cancelled(rx.clone()) => return, + _ = cancelled(rx.clone()) => { release(&app, &id, generation); return; } }; - let result = transfer(&app, &id, &url, rx).await; - app.state::().cancels.lock().remove(&id); + // The task it replaced may have finished the file just as it was stopped. + let result = if took_over && finished_file(&app, &id) { Ok(true) } else { transfer(&app, &id, &url, rx).await }; + release(&app, &id, generation); + // Once paused, removed or replaced, the outcome is no longer this task's to + // report, except a finished file, which is complete whatever happened since. + if *stopped.borrow() && !matches!(result, Ok(true)) { + return; + } match result { Ok(true) => { update(&app, &id, |i| { i.status = Status::Completed; + i.error = None; i.speed = 0; i.received = i.total.max(i.received); }); @@ -236,6 +277,30 @@ fn spawn(app: AppHandle, id: String, url: String) { }); } +/// Drops the worker entry, unless a newer task has taken it over. +fn release(app: &AppHandle, id: &str, generation: u64) { + let state = app.state::(); + let mut workers = state.workers.lock(); + if workers.get(id).map(|w| w.generation) == Some(generation) { + workers.remove(id); + } +} + +/// The download's file is in place and nothing is left to transfer. +fn finished_file(app: &AppHandle, id: &str) -> bool { + let Some(path) = app.state::().items.lock().iter().find(|i| i.id == id).map(|i| PathBuf::from(&i.file_path)) else { return false }; + path.exists() && !part_path(&path).exists() +} + +fn part_path(path: &Path) -> PathBuf { + path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin"))) +} + +/// Resolves once a worker task has exited. +async fn exited(mut done: watch::Receiver<()>) { + while done.changed().await.is_ok() {} +} + async fn cancelled(mut rx: watch::Receiver) { while !*rx.borrow() { if rx.changed().await.is_err() { @@ -248,10 +313,7 @@ async fn cancelled(mut rx: watch::Receiver) { async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch::Receiver) -> Result { let Some(item) = app.state::().items.lock().iter().find(|i| i.id == id).cloned() else { return Ok(false) }; let final_path = PathBuf::from(&item.file_path); - let part_path = final_path.with_extension(format!( - "{}.part", - final_path.extension().and_then(|e| e.to_str()).unwrap_or("bin") - )); + let part_path = part_path(&final_path); let existing = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0); let client = app.state::().client.clone(); @@ -259,7 +321,10 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch if existing > 0 { request = request.header("Range", format!("bytes={existing}-")); } - let response = request.send().await.map_err(|e| format!("Could not reach the server: {e}"))?; + let response = tokio::select! { + r = request.send() => r.map_err(|e| format!("Could not reach the server: {e}"))?, + _ = cancelled(rx.clone()) => return Ok(false), + }; let status = response.status(); if status.as_u16() == 401 || status.as_u16() == 403 { return Err("The server does not allow downloads for this account.".into()); @@ -336,10 +401,14 @@ async fn transfer(app: &AppHandle, id: &str, url: &str, rx: watch Ok(true) } -fn cancel(app: &AppHandle, id: &str) { - if let Some(tx) = app.state::().cancels.lock().remove(id) { - let _ = tx.send(true); - } +/// Stops the transfer for `id`, if one is running; the receiver closes once it has exited. +/// The entry stays until then, so a task started meanwhile knows to wait for it. +fn cancel(app: &AppHandle, id: &str) -> Option> { + let state = app.state::(); + let workers = state.workers.lock(); + let worker = workers.get(id)?; + let _ = worker.cancel.send(true); + Some(worker.done.clone()) } #[tauri::command] @@ -356,7 +425,7 @@ pub fn download_pause(app: AppHandle, id: String) { #[tauri::command] pub fn download_resume(app: AppHandle, id: String, url: String) { - cancel(&app, &id); + // `spawn` takes over from a transfer still winding down. update(&app, &id, |i| { i.status = Status::Queued; i.error = None; @@ -366,7 +435,7 @@ pub fn download_resume(app: AppHandle, id: String, url: String) { #[tauri::command] pub async fn download_remove(app: AppHandle, id: String, delete_files: bool) -> Result<(), String> { - cancel(&app, &id); + let running = cancel(&app, &id); let removed = { let state = app.state::(); let mut items = state.items.lock(); @@ -375,14 +444,24 @@ pub async fn download_remove(app: AppHandle, id: String, delete_f }; if let (Some(item), true) = (removed, delete_files) { let path = PathBuf::from(&item.file_path); - // Give the cancelled transfer a moment to release its file handle. - tokio::time::sleep(Duration::from_millis(150)).await; + // Let the cancelled transfer release its file handle first. + if let Some(done) = running { + let _ = tokio::time::timeout(Duration::from_secs(10), exited(done)).await; + } let _ = tokio::fs::remove_file(&path).await; - let part = path.with_extension(format!("{}.part", path.extension().and_then(|e| e.to_str()).unwrap_or("bin"))); - let _ = tokio::fs::remove_file(&part).await; + let _ = tokio::fs::remove_file(part_path(&path)).await; + // Older downloads shared artwork between a season's episodes: keep what others still use. + let in_use: HashSet = app + .state::() + .items + .lock() + .iter() + .filter_map(|i| i.meta.get("localAssets").and_then(Value::as_object)) + .flat_map(|a| a.values().filter_map(Value::as_str).map(str::to_owned)) + .collect(); if let Value::Object(assets) = &item.meta["localAssets"] { for v in assets.values() { - if let Some(p) = v.as_str() { + if let Some(p) = v.as_str().filter(|p| !in_use.contains(*p)) { let _ = tokio::fs::remove_file(p).await; } } diff --git a/src/app/queries.ts b/src/app/queries.ts index 80e5bb9..e3aceb3 100644 --- a/src/app/queries.ts +++ b/src/app/queries.ts @@ -1,7 +1,7 @@ import { QueryClient, useQuery, type UseQueryOptions } from '@tanstack/react-query'; import * as api from '../plex/api'; import type { Item, Section } from '../plex/types'; -import { useServer } from './session'; +import { useServer, useSession } from './session'; import { useSettings } from './settings'; export const queryClient = new QueryClient({ @@ -27,6 +27,13 @@ export const PROGRESS = { ...WATCH_STATE, staleTime: 15_000, refetchInterval: 60 // app doesn't change visibility, so a window focus counts as well. window.addEventListener('focus', () => queryClient.getQueryCache().onFocus()); +// Keys carry the server but not the account, and another account (or a Home profile) on +// the same server sees different watch state and libraries. Whenever the credentials +// behind the connection change, nothing cached under the old ones may be shown. +useSession.subscribe((st, prev) => { + if (prev.server && st.server !== prev.server && st.server?.token !== prev.server.token) queryClient.clear(); +}); + /** Every key starts with the server so switching servers never mixes caches. */ export function useKey(...parts: unknown[]) { const server = useServer(); diff --git a/src/downloads/store.ts b/src/downloads/store.ts index 9820dc8..d56474e 100644 --- a/src/downloads/store.ts +++ b/src/downloads/store.ts @@ -52,12 +52,16 @@ function sanitize(s: string) { return s.replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim() || 'Untitled'; } -/** Trims metadata kept for offline display: no extras, related hubs or raw blobs. */ -function slim(raw: any) { +/** + * Trims metadata kept for offline display: no extras, related hubs or raw blobs, and + * only the version downloaded, so its streams describe the file that plays. + */ +function slim(raw: any, mediaIndex: number) { const { Extras, Related, OnDeck, ...rest } = raw ?? {}; void Extras; void Related; void OnDeck; + if (Array.isArray(rest.Media) && rest.Media[mediaIndex]) rest.Media = [rest.Media[mediaIndex]]; return rest; } @@ -102,9 +106,12 @@ export const useDownloads = create((set, get) => ({ try { await get().init(); const item = await api.metadata(server, input.id); - const media = item.media[0]; + // A download is one file. A version split across several (CD1, CD2) would be + // kept as its first part only, so prefer a version in one piece. + const media = item.media.find((m) => m.parts.length === 1) ?? item.media[0]; const part = media?.parts[0]; if (!part) throw new Error('This title has no downloadable file.'); + if (media.parts.length > 1) throw new Error('This title is split across several files, which Kaleido can’t download yet.'); const id = get().idFor(item.id); if (get().items.some((d) => d.id === id && d.status !== 'failed')) { toast('This title is already in Downloads.'); @@ -129,7 +136,7 @@ export const useDownloads = create((set, get) => ({ url: server.signed(part.key, { download: 1 }), folder, fileName: sanitize(baseName), - meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw) } satisfies DownloadMeta, + meta: { serverId: server.machineId, serverName: server.name, ratingKey: item.id, partKey: part.key, raw: slim(item.raw, item.media.indexOf(media)) } satisfies DownloadMeta, assets, }, }); diff --git a/src/player/store.ts b/src/player/store.ts index ea32564..3b1439d 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -2,12 +2,14 @@ import { create } from 'zustand'; import * as api from '../plex/api'; import { directUrl, previewUrl, reportTimeline, stopTranscode, transcodeUrl, type Delivery } from '../plex/playback'; import type { Item, Stream } from '../plex/types'; +import type { PlexServer } from '../plex/client'; import { useSession } from '../app/session'; +import { useDownloads, type Download } from '../downloads/store'; import { useSettings, SUBTITLE_MARGIN, type Preferences, type Quality, type Upscaling } from '../app/settings'; import { followVideoSize, noteMpvLog, requestEnhancement, watchPerformance } from './enhance'; import { channelLabel } from '../app/format'; import { invalidateLibrary } from '../app/queries'; -import { keepAwake, isNative, win } from '../platform/native'; +import { invoke, keepAwake, isNative, win } from '../platform/native'; import { mpv, type MpvEvent, type MpvTrack } from './engine'; import { toast } from '../ui/overlays'; import { stopThemeMusic } from './theme'; @@ -32,6 +34,8 @@ export interface PlayOptions { /** A local file path (offline download). */ localFile?: string; quality?: Quality; + /** Keep these track choices (UI keys) instead of applying the preferences again. */ + tracks?: { audioKey: string; subKey: string }; } interface PlayerState { @@ -113,7 +117,16 @@ let loadToken = 0; let wasFullscreenBeforePlay = false; let pendingExternal: Track | null = null; -const server = () => useSession.getState().server; +/** + * The server this playback belongs to, fixed when it starts. Progress, watched state + * and transcodes always go there, never to whichever server is selected later. A + * download plays without one unless its own server is the one connected. + */ +let playServer: PlexServer | null = null; +/** The download being played, whose saved metadata keeps the offline resume point. */ +let playDownload: Download | null = null; + +const server = () => playServer; /** * mpv applies its volume on a cubic curve, so halfway on a linear slider was @@ -218,8 +231,34 @@ async function applySubtitleStyle(prefs: Preferences = useSettings.getState()) { } } +/** A download's watch was counted this session; its resume point stays cleared. */ +let localScrobbled = false; + +/** + * Keeps a download's resume point (or, once watched, its watch count) in its saved + * metadata, which is all an offline title has to resume from. + */ +function saveLocalProgress(watched = false) { + const d = playDownload; + const { item, position, delivery, firstFrame } = usePlayer.getState(); + // Before the first frame the position is only where it was asked to start. + if (!d || !item || delivery?.mode !== 'local' || !firstFrame || (localScrobbled && !watched)) return; + const raw = { ...(d.meta.raw ?? {}) }; + if (watched) { + if (localScrobbled) return; + localScrobbled = true; + raw.viewOffset = 0; + raw.viewCount = (Number(raw.viewCount) || 0) + 1; + raw.lastViewedAt = Math.floor(Date.now() / 1000); + } else raw.viewOffset = Math.max(0, Math.round(position * 1000)); + const meta = { ...d.meta, raw }; + playDownload = { ...d, meta }; + invoke('download_write_meta', { id: d.id, meta }).catch(() => {}); +} + /** Reports progress to Plex; resolves true if the reply says the stream was stopped. */ function report(state: 'playing' | 'paused' | 'buffering' | 'stopped'): Promise { + if (state === 'paused' || state === 'stopped') saveLocalProgress(); const s = server(); const { item, position, delivery } = usePlayer.getState(); if (!s || !item || !session || item.type === 'clip') return Promise.resolve(false); @@ -266,9 +305,11 @@ function onTerminated(text: string) { function checkScrobble() { const { item, position, duration } = usePlayer.getState(); const s = server(); - if (!item || !s || scrobbled || !duration || item.type === 'clip') return; + if (!item || scrobbled || !duration || item.type === 'clip') return; const percent = useSettings.getState().watchedPercent; if (position / duration >= percent / 100) { + saveLocalProgress(true); + if (!s) return; scrobbled = true; api .setWatched(s, item.id, true) @@ -317,25 +358,12 @@ function stopCountdown() { countdownTimer = null; } -/** Applies Plex/user track preferences once mpv has loaded the file. */ -async function applyInitialTracks(tracks: MpvTrack[]) { - const st = usePlayer.getState(); - const prefs = useSettings.getState(); - const direct = st.delivery?.mode !== 'transcode'; - const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); - - let audio = st.audioTracks; - let subs = st.subTracks; - if (direct) { - audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); - subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); - // Files without Plex stream info (offline) use mpv's own list. - if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); - if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); - } - - // Audio: preferred language, else Plex's selection, else the file default. - let audioKey = st.audioKey; +/** + * The tracks to play: a choice already made is kept ('' audio and '__init' subtitles + * mean none yet), otherwise the preferred audio language, then Plex's selection, then + * the file default; subtitles follow the subtitle mode. + */ +function preferredTracks(audio: Track[], subs: Track[], prefs: Preferences, audioKey = '', subKey = '__init') { if (!audioKey) { const lang = prefs.audioLanguage; audioKey = @@ -345,8 +373,6 @@ async function applyInitialTracks(tracks: MpvTrack[]) { audio[0]?.key || ''; } - // Subtitles: follow the subtitle mode. - let subKey = st.subKey; if (subKey === '__init') { const lang = prefs.subtitleLanguage || audio.find((t) => t.key === audioKey)?.language || ''; const inLang = subs.filter((t) => !lang || t.language === lang); @@ -364,6 +390,87 @@ async function applyInitialTracks(tracks: MpvTrack[]) { subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? ''; } } + return { audioKey, subKey }; +} + +type Selection = { audioStreamID?: string; subtitleStreamID?: string }; + +/** The item with Plex's stream selection updated locally to match `sel`. */ +function withSelection(item: Item, mediaIndex: number, sel: Selection): Item { + const media = item.media.map((m, i) => + i !== mediaIndex + ? m + : { + ...m, + parts: m.parts.map((p) => ({ + ...p, + streams: p.streams.map((x) => + x.streamType === 2 && sel.audioStreamID !== undefined + ? { ...x, selected: x.id === sel.audioStreamID } + : x.streamType === 3 && sel.subtitleStreamID !== undefined + ? { ...x, selected: x.id === sel.subtitleStreamID } + : x, + ), + })), + }, + ); + return { ...item, media }; +} + +const streamId = (tracks: Track[], key: string) => tracks.find((t) => t.key === key)?.stream?.id; + +/** + * What Plex must be told so its selection on this media matches the given streams + * (subtitle '' is none, undefined leaves either as it is). Empty if it already does. + */ +function selectionFor(item: Item, mediaIndex: number, audioId: string | undefined, subId: string | undefined): Selection { + const streams = item.media[mediaIndex]?.parts.flatMap((p) => p.streams) ?? []; + const sel: Selection = {}; + if (audioId && !streams.some((x) => x.streamType === 2 && x.selected && x.id === audioId)) sel.audioStreamID = audioId; + if (subId !== undefined && (streams.find((x) => x.streamType === 3 && x.selected)?.id ?? '') !== subId) sel.subtitleStreamID = subId || '0'; + return sel; +} + +/** Saves a track choice on the server; resolves to the item with that selection. */ +async function saveSelection(s: PlexServer, item: Item, mediaIndex: number, sel: Selection): Promise { + const part = item.media[mediaIndex]?.parts[0]; + if (!part || (sel.audioStreamID === undefined && sel.subtitleStreamID === undefined)) return item; + await api.selectStreams(s, part.id, sel); + return withSelection(item, mediaIndex, sel); +} + +/** Saves a choice made during direct play, so other Plex apps (and a later conversion) use it too. */ +function rememberSelection(st: PlayerState, audioId: string | undefined, subId: string | undefined) { + const s = server(); + const { item, mediaIndex } = st; + if (!s || !item) return; + const sel = selectionFor(item, mediaIndex, audioId, subId); + saveSelection(s, item, mediaIndex, sel) + .then(() => { + const now = usePlayer.getState(); + if (now.item?.id === item.id && now.mediaIndex === mediaIndex) usePlayer.setState({ item: withSelection(now.item, mediaIndex, sel) }); + }) + .catch(() => {}); +} + +/** Applies Plex/user track preferences once mpv has loaded the file. */ +async function applyInitialTracks(tracks: MpvTrack[]) { + const st = usePlayer.getState(); + const prefs = useSettings.getState(); + const direct = st.delivery?.mode !== 'transcode'; + const byFF = (type: string, idx: number) => tracks.find((t) => t.type === type && t['ff-index'] === idx && !t.external); + + let audio = st.audioTracks; + let subs = st.subTracks; + if (direct) { + audio = audio.map((t) => ({ ...t, mpvId: t.stream ? (byFF('audio', t.stream.index)?.id ?? null) : t.mpvId })); + subs = subs.map((t) => ({ ...t, mpvId: t.stream && !t.external ? (byFF('sub', t.stream.index)?.id ?? null) : t.mpvId })); + // Files without Plex stream info (offline) use mpv's own list. + if (!audio.length) audio = tracks.filter((t) => t.type === 'audio').map(mpvTrackLabel); + if (!subs.length) subs = tracks.filter((t) => t.type === 'sub').map(mpvTrackLabel); + } + + const { audioKey, subKey } = preferredTracks(audio, subs, prefs, st.audioKey, st.subKey); usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey }); if (direct) { const a = audio.find((t) => t.key === audioKey); @@ -501,6 +608,9 @@ function onEvent(e: MpvEvent) { } } +/** The tracks playing now, to carry over when the same media restarts (a choice not made yet stays open). */ +const currentTracks = (st: PlayerState) => ({ audioKey: st.audioKey, subKey: st.subKey }); + /** Direct play failed: retry once through Plex's converter. */ let triedFallback = false; function fallbackAfterError() { @@ -509,7 +619,7 @@ function fallbackAfterError() { triedFallback = true; toast('Direct playback failed. Asking Plex to convert this video.'); usePlayer.setState({ error: '' }); - st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080' }); + st.play(st.item, { offsetMs: st.position * 1000 || startOffsetMs, mediaIndex: st.mediaIndex, quality: '1080', tracks: currentTracks(st) }); } function maybeCredits(pos: number) { @@ -567,7 +677,8 @@ export const usePlayer = create((set, get) => ({ async play(input, opts = {}) { const token = ++loadToken; - const s = server(); + // Closing or starting something else while this one is still setting up wins. + const stale = () => token !== loadToken; const prefs = useSettings.getState(); stopThemeMusic(); stopCountdown(); @@ -576,13 +687,25 @@ export const usePlayer = create((set, get) => ({ return; } const previous = get(); + // The previous title's reporting ends here, against its own server. + if (reportTimer) clearInterval(reportTimer); + reportTimer = null; if (previous.open && previous.item) { report('stopped'); - if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session); + const ps = server(); + if (previous.delivery?.session && ps) stopTranscode(ps, previous.delivery.session); } + session = ''; + const current = useSession.getState().server; + const download = opts.localFile ? (useDownloads.getState().items.find((d) => d.filePath === opts.localFile) ?? null) : null; + const s = opts.localFile ? (current && download && current.machineId === download.meta.serverId ? current : null) : current; + playServer = s; + playDownload = download; + localScrobbled = false; if (!previous.open) { triedFallback = false; wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false); + if (stale()) return; } set({ open: true, @@ -604,8 +727,8 @@ export const usePlayer = create((set, get) => ({ chapters: [], audioTracks: [], subTracks: [], - audioKey: '', - subKey: '__init', + audioKey: opts.tracks?.audioKey ?? '', + subKey: opts.tracks?.subKey ?? '__init', video: null, fullscreen: wasFullscreenBeforePlay, mini: false, @@ -619,16 +742,16 @@ export const usePlayer = create((set, get) => ({ if (!opts.localFile && s && (!input.media.length || !input.media[0].parts[0]?.streams.length || !input.raw?.Marker)) { item = await api.metadata(s, input.id).catch(() => input); } - if (token !== loadToken) return; + if (stale()) return; const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1)); - const media = item.media[mediaIndex]; + let media = item.media[mediaIndex]; let offsetMs = opts.offsetMs ?? (opts.resume !== false && item.viewOffset && item.viewOffset < item.duration * 0.97 ? item.viewOffset : 0); - startOffsetMs = offsetMs; const local = useSession.getState().connection?.local ?? true; const quality: Quality = opts.quality ?? (local ? prefs.quality : prefs.remoteQuality); - session = crypto.randomUUID(); - sessionAnswered = false; - scrobbled = false; + const streams = media?.parts.flatMap((p) => p.streams) ?? []; + const audioTracks = streams.filter((x) => x.streamType === 2).map(audioTrackFromStream); + const subTracks = streams.filter((x) => x.streamType === 3).map(subTrackFromStream); + let tracks: { audioKey: string; subKey: string } | null = null; let delivery: Delivery; if (opts.localFile) { @@ -638,30 +761,43 @@ export const usePlayer = create((set, get) => ({ } else if (quality === 'original') { delivery = { url: directUrl(s, media), mode: 'direct', label: 'Original', absoluteTime: false }; } else { + // Plex converts (and burns in) the tracks selected on the server, so the chosen + // ones are saved there before the conversion starts, not after. + tracks = preferredTracks(audioTracks, subTracks, prefs, opts.tracks?.audioKey, opts.tracks?.subKey); + const audioStreamID = streamId(audioTracks, tracks.audioKey); + const subtitleStreamID = streamId(subTracks, tracks.subKey) ?? ''; + const base = item; + item = await saveSelection(s, base, mediaIndex, selectionFor(base, mediaIndex, audioStreamID, subtitleStreamID)).catch(() => base); + if (stale()) return; + media = item.media[mediaIndex]; const tsession = crypto.randomUUID(); delivery = { - url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }), + url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local, audioStreamID, subtitleStreamID: subtitleStreamID || undefined }), mode: 'transcode', session: tsession, label: quality === '2160' ? '4K' : `${quality}p`, absoluteTime: true, }; } + startOffsetMs = offsetMs; + session = crypto.randomUUID(); + sessionAnswered = false; + scrobbled = false; - const streams = media?.parts.flatMap((p) => p.streams) ?? []; set({ item, delivery, mediaIndex, quality, duration: (item.duration || media?.duration || 0) / 1000, - audioTracks: streams.filter((x) => x.streamType === 2).map(audioTrackFromStream), - subTracks: streams.filter((x) => x.streamType === 3).map(subTrackFromStream), + audioTracks, + subTracks, + ...(tracks ?? {}), }); await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough }); if (!unlisten) unlisten = await mpv.on(onEvent); - if (token !== loadToken) return; + if (stale()) return; // mpv keeps pause across files: a title paused and closed would start paused. await mpv.set('pause', false); await mpv.set('mute', false); @@ -669,16 +805,21 @@ export const usePlayer = create((set, get) => ({ await mpv.set('speed', 1); await mpv.set('audio-delay', 0); await applySubtitleStyle(prefs); + if (stale()) return; followVideoSize(); await requestEnhancement(); + if (stale()) return; watchPerformance(true); await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title); + if (stale()) return; await mpv.show(true); + if (stale()) return; const fileOpts = [ delivery.mode === 'transcode' ? 'rebase-start-time=no' : 'rebase-start-time=yes', offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none', ].join(','); await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts); + if (stale()) return; keepAwake(true); report('buffering'); reportTimer && clearInterval(reportTimer); @@ -702,6 +843,10 @@ export const usePlayer = create((set, get) => ({ if (st.item && !st.error) report('stopped'); const s = server(); if (st.delivery?.session && s) stopTranscode(s, st.delivery.session); + // Nothing more is reported for this playback, whatever mpv says while it stops. + session = ''; + playServer = null; + playDownload = null; keepAwake(false); watchPerformance(false); if (isNative) { @@ -794,35 +939,30 @@ export const usePlayer = create((set, get) => ({ const t = st.audioTracks.find((x) => x.key === key); if (!t) return; set({ audioKey: key }); - const s = server(); - const part = st.item?.media[st.mediaIndex]?.parts[0]; - if (s && part && t.stream) api.selectStreams(s, part.id, { audioStreamID: t.stream.id }).catch(() => {}); if (st.delivery?.mode === 'transcode' && st.item) { - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality }); + // The restart saves the choice on the server before converting with it. + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), audioKey: key } }); return; } if (t.mpvId) await mpv.set('aid', t.mpvId).catch(() => {}); + rememberSelection(st, t.stream?.id, undefined); }, async selectSubtitle(key) { const st = get(); set({ subKey: key }); - const s = server(); - const part = st.item?.media[st.mediaIndex]?.parts[0]; - const t = st.subTracks.find((x) => x.key === key); - if (s && part) api.selectStreams(s, part.id, { subtitleStreamID: t?.stream?.id ?? '0' }).catch(() => {}); if (st.delivery?.mode === 'transcode' && st.item) { - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality }); - usePlayer.setState({ subKey: key }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: st.quality, tracks: { ...currentTracks(st), subKey: key } }); return; } await setMpvSubtitle(key); + rememberSelection(st, undefined, streamId(st.subTracks, key) ?? ''); }, async setQuality(q) { const st = get(); if (!st.item || q === st.quality) return; - await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q }); + await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: st.mediaIndex, quality: q, tracks: currentTracks(st) }); }, async selectVersion(index) { @@ -885,6 +1025,24 @@ usePlayer.subscribe((st, prev) => { bridgeMiniWindow(usePlayer); +/** + * Signing out, or switching server or profile, ends a stream from the old one: its + * progress belongs to that account. A download keeps playing, without reporting. + * A reconnect to the same server with the same credentials carries on. + */ +useSession.subscribe((st, prev) => { + const old = prev.server; + if (!old || st.server === old) return; + const same = !!st.server && st.server.machineId === old.machineId && st.server.token === old.token; + if (playServer !== old) return; + if (same) { + playServer = st.server; + return; + } + if (usePlayer.getState().open && !playDownload) usePlayer.getState().close(); + playServer = null; +}); + /** Subtitle look changes apply to the playing video straight away. */ const SUBTITLE_PREFS = ['subtitleScale', 'subtitleColor', 'subtitleEdge', 'subtitleBox', 'subtitleBold', 'subtitlePosition'] as const; useSettings.subscribe((prefs, prev) => { diff --git a/src/plex/client.ts b/src/plex/client.ts index 3548c35..a64ce79 100644 --- a/src/plex/client.ts +++ b/src/plex/client.ts @@ -121,23 +121,41 @@ export async function plexRequest(url: string, token: string | null | u const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000); const onAbort = () => controller.abort(); opts.signal?.addEventListener('abort', onAbort); + // The timeout and the caller's cancel cover the body as well as the headers: a reply + // that stalls part way must still end. (Rejects only once aborted.) + const aborted = new Promise((_, reject) => + controller.signal.addEventListener('abort', () => reject(opts.signal?.aborted ? opts.signal.reason : new PlexError('The server took too long to respond.', 0)), { once: true }), + ); + aborted.catch(() => {}); + if (opts.signal?.aborted) controller.abort(); let response: Response; + let text: string; try { - response = await httpFetch(withParams(url, opts.params), { - method: opts.method ?? 'GET', - headers: { ...plexHeaders(token), ...opts.headers }, - body: opts.body ?? undefined, - signal: controller.signal, - }); - } catch (e: any) { - if (opts.signal?.aborted) throw e; - throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0); + try { + response = await Promise.race([ + httpFetch(withParams(url, opts.params), { + method: opts.method ?? 'GET', + headers: { ...plexHeaders(token), ...opts.headers }, + body: opts.body ?? undefined, + signal: controller.signal, + }), + aborted, + ]); + } catch (e: any) { + if (opts.signal?.aborted) throw e; + throw new PlexError(controller.signal.aborted ? 'The server took too long to respond.' : 'Could not reach the server.', 0); + } + if (!response.ok) throw new PlexError(statusMessage(response.status), response.status); + try { + text = await Promise.race([response.text(), aborted]); + } catch (e: any) { + if (opts.signal?.aborted || e instanceof PlexError) throw e; + throw new PlexError('The connection to the server was lost.', 0); + } } finally { clearTimeout(timer); opts.signal?.removeEventListener('abort', onAbort); } - if (!response.ok) throw new PlexError(statusMessage(response.status), response.status); - const text = await response.text(); if (opts.text) return text as unknown as T; if (!text.trim()) return {} as T; try { diff --git a/src/plex/playback.ts b/src/plex/playback.ts index 60408da..39464b1 100644 --- a/src/plex/playback.ts +++ b/src/plex/playback.ts @@ -39,6 +39,10 @@ export function transcodeUrl( path: `/library/metadata/${item.id}`, mediaIndex: opts.mediaIndex, partIndex: 0, + // Plex converts the part's selected streams; callers save the selection first and + // name it here as well. + audioStreamID: opts.audioStreamID, + subtitleStreamID: opts.subtitleStreamID, protocol: 'hls', session: opts.session, offset: (opts.offsetMs / 1000).toFixed(1), diff --git a/src/screens/LibraryBrowser.tsx b/src/screens/LibraryBrowser.tsx index 70d9cae..6d7e9c7 100644 --- a/src/screens/LibraryBrowser.tsx +++ b/src/screens/LibraryBrowser.tsx @@ -236,6 +236,33 @@ function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { secti loadPage(0); }, [loadPage]); + // Pages are copied out of the cache, so nothing re-renders when it is invalidated + // (watched state, edits, deletions, library changes): fetch the loaded ones again. + const loaded = useRef(pages); + loaded.current = pages; + useEffect(() => { + const prefix = JSON.stringify([server.machineId, 'libraryPage', section.id, params]); + const due = new Set(); + let timer: ReturnType | null = null; + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { + if (event.type !== 'updated' || event.action.type !== 'invalidate') return; + const key = event.query.queryKey; + const p = key[4]; + if (typeof p !== 'number' || !loaded.current[p] || JSON.stringify(key.slice(0, 4)) !== prefix) return; + due.add(p); + // One pass after the whole invalidation, not one per page as it happens. + timer ??= setTimeout(() => { + timer = null; + for (const page of due) loadPage(page); + due.clear(); + }); + }); + return () => { + unsubscribe(); + if (timer) clearTimeout(timer); + }; + }, [loadPage]); + const gap = 16; const target = CARD_WIDTH[posterSize]; const cols = Math.max(2, Math.floor((width + gap) / (target + gap))); diff --git a/src/ui/Hero.tsx b/src/ui/Hero.tsx index cc85c9c..122163a 100644 --- a/src/ui/Hero.tsx +++ b/src/ui/Hero.tsx @@ -43,14 +43,14 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari img.decode?.().catch(() => {}); }, [upcoming?.id]); + // Pause rotation when the hero is scrolled away; it picks up again on its return. + const [visible, setVisible] = useState(true); useEffect(() => { - if (!rotate || reduced || count < 2 || hover) return; + if (!rotate || reduced || count < 2 || hover || !visible) return; const t = setTimeout(() => go(index + 1), ROTATE_MS); return () => clearTimeout(t); - }, [index, rotate, reduced, count, hover]); + }, [index, rotate, reduced, count, hover, visible]); - // Pause rotation when the hero is scrolled away. - const [visible, setVisible] = useState(true); useEffect(() => { const el = root.current; if (!el) return; @@ -60,7 +60,6 @@ export function Hero({ features, variant = 'home' }: { features: Feature[]; vari }, []); const go = (i: number) => { - if (!visible && i !== index) return; setIndex(((i % count) + count) % count); setCopyKey((k) => k + 1); }; diff --git a/src/ui/media.tsx b/src/ui/media.tsx index da07294..11b9136 100644 --- a/src/ui/media.tsx +++ b/src/ui/media.tsx @@ -1,6 +1,6 @@ import { memo, useEffect, useRef, useState, type ReactNode } from 'react'; import type { Item } from '../plex/types'; -import { useServer } from '../app/session'; +import { useServer, useSession } from '../app/session'; import { useSettings } from '../app/settings'; import { art, displayTitle, duration, episodeLabel, formatBadges, isWatched, progress, remaining, remainingEpisodes } from '../app/format'; import { itemMenu, openItem, playWithVersion } from '../app/actions'; @@ -90,7 +90,8 @@ export function Facts({ item, withFormats = true, episode = true, children }: { /** Original clear-logo artwork, falling back to the title in type. */ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight = 130, as: As = 'h1' }: { item: Item; logo?: string; className?: string; maxWidth?: number; maxHeight?: number; as?: 'h1' | 'h2' }) { - const server = useServer(); + // The player shows this offline too, where there is no server to draw the logo from. + const server = useSession((s) => s.server); const path = logo ?? item.logo; const [failed, setFailed] = useState(false); const [ready, setReady] = useState(false); @@ -99,7 +100,7 @@ export function TitleArt({ item, logo, className = '', maxWidth = 420, maxHeight setReady(false); }, [path]); const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title; - if (!path || failed) + if (!path || failed || !server) return ( {title} From b5dc5d8666278eddfcc89bf9fecfdd367aabb2ed Mon Sep 17 00:00:00 2001 From: Elijah Date: Fri, 6 Nov 2026 19:29:16 -0700 Subject: [PATCH 15/34] Blend the colour wash between titles and keep full screen for the miniplayer - The backdrop's colour wash is one layer whose corner colours are registered custom properties, so a change of title blends them instead of stacking a half-opacity layer and removing the old one (which made the colour jump). Outgoing artwork fades out before it is removed, and quick changes keep the layer that is on screen. - Going to the miniplayer no longer leaves full screen. Esc while browsing leaves full screen first, Windows' caption buttons show Exit full screen in place of maximize, closing the miniplayer keeps the window as it is, and the player's full-screen state follows changes made outside it. Co-Authored-By: Claude Opus 5.5 --- src/app/App.tsx | 6 +++-- src/app/TopBar.tsx | 26 +++++++++++++----- src/app/format.ts | 21 ++++++++++----- src/player/store.ts | 29 +++++++++++++------- src/styles/app.css | 42 ++++++++++++++++++++++++++--- src/ui/Backdrop.tsx | 65 ++++++++++++++++++++++++++++----------------- 6 files changed, 135 insertions(+), 54 deletions(-) diff --git a/src/app/App.tsx b/src/app/App.tsx index 6623697..c0e8786 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -11,7 +11,7 @@ import { PageLoader } from '../ui/primitives'; import { Splash } from '../screens/Splash'; import { SignIn } from '../screens/SignIn'; import { ServerPicker } from '../screens/ServerPicker'; -import { isMac, win } from '../platform/native'; +import { isMac, isNative, win } from '../platform/native'; import { usePlayer } from '../player/store'; import { PlayerOverlay } from '../player/PlayerOverlay'; import { DialogHost } from '../screens/dialogs/DialogHost'; @@ -111,7 +111,9 @@ function useGlobalShortcuts() { win.isFullscreen().then((fs) => win.setFullscreen(!fs)); } else if ((e.key === 'Escape' || e.key === 'Backspace') && !isTyping(e.target) && !document.querySelector('.menu-layer, .dialog-layer')) { if (e.key === 'Escape' && document.fullscreenElement) return; - useRouter.getState().back(); + // Esc leaves full screen first (kept from the player when it went to the corner). + if (e.key === 'Escape' && isNative) win.isFullscreen().then((fs) => (fs ? win.setFullscreen(false) : useRouter.getState().back())); + else useRouter.getState().back(); } else if ((e.ctrlKey || e.metaKey) && e.key === ',') { e.preventDefault(); navigate({ name: 'settings', mode: 'app', tab: 'general' }); diff --git a/src/app/TopBar.tsx b/src/app/TopBar.tsx index 3c538fc..6007226 100644 --- a/src/app/TopBar.tsx +++ b/src/app/TopBar.tsx @@ -19,13 +19,21 @@ const NAV = [ /** Caption buttons drawn by the page; macOS shows its own traffic lights instead. */ export function WindowControls() { const [maximized, setMaximized] = useState(false); + const [fullscreen, setFullscreen] = useState(false); useEffect(() => { if (!isNative || isMac) return; let off: (() => void) | undefined; - const sync = () => win.isMaximized().then(setMaximized); + let gone = false; + const sync = () => { + win.isMaximized().then((m) => !gone && setMaximized(m)); + win.isFullscreen().then((f) => !gone && setFullscreen(f)); + }; sync(); - win.onResized(sync).then((u) => (off = u)); - return () => off?.(); + win.onResized(sync).then((u) => (gone ? u() : (off = u))); + return () => { + gone = true; + off?.(); + }; }, []); if (!isNative || isMac) return null; return ( @@ -33,9 +41,15 @@ export function WindowControls() { - + {fullscreen ? ( + + ) : ( + + )} diff --git a/src/app/format.ts b/src/app/format.ts index 47d138a..a41b82d 100644 --- a/src/app/format.ts +++ b/src/app/format.ts @@ -174,17 +174,24 @@ export function plural(n: number, word: string, pluralWord = `${word}s`) { return `${n.toLocaleString()} ${n === 1 ? word : pluralWord}`; } -/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */ -export function washGradient(u: Item['ultraBlur'], strength = 1): string { - if (!u) return ''; +/** Hex UltraBlur colors → the wash's four corner colours, each at its own strength. */ +export function washColors(u: Item['ultraBlur'], strength = 1) { + if (!u) return null; const c = (hex: string, a: number) => { const n = parseInt(hex, 16); return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${(a * strength).toFixed(3)})`; }; + return { topRight: c(u.topRight, 0.95), topLeft: c(u.topLeft, 0.7), bottomRight: c(u.bottomRight, 0.55), bottomLeft: c(u.bottomLeft, 0.45) }; +} + +/** Hex UltraBlur colors → CSS gradient layers for the artwork colour wash. */ +export function washGradient(u: Item['ultraBlur'], strength = 1): string { + const c = washColors(u, strength); + if (!c) return ''; return [ - `radial-gradient(ellipse at 100% 0%, ${c(u.topRight, 0.95)} 0%, transparent 62%)`, - `radial-gradient(ellipse at 0% 0%, ${c(u.topLeft, 0.7)} 0%, transparent 55%)`, - `radial-gradient(ellipse at 100% 100%, ${c(u.bottomRight, 0.55)} 0%, transparent 60%)`, - `radial-gradient(ellipse at 0% 100%, ${c(u.bottomLeft, 0.45)} 0%, transparent 60%)`, + `radial-gradient(ellipse at 100% 0%, ${c.topRight} 0%, transparent 62%)`, + `radial-gradient(ellipse at 0% 0%, ${c.topLeft} 0%, transparent 55%)`, + `radial-gradient(ellipse at 100% 100%, ${c.bottomRight} 0%, transparent 60%)`, + `radial-gradient(ellipse at 0% 100%, ${c.bottomLeft} 0%, transparent 60%)`, ].join(', '); } diff --git a/src/player/store.ts b/src/player/store.ts index 3b1439d..ca60b1e 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -702,10 +702,12 @@ export const usePlayer = create((set, get) => ({ playServer = s; playDownload = download; localScrobbled = false; + // From the miniplayer the window may have gone full screen (or left it) since. + const fullscreenNow = await win.isFullscreen().catch(() => false); + if (stale()) return; if (!previous.open) { triedFallback = false; - wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false); - if (stale()) return; + wasFullscreenBeforePlay = fullscreenNow; } set({ open: true, @@ -730,7 +732,7 @@ export const usePlayer = create((set, get) => ({ audioKey: opts.tracks?.audioKey ?? '', subKey: opts.tracks?.subKey ?? '__init', video: null, - fullscreen: wasFullscreenBeforePlay, + fullscreen: fullscreenNow, mini: false, videoGamma: '', enhance: { ...previous.enhance, bypass: false, preparing: false }, @@ -856,8 +858,12 @@ export const usePlayer = create((set, get) => ({ await mpv.show(false).catch(() => {}); } set({ open: false, mini: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); - const fs = await win.isFullscreen().catch(() => false); - if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false); + // Closing the full player hands back the window it found; closing the + // miniplayer leaves browsing as it is, full screen or not. + if (!st.mini) { + const fs = await win.isFullscreen().catch(() => false); + if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false); + } if (st.item) invalidateLibrary(); }, @@ -913,12 +919,8 @@ export const usePlayer = create((set, get) => ({ async minimize() { const st = get(); if (!st.open || st.mini) return; + // Full screen stays for browsing; Esc or the window controls leave it. set({ mini: true }); - // Full screen was for the video; browsing goes back to the window. - if (st.fullscreen && !wasFullscreenBeforePlay) { - await win.setFullscreen(false).catch(() => {}); - set({ fullscreen: false }); - } if (separateMini) { // Once the page is opaque again (no video in it), the video moves into // the miniplayer's own window (miniWindow.ts). @@ -1025,6 +1027,13 @@ usePlayer.subscribe((st, prev) => { bridgeMiniWindow(usePlayer); +// Full screen can change outside the player (Esc or the window controls while +// browsing with the miniplayer, the OS): the player's controls follow it. +win.onResized(() => { + if (!usePlayer.getState().open) return; + win.isFullscreen().then((fs) => usePlayer.getState().fullscreen !== fs && usePlayer.setState({ fullscreen: fs }), () => {}); +}); + /** * Signing out, or switching server or profile, ends a stream from the old one: its * progress belongs to that account. A download keeps playing, without reporting. diff --git a/src/styles/app.css b/src/styles/app.css index a1d258e..8f670c6 100644 --- a/src/styles/app.css +++ b/src/styles/app.css @@ -515,6 +515,12 @@ html.splash-arrival .auth-screen { .backdrop-layer.ready { opacity: 1; } +/* The outgoing art fades too, a beat behind the incoming, so nothing of it is + left to vanish through the new art's faded edges. */ +.backdrop-layer.ready.leaving { + opacity: 0; + transition-delay: 180ms; +} /* The colour wash lives outside the clipped backdrop so it can carry on down the page behind the rows, fading out as it goes. */ .backdrop-tint { @@ -528,14 +534,42 @@ html.splash-arrival .auth-screen { -webkit-mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%); mask-image: linear-gradient(180deg, #000 0%, rgba(0, 0, 0, 0.75) 45%, transparent 100%); } +/* Registered as colours so a change of title blends the wash from one set of + colours to the next, instead of swapping the gradient outright. */ +@property --wash-tr { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-tl { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-br { + syntax: ''; + inherits: false; + initial-value: transparent; +} +@property --wash-bl { + syntax: ''; + inherits: false; + initial-value: transparent; +} .backdrop-wash { position: absolute; inset: 0; - opacity: 0; - transition: opacity 420ms var(--ease); -} -.backdrop-wash.ready { opacity: 0.5; + background: + radial-gradient(ellipse at 100% 0%, var(--wash-tr) 0%, transparent 62%), + radial-gradient(ellipse at 0% 0%, var(--wash-tl) 0%, transparent 55%), + radial-gradient(ellipse at 100% 100%, var(--wash-br) 0%, transparent 60%), + radial-gradient(ellipse at 0% 100%, var(--wash-bl) 0%, transparent 60%); + transition: + --wash-tr 700ms var(--ease), + --wash-tl 700ms var(--ease), + --wash-br 700ms var(--ease), + --wash-bl 700ms var(--ease); } .backdrop-art { position: absolute; diff --git a/src/ui/Backdrop.tsx b/src/ui/Backdrop.tsx index 15116b6..f3338a9 100644 --- a/src/ui/Backdrop.tsx +++ b/src/ui/Backdrop.tsx @@ -1,21 +1,25 @@ -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, type CSSProperties } from 'react'; import type { Item } from '../plex/types'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -import { art, washGradient } from '../app/format'; +import { art, washColors } from '../app/format'; interface Layer { key: number; src: string; - wash: string; + blur: Item['ultraBlur']; ready: boolean; } +/** How long an outgoing layer lingers: its fade (with delay) plus a margin. */ +const LEAVE_MS = 700; + /** * Artwork-led page background. The image sits top-right and fades into the * page toward its left and bottom edges; the UltraBlur colour wash tints the - * page beneath it and carries on down behind the rows. Changes crossfade; the - * outgoing layer stays until the new image has decoded. + * page beneath it and carries on down behind the rows. Artwork crossfades + * once the new image has decoded, and the wash's colours blend into the new + * title's at the same moment (registered custom properties, app.css). */ export function Backdrop({ item, className = '', width = 1600, height = 900, wash: forceWash }: { item: Item | null | undefined; className?: string; width?: number; height?: number; wash?: Item['ultraBlur'] }) { const server = useServer(); @@ -25,39 +29,50 @@ export function Backdrop({ item, className = '', width = 1600, height = 900, was const path = item ? art.backdrop(item) : ''; const src = path ? server.image(path, width, height) : ''; const blur = forceWash ?? item?.ultraBlur ?? null; - const wash = colorWash && blur ? washGradient(blur) : ''; + const blurKey = blur ? `${blur.topLeft}${blur.topRight}${blur.bottomRight}${blur.bottomLeft}` : ''; useEffect(() => { - if (!src && !wash) return; + if (!src && !blur) return; setLayers((prev) => { - if (prev.length && prev[prev.length - 1].src === src) { - // Same art, maybe new wash. - return prev.map((l, i) => (i === prev.length - 1 ? { ...l, wash } : l)); - } - return [...prev.slice(-1), { key: ++counter.current, src, wash, ready: !src }]; + const last = prev[prev.length - 1]; + // Same art, maybe new colours: the wash blends to them in place. + if (last && last.src === src) return prev.map((l) => (l === last ? { ...l, blur } : l)); + // Keep only what is on screen (the newest layer that has shown) under the new one. + const shown = prev.filter((l) => l.ready).slice(-1); + return [...shown, { key: ++counter.current, src, blur, ready: !src }]; }); - }, [src, wash]); + }, [src, blurKey]); - const onReady = (key: number) => - setLayers((prev) => { - const idx = prev.findIndex((l) => l.key === key); - if (idx < 0) return prev; - const next = prev.map((l) => (l.key === key ? { ...l, ready: true } : l)); - // Drop older layers once the newest is visible (after its fade). - setTimeout(() => setLayers((p) => (p.length > 1 && p[p.length - 1].key === key ? p.slice(-1) : p)), 500); - return next; - }); + const onReady = (key: number) => setLayers((prev) => (prev.some((l) => l.key === key && !l.ready) ? prev.map((l) => (l.key === key ? { ...l, ready: true } : l)) : prev)); + + // Once the newest layer is in, the ones beneath fade out and then go. + const newest = layers[layers.length - 1]; + useEffect(() => { + if (!newest?.ready || layers.length < 2) return; + const t = setTimeout(() => setLayers((p) => (p[p.length - 1]?.key === newest.key ? p.slice(-1) : p)), LEAVE_MS); + return () => clearTimeout(t); + }, [newest?.key, newest?.ready, layers.length]); + + let top = -1; + layers.forEach((l, i) => l.ready && (top = i)); + const colors = top >= 0 ? washColors(layers[top].blur) : null; + const washStyle = { + '--wash-tr': colors?.topRight ?? 'transparent', + '--wash-tl': colors?.topLeft ?? 'transparent', + '--wash-br': colors?.bottomRight ?? 'transparent', + '--wash-bl': colors?.bottomLeft ?? 'transparent', + } as CSSProperties; return ( <> {colorWash && (