diff --git a/CHANGELOG.md b/CHANGELOG.md index 89d5b1c..6656595 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,61 +1,5 @@ # Changelog -## 1.0.1 - -A quicker start, a Stop button, and recovery when the server drops out mid-video. - -- Kaleido starts faster: the opening animation is shorter, so you reach your library in about a second. -- The player has a Stop button, next to the forward controls, which closes the player completely instead of moving it to the miniplayer. -- If your Plex server goes down while you're watching, the player waits for it once the buffered video runs out, then carries on from the same spot when the server is back. Before, it treated the video as finished and Play started it again from the beginning. Pressing Play while it waits tries to reconnect straight away. - -## 1.0.0 - -Kaleido is out of beta. This release reworks the show and season pages and smooths out watching a series. - -- Season pages show their episodes as a grid of cards, each with its still, description and watched state, in place of the long episode list. -- Click the season's name under the show's logo to switch to another season. -- Show pages list seasons once, as a row of posters. A show with only one season shows its episodes directly. -- Episodes you've watched stay marked as watched when you rewatch them and stop partway through. The leftover position only shows on the episode you're up to. -- When the next episode plays, whether automatically or with Next, it starts from the beginning instead of near the end of an earlier viewing. -- Click a show's name under a Continue Watching card to go to the show. -- Continue Watching starts at the first title when something new is added, instead of scrolling it off the left edge. -- Season posters outside their show's page, such as New Seasons, are labelled with the show's name. -- Season pages show the year the season aired, and their Play button agrees with the show page about which episode is next. -- Movie and episode pages show the runtime in their details, with the time left on the Resume button. - -## 0.1.0-beta.19 - -Up Next fixes. - -- Up Next now opens every time the credits start: going back to the credits and seeking into the episode brings it back when they come round again, and it always opens when an episode reaches the end. -- The back arrow and a full-screen button are back at the top of Up Next, so you can return to browsing (playback continues in the miniplayer) or leave full screen. -- Click the show's logo to go to its page, with playback moving to the miniplayer. -- The Play next episode countdown fills smoothly. -- The episode rows are sized to fill the screen instead of leaving a gap at the bottom. -- The backdrop now shows the next episode, and its description is easier to read over bright artwork. - -## 0.1.0-beta.18 - -A rebuilt Up Next screen that looks and works like the rest of Kaleido. - -- Up Next now uses the same artwork backdrop, colour wash, buttons and cards as the title pages. The credits keep playing in the top-left corner beside the next episode, and the Play next episode button fills as the countdown runs. -- The Season and Related shows rows scroll with the side arrows, like every other row, instead of scrollbars. The season row starts at the episode you just watched. -- Click the video or press Esc to go back to the credits; at the end of an episode this no longer restarts it from the beginning. -- Up Next fits smaller windows, and the window buttons stay visible on Mac while it's open. -- Playback settings are a simple list again: Skip intros, Skip movie credits, Automatic skip delay and Autoplay next episode. - -## 0.1.0-beta.17 - -- Fix the Up Next countdown stalling when the native video has keyboard focus instead of the webview. Count elapsed time accurately through delayed timer callbacks, and keep the countdown independent of the video's pause state, as on Android TV. -- Open Up Next at the first episode credit marker, including after seeking into credits, independently of movie-credit skip preferences. Open the screen immediately while episode context loads, and start autoplay once the next episode is known. Without markers, use the end of the episode as a fallback. -- Cancel autoplay on mouse movement, clicks, scrolling or keypresses. A stationary pointer does not cancel it; cancelled autoplay stays cancelled when delayed metadata arrives. -- Match the Android TV screen more closely: remove the extra toolbar actions, Cancel autoplay button and autoplay-status text; show only a white video outline on hover or keyboard focus. Use compact episode metadata, full runtime, landscape related shows and captions beneath the artwork. - -## 0.1.0-beta.16 - -- Simplify playback settings: group intro, credits and skip-delay choices together, show the delay only when automatic skipping is enabled, and combine the next-episode switch and countdown into one Off / After … seconds selection. Existing preferences are preserved. -- Make Up Next readable over bright artwork with a dark backdrop across the page, brighter secondary text and larger synopsis and autoplay hints. The playing video stays at its original brightness. - ## 0.1.0-beta.15 A new Up Next screen, adapted from Kaleido for Android TV for mouse and keyboard. diff --git a/docs/development.md b/docs/development.md index dbf8d76..a7911e8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -47,11 +47,13 @@ Playback tests change real Plex progress; resume an in-progress title near its s position, or restore it afterwards. Selecting audio or subtitle tracks is saved to Plex for that file. -Up Next (`player/PostPlay.tsx`) opens at an episode's first credits marker, or at the end -without markers. The video is drawn into its top-left frame (`player_rect`) behind a -matching hole in the page; check that the two line up after resizing, changing display -scale and returning to the video. In the browser, open it from the console by setting -`postPlay: true` (with `item`, `nextUp`, `episodeContextReady`) on `__kaleido.usePlayer`. +Up Next: automatic episode credits open the screen immediately; button-only credits +open it on click, and EOF opens it regardless of the credits preference. There is one +autoplay timer. Clicks, keypresses (including Tab), and scrolling cancel it; pointer +movement leaves it running. Esc returns to the video; F/F11 toggles full screen. +The video rectangle must follow window resizes and DPI changes and return to the full +window on dismissal, episode changes, errors, and closing. Verify those native video +transitions on a GPU-equipped machine; browser layout checks cannot prove rendering. ## Diagnostics diff --git a/package-lock.json b/package-lock.json index a12cc89..bbfdf4d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "kaleido-desktop", - "version": "1.0.1", + "version": "0.1.0-beta.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "kaleido-desktop", - "version": "1.0.1", + "version": "0.1.0-beta.15", "dependencies": { "@fontsource-variable/inter": "^5.3.0", "@tanstack/react-query": "^5.105.0", diff --git a/package.json b/package.json index ffa1da4..3700006 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "kaleido-desktop", "private": true, - "version": "1.0.1", + "version": "0.1.0-beta.15", "type": "module", "scripts": { "dev": "vite", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index fd8584e..c4c276e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2173,7 +2173,7 @@ dependencies = [ [[package]] name = "kaleido" -version = "1.0.1" +version = "0.1.0-beta.15" dependencies = [ "fs2", "futures-util", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c879aaf..e8daa1f 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "kaleido" -version = "1.0.1" +version = "0.1.0-beta.15" 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 e6ecb1d..ad6166f 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": "1.0.1", + "version": "0.1.0-beta.15", "identifier": "tv.kaleido.desktop", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/app/format.ts b/src/app/format.ts index e4a7ba9..a41b82d 100644 --- a/src/app/format.ts +++ b/src/app/format.ts @@ -36,19 +36,10 @@ export function progress(item: Item): number { return Math.min(1, Math.max(0, item.viewOffset / item.duration)); } -/** - * Watched once Plex has counted a full play. A rewatch left partway through keeps the - * title watched; its position only matters for resuming (`resumable`). - */ export function isWatched(item: Item, percent = 90): boolean { if (item.type === 'show' || item.type === 'season') return item.leafCount > 0 && item.viewedLeafCount >= item.leafCount; - if (item.viewCount > 0) return true; - return item.viewOffset > 0 && item.duration > 0 && item.viewOffset / item.duration >= percent / 100; -} - -/** Has a saved position worth resuming from (not one at the very end). */ -export function resumable(item: Item): boolean { - return item.viewOffset > 0 && item.duration > 0 && item.viewOffset < item.duration * 0.97; + if (item.viewOffset > 0 && item.duration > 0) return item.viewCount > 0 && item.viewOffset / item.duration >= percent / 100; + return item.viewCount > 0; } export function remainingEpisodes(item: Item): number { diff --git a/src/app/keyboardNav.ts b/src/app/keyboardNav.ts index 4e01527..8a77535 100644 --- a/src/app/keyboardNav.ts +++ b/src/app/keyboardNav.ts @@ -1,9 +1,9 @@ /** * Arrow-key movement between titles, for keyboard users. Focus moves to the * nearest card in the pressed direction (by on-screen geometry), so it works - * the same across shelves, grids and people rows. + * the same across shelves, grids, episode lists and people rows. */ -const TARGETS = '.card, .person-card:not(:disabled), .shelf-title-link'; +const TARGETS = '.card, .person-card:not(:disabled), .episode-row, .shelf-title-link'; function center(r: DOMRect) { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; diff --git a/src/player/PlayerOverlay.tsx b/src/player/PlayerOverlay.tsx index 5094fb2..16023dc 100644 --- a/src/player/PlayerOverlay.tsx +++ b/src/player/PlayerOverlay.tsx @@ -506,8 +506,8 @@ 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 postPlayDismissed = usePlayer((s) => s.postPlayDismissed); const paused = usePlayer((s) => s.paused); const ready = usePlayer((s) => s.firstFrame); const lastSeek = usePlayer((s) => s.lastSeek); @@ -520,9 +520,8 @@ function SkipButton() { 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 episodeCredits = marker?.type === 'credits' && item?.type === 'episode'; - const mode = marker?.type === 'intro' ? skipIntro : episodeCredits ? 'button' : skipCredits; - const auto = !!marker && !episodeCredits && mode === 'auto'; + 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 = () => { @@ -570,7 +569,7 @@ function SkipButton() { return () => window.removeEventListener('keydown', onKey, true); }, [counting]); - if (!marker || (episodeCredits && !postPlayDismissed) || mode === 'off' || countdown !== null) return null; + if (!marker || mode === 'off' || countdown !== null) return null; const what = marker.type === 'intro' ? 'intro' : 'credits'; const elapsed = counting ? Math.max(0, position - counting.from) : 0; return ( @@ -758,7 +757,7 @@ function MiniPlayer() {
- {(loading || st.buffering || st.reconnecting) && !st.error ? ( + {(loading || st.buffering) && !st.error ? ( ) : st.error ? ( Playback stopped @@ -911,7 +910,7 @@ export function PlayerOverlay() { }, [st.open, st.mini, seekStep, poke]); // The macOS traffic lights fade with the rest of the player's chrome. - const chromeHidden = st.open && !st.mini && !st.postPlay && !visible && st.firstFrame && !st.error; + const chromeHidden = st.open && !st.mini && !visible && st.firstFrame && !st.error; useEffect(() => { if (!chromeHidden) return; win.setButtonsVisible(false); @@ -965,12 +964,10 @@ export function PlayerOverlay() { {!st.fullscreen && }
- {(loading || st.buffering || st.seeking || preparing || st.reconnecting) && !st.error && ( + {(loading || st.buffering || st.seeking || preparing) && !st.error && (
- {st.reconnecting ? ( -

Lost connection to {server?.name ?? 'the server'}

- ) : preparing && ( + {preparing && (

Preparing {UPSCALING[st.enhance.active].label} upscaling First time on this computer only @@ -1025,8 +1022,6 @@ export function PlayerOverlay() {

- {/* Balances Stop on the other side, so play/pause stays centred. */} -
- - {!fullscreen && } -
- -
-
-
-
- - {upcoming || !contextReady ? 'Up next' : 'More to watch'} - - {item.grandparentId ? ( - - ) : ( - - )} - {upcoming ? ( - <> -

{upcoming.title}

- - {upcoming.summary &&

{upcoming.summary}

} - - - ) : ( - contextReady &&

You’ve reached the end of this series.

- )} -
-
- - {server && } - - ); -} - -/** - * Draws the native video into the frame's rectangle and cuts the same hole in - * the page, following window resizes and display scale changes. - */ -function useVideoRect(root: React.RefObject, frame: React.RefObject) { - useLayoutEffect(() => { - const el = frame.current; - const page = root.current; - if (!el || !page) return; - let raf = 0; + useEffect(() => { + const el = video.current; + if (!el) return; + let frame = 0; const place = () => { - cancelAnimationFrame(raf); - raf = requestAnimationFrame(() => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { const r = el.getBoundingClientRect(); - page.style.setProperty('--up-x', `${r.x}px`); - page.style.setProperty('--up-y', `${r.y}px`); - page.style.setProperty('--up-w', `${r.width}px`); - page.style.setProperty('--up-h', `${r.height}px`); - page.classList.add('placed'); + const style = root.current!.style; + for (const [key, value] of Object.entries({ x: r.x, y: r.y, w: r.width, h: r.height })) style.setProperty(`--up-video-${key}`, `${value}px`); const dpr = window.devicePixelRatio || 1; - // A pixel of overdraw on each side keeps the hole covered at any scale. if (isNative) mpv.rect({ x: r.x * dpr - 1, y: r.y * dpr - 1, width: r.width * dpr + 2, height: r.height * dpr + 2 }).catch(() => {}); + root.current!.classList.add('placed'); }); }; - const ro = new ResizeObserver(place); - ro.observe(el); + const observer = new ResizeObserver(place); + observer.observe(el); window.addEventListener('resize', place); place(); return () => { - cancelAnimationFrame(raf); - ro.disconnect(); + cancelAnimationFrame(frame); + observer.disconnect(); window.removeEventListener('resize', place); if (isNative) mpv.rect(null).catch(() => {}); }; }, []); -} - -/** Where the playing episode is, under the video. Its own subscription: position ticks re-render only this. */ -function NowPlaying({ item }: { item: Item }) { - const position = usePlayer((s) => s.position); - const total = usePlayer((s) => s.duration); - return ( -
-
- - {episodeLabel(item)} · {item.title} - - −{clock(Math.max(0, total - position))} -
-
- -
-
- ); -} - -/** - * Play next episode. While autoplay counts down, a lighter fill sweeps across it. - * The store counts in 50 ms steps; the fill is drawn every frame between them. - */ -function PlayNext({ ref }: { ref: React.Ref }) { - const counting = usePlayer((s) => s.countdown !== null && s.countdownTotal > 0); - const fill = useRef(null); - useEffect(() => { - if (!counting) return; - let last = { value: usePlayer.getState().countdown ?? 0, at: performance.now() }; - const unsubscribe = usePlayer.subscribe((s, prev) => { - if (s.countdown !== prev.countdown && s.countdown !== null) last = { value: s.countdown, at: performance.now() }; - }); - let raf = 0; - const draw = () => { - const { countdownTotal: total } = usePlayer.getState(); - // Run on from the last step, but never more than a couple of steps ahead (a held countdown stays held). - const remaining = Math.max(0, last.value - Math.min(performance.now() - last.at, 120) / 1000); - if (fill.current && total) fill.current.style.transform = `scaleX(${1 - remaining / total})`; - raf = requestAnimationFrame(draw); - }; - draw(); - return () => { - unsubscribe(); - cancelAnimationFrame(raf); - }; - }, [counting]); - return ( - - ); -} - -function UpNextRows({ item, nextUp }: { item: Item; nextUp: Item | null }) { - const server = useSession((s) => s.server)!; - const season = useQuery({ - queryKey: [server.machineId, 'children', item.parentId], - queryFn: () => api.children(server, item.parentId), - enabled: !!item.parentId, - staleTime: 30_000, - }); - const related = useQuery({ - queryKey: [server.machineId, 'related', item.grandparentId], - queryFn: () => api.related(server, item.grandparentId), - enabled: !!item.grandparentId, - staleTime: 10 * 60_000, - }); - const episodes = (season.data ?? []).filter((e) => e.type === 'episode'); - const seen = new Set([item.grandparentId]); - const shows = (related.data ?? []).flatMap((h) => h.items).filter((i) => i.type === 'show' && !seen.has(i.id) && !!seen.add(i.id)); - - // The season row starts just before the playing episode. - const seasonRow = useRef(null); - useLayoutEffect(() => { - const row = seasonRow.current?.querySelector('.shelf'); - const current = row?.querySelector('[aria-current]'); - if (!row || !current) return; - const start = (current.previousElementSibling as HTMLElement | null) ?? current; - const target = row.scrollLeft + start.getBoundingClientRect().left - row.getBoundingClientRect().left - parseFloat(getComputedStyle(row).paddingLeft); - row.scrollTo({ left: target, behavior: 'instant' }); - }, [episodes.length]); + const watch = () => { + if (st.ended) st.togglePause(); + st.dismissPostPlay(); + }; const choose = (episode: Item) => { - const st = usePlayer.getState(); - if (episode.id === item.id) st.dismissPostPlay(); + if (episode.id === item.id) watch(); else st.play(episode, { resume: true, quality: st.quality }); }; const browse = async (show: Item) => { - await usePlayer.getState().close(); + await st.close(); navigate({ name: 'item', id: show.id, title: show.title }); }; - if (!episodes.length && !shows.length) return null; + const rail = (label: string, items: Item[], episodes: boolean) => items.length > 0 && ( +
+

{label}

+
+ {items.map((entry) => ( + + ))} +
+
+ ); + return ( -
- {episodes.length > 0 && ( -
- - {episodes.map((ep) => ( - choose(ep)} - /> - ))} - +
+
{server && }
+
+ + + {st.fullscreen && } + {!st.fullscreen && } +
+
+
+ +
{episodeLabel(item)} · {item.title}{st.ended ? 'Finished' : `−${clock(Math.max(0, st.duration - st.position))}`}
+
- )} - {shows.length > 0 && ( - - {shows.map((show) => ( - void browse(show)} /> - ))} - - )} +
+ {upcoming ? 'Up next' : 'More to watch'} + + {upcoming ? <> +

{upcoming.title}

+ + {upcoming.summary &&

{upcoming.summary}

} +
+ + {counting && } +
+

{counting ? 'Autoplay is on · Click, scroll or press any key to cancel' : 'Autoplay is off for this episode'}

+ :

You’ve reached the end of this series.

} +
+
+
+ {rail(item.parentIndex ? `Season ${item.parentIndex}` : 'Episodes', season, true)} + {rail('Related shows', related, false)} +
); } - -function UpNextCard({ item, caption, current, onChoose }: { item: Item; caption: string; current?: boolean; onChoose: () => void }) { - const server = useSession((s) => s.server)!; - const episode = item.type === 'episode'; - const title = episode ? `${item.index}. ${item.title}` : item.title; - const progress = episode && !current && item.viewOffset && item.duration ? item.viewOffset / item.duration : 0; - return ( -
{ - if (e.key !== 'Enter' && e.key !== ' ') return; - e.preventDefault(); - onChoose(); - }} - > -
- {title}} /> -
- {episode && !current && ( -
- -
- )} - {progress > 0 && ( - - - - )} -
-
-
- {title} -
- {caption &&
{caption}
} -
-
- ); -} diff --git a/src/player/miniWindow.ts b/src/player/miniWindow.ts index eebe2b2..2f1966c 100644 --- a/src/player/miniWindow.ts +++ b/src/player/miniWindow.ts @@ -30,7 +30,6 @@ interface PlayerView { duration: number; firstFrame: boolean; buffering: boolean; - reconnecting: boolean; error: string; } @@ -51,8 +50,7 @@ function view(st: PlayerView): MiniState { position: st.position, duration: st.duration, loading: !st.firstFrame && !st.error, - // Waiting for the server to come back shows as buffering. - buffering: st.buffering || st.reconnecting, + buffering: st.buffering, error: !!st.error, }; } diff --git a/src/player/store.test.ts b/src/player/store.test.ts index df87345..4d67b8d 100644 --- a/src/player/store.test.ts +++ b/src/player/store.test.ts @@ -4,8 +4,8 @@ import type { MpvEvent } from './engine'; const harness = vi.hoisted(() => { const memory = new Map(); vi.stubGlobal('localStorage', { getItem: (k: string) => memory.get(k) ?? null, setItem: (k: string, v: string) => memory.set(k, v), removeItem: (k: string) => memory.delete(k) }); - vi.stubGlobal('document', Object.assign(new EventTarget(), { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } })); - return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true, identity: vi.fn() }; + vi.stubGlobal('document', { hidden: false, hasFocus: () => true, documentElement: { classList: { toggle: vi.fn() } } }); + return { event: (_e: MpvEvent) => {}, next: [] as unknown[], focused: true }; }); vi.mock('../platform/native', () => ({ @@ -20,7 +20,7 @@ vi.mock('./engine', () => ({ mpv: { } })); vi.mock('../app/session', async () => { const { create } = await import('zustand'); - return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only', name: 'Test', get: harness.identity }, connection: { local: true } })) }; + return { useSession: create(() => ({ server: { machineId: 'test', token: 'test-only' }, connection: { local: true } })) }; }); vi.mock('../downloads/store', () => ({ useDownloads: { getState: () => ({ items: [] }) } })); vi.mock('../app/queries', () => ({ invalidateLibrary: vi.fn() })); @@ -42,11 +42,7 @@ const episode = (id = '1') => parseItem({ ratingKey: id, type: 'episode', title: Media: [{ Part: [{ key: '/video', Stream: [{ id: 'audio', streamType: 2 }] }] }], }); const time = (position: number) => harness.event({ type: 'property', name: 'time-pos', value: position }); -/** The stream ending at `position` (by default the real end of the 100 s episode). */ -const eof = (position = 99.6) => { - usePlayer.setState({ position }); - harness.event({ type: 'end-file', reason: 'eof' }); -}; +const eof = () => harness.event({ type: 'end-file', reason: 'eof' }); beforeEach(async () => { vi.useFakeTimers(); @@ -71,25 +67,15 @@ describe('Up Next playback lifecycle', () => { time(81); expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5, countdownTotal: 5 }); }); - it.each(['button', 'off', 'auto'] as const)('opens at the first credits frame with movie credit skipping set to %s', (skipCredits) => { - useSettings.setState({ skipCredits }); - time(79.9); + it('leaves button-only credits to the viewer, and opens on a deliberate skip', () => { + useSettings.setState({ skipCredits: 'button' }); + time(81); + vi.advanceTimersByTime(2000); + time(83); expect(usePlayer.getState().postPlay).toBe(false); - time(80); + usePlayer.getState().showPostPlay(); expect(usePlayer.getState().postPlay).toBe(true); }); - it('counts while the native video owns focus instead of the webview', () => { - harness.focused = false; - time(81); - vi.advanceTimersByTime(1000); - expect(usePlayer.getState().countdown).toBeCloseTo(4); - }); - it('counts elapsed time even when the webview delivers timer callbacks late', () => { - time(81); - vi.setSystemTime(Date.now() + 2000); - vi.advanceTimersByTime(50); - expect(usePlayer.getState().countdown).toBeCloseTo(2.95); - }); it('opens at EOF even when automatic credit skipping is off', () => { useSettings.setState({ skipCredits: 'off' }); eof(); @@ -106,14 +92,6 @@ describe('Up Next playback lifecycle', () => { expect(next).toHaveBeenCalledOnce(); usePlayer.setState({ playNext: original }); }); - it('starts the next episode from the beginning, ignoring an earlier partial viewing', async () => { - const original = usePlayer.getState().play; - const spy = vi.fn().mockResolvedValue(undefined); - usePlayer.setState({ play: spy, nextUp: { ...episode('2'), viewOffset: 88000 } }); - await usePlayer.getState().playNext(); - expect(spy).toHaveBeenCalledWith(expect.objectContaining({ id: '2' }), expect.objectContaining({ resume: false })); - usePlayer.setState({ play: original }); - }); it('cancels autoplay while keeping the screen open, including across EOF', () => { time(81); usePlayer.getState().cancelCountdown(); @@ -121,30 +99,18 @@ describe('Up Next playback lifecycle', () => { vi.advanceTimersByTime(10000); expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true }); }); - it('returns to credits without reopening while they play', () => { + it('returns to credits without reopening on the next time event or EOF', () => { time(81); usePlayer.getState().dismissPostPlay(); time(82); + eof(); expect(usePlayer.getState()).toMatchObject({ postPlay: false, countdown: null }); }); - it('reopens at the end after returning to the credits', () => { - time(81); - usePlayer.getState().dismissPostPlay(); - eof(); - expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 }); - }); - it('reopens when the credits start again after seeking back into the episode', () => { - time(81); - usePlayer.getState().dismissPostPlay(); - usePlayer.getState().seek(40); - time(40); - expect(usePlayer.getState().postPlay).toBe(false); - time(80); - expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: 5 }); - }); - it.each(['hidden', 'mini'] as const)('holds the countdown while %s', (reason) => { + it.each(['hidden', 'unfocused', 'paused', 'mini'] as const)('holds the countdown while %s', (reason) => { time(81); if (reason === 'hidden') Object.assign(document, { hidden: true }); + if (reason === 'unfocused') harness.focused = false; + if (reason === 'paused') usePlayer.setState({ paused: true }); if (reason === 'mini') usePlayer.setState({ mini: true }); vi.advanceTimersByTime(20000); expect(usePlayer.getState().countdown).toBe(5); @@ -160,22 +126,6 @@ describe('Up Next playback lifecycle', () => { vi.advanceTimersByTime(1000); expect(usePlayer.getState().countdown).toBeCloseTo(4); }); - it('keeps counting while credits are paused, like Android Up Next', () => { - time(81); - usePlayer.setState({ paused: true }); - vi.advanceTimersByTime(1000); - expect(usePlayer.getState().countdown).toBeCloseTo(4); - }); - it('does not spend hidden time when the app returns before another timer tick', () => { - time(80); - Object.assign(document, { hidden: true }); - document.dispatchEvent(new Event('visibilitychange')); - vi.setSystemTime(Date.now() + 60000); - Object.assign(document, { hidden: false }); - document.dispatchEvent(new Event('visibilitychange')); - vi.advanceTimersByTime(50); - expect(usePlayer.getState().countdown).toBeCloseTo(4.95); - }); it('shows a finale without an autoplay target', () => { usePlayer.setState({ nextUp: null }); eof(); @@ -186,43 +136,30 @@ describe('Up Next playback lifecycle', () => { time(81); expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null }); }); - it('opens when seeking into credits instead of suppressing Up Next', () => { + it('treats a seek into credits as a choice to watch them', () => { usePlayer.getState().seek(81); time(81); vi.advanceTimersByTime(2000); time(83); - expect(usePlayer.getState().postPlay).toBe(true); + expect(usePlayer.getState().postPlay).toBe(false); expect(mpv.command).toHaveBeenCalledWith('seek', '81.000', 'absolute+exact'); }); - it.each(['ended', 'credits'] as const)('shows Up Next immediately and loads slow episode context after %s', async (reason) => { + it.each(['ended', 'button'] as const)('waits for slow episode context after %s', async (reason) => { let resolve!: (items: ReturnType[]) => void; vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); await usePlayer.getState().play(episode(), { resume: false }); usePlayer.setState({ firstFrame: true }); useSettings.setState({ skipCredits: 'button' }); if (reason === 'ended') eof(); - else time(80); - expect(usePlayer.getState().postPlay).toBe(true); - expect(usePlayer.getState().countdown).toBeNull(); + else usePlayer.getState().showPostPlay(); + expect(usePlayer.getState().postPlay).toBe(false); resolve([episode(), episode('2')]); - await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true)); + await vi.waitFor(() => expect(usePlayer.getState().postPlay).toBe(true)); expect(usePlayer.getState().nextUp?.id).toBe('2'); expect(usePlayer.getState().countdownTotal).toBe(5); expect(usePlayer.getState().countdown).toBeGreaterThan(4.9); expect(usePlayer.getState().countdown).toBeLessThanOrEqual(5); }); - it('keeps autoplay cancelled when episode context arrives after interaction', async () => { - let resolve!: (items: ReturnType[]) => void; - vi.mocked(api.allLeaves).mockImplementationOnce(() => new Promise((done) => { resolve = done; })); - await usePlayer.getState().play(episode(), { resume: false }); - usePlayer.setState({ firstFrame: true }); - time(80); - usePlayer.getState().cancelCountdown(); - resolve([episode(), episode('2')]); - await vi.waitFor(() => expect(usePlayer.getState().episodeContextReady).toBe(true)); - vi.advanceTimersByTime(10000); - expect(usePlayer.getState()).toMatchObject({ postPlay: true, countdown: null, postPlayDismissed: true }); - }); it('clears Up Next and its timer when playback closes', async () => { time(81); await usePlayer.getState().close(); @@ -230,51 +167,3 @@ describe('Up Next playback lifecycle', () => { expect(usePlayer.getState()).toMatchObject({ open: false, postPlay: false, countdown: null }); }); }); - -describe('Losing the server mid-stream', () => { - it('waits for the server instead of ending when the stream is cut off early', () => { - eof(42); - expect(usePlayer.getState()).toMatchObject({ reconnecting: true, ended: false, postPlay: false }); - }); - it('resumes from where it stopped once the server answers again', async () => { - const original = usePlayer.getState().play; - const play = vi.fn().mockResolvedValue(undefined); - usePlayer.setState({ play }); - harness.identity.mockRejectedValueOnce(new Error('unreachable')); - eof(42); - await vi.advanceTimersByTimeAsync(2000); - expect(play).not.toHaveBeenCalled(); - expect(usePlayer.getState().reconnecting).toBe(true); - harness.identity.mockResolvedValueOnce({}); - await vi.advanceTimersByTimeAsync(3000); - expect(play).toHaveBeenCalledWith(expect.objectContaining({ id: '1' }), expect.objectContaining({ offsetMs: 42000, keepMini: true })); - expect(usePlayer.getState().reconnecting).toBe(false); - usePlayer.setState({ play: original }); - }); - it('tries straight away on Play instead of starting over', async () => { - const original = usePlayer.getState().play; - const play = vi.fn().mockResolvedValue(undefined); - usePlayer.setState({ play }); - harness.identity.mockResolvedValueOnce({}); - eof(42); - usePlayer.getState().togglePause(); - await vi.waitFor(() => expect(play).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ offsetMs: 42000 }))); - expect(mpv.command).not.toHaveBeenCalledWith('seek', '0.000', 'absolute+exact'); - usePlayer.setState({ play: original }); - }); - it('treats a second cut-off at the same place as the real end of the file', async () => { - harness.identity.mockResolvedValueOnce({}); - eof(42); - await vi.advanceTimersByTimeAsync(2000); - usePlayer.setState({ firstFrame: true }); - eof(42.5); - expect(usePlayer.getState()).toMatchObject({ reconnecting: false, ended: true }); - }); - it('stops waiting when the player is closed', async () => { - eof(42); - await usePlayer.getState().close(); - harness.identity.mockClear(); - await vi.advanceTimersByTimeAsync(10000); - expect(harness.identity).not.toHaveBeenCalled(); - }); -}); diff --git a/src/player/store.ts b/src/player/store.ts index 0606a41..d494670 100644 --- a/src/player/store.ts +++ b/src/player/store.ts @@ -36,8 +36,6 @@ export interface PlayOptions { quality?: Quality; /** Keep these track choices (UI keys) instead of applying the preferences again. */ tracks?: { audioKey: string; subKey: string }; - /** Reloading the same title in place (after an outage): stay in the miniplayer if it's there. */ - keepMini?: boolean; } interface PlayerState { @@ -50,8 +48,6 @@ interface PlayerState { error: string; /** The server owner stopped this stream (error holds their message). */ terminated: boolean; - /** The stream was cut off before the end (the server went away); waiting for it to come back. */ - reconnecting: boolean; position: number; duration: number; cacheTime: number; @@ -74,7 +70,6 @@ interface PlayerState { nextUp: Item | null; /** The episode before this one, for the previous-episode button. */ prevUp: Item | null; - episodeContextReady: boolean; countdown: number | null; countdownTotal: number; postPlay: boolean; @@ -120,12 +115,13 @@ let lastReport = 0; let sessionAnswered = false; let reportTimer: ReturnType | null = null; let countdownTimer: ReturnType | null = null; -let unwatchCountdown: (() => void) | null = null; let scrobbled = false; let unlisten: (() => void) | null = null; let loadToken = 0; let wasFullscreenBeforePlay = false; let pendingExternal: Track | null = null; +let neighboursReady = false; +let postPlayRequested = false; /** * The server this playback belongs to, fixed when it starts. Progress, watched state @@ -342,33 +338,27 @@ async function findNeighbours(item: Item): Promise<{ prevUp: Item | null; nextUp } } -function openPostPlay() { - const st = usePlayer.getState(); - if (!st.open || st.error || st.item?.type !== 'episode' || st.postPlay || st.postPlayDismissed) return; - usePlayer.setState({ postPlay: true }); - startCountdown(); -} - function startCountdown() { const st = usePlayer.getState(); - if (!st.open || !st.postPlay || st.error || !st.nextUp || st.postPlayDismissed || st.countdown !== null) return; + if (!st.open || st.error || st.item?.type !== 'episode' || st.postPlay || st.postPlayDismissed) return; const settings = useSettings.getState(); - const total = settings.autoplayNext ? settings.countdownSeconds : 0; + // Don't mistake a slow context request for the end of the series. + if (!neighboursReady) return; + postPlayRequested = false; + const total = st.nextUp && settings.autoplayNext ? settings.countdownSeconds : 0; + usePlayer.setState({ postPlay: true, countdown: total > 0 ? total : null, countdownTotal: total }); if (total <= 0) return; - stopCountdown(); - usePlayer.setState({ countdown: total, countdownTotal: total }); let lastTick = performance.now(); - const visibilityChanged = () => { lastTick = performance.now(); }; - document.addEventListener('visibilitychange', visibilityChanged); - unwatchCountdown = () => document.removeEventListener('visibilitychange', visibilityChanged); + countdownTimer && clearInterval(countdownTimer); countdownTimer = setInterval(() => { const now = performance.now(); - const elapsed = Math.max(0, (now - lastTick) / 1000); + // Never spend time hidden, in the separate miniplayer, or behind another app. + // Cap a delayed tick so sleep / a suspended web view cannot skip an episode. + const elapsed = Math.min((now - lastTick) / 1000, 0.1); lastTick = now; const current = usePlayer.getState(); if (!current.open || !current.postPlay || current.error || current.countdown === null) return stopCountdown(); - // Native video can own keyboard focus while the webview is still on screen. - if (document.hidden || current.mini) return; + if (document.hidden || !document.hasFocus() || current.mini || (current.paused && !current.ended)) return; const remaining = Math.max(0, current.countdown - elapsed); usePlayer.setState({ countdown: remaining }); if (remaining === 0) { @@ -381,8 +371,6 @@ function startCountdown() { function stopCountdown() { if (countdownTimer) clearInterval(countdownTimer); countdownTimer = null; - unwatchCountdown?.(); - unwatchCountdown = null; } /** @@ -601,7 +589,7 @@ function onEvent(e: MpvEvent) { } break; case 'eof-reached': - if (v === true) onStreamEnd(); + if (v === true) onEnded(); break; } break; @@ -622,14 +610,11 @@ function onEvent(e: MpvEvent) { // (Briefly: an unreachable server shouldn't hold up the error.) const failed = session; Promise.race([report('buffering'), new Promise((r) => setTimeout(() => r(false), 3000))]).then((terminated) => { - const now = usePlayer.getState(); - if (terminated || !now.open || session !== failed) return; - // Partway through a stream that was playing, it's the connection that failed. - if (cutShort(now)) return onStreamEnd(); + if (terminated || !usePlayer.getState().open || session !== failed) return; usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' }); fallbackAfterError(); }); - } else if (e.reason === 'eof') onStreamEnd(); + } else if (e.reason === 'eof') onEnded(); break; case 'log': noteMpvLog(e.level, e.prefix, e.text); @@ -654,69 +639,9 @@ function fallbackAfterError() { function maybeCredits(pos: number) { const st = usePlayer.getState(); - if (st.item?.type !== 'episode' || !st.firstFrame) return; - const inCredits = st.item.markers.some((m) => m.type === 'credits' && pos * 1000 >= m.start && pos * 1000 < m.end); - // Leaving the credits (seeking back into the episode) re-arms Up Next for the next time they start. - if (!inCredits) { - if (st.postPlayDismissed && !st.postPlay && !st.ended) usePlayer.setState({ postPlayDismissed: false }); - } else if (!st.postPlayDismissed) openPostPlay(); -} - -/** - * A streamed title stopping well short of its end means the connection went - * (mpv plays out its buffer, then sees the cut-off stream as the end of the file). - */ -const CUT_SHORT_MARGIN = 15; -let reconnectTimer: ReturnType | null = null; -/** Where the last cut-off happened, so a file that really does end early isn't retried forever. */ -let lastCutAt: number | null = null; - -function cutShort(st: PlayerState) { - return st.delivery?.mode !== 'local' && st.firstFrame && st.duration > 0 && st.position < st.duration - CUT_SHORT_MARGIN; -} - -/** The stream ran out: a real ending, or a lost connection to wait out. */ -function onStreamEnd() { - const st = usePlayer.getState(); - if (!cutShort(st)) return onEnded(); - if (st.reconnecting || st.ended) return; - // Cut off at the same place again once the server answered: the file itself ends there. - if (lastCutAt !== null && Math.abs(st.position - lastCutAt) < 5) return onEnded(); - lastCutAt = st.position; - usePlayer.setState({ reconnecting: true, buffering: false }); - keepAwake(false); - scheduleReconnect(2000); -} - -function stopReconnecting() { - if (reconnectTimer) clearTimeout(reconnectTimer); - reconnectTimer = null; -} - -function scheduleReconnect(delay: number) { - stopReconnecting(); - reconnectTimer = setTimeout(() => void tryReconnect(), delay); -} - -/** Resumes where the stream was cut off if the server answers; otherwise checks again shortly. */ -async function tryReconnect(): Promise { - stopReconnecting(); - const st = usePlayer.getState(); - const s = server(); - if (!st.open || !st.reconnecting || !st.item || !s) return false; - const reachable = await s.get('/identity', undefined, { timeout: 4000 }).then( - () => true, - () => false, - ); - const now = usePlayer.getState(); - if (!now.open || !now.reconnecting || now.item?.id !== st.item.id) return false; - if (!reachable) { - scheduleReconnect(3000); - return false; - } - usePlayer.setState({ reconnecting: false }); - await now.play(now.item, { offsetMs: now.position * 1000, mediaIndex: now.mediaIndex, quality: now.quality, tracks: currentTracks(now), keepMini: true }); - return true; + if (st.item?.type !== 'episode' || !st.firstFrame || st.paused || st.postPlayDismissed || Date.now() - st.lastSeek < 1500) return; + const credits = st.item.markers.find((m) => m.type === 'credits'); + if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits === 'auto') startCountdown(); } function onEnded() { @@ -725,11 +650,7 @@ function onEnded() { usePlayer.setState({ ended: true }); report('stopped'); checkScrobble(); - // Reaching the end always offers Up Next, as on Android, even after watching the credits. - if (st.item?.type === 'episode' && !st.postPlay) { - usePlayer.setState({ postPlayDismissed: false }); - openPostPlay(); - } + if (st.item?.type === 'episode') startCountdown(); } export const usePlayer = create((set, get) => ({ @@ -741,7 +662,6 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, - reconnecting: false, position: 0, duration: 0, cacheTime: 0, @@ -762,7 +682,6 @@ export const usePlayer = create((set, get) => ({ ended: false, nextUp: null, prevUp: null, - episodeContextReady: false, countdown: null, countdownTotal: 0, postPlay: false, @@ -778,6 +697,8 @@ export const usePlayer = create((set, get) => ({ // Closing or starting something else while this one is still setting up wins. const stale = () => token !== loadToken; const prefs = useSettings.getState(); + neighboursReady = false; + postPlayRequested = false; stopThemeMusic(); stopCountdown(); if (!isNative) { @@ -785,8 +706,6 @@ export const usePlayer = create((set, get) => ({ return; } const previous = get(); - stopReconnecting(); - if (previous.item?.id !== input.id) lastCutAt = null; // The previous title's reporting ends here, against its own server. if (reportTimer) clearInterval(reportTimer); reportTimer = null; @@ -815,7 +734,6 @@ export const usePlayer = create((set, get) => ({ firstFrame: false, error: '', terminated: false, - reconnecting: false, position: (opts.offsetMs ?? 0) / 1000, lastSeek: 0, duration: input.duration / 1000, @@ -825,7 +743,6 @@ export const usePlayer = create((set, get) => ({ ended: false, nextUp: null, prevUp: null, - episodeContextReady: false, countdown: null, countdownTotal: 0, postPlay: false, @@ -837,7 +754,7 @@ export const usePlayer = create((set, get) => ({ subKey: opts.tracks?.subKey ?? '__init', video: null, fullscreen: fullscreenNow, - mini: opts.keepMini ? previous.open && previous.mini : false, + mini: false, videoGamma: '', enhance: { ...previous.enhance, bypass: false, preparing: false }, }); @@ -901,15 +818,6 @@ export const usePlayer = create((set, get) => ({ ...(tracks ?? {}), }); - findNeighbours(item).then((n) => { - if (token !== loadToken) return; - set({ ...n, episodeContextReady: true }); - const current = get(); - if (current.postPlay) startCountdown(); - else if (current.ended) openPostPlay(); - else maybeCredits(current.position); - }); - await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough }); if (!unlisten) unlisten = await mpv.on(onEvent); if (stale()) return; @@ -934,9 +842,6 @@ export const usePlayer = create((set, get) => ({ offsetMs > 0 && delivery.mode !== 'transcode' ? `start=${(offsetMs / 1000).toFixed(2)}` : 'start=none', ].join(','); await mpv.command('loadfile', delivery.url, 'replace', -1, fileOpts); - // A file left paused at its end (keep-open) re-pauses as soon as it's unpaused - // above, so a reload in place (after an outage) would open paused: unpause again. - await mpv.set('pause', false); if (stale()) return; keepAwake(true); report('buffering'); @@ -945,6 +850,18 @@ export const usePlayer = create((set, get) => ({ const st = get(); if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing'); }, 10000); + findNeighbours(item).then((n) => { + if (token !== loadToken) return; + neighboursReady = true; + set(n); + const current = get(); + // Metadata may arrive after EOF / the credits. Open only once it is known + // whether there is a next episode, without restarting a cancelled timer. + if (!current.postPlay) { + if (postPlayRequested || current.ended) startCountdown(); + else maybeCredits(current.position); + } + }); } catch (e: any) { if (token !== loadToken) return; set({ error: e?.message ?? String(e), buffering: false }); @@ -955,8 +872,6 @@ export const usePlayer = create((set, get) => ({ loadToken++; const st = get(); stopCountdown(); - stopReconnecting(); - lastCutAt = null; if (reportTimer) clearInterval(reportTimer); reportTimer = null; if (st.item && !st.error) report('stopped'); @@ -974,7 +889,7 @@ export const usePlayer = create((set, get) => ({ await mpv.command('stop').catch(() => {}); await mpv.show(false).catch(() => {}); } - set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, reconnecting: false, countdown: null, nextUp: null, prevUp: null, firstFrame: false }); + set({ open: false, mini: false, postPlay: false, item: null, delivery: null, error: '', terminated: false, countdown: null, nextUp: null, prevUp: null, firstFrame: 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) { @@ -986,13 +901,6 @@ export const usePlayer = create((set, get) => ({ togglePause() { const st = get(); - // Play while the server is away: try it now rather than at the next check. - if (st.reconnecting) { - tryReconnect().then((resumed) => { - if (!resumed && get().reconnecting) toast(`Still can’t reach ${server()?.name ?? 'the server'}.`); - }); - return; - } if (st.ended) { st.seek(0); set({ ended: false }); @@ -1003,7 +911,8 @@ 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, lastSeek: Date.now() }); + const choseCredits = st.item?.type === 'episode' && st.item.markers.some((m) => m.type === 'credits' && target * 1000 >= m.start && target * 1000 < m.end); + set({ position: target, ended: false, lastSeek: Date.now(), ...(choseCredits ? { postPlayDismissed: true } : {}) }); if (st.postPlay) st.dismissPostPlay(); mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {}); }, @@ -1099,15 +1008,13 @@ export const usePlayer = create((set, get) => ({ const st = get(); stopCountdown(); if (!st.nextUp) return; - // Watching on through a season starts each episode from the top, never at a - // stale position left by an earlier, unfinished viewing. - await st.play(st.nextUp, { resume: false, quality: st.quality }); + await st.play(st.nextUp, { resume: true, quality: st.quality }); }, async playPrevious() { const st = get(); if (!st.prevUp) return; - await st.play(st.prevUp, { resume: false, quality: st.quality }); + await st.play(st.prevUp, { resume: true, quality: st.quality }); }, cancelCountdown() { @@ -1117,8 +1024,9 @@ export const usePlayer = create((set, get) => ({ showPostPlay() { // A deliberate Skip credits can reopen a screen previously dismissed. + postPlayRequested = true; set({ postPlayDismissed: false }); - openPostPlay(); + startCountdown(); }, dismissPostPlay() { diff --git a/src/plex/plex.test.ts b/src/plex/plex.test.ts index fdd06ff..8be9e2e 100644 --- a/src/plex/plex.test.ts +++ b/src/plex/plex.test.ts @@ -3,7 +3,7 @@ import { parseItem, parseScores } from './parse'; import { isLocalAddress } from './account'; import { partAt } from './playback'; import { headerSafe } from './client'; -import { duration, formatBadges, isWatched, remaining, resumable, washGradient } from '../app/format'; +import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format'; import { buildFeatures } from '../screens/discover'; import type { Hub } from './types'; @@ -65,16 +65,10 @@ describe('parsing', () => { }); describe('watched rules', () => { - it('keeps a title watched while it is being rewatched', () => { - expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(true); + it('treats a resumed title as watched only past the threshold', () => { + expect(isWatched(movie({ viewCount: 1, viewOffset: 3000000 }), 90)).toBe(false); + expect(isWatched(movie({ viewCount: 1, viewOffset: 5700000 }), 90)).toBe(true); expect(isWatched(movie({ viewCount: 1 }), 90)).toBe(true); - expect(resumable(movie({ viewCount: 1, viewOffset: 3000000 }))).toBe(true); - }); - - it('counts an unplayed title as watched only past the threshold', () => { - expect(isWatched(movie({ viewOffset: 3000000 }), 90)).toBe(false); - expect(isWatched(movie({ viewOffset: 5700000 }), 90)).toBe(true); - expect(isWatched(movie({}), 90)).toBe(false); }); it('uses episode counts for shows', () => { diff --git a/src/screens/Item.tsx b/src/screens/Item.tsx index dba8e82..ebaf887 100644 --- a/src/screens/Item.tsx +++ b/src/screens/Item.tsx @@ -4,12 +4,12 @@ import type { Item } from '../plex/types'; import { PROGRESS, useChildren, useItem, useRelated, useServerQuery } from '../app/queries'; import { useServer } from '../app/session'; import { useSettings } from '../app/settings'; -import { goBack, navigate } from '../app/router'; -import { canManage, itemMenu, openDialog, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions'; -import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, remainingEpisodes, resolutionLabel, resumable, technicalLine } from '../app/format'; +import { goBack, navigate, useRouter } from '../app/router'; +import { canManage, itemMenu, openDialog, openItem, playItem, playWithVersion, setWatched, shuffleItem } from '../app/actions'; +import { bitrate, channelLabel, date, duration, episodeLabel, extraLabel, fileSize, isWatched, remaining, resolutionLabel, technicalLine } from '../app/format'; import { Backdrop } from '../ui/Backdrop'; -import { EpisodeCard, Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; -import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader } from '../ui/primitives'; +import { Facts, HubShelf, LandscapeCard, PersonCard, PosterCard, Shelf, TitleArt } from '../ui/media'; +import { Artwork, Button, EmptyState, ErrorState, IconButton, PageLoader, Select } from '../ui/primitives'; import { Icon } from '../ui/Icon'; import { openMenu } from '../ui/overlays'; import { useDownloads } from '../downloads/store'; @@ -255,12 +255,11 @@ function AboutPanel({ item }: { item: Item }) { // —— Movie —————————————————————————————————————————————————————————— function MovieDetail({ item }: { item: Item }) { - const resume = resumable(item); + const resume = item.viewOffset > 0 && !isWatched(item); return (
- {/* The Resume button carries the time left; the facts give the runtime. */} - +
+ {p > 0 && !watched && ( + + + + )} +
+
+

+ {ep.title} + {watched && } +

+
+ {[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')} +
+ {ep.summary &&

{ep.summary}

} +
+
); } -function EpisodesSection({ episodes, subtitle, upNextId }: { episodes: Item[] | undefined; subtitle?: string; upNextId?: string }) { +function Episodes({ seasons, initialSeason, showPicker = true }: { seasons: Item[]; initialSeason?: string; showPicker?: boolean }) { + const saved = useRouter((s) => s.current.state.season as string | undefined); + const [seasonId, setSeasonId] = useState(saved ?? initialSeason ?? seasons[0]?.id); + useEffect(() => { + if (!seasonId && seasons[0]) setSeasonId(initialSeason ?? seasons[0].id); + }, [seasons, initialSeason]); + const episodes = useChildren(seasonId); + const season = seasons.find((s) => s.id === seasonId); + if (!seasons.length) return null; return (
-
-

- Episodes - {subtitle && {subtitle}} -

+
+

Episodes

+ {showPicker && seasons.length > 1 && ( + set('skipIntro', v)} options={skipOptions} /> - + ({ value: v, label: v ? `${v} seconds` : 'Skip straight away' }))} /> - - set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />