Create Kaleido Desktop, a cinematic Plex client for Windows
Tauri 2 shell with a React/TypeScript interface and libmpv playback composed beneath the web view (DirectComposition on Windows). Shared code with per-OS platform modules and configs so macOS and Linux can follow. - Plex sign-in (browser, plex.tv/link or manual), server selection, Plex Home - Home, Movies and TV Shows (Discover, Library, Collections), search, people - Title pages with logos, ratings, cast, extras, seasons and episodes - Direct play with Plex conversion fallback, tracks, markers, autoplay - Metadata editing, artwork, fix match, refresh, analyze and deletion - Resumable offline downloads - App settings and Plex server administration with a live dashboard - Signed updater feed and Forgejo CI Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
00d72e70f4
121 changed files with 25315 additions and 0 deletions
258
src/app/App.tsx
Normal file
258
src/app/App.tsx
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { queryClient, invalidateLibrary } from './queries';
|
||||
import { useSession } from './session';
|
||||
import { useRouter, navigate, type Route } from './router';
|
||||
import { useSettings } from './settings';
|
||||
import { TopBar } from './TopBar';
|
||||
import { MenuHost, ToastHost, ConfirmHost } from '../ui/overlays';
|
||||
import { HoverPreviewHost } from '../ui/HoverPreview';
|
||||
import { PageLoader } from '../ui/primitives';
|
||||
import { Splash } from '../screens/Splash';
|
||||
import { SignIn } from '../screens/SignIn';
|
||||
import { ServerPicker } from '../screens/ServerPicker';
|
||||
import { win } from '../platform/native';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { PlayerOverlay } from '../player/PlayerOverlay';
|
||||
import { DialogHost } from '../screens/dialogs/DialogHost';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { libraryRevision } from '../plex/api';
|
||||
import { checkForUpdate } from './updater';
|
||||
import { Home } from '../screens/Home';
|
||||
import { SectionScreen } from '../screens/Section';
|
||||
import { ItemScreen } from '../screens/Item';
|
||||
|
||||
const Search = lazy(() => import('../screens/Search'));
|
||||
const Downloads = lazy(() => import('../screens/Downloads'));
|
||||
const Settings = lazy(() => import('../screens/settings/Settings'));
|
||||
const Person = lazy(() => import('../screens/Person'));
|
||||
const HubScreen = lazy(() => import('../screens/HubScreen'));
|
||||
|
||||
function Screen({ route }: { route: Route }) {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return <Home />;
|
||||
case 'section':
|
||||
return <SectionScreen kind={route.kind} tab={route.tab} />;
|
||||
case 'item':
|
||||
return <ItemScreen id={route.id} />;
|
||||
case 'person':
|
||||
return <Person id={route.id} title={route.title} thumb={route.thumb} />;
|
||||
case 'hub':
|
||||
return <HubScreen hubKey={route.key} title={route.title} />;
|
||||
case 'search':
|
||||
return <Search initial={route.query} />;
|
||||
case 'downloads':
|
||||
return <Downloads />;
|
||||
case 'settings':
|
||||
return <Settings mode={route.mode} tab={route.tab} />;
|
||||
}
|
||||
}
|
||||
|
||||
/** One scroll container per history entry; its position is restored on Back. */
|
||||
function Page({ onScrolled }: { onScrolled: (top: number) => void }) {
|
||||
const entry = useRouter((s) => s.current);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const target = entry.scroll;
|
||||
el.scrollTop = target;
|
||||
onScrolled(target);
|
||||
if (!target) return;
|
||||
// Content may still be loading; keep trying briefly until it is tall enough.
|
||||
let tries = 0;
|
||||
const t = setInterval(() => {
|
||||
if (!ref.current || tries++ > 30) return clearInterval(t);
|
||||
ref.current.scrollTop = target;
|
||||
if (Math.abs(ref.current.scrollTop - target) < 2) clearInterval(t);
|
||||
}, 50);
|
||||
return () => clearInterval(t);
|
||||
}, [entry]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="main-scroll"
|
||||
data-route={entry.route.name}
|
||||
onScroll={(e) => {
|
||||
const top = (e.target as HTMLDivElement).scrollTop;
|
||||
entry.scroll = top;
|
||||
onScrolled(top);
|
||||
}}
|
||||
>
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<main className="page-enter" key={entry.id}>
|
||||
<Screen route={entry.route} />
|
||||
</main>
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useGlobalShortcuts() {
|
||||
useEffect(() => {
|
||||
const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(t.tagName));
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'f')) {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'search' });
|
||||
} else if (e.altKey && e.key === 'ArrowLeft') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.altKey && e.key === 'ArrowRight') {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
} else if (e.key === 'F11') {
|
||||
e.preventDefault();
|
||||
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();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === ',') {
|
||||
e.preventDefault();
|
||||
navigate({ name: 'settings', mode: 'app', tab: 'general' });
|
||||
}
|
||||
};
|
||||
// Mouse back/forward buttons.
|
||||
const onMouse = (e: MouseEvent) => {
|
||||
if (usePlayer.getState().open) return;
|
||||
if (e.button === 3) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().back();
|
||||
} else if (e.button === 4) {
|
||||
e.preventDefault();
|
||||
useRouter.getState().forward();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
window.addEventListener('mouseup', onMouse);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
window.removeEventListener('mouseup', onMouse);
|
||||
};
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** Refreshes browsing when the server's libraries change. */
|
||||
function useLibrarySync() {
|
||||
const server = useSession((s) => s.server);
|
||||
useEffect(() => {
|
||||
if (!server) return;
|
||||
let last = '';
|
||||
let stopped = false;
|
||||
const tick = async () => {
|
||||
if (stopped || document.hidden || usePlayer.getState().open) return;
|
||||
try {
|
||||
const rev = await libraryRevision(server);
|
||||
if (last && rev !== last) invalidateLibrary();
|
||||
last = rev;
|
||||
} catch {
|
||||
/* transient */
|
||||
}
|
||||
};
|
||||
tick();
|
||||
const t = setInterval(tick, 20000);
|
||||
const onVisible = () => !document.hidden && tick();
|
||||
document.addEventListener('visibilitychange', onVisible);
|
||||
return () => {
|
||||
stopped = true;
|
||||
clearInterval(t);
|
||||
document.removeEventListener('visibilitychange', onVisible);
|
||||
};
|
||||
}, [server]);
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const [scrolled, setScrolled] = useState(false);
|
||||
const playerOpen = usePlayer((s) => s.open);
|
||||
const startPage = useSettings.getState().startPage;
|
||||
useGlobalShortcuts();
|
||||
useLibrarySync();
|
||||
useEffect(() => {
|
||||
if (startPage !== 'home') useRouter.getState().reset(startPage === 'movies' ? { name: 'section', kind: 'movie', tab: 'discover' } : { name: 'section', kind: 'show', tab: 'discover' });
|
||||
useDownloads.getState().init().then(() => useDownloads.getState().resumeInterrupted());
|
||||
const t = setTimeout(() => checkForUpdate(false), 8000);
|
||||
return () => clearTimeout(t);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell" aria-hidden={playerOpen}>
|
||||
<TopBar solid={scrolled} />
|
||||
<Page onScrolled={(top) => setScrolled(top > 24)} />
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function OfflineShell() {
|
||||
const error = useSession((s) => s.error);
|
||||
const init = useSession((s) => s.init);
|
||||
useEffect(() => {
|
||||
useDownloads.getState().init();
|
||||
useRouter.getState().reset({ name: 'downloads' });
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<div className="app-shell offline">
|
||||
<div className="offline-banner" data-tauri-drag-region>
|
||||
<span>{error || 'You’re offline.'}</span>
|
||||
<button className="btn text" onClick={() => init()}>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
<div className="main-scroll">
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Downloads offline />
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
<PlayerOverlay />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
const status = useSession((s) => s.status);
|
||||
const hasServer = useSession((s) => !!s.server);
|
||||
const reducedMotion = useSettings((s) => s.reducedMotion);
|
||||
const [splashDone, setSplashDone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
useSession.getState().init();
|
||||
// The window appears once the first frame is painted (no white flash).
|
||||
requestAnimationFrame(() => win.show());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('reduced-motion', reducedMotion);
|
||||
}, [reducedMotion]);
|
||||
|
||||
// Switching servers or users starts browsing fresh.
|
||||
const serverId = useSession((s) => s.server?.machineId);
|
||||
useEffect(() => {
|
||||
if (serverId) useRouter.getState().reset({ name: 'home' });
|
||||
}, [serverId]);
|
||||
|
||||
let body;
|
||||
if (status === 'loading') body = null;
|
||||
else if (status === 'signed-out') body = <SignIn />;
|
||||
else if (status === 'choose-server' || (status === 'connecting' && !hasServer)) body = <ServerPicker />;
|
||||
else if (status === 'offline') body = <OfflineShell />;
|
||||
else body = <Shell />;
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{body}
|
||||
{(!splashDone || status === 'loading') && <Splash ready={status !== 'loading'} onDone={() => setSplashDone(true)} />}
|
||||
<HoverPreviewHost />
|
||||
<DialogHost />
|
||||
<MenuHost />
|
||||
<ConfirmHost />
|
||||
<ToastHost />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
126
src/app/TopBar.tsx
Normal file
126
src/app/TopBar.tsx
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { navigate, topLevel, useRouter } from './router';
|
||||
import { useSession } from './session';
|
||||
import { useSettings } from './settings';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { KaleidoMark } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
import { isNative, win } from '../platform/native';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { useHomeUsers } from './useHomeUsers';
|
||||
|
||||
const NAV = [
|
||||
{ id: 'home', label: 'Home', route: { name: 'home' } as const },
|
||||
{ id: 'movies', label: 'Movies', route: { name: 'section', kind: 'movie', tab: 'discover' } as const },
|
||||
{ id: 'shows', label: 'TV Shows', route: { name: 'section', kind: 'show', tab: 'discover' } as const },
|
||||
{ id: 'downloads', label: 'Downloads', route: { name: 'downloads' } as const },
|
||||
];
|
||||
|
||||
function WindowControls() {
|
||||
const [maximized, setMaximized] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!isNative) return;
|
||||
let off: (() => void) | undefined;
|
||||
const sync = () => win.isMaximized().then(setMaximized);
|
||||
sync();
|
||||
win.onResized(sync).then((u) => (off = u));
|
||||
return () => off?.();
|
||||
}, []);
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label={maximized ? 'Restore' : 'Maximize'} onClick={() => win.toggleMaximize()}>
|
||||
<Icon name={maximized ? 'restore' : 'maximize'} size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Avatar() {
|
||||
const user = useSession((s) => s.user);
|
||||
const server = useSession((s) => s.server);
|
||||
const connection = useSession((s) => s.connection);
|
||||
const showServerPicker = useSession((s) => s.showServerPicker);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const home = useHomeUsers();
|
||||
const initial = (user?.title || server?.name || 'K').slice(0, 1).toUpperCase();
|
||||
const menu = (el: HTMLElement) => {
|
||||
const items: MenuItem[] = [
|
||||
{ heading: user ? user.title : 'Kaleido' },
|
||||
{
|
||||
label: server ? `${server.name}` : 'No server',
|
||||
hint: connection ? (connection.relay ? 'Relay' : connection.local ? 'Local' : 'Remote') : '',
|
||||
icon: 'server',
|
||||
onSelect: showServerPicker,
|
||||
},
|
||||
];
|
||||
if (home.users.length > 1) {
|
||||
items.push({
|
||||
label: 'Switch profile',
|
||||
icon: 'users',
|
||||
submenu: home.users.map((u) => ({ label: u.title, checked: u.uuid === user?.uuid, onSelect: () => home.switchTo(u) })),
|
||||
});
|
||||
}
|
||||
items.push(
|
||||
{ divider: true },
|
||||
{ label: 'Settings', icon: 'settings', onSelect: () => navigate({ name: 'settings', mode: 'app', tab: 'general' }) },
|
||||
);
|
||||
if (server?.owned) items.push({ label: 'Server dashboard', icon: 'activity', onSelect: () => navigate({ name: 'settings', mode: 'server', tab: 'dashboard' }) });
|
||||
items.push({ divider: true }, { label: 'Sign out', icon: 'logout', onSelect: signOut });
|
||||
openMenu(items, el, { align: 'end', minWidth: 250 });
|
||||
};
|
||||
return (
|
||||
<button className="avatar-btn" aria-label="Account" onClick={(e) => menu(e.currentTarget)}>
|
||||
{user?.thumb ? <img src={user.thumb} alt="" draggable={false} /> : <span>{initial}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TopBar({ solid }: { solid: boolean }) {
|
||||
const current = useRouter((s) => s.current.route);
|
||||
const canBack = useRouter((s) => s.index > 0);
|
||||
const back = useRouter((s) => s.back);
|
||||
const active = topLevel(current);
|
||||
const activeDownloads = useDownloads((s) => s.items.filter((d) => d.status === 'downloading' || d.status === 'queued').length);
|
||||
const startPage = useSettings((s) => s.startPage);
|
||||
void startPage;
|
||||
const showBack = canBack && !active;
|
||||
|
||||
return (
|
||||
<header className={`topbar${solid ? ' solid' : ''}`} data-tauri-drag-region>
|
||||
<div className="topbar-left" data-tauri-drag-region>
|
||||
<button className={`nav-back${showBack ? ' show' : ''}`} aria-label="Back" onClick={back} tabIndex={showBack ? 0 : -1}>
|
||||
<Icon name="arrowLeft" size={19} />
|
||||
</button>
|
||||
<button className="brand" onClick={() => navigate({ name: 'home' })} aria-label="Kaleido home">
|
||||
<KaleidoMark size={24} />
|
||||
<span>KALEIDO</span>
|
||||
</button>
|
||||
<nav className="primary-nav" aria-label="Main navigation" data-tauri-drag-region>
|
||||
{NAV.map((n) => (
|
||||
<button key={n.id} className={`nav-item${active === n.id ? ' active' : ''}`} onClick={() => navigate(n.route)}>
|
||||
{n.label}
|
||||
{n.id === 'downloads' && activeDownloads > 0 && <span className="nav-count">{activeDownloads}</span>}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
<div className="topbar-right" data-tauri-drag-region>
|
||||
<button className={`icon-btn${active === 'search' ? ' on' : ''}`} aria-label="Search" title="Search (Ctrl+K)" onClick={() => navigate({ name: 'search' })}>
|
||||
<Icon name="search" size={19} />
|
||||
</button>
|
||||
<button className={`icon-btn${active === 'settings' ? ' on' : ''}`} aria-label="Settings" title="Settings" onClick={() => navigate({ name: 'settings', mode: 'app', tab: 'general' })}>
|
||||
<Icon name="settings" size={19} />
|
||||
</button>
|
||||
<Avatar />
|
||||
<WindowControls />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
230
src/app/actions.ts
Normal file
230
src/app/actions.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { navigate } from './router';
|
||||
import { useSession } from './session';
|
||||
import { invalidateItem, invalidateLibrary } from './queries';
|
||||
import { isWatched } from './format';
|
||||
import { useSettings } from './settings';
|
||||
import { usePlayer, type PlayOptions } from '../player/store';
|
||||
import { confirmDialog, toast, toastError, type MenuItem } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
|
||||
const server = () => {
|
||||
const s = useSession.getState().server;
|
||||
if (!s) throw new Error('Not connected to a server.');
|
||||
return s;
|
||||
};
|
||||
|
||||
export const canManage = () => !!useSession.getState().server?.owned;
|
||||
|
||||
export function openItem(item: Item) {
|
||||
if (item.type === 'clip') {
|
||||
playItem(item, { resume: false });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'person') {
|
||||
navigate({ name: 'person', id: item.id, title: item.title, thumb: item.thumb });
|
||||
return;
|
||||
}
|
||||
navigate({ name: 'item', id: item.id, title: item.title });
|
||||
}
|
||||
|
||||
/** Plays a title. Shows and seasons play their next episode. */
|
||||
export async function playItem(item: Item, opts: PlayOptions = {}) {
|
||||
try {
|
||||
if (item.type === 'show' || item.type === 'season') {
|
||||
const s = server();
|
||||
const full = await api.metadata(s, item.id);
|
||||
let next = await api.onDeckFor(s, full);
|
||||
if (!next) {
|
||||
const leaves = await api.allLeaves(s, item.id);
|
||||
next = leaves.find((e) => !isWatched(e)) ?? leaves[0] ?? null;
|
||||
}
|
||||
if (!next) throw new Error('There are no episodes to play.');
|
||||
await usePlayer.getState().play(next, { resume: true, ...opts });
|
||||
return;
|
||||
}
|
||||
if (item.type === 'collection') {
|
||||
const items = await api.collectionItems(server(), item.id);
|
||||
if (items[0]) await playItem(items[0], opts);
|
||||
return;
|
||||
}
|
||||
const local = useDownloads.getState().localFileFor(item.id);
|
||||
if (local && !opts.localFile && !useSession.getState().server) opts = { ...opts, localFile: local };
|
||||
await usePlayer.getState().play(item, { resume: true, ...opts });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function shuffleItem(item: Item) {
|
||||
try {
|
||||
const leaves = await api.allLeaves(server(), item.id);
|
||||
if (!leaves.length) return;
|
||||
const pick = leaves[Math.floor(Math.random() * leaves.length)];
|
||||
await usePlayer.getState().play(pick, { resume: false });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function setWatched(item: Item, watched: boolean) {
|
||||
try {
|
||||
await api.setWatched(server(), item.id, watched);
|
||||
toast(watched ? `Marked “${item.title}” watched` : `Marked “${item.title}” unwatched`, 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeFromContinueWatching(item: Item) {
|
||||
try {
|
||||
await api.removeFromContinueWatching(server(), item.id);
|
||||
toast('Removed from Continue Watching', 'success');
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
}
|
||||
|
||||
async function run(label: string, fn: () => Promise<unknown>, done?: string) {
|
||||
try {
|
||||
await fn();
|
||||
if (done) toast(done, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
void label;
|
||||
}
|
||||
|
||||
export const admin = {
|
||||
refresh: (item: Item) =>
|
||||
run('refresh', async () => {
|
||||
await api.refreshMetadata(server(), item.id);
|
||||
setTimeout(() => invalidateItem(item.id), 4000);
|
||||
}, `Refreshing metadata for “${item.title}”`),
|
||||
analyze: (item: Item) => run('analyze', () => api.analyze(server(), item.id), `Analyzing “${item.title}”`),
|
||||
unmatch: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Unmatch this title?', message: `Plex will remove the metadata for “${item.title}” and show it by its file name until it is matched again.`, confirm: 'Unmatch', danger: true }))) return;
|
||||
await run('unmatch', async () => {
|
||||
await api.unmatch(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Title unmatched');
|
||||
},
|
||||
split: async (item: Item) => {
|
||||
if (!(await confirmDialog({ title: 'Split apart?', message: `Each version of “${item.title}” will become a separate title.`, confirm: 'Split apart' }))) return;
|
||||
await run('split', async () => {
|
||||
await api.splitApart(server(), item.id);
|
||||
invalidateLibrary();
|
||||
}, 'Versions split apart');
|
||||
},
|
||||
remove: async (item: Item, onDone?: () => void) => {
|
||||
const ok = await confirmDialog({
|
||||
title: `Delete “${item.title}”?`,
|
||||
message: 'This permanently deletes the media files from the server’s disk and removes the title from the library. This cannot be undone.',
|
||||
confirm: 'Delete files',
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
try {
|
||||
await api.deleteItem(server(), item.id);
|
||||
toast(`Deleted “${item.title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onDone?.();
|
||||
} catch (e: any) {
|
||||
toast(e?.status === 403 || e?.status === 401 ? 'The server does not allow media deletion. Enable it in Settings › Plex server › Library.' : e.message, 'error');
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// —— Dialog routing ——————————————————————————————————————————————
|
||||
|
||||
export type DialogRequest =
|
||||
| { kind: 'edit'; item: Item }
|
||||
| { kind: 'match'; item: Item }
|
||||
| { kind: 'info'; item: Item }
|
||||
| { kind: 'artwork'; item: Item; type: 'poster' | 'art' | 'clearLogo' }
|
||||
| { kind: 'collection'; item: Item }
|
||||
| { kind: 'playlist'; item: Item }
|
||||
| { kind: 'trailer'; item: Item }
|
||||
| { kind: 'synopsis'; item: Item }
|
||||
| { kind: 'versions'; item: Item; onPick: (index: number) => void };
|
||||
|
||||
export const useDialogs = create<{ dialog: DialogRequest | null; open(d: DialogRequest): void; close(): void }>((set) => ({
|
||||
dialog: null,
|
||||
open: (dialog) => set({ dialog }),
|
||||
close: () => set({ dialog: null }),
|
||||
}));
|
||||
export const openDialog = (d: DialogRequest) => useDialogs.getState().open(d);
|
||||
|
||||
/** Plays with a version choice when a title has several. */
|
||||
export function playWithVersion(item: Item, opts: PlayOptions = {}) {
|
||||
if (item.media.length > 1 && opts.mediaIndex === undefined) {
|
||||
openDialog({ kind: 'versions', item, onPick: (mediaIndex) => playItem(item, { ...opts, mediaIndex }) });
|
||||
return;
|
||||
}
|
||||
playItem(item, opts);
|
||||
}
|
||||
|
||||
/** The full context menu for a title, as on cards and the detail page "More" button. */
|
||||
export function itemMenu(item: Item, ctx: { continueWatching?: boolean; onDeleted?: () => void; detail?: boolean } = {}): MenuItem[] {
|
||||
const owned = canManage();
|
||||
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
|
||||
const watched = isWatched(item, useSettings.getState().watchedPercent);
|
||||
const downloads = useDownloads.getState();
|
||||
const items: MenuItem[] = [];
|
||||
if (playable) {
|
||||
items.push({ label: item.viewOffset ? 'Resume' : 'Play', icon: 'play', onSelect: () => playWithVersion(item) });
|
||||
if (item.viewOffset) items.push({ label: 'Play from beginning', icon: 'replay10', onSelect: () => playWithVersion(item, { offsetMs: 0, resume: false }) });
|
||||
if (item.type === 'show' || item.type === 'season') items.push({ label: 'Shuffle episodes', icon: 'shuffle', onSelect: () => shuffleItem(item) });
|
||||
}
|
||||
if (!ctx.detail) items.push({ label: 'Details', icon: 'info', onSelect: () => openItem(item) });
|
||||
if (item.type === 'episode') {
|
||||
items.push({ label: 'Go to season', icon: 'layers', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.grandparentId }) });
|
||||
}
|
||||
if (item.type === 'season') items.push({ label: 'Go to show', icon: 'tv', onSelect: () => navigate({ name: 'item', id: item.parentId }) });
|
||||
if (playable && item.type !== 'clip') {
|
||||
items.push({ divider: true });
|
||||
items.push({ label: watched ? 'Mark unwatched' : 'Mark watched', icon: watched ? 'minus' : 'check', onSelect: () => setWatched(item, !watched) });
|
||||
if (ctx.continueWatching || (item.viewOffset > 0 && !watched)) items.push({ label: 'Remove from Continue Watching', icon: 'x', onSelect: () => removeFromContinueWatching(item) });
|
||||
}
|
||||
if (item.type === 'movie' || item.type === 'episode') {
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
items.push(
|
||||
dl
|
||||
? { label: dl.status === 'completed' ? 'Downloaded' : 'Downloading…', icon: 'downloaded', onSelect: () => navigate({ name: 'downloads' }) }
|
||||
: { label: 'Download', icon: 'download', onSelect: () => downloads.start(item) },
|
||||
);
|
||||
} else if (item.type === 'season' || item.type === 'show') {
|
||||
items.push({ label: item.type === 'show' ? 'Download all episodes' : 'Download season', icon: 'download', onSelect: () => downloads.startAll(item) });
|
||||
}
|
||||
if (['movie', 'show', 'season', 'episode'].includes(item.type)) {
|
||||
items.push({ label: 'Add to playlist…', icon: 'queue', onSelect: () => openDialog({ kind: 'playlist', item }) });
|
||||
}
|
||||
if (owned && ['movie', 'show'].includes(item.type)) items.push({ label: 'Add to collection…', icon: 'collection', onSelect: () => openDialog({ kind: 'collection', item }) });
|
||||
if (['movie', 'episode'].includes(item.type)) items.push({ label: 'Media info', icon: 'info', onSelect: () => openDialog({ kind: 'info', item }) });
|
||||
if (owned && ['movie', 'show', 'season', 'episode', 'collection'].includes(item.type)) {
|
||||
const manage: MenuItem[] = [
|
||||
{ label: 'Edit metadata…', icon: 'edit', onSelect: () => openDialog({ kind: 'edit', item }) },
|
||||
{ label: 'Change poster…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'poster' }) },
|
||||
{ label: 'Change background…', icon: 'image', onSelect: () => openDialog({ kind: 'artwork', item, type: 'art' }) },
|
||||
{ label: 'Refresh metadata', icon: 'refresh', onSelect: () => admin.refresh(item) },
|
||||
];
|
||||
if (item.type !== 'collection') manage.push({ label: 'Analyze', icon: 'activity', onSelect: () => admin.analyze(item) });
|
||||
if (item.type === 'movie' || item.type === 'show') {
|
||||
manage.push({ label: 'Fix match…', icon: 'wand', onSelect: () => openDialog({ kind: 'match', item }) });
|
||||
manage.push({ label: 'Unmatch', icon: 'unlink', onSelect: () => admin.unmatch(item) });
|
||||
}
|
||||
if (item.type === 'movie' && item.media.length > 1) manage.push({ label: 'Split apart', icon: 'split', onSelect: () => admin.split(item) });
|
||||
if (item.type !== 'collection') {
|
||||
manage.push({ divider: true });
|
||||
manage.push({ label: 'Delete from server…', icon: 'trash', danger: true, onSelect: () => admin.remove(item, ctx.onDeleted) });
|
||||
}
|
||||
items.push({ divider: true });
|
||||
items.push({ label: 'Manage', icon: 'tool', submenu: manage });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
190
src/app/format.ts
Normal file
190
src/app/format.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import type { Item, Media } from '../plex/types';
|
||||
|
||||
export function duration(ms: number): string {
|
||||
if (!ms || ms < 0) return '';
|
||||
const m = Math.round(ms / 60000);
|
||||
if (m < 60) return `${m}m`;
|
||||
const h = Math.floor(m / 60);
|
||||
return m % 60 ? `${h}h ${m % 60}m` : `${h}h`;
|
||||
}
|
||||
|
||||
export function clock(seconds: number, forceHours = false): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) seconds = 0;
|
||||
const s = Math.floor(seconds % 60);
|
||||
const m = Math.floor((seconds / 60) % 60);
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return h || forceHours ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
|
||||
}
|
||||
|
||||
export function remaining(item: Item): string {
|
||||
if (!item.duration || !item.viewOffset) return '';
|
||||
const left = Math.max(0, item.duration - item.viewOffset);
|
||||
const m = Math.round(left / 60000);
|
||||
if (m < 1) return 'Almost done';
|
||||
return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m left` : `${m}m left`;
|
||||
}
|
||||
|
||||
export function episodeLabel(item: Item, long = false): string {
|
||||
if (item.type !== 'episode') return '';
|
||||
if (long) return `Season ${item.parentIndex} · Episode ${item.index}`;
|
||||
return `S${item.parentIndex} · E${item.index}`;
|
||||
}
|
||||
|
||||
export function progress(item: Item): number {
|
||||
if (!item.duration || !item.viewOffset) return 0;
|
||||
return Math.min(1, Math.max(0, item.viewOffset / item.duration));
|
||||
}
|
||||
|
||||
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.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 {
|
||||
return Math.max(0, item.leafCount - item.viewedLeafCount);
|
||||
}
|
||||
|
||||
export function displayTitle(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentTitle || item.title;
|
||||
if (item.type === 'season') return item.parentTitle ? `${item.parentTitle}` : item.title;
|
||||
return item.title;
|
||||
}
|
||||
|
||||
export function subtitleFor(item: Item): string {
|
||||
switch (item.type) {
|
||||
case 'episode':
|
||||
return `${episodeLabel(item)} ${item.title}`;
|
||||
case 'season':
|
||||
return item.title + (item.leafCount ? ` · ${item.leafCount} episodes` : '');
|
||||
case 'show':
|
||||
return [item.year || '', item.childCount ? `${item.childCount} season${item.childCount === 1 ? '' : 's'}` : ''].filter(Boolean).join(' · ');
|
||||
case 'collection':
|
||||
return item.childCount ? `${item.childCount} titles` : 'Collection';
|
||||
case 'clip':
|
||||
return [extraLabel(item), duration(item.duration)].filter(Boolean).join(' · ');
|
||||
default:
|
||||
return [item.year || '', duration(item.duration)].filter(Boolean).join(' · ');
|
||||
}
|
||||
}
|
||||
|
||||
export function extraLabel(item: Item): string {
|
||||
const map: Record<string, string> = {
|
||||
trailer: 'Trailer',
|
||||
behindTheScenes: 'Behind the scenes',
|
||||
deletedScene: 'Deleted scene',
|
||||
featurette: 'Featurette',
|
||||
interview: 'Interview',
|
||||
sceneOrSample: 'Scene',
|
||||
short: 'Short',
|
||||
};
|
||||
return map[item.subtype] ?? (item.type === 'clip' ? 'Extra' : '');
|
||||
}
|
||||
|
||||
/** Image path choices per presentation. */
|
||||
export const art = {
|
||||
poster(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentThumb || item.parentThumb || item.thumb;
|
||||
if (item.type === 'season') return item.thumb || item.parentThumb;
|
||||
return item.thumb;
|
||||
},
|
||||
landscape(item: Item): string {
|
||||
if (item.type === 'episode' || item.type === 'clip') return item.thumb || item.art;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
backdrop(item: Item): string {
|
||||
if (item.type === 'episode') return item.grandparentArt || item.art || item.thumb;
|
||||
return item.art || item.grandparentArt || item.thumb;
|
||||
},
|
||||
};
|
||||
|
||||
export function resolutionLabel(m?: Media): string {
|
||||
if (!m) return '';
|
||||
const r = m.videoResolution.toLowerCase();
|
||||
if (r === '4k') return '4K';
|
||||
if (r === 'sd') return 'SD';
|
||||
if (/^\d+$/.test(r)) return `${r}p`;
|
||||
if (m.height >= 2000) return '4K';
|
||||
if (m.height >= 1000) return '1080p';
|
||||
if (m.height >= 700) return '720p';
|
||||
return r.toUpperCase();
|
||||
}
|
||||
|
||||
export function channelLabel(n: number): string {
|
||||
return n === 1 ? 'Mono' : n === 2 ? 'Stereo' : n === 6 ? '5.1' : n === 8 ? '7.1' : n ? `${n} ch` : '';
|
||||
}
|
||||
|
||||
/** Format badges: 4K, HDR flavor, Atmos/5.1 — the facts that matter at a glance. */
|
||||
export function formatBadges(item: Item): string[] {
|
||||
const m = item.media[0];
|
||||
if (!m) return [];
|
||||
const out: string[] = [];
|
||||
const res = resolutionLabel(m);
|
||||
if (res === '4K' || res === '1080p' || res === '720p') out.push(res.toUpperCase());
|
||||
if (m.dynamicRange === 'Dolby Vision') out.push('DOLBY VISION');
|
||||
else if (m.dynamicRange) out.push(m.dynamicRange === 'HDR10' ? 'HDR' : m.dynamicRange);
|
||||
if (m.atmos) out.push('ATMOS');
|
||||
else if (m.audioChannels >= 6) out.push(channelLabel(m.audioChannels));
|
||||
return out;
|
||||
}
|
||||
|
||||
export function technicalLine(m?: Media): string {
|
||||
if (!m) return '';
|
||||
return [
|
||||
m.videoCodec.toUpperCase(),
|
||||
[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' '),
|
||||
m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
export function fileSize(bytes: number): string {
|
||||
if (!bytes) return '';
|
||||
if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(2)} TB`;
|
||||
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
|
||||
return `${Math.round(bytes / 1e3)} KB`;
|
||||
}
|
||||
|
||||
export function bitrate(kbps: number): string {
|
||||
if (!kbps) return '';
|
||||
return kbps >= 1000 ? `${(kbps / 1000).toFixed(kbps >= 10000 ? 0 : 1)} Mbps` : `${kbps} kbps`;
|
||||
}
|
||||
|
||||
export function date(value: string | number): string {
|
||||
if (!value) return '';
|
||||
const d = typeof value === 'number' ? new Date(value * 1000) : new Date(value);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
|
||||
}
|
||||
|
||||
export function relativeTime(seconds: number): string {
|
||||
if (!seconds) return '';
|
||||
const diff = Date.now() / 1000 - seconds;
|
||||
if (diff < 60) return 'just now';
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)} min ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)} hr ago`;
|
||||
if (diff < 86400 * 30) return `${Math.floor(diff / 86400)} days ago`;
|
||||
return date(seconds);
|
||||
}
|
||||
|
||||
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 '';
|
||||
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 [
|
||||
`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%)`,
|
||||
].join(', ');
|
||||
}
|
||||
91
src/app/keyboardNav.ts
Normal file
91
src/app/keyboardNav.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* 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, episode lists and people rows.
|
||||
*/
|
||||
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 };
|
||||
}
|
||||
|
||||
function nearest(from: HTMLElement, dir: 'left' | 'right' | 'up' | 'down'): HTMLElement | null {
|
||||
const a = from.getBoundingClientRect();
|
||||
const ac = center(a);
|
||||
const scope = from.closest('.main-scroll') ?? document;
|
||||
let best: HTMLElement | null = null;
|
||||
let bestScore = Infinity;
|
||||
for (const el of scope.querySelectorAll<HTMLElement>(TARGETS)) {
|
||||
if (el === from || el.offsetParent === null) continue;
|
||||
const b = el.getBoundingClientRect();
|
||||
const bc = center(b);
|
||||
const dx = bc.x - ac.x;
|
||||
const dy = bc.y - ac.y;
|
||||
let primary: number;
|
||||
let secondary: number;
|
||||
switch (dir) {
|
||||
case 'right':
|
||||
if (b.left < a.right - 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'left':
|
||||
if (b.right > a.left + 4 || Math.abs(dy) > a.height * 0.6) continue;
|
||||
primary = -dx;
|
||||
secondary = Math.abs(dy);
|
||||
break;
|
||||
case 'down':
|
||||
if (b.top < a.bottom - 4) continue;
|
||||
primary = dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
case 'up':
|
||||
if (b.bottom > a.top + 4) continue;
|
||||
primary = -dy;
|
||||
secondary = Math.abs(dx);
|
||||
break;
|
||||
}
|
||||
// Prefer the next row/column first, then the closest within it.
|
||||
const score = primary + secondary * (dir === 'up' || dir === 'down' ? 0.35 : 2);
|
||||
if (score < bestScore) {
|
||||
bestScore = score;
|
||||
best = el;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export function installKeyboardNav() {
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
|
||||
const target = e.target as HTMLElement;
|
||||
if (document.documentElement.classList.contains('player-open')) return;
|
||||
if (document.querySelector('.menu-layer, .dialog-layer')) return;
|
||||
|
||||
// "/" focuses the nearest search field.
|
||||
if (e.key === '/' && !target.closest('input, textarea')) {
|
||||
const field = document.querySelector<HTMLInputElement>('.lib-search input, .search-field input');
|
||||
if (field) {
|
||||
e.preventDefault();
|
||||
field.focus();
|
||||
field.select();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!target.matches?.(TARGETS)) return;
|
||||
if ((e.key === 'ContextMenu' || (e.shiftKey && e.key === 'F10')) && !target.matches('.shelf-title-link')) {
|
||||
e.preventDefault();
|
||||
const r = target.getBoundingClientRect();
|
||||
target.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 24, clientY: r.top + 24 }));
|
||||
return;
|
||||
}
|
||||
const dir = ({ ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down' } as const)[e.key as 'ArrowLeft'];
|
||||
if (!dir) return;
|
||||
const next = nearest(target, dir);
|
||||
if (!next) return;
|
||||
e.preventDefault();
|
||||
next.focus({ preventScroll: true });
|
||||
next.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
|
||||
});
|
||||
}
|
||||
53
src/app/queries.ts
Normal file
53
src/app/queries.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
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 { useSettings } from './settings';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 60_000,
|
||||
gcTime: 30 * 60_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/** Every key starts with the server so switching servers never mixes caches. */
|
||||
export function useKey(...parts: unknown[]) {
|
||||
const server = useServer();
|
||||
return [server.machineId, ...parts];
|
||||
}
|
||||
|
||||
export function useServerQuery<T>(parts: unknown[], fn: (s: ReturnType<typeof useServer>) => Promise<T>, opts: Partial<UseQueryOptions<T>> = {}) {
|
||||
const server = useServer();
|
||||
return useQuery<T>({ queryKey: [server.machineId, ...parts], queryFn: () => fn(server), ...opts } as UseQueryOptions<T>);
|
||||
}
|
||||
|
||||
export const useSections = () => useServerQuery(['sections'], (s) => api.sections(s), { staleTime: 5 * 60_000 });
|
||||
|
||||
/** The library a Movies or TV destination shows: the user's choice, else the first. */
|
||||
export function useSectionFor(kind: 'movie' | 'show'): { section: Section | null; all: Section[]; loading: boolean } {
|
||||
const { data, isLoading } = useSections();
|
||||
const chosen = useSettings((s) => (kind === 'movie' ? s.movieSection : s.showSection));
|
||||
const all = (data ?? []).filter((s) => s.type === kind && !s.hidden);
|
||||
return { section: all.find((s) => s.id === chosen) ?? all[0] ?? null, all, loading: isLoading };
|
||||
}
|
||||
|
||||
export const useItem = (id: string | undefined, opts: Partial<UseQueryOptions<Item>> = {}) =>
|
||||
useServerQuery(['item', id], (s) => api.metadata(s, id!), { enabled: !!id, staleTime: 30_000, ...opts });
|
||||
|
||||
export const useChildren = (id: string | undefined) => useServerQuery(['children', id], (s) => api.children(s, id!), { enabled: !!id, staleTime: 30_000 });
|
||||
|
||||
export const useRelated = (id: string | undefined) => useServerQuery(['related', id], (s) => api.related(s, id!), { enabled: !!id, staleTime: 10 * 60_000 });
|
||||
|
||||
/** After a watched-state or metadata change, refresh everything that may show it. */
|
||||
export function invalidateLibrary() {
|
||||
queryClient.invalidateQueries({ predicate: (q) => !['sections', 'libraryMeta', 'filterOptions', 'serverPrefs'].includes(String(q.queryKey[1])) });
|
||||
}
|
||||
|
||||
export function invalidateItem(id: string) {
|
||||
queryClient.invalidateQueries({ predicate: (q) => q.queryKey.includes(id) });
|
||||
}
|
||||
101
src/app/router.ts
Normal file
101
src/app/router.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { create } from 'zustand';
|
||||
|
||||
export type SectionKind = 'movie' | 'show';
|
||||
export type SectionTab = 'discover' | 'library' | 'collections';
|
||||
|
||||
export type Route =
|
||||
| { name: 'home' }
|
||||
| { name: 'section'; kind: SectionKind; tab: SectionTab }
|
||||
| { name: 'item'; id: string; title?: string }
|
||||
| { name: 'person'; id: string; title: string; thumb?: string }
|
||||
| { name: 'hub'; key: string; title: string }
|
||||
| { name: 'search'; query?: string }
|
||||
| { name: 'downloads' }
|
||||
| { name: 'settings'; mode: 'app' | 'server'; tab: string };
|
||||
|
||||
export interface Entry {
|
||||
id: number;
|
||||
route: Route;
|
||||
scroll: number;
|
||||
/** Per-screen state to restore on Back (e.g. selected season, library offset). */
|
||||
state: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface RouterState {
|
||||
entries: Entry[];
|
||||
index: number;
|
||||
current: Entry;
|
||||
navigate(route: Route, opts?: { replace?: boolean }): void;
|
||||
back(): void;
|
||||
forward(): void;
|
||||
canBack(): boolean;
|
||||
saveScroll(scroll: number): void;
|
||||
setState(patch: Record<string, unknown>): void;
|
||||
reset(route: Route): void;
|
||||
}
|
||||
|
||||
let nextId = 1;
|
||||
const entry = (route: Route): Entry => ({ id: nextId++, route, scroll: 0, state: {} });
|
||||
const MAX = 60;
|
||||
|
||||
const sameDestination = (a: Route, b: Route) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
export const useRouter = create<RouterState>((set, get) => {
|
||||
const first = entry({ name: 'home' });
|
||||
return {
|
||||
entries: [first],
|
||||
index: 0,
|
||||
current: first,
|
||||
navigate(route, opts) {
|
||||
const { entries, index } = get();
|
||||
if (sameDestination(entries[index].route, route)) return;
|
||||
const e = entry(route);
|
||||
let next = entries.slice(0, index + 1);
|
||||
if (opts?.replace) next[next.length - 1] = e;
|
||||
else next.push(e);
|
||||
if (next.length > MAX) next = next.slice(next.length - MAX);
|
||||
set({ entries: next, index: next.length - 1, current: e });
|
||||
},
|
||||
back() {
|
||||
const { entries, index } = get();
|
||||
if (index > 0) set({ index: index - 1, current: entries[index - 1] });
|
||||
},
|
||||
forward() {
|
||||
const { entries, index } = get();
|
||||
if (index < entries.length - 1) set({ index: index + 1, current: entries[index + 1] });
|
||||
},
|
||||
canBack: () => get().index > 0,
|
||||
saveScroll(scroll) {
|
||||
get().current.scroll = scroll;
|
||||
},
|
||||
setState(patch) {
|
||||
const cur = get().current;
|
||||
cur.state = { ...cur.state, ...patch };
|
||||
},
|
||||
reset(route) {
|
||||
const e = entry(route);
|
||||
set({ entries: [e], index: 0, current: e });
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const navigate = (route: Route, opts?: { replace?: boolean }) => useRouter.getState().navigate(route, opts);
|
||||
export const goBack = () => useRouter.getState().back();
|
||||
|
||||
/** The top-level destination a route belongs to, for the navigation highlight. */
|
||||
export function topLevel(route: Route): string {
|
||||
switch (route.name) {
|
||||
case 'home':
|
||||
return 'home';
|
||||
case 'section':
|
||||
return route.kind === 'movie' ? 'movies' : 'shows';
|
||||
case 'search':
|
||||
return 'search';
|
||||
case 'downloads':
|
||||
return 'downloads';
|
||||
case 'settings':
|
||||
return 'settings';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
213
src/app/session.ts
Normal file
213
src/app/session.ts
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
import { create } from 'zustand';
|
||||
import { appInfo, devSession, isNative, secrets } from '../platform/native';
|
||||
import { configureClient, PlexError, PlexServer } from '../plex/client';
|
||||
import * as account from '../plex/account';
|
||||
import type { PlexUser, ServerResource } from '../plex/types';
|
||||
|
||||
export type Status = 'loading' | 'signed-out' | 'choose-server' | 'connecting' | 'ready' | 'offline';
|
||||
|
||||
interface StoredServer {
|
||||
id: string;
|
||||
name: string;
|
||||
uri: string;
|
||||
owned: boolean;
|
||||
manual?: boolean;
|
||||
}
|
||||
|
||||
interface SessionState {
|
||||
status: Status;
|
||||
error: string;
|
||||
accountToken: string | null;
|
||||
user: PlexUser | null;
|
||||
resources: ServerResource[];
|
||||
server: PlexServer | null;
|
||||
connection: { local: boolean; relay: boolean } | null;
|
||||
init(): Promise<void>;
|
||||
completeSignIn(token: string): Promise<void>;
|
||||
refreshResources(): Promise<ServerResource[]>;
|
||||
chooseServer(resource: ServerResource): Promise<void>;
|
||||
connectManual(uri: string, token: string): Promise<void>;
|
||||
reconnect(): Promise<void>;
|
||||
switchUser(token: string): Promise<void>;
|
||||
showServerPicker(): void;
|
||||
signOut(): Promise<void>;
|
||||
}
|
||||
|
||||
const SERVER_KEY = 'kaleido.server';
|
||||
const loadStoredServer = (): StoredServer | null => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SERVER_KEY) ?? 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const storeServer = (s: StoredServer | null) => (s ? localStorage.setItem(SERVER_KEY, JSON.stringify(s)) : localStorage.removeItem(SERVER_KEY));
|
||||
|
||||
export const useSession = create<SessionState>((set, get) => ({
|
||||
status: 'loading',
|
||||
error: '',
|
||||
accountToken: null,
|
||||
user: null,
|
||||
resources: [],
|
||||
server: null,
|
||||
connection: null,
|
||||
|
||||
async init() {
|
||||
const info = await appInfo();
|
||||
configureClient({ version: info.version, deviceName: info.deviceName });
|
||||
let token = await secrets.get('account-token');
|
||||
const stored = loadStoredServer();
|
||||
|
||||
if (!token) {
|
||||
const dev = await devSession();
|
||||
if (dev) {
|
||||
// The development token is the owner's account token.
|
||||
try {
|
||||
await account.getUser(dev.token);
|
||||
token = dev.token;
|
||||
await secrets.set('account-token', token);
|
||||
} catch {
|
||||
try {
|
||||
await get().connectManual(dev.server, dev.token);
|
||||
return;
|
||||
} catch {
|
||||
/* fall through to sign-in */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (stored?.manual) {
|
||||
const serverToken = await secrets.get('server-token');
|
||||
if (serverToken) {
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch (e: any) {
|
||||
set({ status: 'offline', error: e.message });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
set({ status: 'signed-out' });
|
||||
return;
|
||||
}
|
||||
set({ accountToken: token });
|
||||
try {
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
} catch (e: any) {
|
||||
if (e instanceof PlexError && (e.status === 401 || e.status === 403)) {
|
||||
await secrets.delete('account-token');
|
||||
set({ status: 'signed-out', accountToken: null, error: 'Your Plex session has expired. Sign in again.' });
|
||||
return;
|
||||
}
|
||||
// plex.tv unreachable: try the last server directly.
|
||||
if (stored) {
|
||||
const serverToken = (await secrets.get('server-token')) ?? token;
|
||||
try {
|
||||
await get().connectManual(stored.uri, serverToken);
|
||||
return;
|
||||
} catch {
|
||||
/* offline */
|
||||
}
|
||||
}
|
||||
set({ status: 'offline', error: 'Kaleido cannot reach Plex right now. Downloaded titles are still available.' });
|
||||
return;
|
||||
}
|
||||
const resources = await get().refreshResources().catch(() => [] as ServerResource[]);
|
||||
const preferred = resources.find((r) => r.id === stored?.id);
|
||||
if (preferred) {
|
||||
await get().chooseServer(preferred);
|
||||
return;
|
||||
}
|
||||
if (resources.length === 1) {
|
||||
await get().chooseServer(resources[0]);
|
||||
return;
|
||||
}
|
||||
set({ status: resources.length ? 'choose-server' : 'choose-server', error: resources.length ? '' : 'No Plex Media Servers are available to this account.' });
|
||||
},
|
||||
|
||||
async completeSignIn(token) {
|
||||
await secrets.set('account-token', token);
|
||||
set({ accountToken: token, error: '', status: 'connecting' });
|
||||
const user = await account.getUser(token);
|
||||
set({ user });
|
||||
const resources = await get().refreshResources();
|
||||
if (resources.length === 1) await get().chooseServer(resources[0]);
|
||||
else set({ status: 'choose-server' });
|
||||
},
|
||||
|
||||
async refreshResources() {
|
||||
const token = get().accountToken;
|
||||
if (!token) return [];
|
||||
const resources = await account.getResources(token);
|
||||
resources.sort((a, b) => Number(b.owned) - Number(a.owned) || Number(b.presence) - Number(a.presence) || a.name.localeCompare(b.name));
|
||||
set({ resources });
|
||||
return resources;
|
||||
},
|
||||
|
||||
async chooseServer(resource) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const stored = loadStoredServer();
|
||||
try {
|
||||
const r = await account.connect(resource, stored?.id === resource.id ? stored.uri : undefined);
|
||||
const server = new PlexServer(r.uri, resource.accessToken, r.machineId, resource.name, resource.owned, r.local);
|
||||
storeServer({ id: resource.id, name: resource.name, uri: r.uri, owned: resource.owned });
|
||||
await secrets.set('server-token', resource.accessToken);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: r.relay } });
|
||||
} catch (e: any) {
|
||||
set({ status: 'choose-server', error: e.message ?? String(e) });
|
||||
}
|
||||
},
|
||||
|
||||
async connectManual(uri, token) {
|
||||
set({ status: 'connecting', error: '' });
|
||||
const r = await account.connectManual(uri, token);
|
||||
const owned = await account
|
||||
.getUser(token)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
const server = new PlexServer(r.uri, token, r.machineId, r.name, owned, r.local);
|
||||
storeServer({ id: r.machineId, name: r.name, uri: r.uri, owned, manual: !get().accountToken });
|
||||
await secrets.set('server-token', token);
|
||||
set({ server, status: 'ready', connection: { local: r.local, relay: false } });
|
||||
},
|
||||
|
||||
async reconnect() {
|
||||
const { resources, server } = get();
|
||||
const resource = resources.find((r) => r.id === server?.machineId);
|
||||
if (resource) await get().chooseServer(resource);
|
||||
else await get().init();
|
||||
},
|
||||
|
||||
async switchUser(token) {
|
||||
await secrets.set('account-token', token);
|
||||
storeServer(null);
|
||||
set({ accountToken: token, server: null, status: 'connecting' });
|
||||
await get().init();
|
||||
},
|
||||
|
||||
showServerPicker() {
|
||||
set({ status: 'choose-server', error: '' });
|
||||
get().refreshResources().catch(() => {});
|
||||
},
|
||||
|
||||
async signOut() {
|
||||
const token = get().accountToken;
|
||||
if (token && isNative) await account.signOut(token);
|
||||
await secrets.delete('account-token');
|
||||
await secrets.delete('server-token');
|
||||
storeServer(null);
|
||||
set({ status: 'signed-out', accountToken: null, user: null, server: null, resources: [], connection: null, error: '' });
|
||||
},
|
||||
}));
|
||||
|
||||
/** The connected server. Only call beneath screens rendered when status is ready. */
|
||||
export function useServer(): PlexServer {
|
||||
const s = useSession((st) => st.server);
|
||||
if (!s) throw new Error('No server connection');
|
||||
return s;
|
||||
}
|
||||
102
src/app/settings.ts
Normal file
102
src/app/settings.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
export type Quality = 'original' | '2160' | '1080' | '720' | '480';
|
||||
export type SkipMode = 'off' | 'button' | 'auto';
|
||||
export type SubtitleMode = 'auto' | 'always' | 'forced' | 'off';
|
||||
|
||||
export interface Preferences {
|
||||
// Playback
|
||||
quality: Quality;
|
||||
remoteQuality: Quality;
|
||||
hwdec: boolean;
|
||||
hdrPassthrough: boolean;
|
||||
autoplayNext: boolean;
|
||||
countdownSeconds: number;
|
||||
skipIntro: SkipMode;
|
||||
skipCredits: SkipMode;
|
||||
watchedPercent: number;
|
||||
audioLanguage: string;
|
||||
subtitleMode: SubtitleMode;
|
||||
subtitleLanguage: string;
|
||||
subtitleScale: number;
|
||||
subtitleBackground: boolean;
|
||||
volume: number;
|
||||
seekStep: number;
|
||||
// Interface
|
||||
startPage: 'home' | 'movies' | 'shows';
|
||||
colorWash: boolean;
|
||||
reducedMotion: boolean;
|
||||
posterSize: 'compact' | 'comfortable' | 'large';
|
||||
heroRotation: boolean;
|
||||
themeMusic: boolean;
|
||||
themeVolume: number;
|
||||
// Libraries shown for Movies and TV Shows
|
||||
movieSection: string;
|
||||
showSection: string;
|
||||
// Downloads
|
||||
downloadDir: string;
|
||||
// Remembered library views per section
|
||||
libraryViews: Record<string, { sort: string; filters: Record<string, string> }>;
|
||||
}
|
||||
|
||||
export const defaults: Preferences = {
|
||||
quality: 'original',
|
||||
remoteQuality: '1080',
|
||||
hwdec: true,
|
||||
hdrPassthrough: true,
|
||||
autoplayNext: true,
|
||||
countdownSeconds: 8,
|
||||
skipIntro: 'button',
|
||||
skipCredits: 'button',
|
||||
watchedPercent: 90,
|
||||
audioLanguage: '',
|
||||
subtitleMode: 'auto',
|
||||
subtitleLanguage: '',
|
||||
subtitleScale: 1,
|
||||
subtitleBackground: false,
|
||||
volume: 100,
|
||||
seekStep: 10,
|
||||
startPage: 'home',
|
||||
colorWash: true,
|
||||
reducedMotion: false,
|
||||
posterSize: 'comfortable',
|
||||
heroRotation: true,
|
||||
themeMusic: false,
|
||||
themeVolume: 30,
|
||||
movieSection: '',
|
||||
showSection: '',
|
||||
downloadDir: '',
|
||||
libraryViews: {},
|
||||
};
|
||||
|
||||
interface SettingsState extends Preferences {
|
||||
set<K extends keyof Preferences>(key: K, value: Preferences[K]): void;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export const useSettings = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
...defaults,
|
||||
set: (key, value) => set({ [key]: value } as Partial<SettingsState>),
|
||||
reset: () => set({ ...defaults }),
|
||||
}),
|
||||
{ name: 'kaleido.settings', version: 1 },
|
||||
),
|
||||
);
|
||||
|
||||
export const QUALITY_LABEL: Record<Quality, string> = {
|
||||
original: 'Original quality',
|
||||
'2160': '4K (40 Mbps)',
|
||||
'1080': '1080p (20 Mbps)',
|
||||
'720': '720p (4 Mbps)',
|
||||
'480': '480p (1.5 Mbps)',
|
||||
};
|
||||
|
||||
export const QUALITY_PROFILE: Record<Exclude<Quality, 'original'>, { kbps: number; width: number; height: number }> = {
|
||||
'2160': { kbps: 40000, width: 3840, height: 2160 },
|
||||
'1080': { kbps: 20000, width: 1920, height: 1080 },
|
||||
'720': { kbps: 4000, width: 1280, height: 720 },
|
||||
'480': { kbps: 1500, width: 854, height: 480 },
|
||||
};
|
||||
64
src/app/updater.ts
Normal file
64
src/app/updater.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
/**
|
||||
* Application updates through Tauri's signed updater. The feed
|
||||
* (`updates/latest.json`) lists a build per platform, so the same flow serves
|
||||
* Windows, macOS and Linux.
|
||||
*/
|
||||
import { create } from 'zustand';
|
||||
import { isNative } from '../platform/native';
|
||||
import { toast } from '../ui/overlays';
|
||||
|
||||
interface UpdaterState {
|
||||
checking: boolean;
|
||||
installing: boolean;
|
||||
progress: number;
|
||||
checkedAt: number;
|
||||
error: string;
|
||||
available: { version: string; notes: string } | null;
|
||||
}
|
||||
|
||||
export const useUpdater = create<UpdaterState>(() => ({
|
||||
checking: false,
|
||||
installing: false,
|
||||
progress: 0,
|
||||
checkedAt: 0,
|
||||
error: '',
|
||||
available: null,
|
||||
}));
|
||||
|
||||
let pending: import('@tauri-apps/plugin-updater').Update | null = null;
|
||||
|
||||
export async function checkForUpdate(manual = false) {
|
||||
if (!isNative || useUpdater.getState().checking) return;
|
||||
useUpdater.setState({ checking: true, error: '' });
|
||||
try {
|
||||
const { check } = await import('@tauri-apps/plugin-updater');
|
||||
const update = await check({ timeout: 15000 });
|
||||
pending = update;
|
||||
useUpdater.setState({ available: update ? { version: update.version, notes: update.body ?? '' } : null, checkedAt: Date.now() });
|
||||
if (update && !manual) toast(`Kaleido ${update.version} is available`, 'info', { label: 'Install', onClick: installUpdate });
|
||||
} catch (e: any) {
|
||||
if (manual) useUpdater.setState({ error: `Couldn’t check for updates: ${e?.message ?? e}` });
|
||||
} finally {
|
||||
useUpdater.setState({ checking: false });
|
||||
}
|
||||
}
|
||||
|
||||
export async function installUpdate() {
|
||||
if (!pending) return;
|
||||
useUpdater.setState({ installing: true, progress: 0 });
|
||||
try {
|
||||
let total = 0;
|
||||
let received = 0;
|
||||
await pending.downloadAndInstall((event) => {
|
||||
if (event.event === 'Started') total = event.data.contentLength ?? 0;
|
||||
else if (event.event === 'Progress') {
|
||||
received += event.data.chunkLength;
|
||||
if (total) useUpdater.setState({ progress: received / total });
|
||||
}
|
||||
});
|
||||
const { relaunch } = await import('@tauri-apps/plugin-process');
|
||||
await relaunch();
|
||||
} catch (e: any) {
|
||||
useUpdater.setState({ installing: false, error: `The update couldn’t be installed: ${e?.message ?? e}` });
|
||||
}
|
||||
}
|
||||
41
src/app/useHomeUsers.ts
Normal file
41
src/app/useHomeUsers.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getHomeUsers, switchHomeUser } from '../plex/account';
|
||||
import type { HomeUser } from '../plex/types';
|
||||
import { promptDialog, toastError } from '../ui/overlays';
|
||||
import { useSession } from './session';
|
||||
import { queryClient } from './queries';
|
||||
|
||||
/** Plex Home profiles available to the signed-in account. */
|
||||
export function useHomeUsers() {
|
||||
const token = useSession((s) => s.accountToken);
|
||||
const home = useSession((s) => s.user?.home);
|
||||
const { data } = useQuery({
|
||||
queryKey: ['homeUsers', token],
|
||||
queryFn: () => getHomeUsers(token!),
|
||||
enabled: !!token && !!home,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
return {
|
||||
users: data ?? [],
|
||||
async switchTo(u: HomeUser) {
|
||||
try {
|
||||
let pin: string | undefined;
|
||||
if (u.protected) {
|
||||
const v = await promptDialog({
|
||||
title: `Switch to ${u.title}`,
|
||||
message: 'This profile is protected by a PIN.',
|
||||
confirm: 'Switch',
|
||||
input: { label: 'PIN', type: 'password', placeholder: '4-digit PIN' },
|
||||
});
|
||||
if (v === null) return;
|
||||
pin = v;
|
||||
}
|
||||
const next = await switchHomeUser(token!, u.uuid, pin);
|
||||
queryClient.clear();
|
||||
await useSession.getState().switchUser(next);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
1
src/assets/brand-mark.svg
Normal file
1
src/assets/brand-mark.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><path fill="#C3E8D3" d="M33,4 L55.5,17 L42.5,24.5 L33,19 Z"/><path fill="#71B9B0" d="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z"/><path fill="#3D7C7B" d="M55.5,47 L33,60 L33,45 L42.5,39.5 Z"/><path fill="#D0A977" d="M31,60 L8.5,47 L21.5,39.5 L31,45 Z"/><path fill="#E9D8AE" d="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z"/><path fill="#EEF2DD" d="M8.5,17 L31,4 L31,19 L21.5,24.5 Z"/></svg>
|
||||
|
After Width: | Height: | Size: 444 B |
1
src/assets/imdb.svg
Normal file
1
src/assets/imdb.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 500"><path fill="#F5C518" d="M197,122.7v255.4h-66.2V122.7h66.2ZM338.4,122.7l-15.3,119.4-9.4-64.9c-2.8-20.8-5.4-39-8-54.5h-85.9v255.4h58.1l.3-168.6,24.4,168.6h41.4l23.3-172.3v172.3h58.1V122.7h-86.7ZM447.7,378.1V122.7h49.4c32.1,0,50.6,1.5,61.9,4.5,11.3,3,19.9,7.8,25.7,14.5,6,6.7,9.7,14.2,11.1,22.4,1.4,8.3,2.4,24.5,2.4,48.7v89.6c0,22.9-1.2,38.3-3.5,45.9-2.1,7.7-5.9,13.7-11.3,18.1-5.3,4.5-12,7.4-19.8,9.2-7.9,1.7-19.8,2.6-35.7,2.6h-80.4ZM513.9,166.4v167.6c9.5,0,15.4-1.9,17.6-5.7,2.2-3.8,3.4-14.2,3.4-31.3v-98.9c0-11.5-.4-18.9-1.1-22.2-.7-3.3-2.5-5.7-5.1-7.2-2.6-1.6-7.6-2.3-14.7-2.3ZM684.7,122.7v83.1c5.3-6.1,11.3-10.6,17.7-13.6,6.6-3.1,16.3-4.6,23.9-4.6s16.4,1.4,22.9,4.1c6.4,2.7,11.3,6.6,14.7,11.5,3.3,5,5.4,9.8,6.1,14.5.7,4.7,1,14.7,1,30.2v71.7c0,15.2-1,26.6-3.1,34.2-2,7.4-6.8,14-14.5,19.4-7.6,5.6-16.7,8.3-27.1,8.3s-17.2-1.6-23.8-4.8c-6.6-3.4-12.5-8.2-17.8-14.7l-4.2,16.2h-59.7V122.7h63.9ZM707.1,250.7c0-10.8-.7-17.8-2.1-21.2-1.4-3.2-6.8-5-10.9-5s-6.4,1.5-7.7,4.3c-1.1,3-1.7,10.2-1.7,21.8v67.5c0,11.3.7,18.4,2,21.5,1.4,3.2,4,4.7,7.9,4.7s9.4-1.6,10.7-4.8c1.2-3.2,1.9-11.1,1.9-23.4v-65.5Z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
1
src/assets/rt-hot.svg
Normal file
1
src/assets/rt-hot.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80"><g transform="translate(10.1 0)"><g transform="translate(0 0)"><path fill="#F9D320" d="M2.53115242,19.0988848 C2.76163569,23.9952416 14.8892193,27.8762825 29.8007435,27.7912268 C42.8237918,27.7168773 53.6874349,24.6411896 56.3485502,20.6004461 C55.7421561,19.9265428 54.904684,19.4643866 53.9613383,19.3391822 C53.9714498,19.220223 53.9779926,19.1003717 53.9773978,18.9787361 C53.9663941,17.0423792 52.5460223,15.4477323 50.695316,15.1503346 C50.7440892,14.8999257 50.7696654,14.6408922 50.7681784,14.3759108 C50.7559851,12.2194796 48.9977695,10.481487 46.8413383,10.4936803 C46.7925651,10.4939777 46.7449814,10.4999257 46.6965056,10.5020074 C46.8344981,10.0987361 46.9118216,9.66780669 46.9094424,9.21784387 C46.8969517,7.06141264 45.1390335,5.32342007 42.9826022,5.33561338 C42.4877323,5.33858736 42.0169517,5.43702602 41.5821561,5.60743494 C40.9653532,4.44639405 39.7811152,3.63717472 38.4002974,3.54379182 C38.1597026,1.60743494 36.5055762,0.113605948 34.506171,0.124843367 C33.247881,0.13204461 32.1350186,0.736356877 31.4263197,1.66453532 C30.7075093,0.882379182 29.6773234,0.391672862 28.5314498,0.398215613 C26.3750186,0.410408922 24.637026,2.16862454 24.6492193,4.32475836 C24.6515985,4.73665428 24.718513,5.13249071 24.8386617,5.50453532 C23.9586617,5.66780669 23.1848327,6.12520446 22.6191822,6.77144981 C22.1701115,5.09888476 20.642974,3.86973978 18.8297398,3.8798513 C17.1357621,3.88966543 15.7040892,4.97873606 15.172342,6.48981413 C13.7332342,7.07182156 12.7202974,8.48356877 12.7298141,10.1302602 C12.7318959,10.4960595 12.7878067,10.8481784 12.8838662,11.1836431 C12.398513,10.9713011 11.8634944,10.852342 11.2996283,10.8556134 C9.5994052,10.8654275 8.16327138,11.9622305 7.63598513,13.4822305 C7.13040892,13.2472862 6.56832714,13.1137546 5.973829,13.1173234 C3.81739777,13.1295167 2.07910781,14.8874349 2.09153162,17.0438662 C2.09546468,17.7549442 2.29263941,18.4187361 2.62810409,18.9909294 C2.59390335,19.0254275 2.56386617,19.063197 2.53115242,19.0988848"/><path fill="#DB382A" d="M50.9736803,68.1576208 C49.8275093,69.89829 47.6002974,71.7008178 45.2692937,72.9026022 L49.2541264,32.4853532 C51.7894424,31.6707807 54.2634944,30.5915242 56.085948,29.0438662 L50.9736803,68.1576208 Z M41.3037918,74.5885502 C37.4450558,75.8655762 35.201487,76.2614126 31.9895911,76.5766543 L32.4901115,35.0432714 C36.0383643,34.9415613 40.6301859,34.4606691 44.5427509,33.6255762 L41.3037918,74.5885502 Z M18.29829,74.5885502 L15.0596283,33.6255762 C18.9718959,34.4606691 23.5637175,34.9415613 27.1119703,35.0432714 L27.6124907,76.5766543 C24.4005948,76.2614126 22.1573234,75.8655762 18.29829,74.5885502 Z M8.62869888,68.1576208 L3.51613383,29.0438662 C5.33858736,30.5915242 7.81263941,31.6707807 10.3479554,32.4853532 L14.3327881,72.9026022 C12.0017844,71.7008178 9.77457249,69.89829 8.62869888,68.1576208 Z M50.687881,13.6110037 C50.7384387,13.8578439 50.7666914,14.1130112 50.7681784,14.3750186 C50.7696654,14.64 50.7440892,14.8990335 50.6950186,15.1494424 C52.5460223,15.4465428 53.9663941,17.0411896 53.9773978,18.9778439 C53.9779926,19.0991822 53.9714498,19.2193309 53.9613383,19.3379926 C54.904684,19.463197 55.7421561,19.9253532 56.3485502,20.5992565 C53.6877323,24.6402974 42.8237918,27.7159851 29.8010409,27.790632 C14.8895167,27.8759851 2.76193309,23.9952416 2.53115242,19.0985874 C2.56386617,19.063197 2.59390335,19.0251301 2.62810409,18.9909294 C2.39791822,18.5983643 2.23910781,18.1608922 2.15702602,17.6966543 C0.729219331,19.0518959 -0.13472119,20.1445353 0.0172490706,21.7356134 C0.0318215613,21.9482528 6.3339777,67.0709294 6.3339777,67.0709294 C7.06111524,74.2173978 17.4388104,79.9292193 29.8010409,80 C42.1632714,79.9292193 52.5412639,74.2173978 53.2681041,67.0709294 C53.2681041,67.0709294 59.5702602,21.9482528 59.5848327,21.7356134 C59.8866914,18.5531599 56.162974,15.6642379 50.687881,13.6110037 L50.687881,13.6110037 Z"/></g><path fill="#FFFFFE" d="M15.0596283,33.6255762 L18.29829,74.5885502 C22.1573234,75.8655762 24.4005948,76.2614126 27.6124907,76.5766543 L27.1119703,35.0432714 C23.5637175,34.9415613 18.9718959,34.4606691 15.0596283,33.6255762"/><path fill="#FFFFFE" d="M31.9895911,76.5766543 C35.201487,76.2614126 37.4447584,75.8655762 41.3037918,74.5885502 L44.5424535,33.6255762 C40.6301859,34.4606691 36.0383643,34.9415613 32.4901115,35.0432714 L31.9895911,76.5766543"/><path fill="#FFFFFE" d="M45.2692937,72.9026022 C47.6002974,71.7008178 49.8275093,69.89829 50.9733829,68.1576208 L56.085948,29.0438662 C54.2634944,30.5915242 51.7894424,31.6707807 49.2541264,32.4853532 L45.2692937,72.9026022"/><path fill="#FFFFFE" d="M3.51613383,29.0438662 L8.62840149,68.1576208 C9.77457249,69.89829 12.0017844,71.7008178 14.3327881,72.9026022 L10.3479554,32.4853532 C7.81263941,31.6707807 5.33858736,30.5915242 3.51613383,29.0438662"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
1
src/assets/rt-stale.svg
Normal file
1
src/assets/rt-stale.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 6.2 KiB |
191
src/downloads/store.ts
Normal file
191
src/downloads/store.ts
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import { create } from 'zustand';
|
||||
import * as api from '../plex/api';
|
||||
import { parseItem } from '../plex/parse';
|
||||
import type { Item } from '../plex/types';
|
||||
import { appInfo, invoke, isNative, listen } from '../platform/native';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { isWatched } from '../app/format';
|
||||
import { toast, toastError } from '../ui/overlays';
|
||||
|
||||
export type DownloadStatus = 'queued' | 'downloading' | 'paused' | 'completed' | 'failed';
|
||||
|
||||
export interface DownloadMeta {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
ratingKey: string;
|
||||
partKey: string;
|
||||
raw: any;
|
||||
localAssets?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface Download {
|
||||
id: string;
|
||||
filePath: string;
|
||||
total: number;
|
||||
received: number;
|
||||
status: DownloadStatus;
|
||||
error?: string | null;
|
||||
meta: DownloadMeta;
|
||||
createdAt: number;
|
||||
speed: number;
|
||||
}
|
||||
|
||||
interface DownloadsState {
|
||||
items: Download[];
|
||||
ready: boolean;
|
||||
dir: string;
|
||||
init(): Promise<void>;
|
||||
idFor(ratingKey: string, serverId?: string): string;
|
||||
localFileFor(ratingKey: string): string | null;
|
||||
start(item: Item): Promise<void>;
|
||||
startAll(item: Item): Promise<void>;
|
||||
pause(id: string): void;
|
||||
resume(id: string): Promise<void>;
|
||||
remove(id: string): Promise<void>;
|
||||
resumeInterrupted(): void;
|
||||
setDir(dir: string): Promise<void>;
|
||||
itemOf(d: Download): Item;
|
||||
}
|
||||
|
||||
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) {
|
||||
const { Extras, Related, OnDeck, ...rest } = raw ?? {};
|
||||
void Extras;
|
||||
void Related;
|
||||
void OnDeck;
|
||||
return rest;
|
||||
}
|
||||
|
||||
export const useDownloads = create<DownloadsState>((set, get) => ({
|
||||
items: [],
|
||||
ready: false,
|
||||
dir: '',
|
||||
|
||||
async init() {
|
||||
if (!isNative || get().ready) return;
|
||||
const info = await appInfo();
|
||||
const dir = useSettings.getState().downloadDir || info.defaultDownloadDir;
|
||||
await invoke('download_set_dir', { dir }).catch(() => {});
|
||||
const items = await invoke<Download[]>('download_list');
|
||||
set({ items, ready: true, dir });
|
||||
listen<Download>('download', (d) => {
|
||||
const prev = get().items.find((x) => x.id === d.id);
|
||||
set({ items: prev ? get().items.map((x) => (x.id === d.id ? d : x)) : [d, ...get().items] });
|
||||
if (d.status === 'completed' && prev && prev.status !== 'completed') toast(`Downloaded “${d.meta.raw?.title ?? 'title'}”`, 'success');
|
||||
if (d.status === 'failed' && prev?.status !== 'failed' && d.error) toast(d.error, 'error');
|
||||
});
|
||||
listen<string>('download-removed', (id) => set({ items: get().items.filter((x) => x.id !== id) }));
|
||||
},
|
||||
|
||||
idFor(ratingKey, serverId) {
|
||||
const sid = serverId ?? useSession.getState().server?.machineId ?? 'offline';
|
||||
return `${sid}-${ratingKey}`;
|
||||
},
|
||||
|
||||
localFileFor(ratingKey) {
|
||||
const d = get().items.find((x) => x.meta.ratingKey === ratingKey && x.status === 'completed');
|
||||
return d?.filePath ?? null;
|
||||
},
|
||||
|
||||
async start(input) {
|
||||
const server = useSession.getState().server;
|
||||
if (!isNative) {
|
||||
toast('Downloads are available in the Kaleido desktop app.', 'error');
|
||||
return;
|
||||
}
|
||||
if (!server) return;
|
||||
try {
|
||||
await get().init();
|
||||
const item = await api.metadata(server, input.id);
|
||||
const media = item.media[0];
|
||||
const part = media?.parts[0];
|
||||
if (!part) throw new Error('This title has no downloadable file.');
|
||||
const id = get().idFor(item.id);
|
||||
if (get().items.some((d) => d.id === id && d.status !== 'failed')) {
|
||||
toast('This title is already in Downloads.');
|
||||
return;
|
||||
}
|
||||
const ext = part.file.split('.').pop() || part.container || media.container || 'mkv';
|
||||
const baseName = part.file.split(/[\\/]/).pop() || `${item.title}.${ext}`;
|
||||
const folder =
|
||||
item.type === 'episode'
|
||||
? `${sanitize(item.grandparentTitle)}/Season ${item.parentIndex}`
|
||||
: sanitize(item.year ? `${item.title} (${item.year})` : item.title);
|
||||
const assets: Record<string, string> = {};
|
||||
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
|
||||
if (poster) assets.poster = server.image(poster, 360, 540);
|
||||
if (item.type === 'episode' && item.thumb) assets.still = server.image(item.thumb, 640, 360);
|
||||
const backdrop = item.type === 'episode' ? item.grandparentArt : item.art;
|
||||
if (backdrop) assets.art = server.image(backdrop, 1280, 720);
|
||||
if (item.logo) assets.logo = server.image(item.logo, 600, 200, { format: 'png' });
|
||||
await invoke('download_start', {
|
||||
request: {
|
||||
id,
|
||||
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,
|
||||
assets,
|
||||
},
|
||||
});
|
||||
toast(`Downloading “${item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title}”`, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
|
||||
async startAll(item) {
|
||||
const server = useSession.getState().server;
|
||||
if (!server) return;
|
||||
try {
|
||||
const leaves = await api.allLeaves(server, item.id);
|
||||
const percent = useSettings.getState().watchedPercent;
|
||||
const todo = leaves.filter((e) => !isWatched(e, percent));
|
||||
const list = todo.length ? todo : leaves;
|
||||
toast(`Queued ${list.length} episode${list.length === 1 ? '' : 's'} for download`, 'success');
|
||||
for (const e of list) await get().start(e);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
|
||||
pause(id) {
|
||||
invoke('download_pause', { id }).catch(toastError);
|
||||
},
|
||||
|
||||
async resume(id) {
|
||||
const d = get().items.find((x) => x.id === id);
|
||||
const server = useSession.getState().server;
|
||||
if (!d || !server) return;
|
||||
if (server.machineId !== d.meta.serverId) {
|
||||
toast(`Connect to ${d.meta.serverName} to resume this download.`, 'error');
|
||||
return;
|
||||
}
|
||||
await invoke('download_resume', { id, url: server.signed(d.meta.partKey, { download: 1 }) }).catch(toastError);
|
||||
},
|
||||
|
||||
async remove(id) {
|
||||
await invoke('download_remove', { id, deleteFiles: true }).catch(toastError);
|
||||
},
|
||||
|
||||
resumeInterrupted() {
|
||||
const server = useSession.getState().server;
|
||||
if (!server) return;
|
||||
for (const d of get().items) if (d.status === 'paused' && d.error === 'interrupted' && d.meta.serverId === server.machineId) get().resume(d.id);
|
||||
},
|
||||
|
||||
async setDir(dir) {
|
||||
await invoke('download_set_dir', { dir });
|
||||
useSettings.getState().set('downloadDir', dir);
|
||||
set({ dir });
|
||||
},
|
||||
|
||||
itemOf(d) {
|
||||
return parseItem(d.meta.raw ?? {});
|
||||
},
|
||||
}));
|
||||
30
src/main.tsx
Normal file
30
src/main.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import '@fontsource-variable/inter';
|
||||
import './styles/base.css';
|
||||
import './styles/ui.css';
|
||||
import './styles/app.css';
|
||||
import './styles/screens.css';
|
||||
import './styles/player.css';
|
||||
import { App } from './app/App';
|
||||
import { installKeyboardNav } from './app/keyboardNav';
|
||||
import { useSession } from './app/session';
|
||||
import { useRouter } from './app/router';
|
||||
import { usePlayer } from './player/store';
|
||||
import { useSettings } from './app/settings';
|
||||
|
||||
if (import.meta.env.DEV) (window as any).__kaleido = { useSession, useRouter, usePlayer, useSettings };
|
||||
|
||||
// No browser context menu or text-selection chrome outside inputs: this is an app.
|
||||
window.addEventListener('contextmenu', (e) => {
|
||||
const t = e.target as HTMLElement;
|
||||
if (!t.closest('input, textarea, .selectable')) e.preventDefault();
|
||||
});
|
||||
|
||||
installKeyboardNav();
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
161
src/platform/native.ts
Normal file
161
src/platform/native.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
/**
|
||||
* The boundary between Kaleido and its host. In the desktop app this talks to
|
||||
* the Rust side through Tauri; in a plain browser (used for UI development) it
|
||||
* degrades gracefully: no video, no downloads, tokens in localStorage.
|
||||
*/
|
||||
import type { UnlistenFn } from '@tauri-apps/api/event';
|
||||
|
||||
export const isNative = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||
|
||||
export async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
|
||||
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
|
||||
const { invoke } = await import('@tauri-apps/api/core');
|
||||
return invoke<T>(cmd, args);
|
||||
}
|
||||
|
||||
export async function listen<T>(event: string, handler: (payload: T) => void): Promise<UnlistenFn> {
|
||||
if (!isNative) return () => {};
|
||||
const { listen } = await import('@tauri-apps/api/event');
|
||||
return listen<T>(event, (e) => handler(e.payload));
|
||||
}
|
||||
|
||||
/** HTTP for Plex APIs: native requests avoid CORS and local-network limits. */
|
||||
let nativeFetch: typeof fetch | null = null;
|
||||
export async function httpFetch(input: string, init?: RequestInit): Promise<Response> {
|
||||
if (!isNative) return fetch(input, init);
|
||||
if (!nativeFetch) nativeFetch = (await import('@tauri-apps/plugin-http')).fetch as typeof fetch;
|
||||
return nativeFetch(input, init);
|
||||
}
|
||||
|
||||
export const secrets = {
|
||||
async get(key: string): Promise<string | null> {
|
||||
if (!isNative) return localStorage.getItem(`kaleido.dev.secret.${key}`);
|
||||
return invoke<string | null>('secret_get', { key });
|
||||
},
|
||||
async set(key: string, value: string): Promise<void> {
|
||||
if (!isNative) return localStorage.setItem(`kaleido.dev.secret.${key}`, value);
|
||||
await invoke('secret_set', { key, value });
|
||||
},
|
||||
async delete(key: string): Promise<void> {
|
||||
if (!isNative) return localStorage.removeItem(`kaleido.dev.secret.${key}`);
|
||||
await invoke('secret_delete', { key });
|
||||
},
|
||||
};
|
||||
|
||||
export interface AppInfo {
|
||||
version: string;
|
||||
dataDir: string;
|
||||
defaultDownloadDir: string;
|
||||
platform: string;
|
||||
deviceName: string;
|
||||
}
|
||||
|
||||
let info: AppInfo | null = null;
|
||||
export async function appInfo(): Promise<AppInfo> {
|
||||
if (info) return info;
|
||||
info = isNative
|
||||
? await invoke<AppInfo>('app_info')
|
||||
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', deviceName: 'Browser preview' };
|
||||
return info;
|
||||
}
|
||||
|
||||
/** Local development only: start signed in from the Android project's `.env`. */
|
||||
export async function devSession(): Promise<{ server: string; token: string } | null> {
|
||||
if (!import.meta.env.DEV) return null;
|
||||
try {
|
||||
if (isNative) return await invoke<{ server: string; token: string } | null>('dev_session');
|
||||
const r = await fetch('/__dev/session');
|
||||
if (!r.ok) return null;
|
||||
const j = await r.json();
|
||||
return j.server && j.token ? j : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const win = {
|
||||
async current() {
|
||||
const { getCurrentWindow } = await import('@tauri-apps/api/window');
|
||||
return getCurrentWindow();
|
||||
},
|
||||
async minimize() {
|
||||
if (isNative) (await this.current()).minimize();
|
||||
},
|
||||
async toggleMaximize() {
|
||||
if (isNative) (await this.current()).toggleMaximize();
|
||||
},
|
||||
async close() {
|
||||
if (isNative) (await this.current()).close();
|
||||
},
|
||||
async isMaximized() {
|
||||
return isNative ? (await this.current()).isMaximized() : false;
|
||||
},
|
||||
async setFullscreen(on: boolean) {
|
||||
if (isNative) return (await this.current()).setFullscreen(on);
|
||||
if (on) await document.documentElement.requestFullscreen?.().catch(() => {});
|
||||
else if (document.fullscreenElement) await document.exitFullscreen().catch(() => {});
|
||||
},
|
||||
async isFullscreen() {
|
||||
return isNative ? (await this.current()).isFullscreen() : !!document.fullscreenElement;
|
||||
},
|
||||
async show() {
|
||||
if (isNative) {
|
||||
const w = await this.current();
|
||||
await w.show();
|
||||
await w.setFocus();
|
||||
}
|
||||
},
|
||||
async onResized(cb: () => void): Promise<UnlistenFn> {
|
||||
if (!isNative) {
|
||||
window.addEventListener('resize', cb);
|
||||
return () => window.removeEventListener('resize', cb);
|
||||
}
|
||||
return (await this.current()).onResized(cb);
|
||||
},
|
||||
};
|
||||
|
||||
export async function openExternal(url: string) {
|
||||
if (!isNative) {
|
||||
window.open(url, '_blank', 'noopener');
|
||||
return;
|
||||
}
|
||||
const { openUrl } = await import('@tauri-apps/plugin-opener');
|
||||
await openUrl(url);
|
||||
}
|
||||
|
||||
export async function revealPath(path: string) {
|
||||
if (!isNative) return;
|
||||
const { revealItemInDir } = await import('@tauri-apps/plugin-opener');
|
||||
await revealItemInDir(path);
|
||||
}
|
||||
|
||||
export async function pickFolder(defaultPath?: string): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { open } = await import('@tauri-apps/plugin-dialog');
|
||||
const r = await open({ directory: true, defaultPath, multiple: false });
|
||||
return typeof r === 'string' ? r : null;
|
||||
}
|
||||
|
||||
export async function pickFile(filters?: { name: string; extensions: string[] }[]): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { open } = await import('@tauri-apps/plugin-dialog');
|
||||
const r = await open({ directory: false, multiple: false, filters });
|
||||
return typeof r === 'string' ? r : null;
|
||||
}
|
||||
|
||||
export async function saveFile(defaultPath: string): Promise<string | null> {
|
||||
if (!isNative) return null;
|
||||
const { save } = await import('@tauri-apps/plugin-dialog');
|
||||
return (await save({ defaultPath })) ?? null;
|
||||
}
|
||||
|
||||
/** Converts a local file path to a URL the web view may load (offline artwork). */
|
||||
export async function localFileUrl(path: string): Promise<string> {
|
||||
if (!isNative || !path) return '';
|
||||
const { convertFileSrc } = await import('@tauri-apps/api/core');
|
||||
return convertFileSrc(path);
|
||||
}
|
||||
|
||||
export function keepAwake(enabled: boolean) {
|
||||
if (isNative) invoke('keep_awake', { enabled }).catch(() => {});
|
||||
}
|
||||
566
src/player/PlayerOverlay.tsx
Normal file
566
src/player/PlayerOverlay.tsx
Normal file
|
|
@ -0,0 +1,566 @@
|
|||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { usePlayer } from './store';
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings, QUALITY_LABEL, type Quality } from '../app/settings';
|
||||
import { clock, episodeLabel } from '../app/format';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { Facts, TitleArt } from '../ui/media';
|
||||
import { Button, Spinner } from '../ui/primitives';
|
||||
import { win, isNative } from '../platform/native';
|
||||
import type { Item } from '../plex/types';
|
||||
|
||||
const HIDE_AFTER = 3000;
|
||||
|
||||
function useAutoHide(paused: boolean, pinned: boolean) {
|
||||
const [visible, setVisible] = useState(true);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const poke = useCallback(() => {
|
||||
setVisible(true);
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => setVisible(false), HIDE_AFTER);
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (paused || pinned) {
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
setVisible(true);
|
||||
} else poke();
|
||||
}, [paused, pinned, poke]);
|
||||
return { visible, poke };
|
||||
}
|
||||
|
||||
function Timeline({ onScrub }: { onScrub: (active: boolean) => void }) {
|
||||
const position = usePlayer((s) => s.position);
|
||||
const duration = usePlayer((s) => s.duration);
|
||||
const cacheTime = usePlayer((s) => s.cacheTime);
|
||||
const chapters = usePlayer((s) => s.chapters);
|
||||
const markers = usePlayer((s) => s.item?.markers ?? []);
|
||||
const seek = usePlayer((s) => s.seek);
|
||||
const previewAt = usePlayer((s) => s.previewAt);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [hover, setHover] = useState<{ x: number; t: number } | null>(null);
|
||||
const [drag, setDrag] = useState<number | null>(null);
|
||||
|
||||
const timeAt = (clientX: number) => {
|
||||
const r = ref.current!.getBoundingClientRect();
|
||||
const f = Math.min(1, Math.max(0, (clientX - r.left) / r.width));
|
||||
return { f, t: f * duration, x: clientX - r.left };
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (drag === null) return;
|
||||
const move = (e: PointerEvent) => {
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setDrag(t);
|
||||
setHover({ x, t });
|
||||
};
|
||||
const up = (e: PointerEvent) => {
|
||||
const { t } = timeAt(e.clientX);
|
||||
seek(t);
|
||||
setDrag(null);
|
||||
setHover(null);
|
||||
onScrub(false);
|
||||
};
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', up, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointerup', up);
|
||||
};
|
||||
}, [drag !== null]);
|
||||
|
||||
const shown = drag ?? position;
|
||||
const pct = duration ? (shown / duration) * 100 : 0;
|
||||
const buffered = duration ? Math.min(100, (Math.max(cacheTime, position) / duration) * 100) : 0;
|
||||
const preview = hover ? previewAt(hover.t) : '';
|
||||
const chapter = hover ? [...chapters].reverse().find((c) => c.time <= hover.t) : null;
|
||||
const width = ref.current?.clientWidth ?? 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`timeline${drag !== null ? ' dragging' : ''}`}
|
||||
ref={ref}
|
||||
onPointerMove={(e) => {
|
||||
if (drag === null && duration) {
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setHover({ x, t });
|
||||
}
|
||||
}}
|
||||
onPointerLeave={() => drag === null && setHover(null)}
|
||||
onPointerDown={(e) => {
|
||||
if (!duration) return;
|
||||
e.preventDefault();
|
||||
const { t, x } = timeAt(e.clientX);
|
||||
setDrag(t);
|
||||
setHover({ x, t });
|
||||
onScrub(true);
|
||||
}}
|
||||
role="slider"
|
||||
aria-label="Seek"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={Math.round(duration)}
|
||||
aria-valuenow={Math.round(position)}
|
||||
>
|
||||
<div className="timeline-track">
|
||||
<div className="timeline-buffered" style={{ width: `${buffered}%` }} />
|
||||
<div className="timeline-played" style={{ width: `${pct}%` }} />
|
||||
{duration > 0 &&
|
||||
markers
|
||||
.filter((m) => m.type === 'intro' || m.type === 'credits')
|
||||
.map((m) => <div key={m.id + m.start} className={`timeline-marker ${m.type}`} style={{ left: `${(m.start / 1000 / duration) * 100}%`, width: `${((m.end - m.start) / 1000 / duration) * 100}%` }} />)}
|
||||
{duration > 0 && chapters.slice(1).map((c) => <div key={c.time} className="timeline-chapter" style={{ left: `${(c.time / duration) * 100}%` }} />)}
|
||||
</div>
|
||||
<div className="timeline-thumb" style={{ left: `${pct}%` }} />
|
||||
{hover && (
|
||||
<div className="timeline-preview" style={{ left: Math.min(Math.max(hover.x, 110), width - 110) }}>
|
||||
{preview && <img src={preview} alt="" draggable={false} />}
|
||||
<div className="timeline-preview-text">
|
||||
{chapter && chapters.length > 1 && <span>{chapter.title}</span>}
|
||||
<b>{clock(hover.t, duration >= 3600)}</b>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Panel({ title, onClose, children, className = '' }: { title: string; onClose: () => void; children: ReactNode; className?: string }) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [onClose]);
|
||||
return (
|
||||
<div className={`player-panel ${className}`} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="player-panel-title">{title}</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Option({ selected, label, detail, onClick }: { selected: boolean; label: string; detail?: string; onClick: () => void }) {
|
||||
return (
|
||||
<button className={`panel-option${selected ? ' selected' : ''}`} onClick={onClick}>
|
||||
<span className="panel-check">{selected && <Icon name="check" size={16} />}</span>
|
||||
<span className="panel-label">
|
||||
{label}
|
||||
{detail && <small>{detail}</small>}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TracksPanel({ onClose }: { onClose: () => void }) {
|
||||
const st = usePlayer();
|
||||
return (
|
||||
<Panel title="Audio & Subtitles" onClose={onClose} className="tracks">
|
||||
<div className="panel-columns">
|
||||
<div>
|
||||
<h4>Audio</h4>
|
||||
{st.audioTracks.map((t) => (
|
||||
<Option key={t.key} selected={t.key === st.audioKey} label={t.label} detail={t.detail} onClick={() => st.selectAudio(t.key)} />
|
||||
))}
|
||||
{!st.audioTracks.length && <div className="panel-empty">No audio tracks</div>}
|
||||
</div>
|
||||
<div>
|
||||
<h4>Subtitles</h4>
|
||||
<Option selected={!st.subKey} label="Off" onClick={() => st.selectSubtitle('')} />
|
||||
{st.subTracks.map((t) => (
|
||||
<Option key={t.key} selected={t.key === st.subKey} label={t.label} detail={t.detail} onClick={() => st.selectSubtitle(t.key)} />
|
||||
))}
|
||||
{st.subKey && st.delivery?.mode !== 'transcode' && (
|
||||
<div className="panel-delay">
|
||||
<span>Timing</span>
|
||||
<button onClick={() => st.setSubDelay(st.subDelay - 0.1)}>−</button>
|
||||
<b>{st.subDelay > 0 ? '+' : ''}{st.subDelay.toFixed(1)}s</b>
|
||||
<button onClick={() => st.setSubDelay(st.subDelay + 0.1)}>+</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsPanel({ onClose }: { onClose: () => void }) {
|
||||
const st = usePlayer();
|
||||
const [view, setView] = useState<'main' | 'quality' | 'speed' | 'version' | 'chapters'>('main');
|
||||
const speeds = [0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
const media = st.item?.media ?? [];
|
||||
const local = st.delivery?.mode === 'local';
|
||||
if (view === 'quality')
|
||||
return (
|
||||
<Panel title="Quality" onClose={onClose}>
|
||||
{(Object.keys(QUALITY_LABEL) as Quality[]).map((q) => (
|
||||
<Option key={q} selected={st.quality === q} label={QUALITY_LABEL[q]} detail={q === 'original' ? 'Direct play of the source file' : 'Converted by your Plex server'} onClick={() => (st.setQuality(q), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'speed')
|
||||
return (
|
||||
<Panel title="Playback speed" onClose={onClose}>
|
||||
{speeds.map((s) => (
|
||||
<Option key={s} selected={Math.abs(st.speed - s) < 0.01} label={s === 1 ? 'Normal' : `${s}×`} onClick={() => (st.setSpeed(s), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'version')
|
||||
return (
|
||||
<Panel title="Version" onClose={onClose}>
|
||||
{media.map((m, i) => (
|
||||
<Option key={m.id} selected={st.mediaIndex === i} label={m.title || `${m.videoResolution.toUpperCase()} ${m.videoCodec.toUpperCase()}`} detail={[m.container.toUpperCase(), m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : ''].filter(Boolean).join(' · ')} onClick={() => (st.selectVersion(i), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
if (view === 'chapters')
|
||||
return (
|
||||
<Panel title="Chapters" onClose={onClose} className="chapters">
|
||||
{st.chapters.map((c) => (
|
||||
<Option key={c.time} selected={false} label={c.title} detail={clock(c.time)} onClick={() => (st.seek(c.time), onClose())} />
|
||||
))}
|
||||
</Panel>
|
||||
);
|
||||
const row = (label: string, value: string, go: () => void, disabled = false) => (
|
||||
<button className="panel-row" onClick={go} disabled={disabled}>
|
||||
<span>{label}</span>
|
||||
<b>{value}</b>
|
||||
<Icon name="next" size={14} />
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<Panel title="Playback" onClose={onClose}>
|
||||
{!local && row('Quality', QUALITY_LABEL[st.quality], () => setView('quality'))}
|
||||
{row('Speed', st.speed === 1 ? 'Normal' : `${st.speed}×`, () => setView('speed'))}
|
||||
{media.length > 1 && !local && row('Version', `${st.mediaIndex + 1} of ${media.length}`, () => setView('version'))}
|
||||
{st.chapters.length > 1 && row('Chapters', `${st.chapters.length}`, () => setView('chapters'))}
|
||||
<div className="panel-info">
|
||||
{st.delivery?.mode === 'direct' && 'Direct play'}
|
||||
{st.delivery?.mode === 'transcode' && `Converting to ${st.delivery.label}`}
|
||||
{st.delivery?.mode === 'local' && 'Playing from this computer'}
|
||||
{st.video && st.video.width > 0 && ` · ${st.video.width}×${st.video.height}`}
|
||||
{st.video?.codec && ` · ${st.video.codec.toUpperCase()}`}
|
||||
{st.video?.hwdec && st.video.hwdec !== 'no' ? ' · Hardware decoding' : ''}
|
||||
</div>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
|
||||
function Volume() {
|
||||
const volume = usePlayer((s) => s.volume);
|
||||
const muted = usePlayer((s) => s.muted);
|
||||
const setVolume = usePlayer((s) => s.setVolume);
|
||||
const toggleMute = usePlayer((s) => s.toggleMute);
|
||||
const icon = muted || volume === 0 ? 'mute' : volume < 50 ? 'volumeLow' : 'volume';
|
||||
return (
|
||||
<div className="volume">
|
||||
<button className="player-icon" aria-label={muted ? 'Unmute' : 'Mute'} onClick={toggleMute}>
|
||||
<Icon name={icon} size={22} />
|
||||
</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
value={muted ? 0 : Math.min(100, volume)}
|
||||
onChange={(e) => setVolume(Number(e.target.value))}
|
||||
style={{ ['--v' as string]: `${muted ? 0 : Math.min(100, volume)}%` }}
|
||||
aria-label="Volume"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 skipIntro = useSettings((s) => s.skipIntro);
|
||||
const skipCredits = useSettings((s) => s.skipCredits);
|
||||
const autoSkipped = useRef(new Set<string>());
|
||||
const ms = position * 1000;
|
||||
const marker = item?.markers.find((m) => (m.type === 'intro' || m.type === 'credits') && ms >= m.start && ms < m.end - 1000);
|
||||
const mode = marker?.type === 'intro' ? skipIntro : skipCredits;
|
||||
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);
|
||||
}
|
||||
}, [marker?.id, marker?.start, mode]);
|
||||
if (!marker || mode === 'off' || countdown !== null) return null;
|
||||
if (marker.type === 'credits' && nextUp) return null;
|
||||
return (
|
||||
<button className="skip-button" onClick={() => seek(marker.end / 1000)}>
|
||||
{marker.type === 'intro' ? 'Skip intro' : 'Skip credits'}
|
||||
<Icon name="skipNext" size={16} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function PostPlay() {
|
||||
const server = useSession((s) => s.server);
|
||||
const nextUp = usePlayer((s) => s.nextUp);
|
||||
const countdown = usePlayer((s) => s.countdown);
|
||||
const playNext = usePlayer((s) => s.playNext);
|
||||
const cancel = usePlayer((s) => s.cancelCountdown);
|
||||
if (!nextUp || countdown === null || !server) return null;
|
||||
return (
|
||||
<div className="post-play" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="post-play-art">
|
||||
<img src={server.image(nextUp.thumb, 360, 202)} alt="" draggable={false} />
|
||||
{countdown > 0 && (
|
||||
<svg className="post-play-ring" viewBox="0 0 40 40">
|
||||
<circle cx="20" cy="20" r="17" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-play-text">
|
||||
<span className="micro">Next episode{countdown > 0 ? ` in ${countdown}` : ''}</span>
|
||||
<b>
|
||||
{episodeLabel(nextUp)} · {nextUp.title}
|
||||
</b>
|
||||
<div className="actions">
|
||||
<Button variant="primary" size="sm" icon="play" onClick={playNext}>
|
||||
Play now
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={cancel}>
|
||||
{countdown > 0 ? 'Cancel' : 'Dismiss'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TitleBlock({ item }: { item: Item }) {
|
||||
return (
|
||||
<div className="player-title">
|
||||
<TitleArt item={item.type === 'episode' ? { ...item, logo: item.raw?.Image?.find?.((i: any) => i.type === 'clearLogo')?.url ?? '' } : item} maxWidth={240} maxHeight={60} as="h2" />
|
||||
{item.type === 'episode' && (
|
||||
<div className="player-episode">
|
||||
{episodeLabel(item)} · {item.title}
|
||||
</div>
|
||||
)}
|
||||
{item.type !== 'clip' && <Facts item={item} withFormats={false} episode={false} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlayerOverlay() {
|
||||
const st = usePlayer();
|
||||
const server = useSession((s) => s.server);
|
||||
const [panel, setPanel] = useState<'' | 'tracks' | 'settings'>('');
|
||||
const [scrubbing, setScrubbing] = useState(false);
|
||||
const [flash, setFlash] = useState<{ icon: string; key: number } | null>(null);
|
||||
const { visible, poke } = useAutoHide(st.paused || st.ended, !!panel || scrubbing || st.countdown !== null);
|
||||
const clickTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const seekStep = useSettings((s) => s.seekStep);
|
||||
|
||||
const showFlash = (icon: string) => setFlash({ icon, key: Date.now() });
|
||||
|
||||
useEffect(() => {
|
||||
if (!st.open) setPanel('');
|
||||
}, [st.open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!st.open) return;
|
||||
const onKey = async (e: KeyboardEvent) => {
|
||||
if ((e.target as HTMLElement)?.tagName === 'INPUT' && (e.target as HTMLInputElement).type !== 'range') return;
|
||||
const p = usePlayer.getState();
|
||||
let handled = true;
|
||||
switch (e.key) {
|
||||
case ' ':
|
||||
case 'k':
|
||||
case 'K':
|
||||
p.togglePause();
|
||||
showFlash(p.paused ? 'play' : 'pause');
|
||||
break;
|
||||
case 'ArrowLeft':
|
||||
case 'j':
|
||||
case 'J':
|
||||
p.seekBy(e.shiftKey ? -60 : e.key === 'ArrowLeft' ? -seekStep : -10);
|
||||
showFlash('replay10');
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
case 'l':
|
||||
case 'L':
|
||||
p.seekBy(e.shiftKey ? 60 : e.key === 'ArrowRight' ? seekStep : 10);
|
||||
showFlash('forward10');
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
p.setVolume(p.volume + 5);
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
p.setVolume(p.volume - 5);
|
||||
break;
|
||||
case 'm':
|
||||
case 'M':
|
||||
p.toggleMute();
|
||||
break;
|
||||
case 'f':
|
||||
case 'F':
|
||||
case 'F11':
|
||||
p.toggleFullscreen();
|
||||
break;
|
||||
case 'n':
|
||||
case 'N':
|
||||
if (e.shiftKey && p.nextUp) p.playNext();
|
||||
else handled = false;
|
||||
break;
|
||||
case 'c':
|
||||
case 'C': {
|
||||
const subs = p.subTracks;
|
||||
const i = subs.findIndex((t) => t.key === p.subKey);
|
||||
p.selectSubtitle(i + 1 < subs.length ? subs[i + 1].key : '');
|
||||
break;
|
||||
}
|
||||
case 'Escape': {
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
if (fs) p.toggleFullscreen();
|
||||
else p.close();
|
||||
break;
|
||||
}
|
||||
case 'Backspace':
|
||||
p.close();
|
||||
break;
|
||||
case 'Home':
|
||||
p.seek(0);
|
||||
break;
|
||||
default:
|
||||
if (/^[0-9]$/.test(e.key) && p.duration) p.seek((Number(e.key) / 10) * p.duration);
|
||||
else handled = false;
|
||||
}
|
||||
if (handled) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
poke();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [st.open, seekStep, poke]);
|
||||
|
||||
if (!st.open || !st.item) return null;
|
||||
const item = st.item;
|
||||
const loading = !st.firstFrame && !st.error;
|
||||
const art = item.type === 'episode' ? item.grandparentArt || item.art : item.art;
|
||||
const hideChrome = !visible && !loading && !st.error;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`player${hideChrome ? ' idle' : ''}${loading ? ' loading' : ''}`}
|
||||
onMouseMove={poke}
|
||||
onClick={() => {
|
||||
if (panel) return setPanel('');
|
||||
if (clickTimer.current) return;
|
||||
clickTimer.current = setTimeout(() => {
|
||||
clickTimer.current = null;
|
||||
if (!loading && !st.error) {
|
||||
st.togglePause();
|
||||
showFlash(st.paused ? 'play' : 'pause');
|
||||
}
|
||||
}, 220);
|
||||
}}
|
||||
onDoubleClick={() => {
|
||||
if (clickTimer.current) clearTimeout(clickTimer.current);
|
||||
clickTimer.current = null;
|
||||
st.toggleFullscreen();
|
||||
}}
|
||||
onWheel={(e) => st.setVolume(st.volume + (e.deltaY < 0 ? 5 : -5))}
|
||||
>
|
||||
{(loading || st.error) && server && (
|
||||
<div className="player-cover">
|
||||
{art && <img src={server.image(art, 1280, 720, { blur: 0 })} alt="" />}
|
||||
<div className="player-cover-scrim" />
|
||||
</div>
|
||||
)}
|
||||
<div className="player-gradient top" />
|
||||
<div className="player-gradient bottom" />
|
||||
|
||||
<div className="player-top" data-tauri-drag-region={isNative ? true : undefined} onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<button className="player-back" onClick={() => st.close()} aria-label="Back">
|
||||
<Icon name="arrowLeft" size={22} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{(loading || st.buffering || st.seeking) && !st.error && (
|
||||
<div className="player-center">
|
||||
<Spinner size={44} />
|
||||
</div>
|
||||
)}
|
||||
{flash && !loading && (
|
||||
<div className="player-flash" key={flash.key}>
|
||||
<Icon name={flash.icon} size={34} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{st.error && (
|
||||
<div className="player-error" onClick={(e) => e.stopPropagation()}>
|
||||
<Icon name="alert" size={28} />
|
||||
<h2>Playback stopped</h2>
|
||||
<p>{st.error}</p>
|
||||
<div className="actions">
|
||||
<Button variant="primary" icon="refresh" onClick={() => st.play(item, { offsetMs: st.position * 1000, quality: st.quality === 'original' ? '1080' : st.quality })}>
|
||||
Try converting
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => st.close()}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SkipButton />
|
||||
<PostPlay />
|
||||
|
||||
{!st.error && (
|
||||
<div className="player-bottom" onClick={(e) => e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}>
|
||||
<div className="player-bottom-head">
|
||||
<TitleBlock item={item} />
|
||||
<div className="player-delivery">{st.delivery?.mode === 'transcode' ? st.delivery.label : st.delivery?.mode === 'local' ? 'Offline' : ''}</div>
|
||||
</div>
|
||||
<Timeline onScrub={setScrubbing} />
|
||||
<div className="player-controls">
|
||||
<div className="player-controls-left">
|
||||
<button className="player-icon big" aria-label={st.paused ? 'Play' : 'Pause'} onClick={() => st.togglePause()}>
|
||||
<Icon name={st.paused || st.ended ? 'play' : 'pause'} size={26} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Back 10 seconds" onClick={() => st.seekBy(-10)}>
|
||||
<Icon name="replay10" size={24} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label="Forward 10 seconds" onClick={() => st.seekBy(10)}>
|
||||
<Icon name="forward10" size={24} />
|
||||
</button>
|
||||
{st.nextUp && (
|
||||
<button className="player-icon" aria-label="Next episode" title={`Next: ${episodeLabel(st.nextUp)} ${st.nextUp.title}`} onClick={() => st.playNext()}>
|
||||
<Icon name="skipNext" size={22} />
|
||||
</button>
|
||||
)}
|
||||
<Volume />
|
||||
<span className="player-time">
|
||||
{clock(st.position, st.duration >= 3600)} <span className="dim">/ {clock(st.duration, st.duration >= 3600)}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="player-controls-right">
|
||||
<button className={`player-icon${panel === 'tracks' ? ' on' : ''}${st.subKey ? ' lit' : ''}`} aria-label="Audio and subtitles" onClick={() => setPanel(panel === 'tracks' ? '' : 'tracks')}>
|
||||
<Icon name="captions" size={23} />
|
||||
</button>
|
||||
<button className={`player-icon${panel === 'settings' ? ' on' : ''}`} aria-label="Playback settings" onClick={() => setPanel(panel === 'settings' ? '' : 'settings')}>
|
||||
<Icon name="settings" size={22} />
|
||||
</button>
|
||||
<button className="player-icon" aria-label={st.fullscreen ? 'Exit full screen' : 'Full screen'} onClick={() => st.toggleFullscreen()}>
|
||||
<Icon name={st.fullscreen ? 'collapse' : 'expand'} size={21} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{panel === 'tracks' && <TracksPanel onClose={() => setPanel('')} />}
|
||||
{panel === 'settings' && <SettingsPanel onClose={() => setPanel('')} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/player/engine.ts
Normal file
43
src/player/engine.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
/** Thin typed wrapper over the native mpv commands and its event stream. */
|
||||
import { invoke, isNative, listen } from '../platform/native';
|
||||
|
||||
export interface MpvTrack {
|
||||
id: number;
|
||||
type: 'video' | 'audio' | 'sub';
|
||||
title?: string;
|
||||
lang?: string;
|
||||
codec?: string;
|
||||
default?: boolean;
|
||||
forced?: boolean;
|
||||
external?: boolean;
|
||||
selected?: boolean;
|
||||
'ff-index'?: number;
|
||||
'demux-channel-count'?: number;
|
||||
'external-filename'?: string;
|
||||
}
|
||||
|
||||
export type MpvEvent =
|
||||
| { type: 'property'; name: string; value: any }
|
||||
| { type: 'start-file' | 'file-loaded' | 'playback-restart' | 'seek' }
|
||||
| { type: 'end-file'; reason: string; error?: string | null }
|
||||
| { type: 'log'; level: string; prefix: string; text: string };
|
||||
|
||||
let initialized: Promise<void> | null = null;
|
||||
|
||||
export const mpv = {
|
||||
available: isNative,
|
||||
init(options: { hwdec: boolean; hdr: boolean }) {
|
||||
if (!initialized) {
|
||||
initialized = invoke<void>('player_init', { options: { hwdec: options.hwdec ? 'auto-safe' : 'no', hdr: options.hdr, extra: [] } }).catch((e) => {
|
||||
initialized = null;
|
||||
throw e;
|
||||
});
|
||||
}
|
||||
return initialized;
|
||||
},
|
||||
command: (...args: (string | number)[]) => invoke<void>('player_command', { args: args.map(String) }),
|
||||
set: (name: string, value: unknown) => invoke<void>('player_set', { name, value }),
|
||||
get: <T = any>(name: string) => invoke<T>('player_get', { name }),
|
||||
show: (visible: boolean) => invoke<void>('player_show', { visible }),
|
||||
on: (handler: (e: MpvEvent) => void) => listen<MpvEvent>('mpv', handler),
|
||||
};
|
||||
693
src/player/store.ts
Normal file
693
src/player/store.ts
Normal file
|
|
@ -0,0 +1,693 @@
|
|||
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 { useSession } from '../app/session';
|
||||
import { useSettings, type Quality } from '../app/settings';
|
||||
import { channelLabel } from '../app/format';
|
||||
import { invalidateLibrary } from '../app/queries';
|
||||
import { keepAwake, isNative, win } from '../platform/native';
|
||||
import { mpv, type MpvEvent, type MpvTrack } from './engine';
|
||||
import { toast } from '../ui/overlays';
|
||||
import { stopThemeMusic } from './theme';
|
||||
|
||||
export interface Track {
|
||||
key: string; // stable UI key
|
||||
mpvId: number | null; // null until loaded (external subs)
|
||||
stream?: Stream; // Plex stream, when known
|
||||
label: string;
|
||||
detail: string;
|
||||
language: string;
|
||||
forced: boolean;
|
||||
external: boolean;
|
||||
}
|
||||
|
||||
export interface PlayOptions {
|
||||
/** Start position in ms. Defaults to the saved resume point when `resume` is true. */
|
||||
offsetMs?: number;
|
||||
resume?: boolean;
|
||||
mediaIndex?: number;
|
||||
/** A local file path (offline download). */
|
||||
localFile?: string;
|
||||
quality?: Quality;
|
||||
}
|
||||
|
||||
interface PlayerState {
|
||||
open: boolean;
|
||||
item: Item | null;
|
||||
delivery: Delivery | null;
|
||||
mediaIndex: number;
|
||||
quality: Quality;
|
||||
firstFrame: boolean;
|
||||
error: string;
|
||||
position: number;
|
||||
duration: number;
|
||||
cacheTime: number;
|
||||
paused: boolean;
|
||||
buffering: boolean;
|
||||
seeking: boolean;
|
||||
volume: number;
|
||||
muted: boolean;
|
||||
speed: number;
|
||||
subDelay: number;
|
||||
audioTracks: Track[];
|
||||
subTracks: Track[];
|
||||
audioKey: string;
|
||||
subKey: string; // '' when off
|
||||
chapters: { title: string; time: number }[];
|
||||
video: { width: number; height: number; hwdec: string; codec: string } | null;
|
||||
ended: boolean;
|
||||
nextUp: Item | null;
|
||||
countdown: number | null;
|
||||
postPlayDismissed: boolean;
|
||||
fullscreen: boolean;
|
||||
|
||||
play(item: Item, opts?: PlayOptions): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
togglePause(): void;
|
||||
seek(seconds: number): void;
|
||||
seekBy(delta: number): void;
|
||||
setVolume(v: number): void;
|
||||
toggleMute(): void;
|
||||
setSpeed(s: number): void;
|
||||
setSubDelay(s: number): void;
|
||||
selectAudio(key: string): Promise<void>;
|
||||
selectSubtitle(key: string): Promise<void>;
|
||||
setQuality(q: Quality): Promise<void>;
|
||||
selectVersion(index: number): Promise<void>;
|
||||
playNext(): Promise<void>;
|
||||
cancelCountdown(): void;
|
||||
toggleFullscreen(): Promise<void>;
|
||||
previewAt(seconds: number): string;
|
||||
}
|
||||
|
||||
let session = '';
|
||||
let startOffsetMs = 0;
|
||||
let lastReport = 0;
|
||||
let reportTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let countdownTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let scrobbled = false;
|
||||
let unlisten: (() => void) | null = null;
|
||||
let loadToken = 0;
|
||||
let wasFullscreenBeforePlay = false;
|
||||
let pendingExternal: Track | null = null;
|
||||
|
||||
const server = () => useSession.getState().server;
|
||||
|
||||
function languageName(code: string, fallback: string) {
|
||||
if (!code) return fallback;
|
||||
try {
|
||||
return new Intl.DisplayNames([navigator.language || 'en'], { type: 'language' }).of(code) || fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function audioTrackFromStream(s: Stream): Track {
|
||||
const lang = s.language || languageName(s.languageCode, 'Unknown');
|
||||
const parts = [s.codec.toUpperCase().replace('DCA', 'DTS'), channelLabel(s.channels) || s.audioChannelLayout].filter(Boolean);
|
||||
const title = s.title && !s.title.toLowerCase().includes(lang.toLowerCase()) ? s.title : '';
|
||||
return {
|
||||
key: `p${s.id}`,
|
||||
mpvId: null,
|
||||
stream: s,
|
||||
label: lang,
|
||||
detail: title || parts.join(' '),
|
||||
language: s.languageCode,
|
||||
forced: false,
|
||||
external: false,
|
||||
};
|
||||
}
|
||||
|
||||
function subTrackFromStream(s: Stream): Track {
|
||||
const lang = s.language || languageName(s.languageCode, 'Unknown');
|
||||
const flags = [s.forced ? 'Forced' : '', s.hearingImpaired ? 'SDH' : ''].filter(Boolean);
|
||||
return {
|
||||
key: `p${s.id}`,
|
||||
mpvId: null,
|
||||
stream: s,
|
||||
label: [lang, ...flags].join(' · '),
|
||||
detail: [s.title && s.title !== lang ? s.title : '', s.codec.toUpperCase(), s.key ? 'External' : ''].filter(Boolean).join(' · '),
|
||||
language: s.languageCode,
|
||||
forced: s.forced,
|
||||
external: !!s.key,
|
||||
};
|
||||
}
|
||||
|
||||
function mpvTrackLabel(t: MpvTrack): Track {
|
||||
const lang = t.lang ? languageName(t.lang, t.lang) : t.type === 'sub' ? 'Subtitles' : 'Audio';
|
||||
return {
|
||||
key: `m${t.id}`,
|
||||
mpvId: t.id,
|
||||
label: t.title ? `${lang} · ${t.title}` : lang,
|
||||
detail: [t.codec?.toUpperCase(), t['demux-channel-count'] ? channelLabel(t['demux-channel-count']) : ''].filter(Boolean).join(' '),
|
||||
language: t.lang ?? '',
|
||||
forced: !!t.forced,
|
||||
external: !!t.external,
|
||||
};
|
||||
}
|
||||
|
||||
function report(state: 'playing' | 'paused' | 'buffering' | 'stopped') {
|
||||
const s = server();
|
||||
const { item, position, delivery } = usePlayer.getState();
|
||||
if (!s || !item || !session || item.type === 'clip') return;
|
||||
lastReport = Date.now();
|
||||
const extra: Record<string, string | number> = {};
|
||||
if (delivery?.mode === 'transcode' && delivery.session) extra['X-Plex-Session-Identifier'] = delivery.session;
|
||||
reportTimeline(s, item, state, position * 1000, session, extra).catch(() => {});
|
||||
}
|
||||
|
||||
function checkScrobble() {
|
||||
const { item, position, duration } = usePlayer.getState();
|
||||
const s = server();
|
||||
if (!item || !s || scrobbled || !duration || item.type === 'clip') return;
|
||||
const percent = useSettings.getState().watchedPercent;
|
||||
if (position / duration >= percent / 100) {
|
||||
scrobbled = true;
|
||||
api
|
||||
.setWatched(s, item.id, true)
|
||||
.then(() => invalidateLibrary())
|
||||
.catch(() => (scrobbled = false));
|
||||
}
|
||||
}
|
||||
|
||||
async function findNext(item: Item): Promise<Item | null> {
|
||||
const s = server();
|
||||
if (!s || item.type !== 'episode' || !item.grandparentId) return null;
|
||||
try {
|
||||
const leaves = await api.allLeaves(s, item.grandparentId);
|
||||
const i = leaves.findIndex((e) => e.id === item.id);
|
||||
return i >= 0 ? (leaves[i + 1] ?? null) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function startCountdown() {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.nextUp || st.countdown !== null || st.postPlayDismissed) return;
|
||||
const settings = useSettings.getState();
|
||||
if (!settings.autoplayNext) {
|
||||
usePlayer.setState({ countdown: -1 });
|
||||
return;
|
||||
}
|
||||
usePlayer.setState({ countdown: settings.countdownSeconds });
|
||||
countdownTimer && clearInterval(countdownTimer);
|
||||
countdownTimer = setInterval(() => {
|
||||
const c = usePlayer.getState().countdown;
|
||||
if (c === null || c < 0) return;
|
||||
if (c <= 1) {
|
||||
clearInterval(countdownTimer!);
|
||||
countdownTimer = null;
|
||||
usePlayer.getState().playNext();
|
||||
} else usePlayer.setState({ countdown: c - 1 });
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
function stopCountdown() {
|
||||
if (countdownTimer) clearInterval(countdownTimer);
|
||||
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;
|
||||
if (!audioKey) {
|
||||
const lang = prefs.audioLanguage;
|
||||
audioKey =
|
||||
(lang && audio.find((t) => t.language === lang)?.key) ||
|
||||
audio.find((t) => t.stream?.selected)?.key ||
|
||||
audio.find((t) => t.stream?.default)?.key ||
|
||||
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);
|
||||
switch (prefs.subtitleMode) {
|
||||
case 'off':
|
||||
subKey = '';
|
||||
break;
|
||||
case 'always':
|
||||
subKey = (inLang.find((t) => !t.forced) ?? inLang[0] ?? subs[0])?.key ?? '';
|
||||
break;
|
||||
case 'forced':
|
||||
subKey = inLang.find((t) => t.forced)?.key ?? '';
|
||||
break;
|
||||
default:
|
||||
subKey = subs.find((t) => t.stream?.selected)?.key ?? inLang.find((t) => t.forced)?.key ?? '';
|
||||
}
|
||||
}
|
||||
usePlayer.setState({ audioTracks: audio, subTracks: subs, audioKey, subKey });
|
||||
if (direct) {
|
||||
const a = audio.find((t) => t.key === audioKey);
|
||||
if (a?.mpvId) mpv.set('aid', a.mpvId).catch(() => {});
|
||||
await setMpvSubtitle(subKey);
|
||||
}
|
||||
}
|
||||
|
||||
async function setMpvSubtitle(key: string) {
|
||||
const st = usePlayer.getState();
|
||||
const t = st.subTracks.find((x) => x.key === key);
|
||||
if (!t) {
|
||||
await mpv.set('sid', 'no').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (t.mpvId) {
|
||||
await mpv.set('sid', t.mpvId).catch(() => {});
|
||||
} else if (t.external && t.stream?.key && server()) {
|
||||
pendingExternal = t;
|
||||
const url = server()!.signed(t.stream.key);
|
||||
await mpv.command('sub-add', url, 'select', t.label, t.language || 'und').catch(() => toast('This subtitle could not be loaded.', 'error'));
|
||||
}
|
||||
}
|
||||
|
||||
function onEvent(e: MpvEvent) {
|
||||
const st = usePlayer.getState();
|
||||
if (!st.open) return;
|
||||
switch (e.type) {
|
||||
case 'property': {
|
||||
const v = e.value;
|
||||
switch (e.name) {
|
||||
case 'time-pos':
|
||||
if (typeof v === 'number') {
|
||||
usePlayer.setState({ position: v });
|
||||
checkScrobble();
|
||||
if (Date.now() - lastReport > 10000) report(st.paused ? 'paused' : 'playing');
|
||||
maybeCredits(v);
|
||||
}
|
||||
break;
|
||||
case 'duration':
|
||||
if (typeof v === 'number' && v > 0) usePlayer.setState({ duration: v });
|
||||
break;
|
||||
case 'pause':
|
||||
usePlayer.setState({ paused: !!v });
|
||||
report(v ? 'paused' : 'playing');
|
||||
keepAwake(!v);
|
||||
break;
|
||||
case 'paused-for-cache':
|
||||
usePlayer.setState({ buffering: !!v });
|
||||
break;
|
||||
case 'seeking':
|
||||
usePlayer.setState({ seeking: !!v });
|
||||
break;
|
||||
case 'demuxer-cache-time':
|
||||
if (typeof v === 'number') usePlayer.setState({ cacheTime: v });
|
||||
break;
|
||||
case 'volume':
|
||||
if (typeof v === 'number') usePlayer.setState({ volume: v });
|
||||
break;
|
||||
case 'mute':
|
||||
usePlayer.setState({ muted: !!v });
|
||||
break;
|
||||
case 'speed':
|
||||
if (typeof v === 'number') usePlayer.setState({ speed: v });
|
||||
break;
|
||||
case 'sub-delay':
|
||||
if (typeof v === 'number') usePlayer.setState({ subDelay: v });
|
||||
break;
|
||||
case 'chapter-list':
|
||||
if (Array.isArray(v) && v.length > 1 && !st.chapters.length)
|
||||
usePlayer.setState({ chapters: v.map((c: any, i: number) => ({ title: c.title && !/^\d\d:\d\d/.test(c.title) ? c.title : `Chapter ${i + 1}`, time: c.time })) });
|
||||
break;
|
||||
case 'video-params':
|
||||
if (v?.w) usePlayer.setState({ video: { ...(st.video ?? { hwdec: '', codec: '' }), width: v.w, height: v.h } });
|
||||
break;
|
||||
case 'hwdec-current':
|
||||
usePlayer.setState({ video: { ...(st.video ?? { width: 0, height: 0, codec: '' }), hwdec: v ?? '' } });
|
||||
break;
|
||||
case 'track-list':
|
||||
if (Array.isArray(v)) {
|
||||
if (pendingExternal) {
|
||||
const ext = (v as MpvTrack[]).filter((t) => t.type === 'sub' && t.external).pop();
|
||||
if (ext) {
|
||||
const key = pendingExternal.key;
|
||||
pendingExternal = null;
|
||||
usePlayer.setState({ subTracks: usePlayer.getState().subTracks.map((t) => (t.key === key ? { ...t, mpvId: ext.id } : t)) });
|
||||
}
|
||||
}
|
||||
const video = (v as MpvTrack[]).find((t) => t.type === 'video' && t.selected);
|
||||
if (video) usePlayer.setState({ video: { ...(usePlayer.getState().video ?? { width: 0, height: 0, hwdec: '' }), codec: video.codec ?? '' } });
|
||||
}
|
||||
break;
|
||||
case 'eof-reached':
|
||||
if (v === true) onEnded();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'file-loaded':
|
||||
mpv
|
||||
.get<MpvTrack[]>('track-list')
|
||||
.then(applyInitialTracks)
|
||||
.catch(() => {});
|
||||
break;
|
||||
case 'playback-restart':
|
||||
if (!st.firstFrame) usePlayer.setState({ firstFrame: true });
|
||||
usePlayer.setState({ buffering: false });
|
||||
break;
|
||||
case 'end-file':
|
||||
if (e.reason === 'error') {
|
||||
usePlayer.setState({ error: e.error ? `Playback failed: ${e.error}` : 'This video could not be played.' });
|
||||
fallbackAfterError();
|
||||
} else if (e.reason === 'eof') onEnded();
|
||||
break;
|
||||
case 'log':
|
||||
if (e.level === 'error' && /http|stream|open/i.test(e.prefix + e.text) && !st.firstFrame) console.warn('[mpv]', e.prefix, e.text);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Direct play failed: retry once through Plex's converter. */
|
||||
let triedFallback = false;
|
||||
function fallbackAfterError() {
|
||||
const st = usePlayer.getState();
|
||||
if (triedFallback || !st.item || st.delivery?.mode !== 'direct') return;
|
||||
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' });
|
||||
}
|
||||
|
||||
function maybeCredits(pos: number) {
|
||||
const st = usePlayer.getState();
|
||||
if (st.item?.type !== 'episode' || !st.nextUp || st.countdown !== null) return;
|
||||
const credits = st.item.markers.find((m) => m.type === 'credits' && (m.final || m.end >= st.item!.duration - 5000));
|
||||
if (credits && pos * 1000 >= credits.start && pos * 1000 < credits.end && useSettings.getState().skipCredits !== 'off') startCountdown();
|
||||
}
|
||||
|
||||
function onEnded() {
|
||||
const st = usePlayer.getState();
|
||||
if (st.ended) return;
|
||||
usePlayer.setState({ ended: true });
|
||||
report('stopped');
|
||||
checkScrobble();
|
||||
if (st.nextUp) startCountdown();
|
||||
}
|
||||
|
||||
export const usePlayer = create<PlayerState>((set, get) => ({
|
||||
open: false,
|
||||
item: null,
|
||||
delivery: null,
|
||||
mediaIndex: 0,
|
||||
quality: 'original',
|
||||
firstFrame: false,
|
||||
error: '',
|
||||
position: 0,
|
||||
duration: 0,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: false,
|
||||
seeking: false,
|
||||
volume: 100,
|
||||
muted: false,
|
||||
speed: 1,
|
||||
subDelay: 0,
|
||||
audioTracks: [],
|
||||
subTracks: [],
|
||||
audioKey: '',
|
||||
subKey: '',
|
||||
chapters: [],
|
||||
video: null,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
countdown: null,
|
||||
postPlayDismissed: false,
|
||||
fullscreen: false,
|
||||
|
||||
async play(input, opts = {}) {
|
||||
const token = ++loadToken;
|
||||
const s = server();
|
||||
const prefs = useSettings.getState();
|
||||
stopThemeMusic();
|
||||
stopCountdown();
|
||||
if (!isNative) {
|
||||
toast('Video playback is available in the Kaleido desktop app.', 'error');
|
||||
return;
|
||||
}
|
||||
const previous = get();
|
||||
if (previous.open && previous.item) {
|
||||
report('stopped');
|
||||
if (previous.delivery?.session && s) stopTranscode(s, previous.delivery.session);
|
||||
}
|
||||
if (!previous.open) {
|
||||
triedFallback = false;
|
||||
wasFullscreenBeforePlay = await win.isFullscreen().catch(() => false);
|
||||
}
|
||||
set({
|
||||
open: true,
|
||||
item: input,
|
||||
firstFrame: false,
|
||||
error: '',
|
||||
position: (opts.offsetMs ?? 0) / 1000,
|
||||
duration: input.duration / 1000,
|
||||
cacheTime: 0,
|
||||
paused: false,
|
||||
buffering: true,
|
||||
ended: false,
|
||||
nextUp: null,
|
||||
countdown: null,
|
||||
postPlayDismissed: false,
|
||||
chapters: [],
|
||||
audioTracks: [],
|
||||
subTracks: [],
|
||||
audioKey: '',
|
||||
subKey: '__init',
|
||||
video: null,
|
||||
fullscreen: wasFullscreenBeforePlay,
|
||||
});
|
||||
document.documentElement.classList.add('player-open');
|
||||
|
||||
try {
|
||||
// Full metadata: streams, markers and chapters.
|
||||
let item = input;
|
||||
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;
|
||||
const mediaIndex = Math.min(opts.mediaIndex ?? 0, Math.max(0, item.media.length - 1));
|
||||
const 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();
|
||||
scrobbled = false;
|
||||
|
||||
let delivery: Delivery;
|
||||
if (opts.localFile) {
|
||||
delivery = { url: opts.localFile, mode: 'local', label: 'Downloaded', absoluteTime: false };
|
||||
} else if (!s || !media) {
|
||||
throw new Error('This title has no playable media.');
|
||||
} else if (quality === 'original') {
|
||||
delivery = { url: directUrl(s, media), mode: 'direct', label: 'Original', absoluteTime: false };
|
||||
} else {
|
||||
const tsession = crypto.randomUUID();
|
||||
delivery = {
|
||||
url: transcodeUrl(s, item, { mediaIndex, quality, offsetMs, session: tsession, local }),
|
||||
mode: 'transcode',
|
||||
session: tsession,
|
||||
label: quality === '2160' ? '4K' : `${quality}p`,
|
||||
absoluteTime: true,
|
||||
};
|
||||
}
|
||||
|
||||
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),
|
||||
});
|
||||
|
||||
await mpv.init({ hwdec: prefs.hwdec, hdr: prefs.hdrPassthrough });
|
||||
if (!unlisten) unlisten = await mpv.on(onEvent);
|
||||
if (token !== loadToken) return;
|
||||
await mpv.set('mute', false);
|
||||
await mpv.set('volume', prefs.volume);
|
||||
await mpv.set('speed', 1);
|
||||
await mpv.set('sub-scale', prefs.subtitleScale);
|
||||
await mpv.set('sub-back-color', prefs.subtitleBackground ? '#C0000000' : '#00000000');
|
||||
await mpv.set('sub-border-style', prefs.subtitleBackground ? 'opaque-box' : 'outline-and-shadow');
|
||||
await mpv.set('force-media-title', item.type === 'episode' ? `${item.grandparentTitle} — ${item.title}` : item.title);
|
||||
await mpv.show(true);
|
||||
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);
|
||||
keepAwake(true);
|
||||
report('buffering');
|
||||
reportTimer && clearInterval(reportTimer);
|
||||
reportTimer = setInterval(() => {
|
||||
const st = get();
|
||||
if (st.open && !st.ended) report(st.paused ? 'paused' : st.buffering ? 'buffering' : 'playing');
|
||||
}, 10000);
|
||||
findNext(item).then((next) => token === loadToken && set({ nextUp: next }));
|
||||
} catch (e: any) {
|
||||
if (token !== loadToken) return;
|
||||
set({ error: e?.message ?? String(e), buffering: false });
|
||||
}
|
||||
},
|
||||
|
||||
async close() {
|
||||
loadToken++;
|
||||
const st = get();
|
||||
stopCountdown();
|
||||
if (reportTimer) clearInterval(reportTimer);
|
||||
reportTimer = null;
|
||||
if (st.item && !st.error) report('stopped');
|
||||
const s = server();
|
||||
if (st.delivery?.session && s) stopTranscode(s, st.delivery.session);
|
||||
keepAwake(false);
|
||||
if (isNative) {
|
||||
await mpv.command('stop').catch(() => {});
|
||||
await mpv.show(false).catch(() => {});
|
||||
}
|
||||
document.documentElement.classList.remove('player-open', 'video-active');
|
||||
set({ open: false, item: null, delivery: null, error: '', countdown: null, nextUp: null, firstFrame: false });
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
if (fs && !wasFullscreenBeforePlay) win.setFullscreen(false);
|
||||
if (st.item) invalidateLibrary();
|
||||
},
|
||||
|
||||
togglePause() {
|
||||
const st = get();
|
||||
if (st.ended) {
|
||||
st.seek(0);
|
||||
set({ ended: false });
|
||||
}
|
||||
mpv.command('cycle', 'pause').catch(() => {});
|
||||
},
|
||||
|
||||
seek(seconds) {
|
||||
const st = get();
|
||||
const target = Math.max(0, Math.min(seconds, (st.duration || seconds) - 0.5));
|
||||
set({ position: target, ended: false });
|
||||
if (st.countdown !== null) {
|
||||
stopCountdown();
|
||||
set({ countdown: null });
|
||||
}
|
||||
mpv.command('seek', target.toFixed(3), 'absolute+exact').catch(() => {});
|
||||
},
|
||||
|
||||
seekBy(delta) {
|
||||
const st = get();
|
||||
st.seek(st.position + delta);
|
||||
},
|
||||
|
||||
setVolume(v) {
|
||||
const volume = Math.max(0, Math.min(150, Math.round(v)));
|
||||
set({ volume });
|
||||
useSettings.getState().set('volume', Math.min(100, volume));
|
||||
mpv.set('volume', volume).catch(() => {});
|
||||
if (get().muted && volume > 0) mpv.set('mute', false).catch(() => {});
|
||||
},
|
||||
|
||||
toggleMute() {
|
||||
mpv.command('cycle', 'mute').catch(() => {});
|
||||
},
|
||||
|
||||
setSpeed(speed) {
|
||||
mpv.set('speed', speed).catch(() => {});
|
||||
},
|
||||
|
||||
setSubDelay(delay) {
|
||||
mpv.set('sub-delay', delay).catch(() => {});
|
||||
},
|
||||
|
||||
async selectAudio(key) {
|
||||
const st = 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 });
|
||||
return;
|
||||
}
|
||||
if (t.mpvId) await mpv.set('aid', t.mpvId).catch(() => {});
|
||||
},
|
||||
|
||||
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 });
|
||||
return;
|
||||
}
|
||||
await setMpvSubtitle(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 });
|
||||
},
|
||||
|
||||
async selectVersion(index) {
|
||||
const st = get();
|
||||
if (!st.item || index === st.mediaIndex) return;
|
||||
await st.play(st.item, { offsetMs: st.position * 1000, mediaIndex: index, quality: st.quality });
|
||||
},
|
||||
|
||||
async playNext() {
|
||||
const st = get();
|
||||
stopCountdown();
|
||||
if (!st.nextUp) return;
|
||||
await st.play(st.nextUp, { resume: true, quality: st.quality });
|
||||
},
|
||||
|
||||
cancelCountdown() {
|
||||
stopCountdown();
|
||||
set({ countdown: null, postPlayDismissed: true });
|
||||
},
|
||||
|
||||
async toggleFullscreen() {
|
||||
const fs = await win.isFullscreen().catch(() => false);
|
||||
await win.setFullscreen(!fs);
|
||||
set({ fullscreen: !fs });
|
||||
},
|
||||
|
||||
previewAt(seconds) {
|
||||
const st = get();
|
||||
const s = server();
|
||||
if (!s || !st.item || st.delivery?.mode === 'local') return '';
|
||||
return previewUrl(s, st.item.media[st.mediaIndex], seconds * 1000);
|
||||
},
|
||||
}));
|
||||
|
||||
/** Shown once the first frame is ready, the page turns transparent over the video. */
|
||||
usePlayer.subscribe((st, prev) => {
|
||||
if (st.firstFrame !== prev.firstFrame || st.open !== prev.open || st.error !== prev.error) {
|
||||
document.documentElement.classList.toggle('video-active', st.open && st.firstFrame && !st.error);
|
||||
}
|
||||
});
|
||||
52
src/player/theme.ts
Normal file
52
src/player/theme.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
/** Optional title theme music on detail pages, faded in and out. */
|
||||
import { useSession } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
|
||||
let audio: HTMLAudioElement | null = null;
|
||||
let current = '';
|
||||
let fade: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function fadeTo(target: number, done?: () => void) {
|
||||
if (!audio) return;
|
||||
if (fade) clearInterval(fade);
|
||||
const a = audio;
|
||||
fade = setInterval(() => {
|
||||
const step = 0.02;
|
||||
if (Math.abs(a.volume - target) <= step) {
|
||||
a.volume = target;
|
||||
clearInterval(fade!);
|
||||
fade = null;
|
||||
done?.();
|
||||
} else a.volume += a.volume < target ? step : -step;
|
||||
}, 40);
|
||||
}
|
||||
|
||||
export function playThemeMusic(path: string) {
|
||||
const prefs = useSettings.getState();
|
||||
const server = useSession.getState().server;
|
||||
if (!prefs.themeMusic || !path || !server || document.documentElement.classList.contains('player-open')) return;
|
||||
if (path === current && audio && !audio.paused) return;
|
||||
stopThemeMusic(true);
|
||||
current = path;
|
||||
audio = new Audio(server.signed(path));
|
||||
audio.volume = 0;
|
||||
audio.loop = false;
|
||||
audio.play().then(() => fadeTo(prefs.themeVolume / 100), () => {});
|
||||
}
|
||||
|
||||
export function stopThemeMusic(immediate = false) {
|
||||
current = '';
|
||||
if (!audio) return;
|
||||
const a = audio;
|
||||
audio = null;
|
||||
if (immediate) {
|
||||
a.pause();
|
||||
return;
|
||||
}
|
||||
const prev = audio;
|
||||
audio = a;
|
||||
fadeTo(0, () => {
|
||||
a.pause();
|
||||
if (audio === a) audio = prev;
|
||||
});
|
||||
}
|
||||
182
src/plex/account.ts
Normal file
182
src/plex/account.ts
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
import { arr, bool, num, str } from './parse';
|
||||
import { clientIdentifier, PlexError, plexRequest, PRODUCT } from './client';
|
||||
import type { HomeUser, PlexUser, ServerConnection, ServerResource } from './types';
|
||||
|
||||
const TV = 'https://plex.tv/api/v2';
|
||||
|
||||
export interface Pin {
|
||||
id: number;
|
||||
code: string;
|
||||
}
|
||||
|
||||
export async function createPin(strong: boolean): Promise<Pin> {
|
||||
const j = await plexRequest(`${TV}/pins`, null, { method: 'POST', params: { strong } });
|
||||
return { id: num(j.id), code: str(j.code) };
|
||||
}
|
||||
|
||||
export async function checkPin(pin: Pin): Promise<string | null> {
|
||||
const j = await plexRequest(`${TV}/pins/${pin.id}`, null);
|
||||
const token = str(j.authToken);
|
||||
return token && token !== 'null' ? token : null;
|
||||
}
|
||||
|
||||
/** The browser sign-in page for a strong PIN. */
|
||||
export function authUrl(pin: Pin): string {
|
||||
const params = new URLSearchParams({
|
||||
clientID: clientIdentifier(),
|
||||
code: pin.code,
|
||||
'context[device][product]': PRODUCT,
|
||||
'context[device][platform]': 'Windows',
|
||||
'context[device][device]': 'Windows',
|
||||
});
|
||||
return `https://app.plex.tv/auth#?${params.toString()}`;
|
||||
}
|
||||
|
||||
export async function getUser(token: string): Promise<PlexUser> {
|
||||
const j = await plexRequest(`${TV}/user`, token);
|
||||
return {
|
||||
id: num(j.id),
|
||||
uuid: str(j.uuid),
|
||||
username: str(j.username),
|
||||
title: str(j.title || j.friendlyName || j.username),
|
||||
email: str(j.email),
|
||||
thumb: str(j.thumb),
|
||||
home: bool(j.home),
|
||||
homeAdmin: bool(j.homeAdmin),
|
||||
protected: bool(j.protected),
|
||||
subscription: bool(j.subscription?.active),
|
||||
};
|
||||
}
|
||||
|
||||
export async function signOut(token: string) {
|
||||
await plexRequest(`${TV}/users/signout`, token, { method: 'DELETE' }).catch(() => {});
|
||||
}
|
||||
|
||||
export async function getResources(token: string): Promise<ServerResource[]> {
|
||||
const list = await plexRequest<any[]>(`${TV}/resources`, token, {
|
||||
params: { includeHttps: 1, includeRelay: 1, includeIPv6: 1 },
|
||||
});
|
||||
return arr(list)
|
||||
.filter((r) => str(r.provides).split(',').includes('server'))
|
||||
.map((r) => ({
|
||||
id: str(r.clientIdentifier),
|
||||
name: str(r.name),
|
||||
owned: bool(r.owned),
|
||||
accessToken: str(r.accessToken) || token,
|
||||
productVersion: str(r.productVersion),
|
||||
platform: str(r.platform),
|
||||
presence: bool(r.presence),
|
||||
publicAddress: str(r.publicAddress),
|
||||
sourceTitle: str(r.sourceTitle),
|
||||
httpsRequired: bool(r.httpsRequired),
|
||||
connections: arr(r.connections).map(
|
||||
(c): ServerConnection => ({
|
||||
uri: str(c.uri),
|
||||
local: bool(c.local),
|
||||
relay: bool(c.relay),
|
||||
protocol: str(c.protocol),
|
||||
address: str(c.address),
|
||||
port: num(c.port),
|
||||
IPv6: bool(c.IPv6),
|
||||
}),
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getHomeUsers(token: string): Promise<HomeUser[]> {
|
||||
const j = await plexRequest(`${TV}/home/users`, token);
|
||||
return arr(j.users ?? j).map((u: any) => ({
|
||||
id: num(u.id),
|
||||
uuid: str(u.uuid),
|
||||
title: str(u.title || u.username),
|
||||
username: str(u.username),
|
||||
thumb: str(u.thumb),
|
||||
admin: bool(u.admin),
|
||||
protected: bool(u.protected),
|
||||
restricted: bool(u.restricted),
|
||||
guest: bool(u.guest),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Switches to a Plex Home user; returns that user's account token. */
|
||||
export async function switchHomeUser(token: string, uuid: string, pin?: string): Promise<string> {
|
||||
const j = await plexRequest(`${TV}/home/users/${uuid}/switch`, token, { method: 'POST', params: { pin } });
|
||||
const t = str(j.authToken);
|
||||
if (!t) throw new PlexError('Plex did not accept this profile PIN.', 401);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Whether a server address is on this network: plex.direct names encode the server's IP. */
|
||||
export function isLocalAddress(url: string): boolean {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g, '');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const ip = host.endsWith('.plex.direct') ? host.split('.')[0].replace(/-/g, '.') : host;
|
||||
if (host === 'localhost' || host.endsWith('.local') || (!host.includes('.') && !host.includes(':'))) return true;
|
||||
if (ip.startsWith('fd') || ip.startsWith('fe80')) return true;
|
||||
const o = ip.split('.').map(Number);
|
||||
if (o.length !== 4 || o.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
|
||||
const [a, b] = o;
|
||||
return a === 10 || a === 127 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
|
||||
}
|
||||
|
||||
export interface Reachable {
|
||||
uri: string;
|
||||
machineId: string;
|
||||
name: string;
|
||||
local: boolean;
|
||||
relay: boolean;
|
||||
latency: number;
|
||||
}
|
||||
|
||||
async function probe(uri: string, token: string, timeout: number): Promise<Reachable> {
|
||||
const start = performance.now();
|
||||
const j = await plexRequest(`${uri.replace(/\/$/, '')}/identity`, token, { timeout });
|
||||
const machineId = str(j?.MediaContainer?.machineIdentifier);
|
||||
if (!machineId) throw new PlexError('Not a Plex Media Server');
|
||||
return { uri, machineId, name: '', local: isLocalAddress(uri), relay: false, latency: performance.now() - start };
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the best reachable connection. Local direct connections win, then
|
||||
* remote direct, then Plex Relay. Each tier is probed concurrently.
|
||||
*/
|
||||
export async function connect(resource: ServerResource, preferred?: string): Promise<Reachable> {
|
||||
const conns = resource.connections.filter((c) => c.uri.startsWith('http'));
|
||||
const tiers: ServerConnection[][] = [];
|
||||
if (preferred) {
|
||||
const p = conns.find((c) => c.uri === preferred);
|
||||
if (p) tiers.push([p]);
|
||||
}
|
||||
tiers.push(
|
||||
conns.filter((c) => c.local && !c.relay),
|
||||
conns.filter((c) => !c.local && !c.relay),
|
||||
conns.filter((c) => c.relay),
|
||||
);
|
||||
for (const tier of tiers) {
|
||||
if (!tier.length) continue;
|
||||
try {
|
||||
const winner = await Promise.any(
|
||||
tier.map((c) =>
|
||||
probe(c.uri, resource.accessToken, c.relay ? 12000 : 6000).then((r) => ({ ...r, local: c.local, relay: c.relay, name: resource.name })),
|
||||
),
|
||||
);
|
||||
return winner;
|
||||
} catch {
|
||||
/* next tier */
|
||||
}
|
||||
}
|
||||
throw new PlexError(`Cannot reach ${resource.name}. Check that the server is online and reachable from this computer.`);
|
||||
}
|
||||
|
||||
/** Validates a manual server address with a token. */
|
||||
export async function connectManual(uri: string, token: string): Promise<Reachable & { name: string }> {
|
||||
const base = uri.replace(/\/$/, '');
|
||||
const j = await plexRequest(`${base}/`, token, { timeout: 8000 });
|
||||
const mc = j?.MediaContainer;
|
||||
if (!mc?.machineIdentifier) throw new PlexError('This address is not a Plex Media Server.');
|
||||
return { uri: base, machineId: str(mc.machineIdentifier), name: str(mc.friendlyName) || 'Plex', local: isLocalAddress(base), relay: false, latency: 0 };
|
||||
}
|
||||
361
src/plex/admin.ts
Normal file
361
src/plex/admin.ts
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
/** Plex Media Server administration (owner accounts). */
|
||||
import type { PlexServer } from './client';
|
||||
import { arr, bool, num, parseItem, parseSection, str } from './parse';
|
||||
import type { Item, Section } from './types';
|
||||
|
||||
export interface ServerSetting {
|
||||
id: string;
|
||||
label: string;
|
||||
summary: string;
|
||||
type: 'text' | 'bool' | 'int' | 'double' | string;
|
||||
default: unknown;
|
||||
value: unknown;
|
||||
hidden: boolean;
|
||||
advanced: boolean;
|
||||
group: string;
|
||||
options: { value: string; label: string }[] | null;
|
||||
}
|
||||
|
||||
export async function prefs(s: PlexServer): Promise<ServerSetting[]> {
|
||||
const mc = await s.container('/:/prefs');
|
||||
return arr(mc.Setting).map((x: any) => ({
|
||||
id: str(x.id),
|
||||
label: str(x.label) || str(x.id),
|
||||
summary: str(x.summary),
|
||||
type: str(x.type),
|
||||
default: x.default,
|
||||
value: x.value,
|
||||
hidden: bool(x.hidden),
|
||||
advanced: bool(x.advanced),
|
||||
group: str(x.group),
|
||||
options: x.enumValues
|
||||
? str(x.enumValues)
|
||||
.split('|')
|
||||
.map((pair) => {
|
||||
const i = pair.indexOf(':');
|
||||
return i < 0 ? { value: pair, label: pair } : { value: pair.slice(0, i), label: pair.slice(i + 1) };
|
||||
})
|
||||
: null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function setPrefs(s: PlexServer, values: Record<string, string | number | boolean>) {
|
||||
const params: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(values)) params[k] = typeof v === 'boolean' ? (v ? 'true' : 'false') : String(v);
|
||||
await s.send('PUT', '/:/prefs', params);
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
sessionKey: string;
|
||||
sessionId: string;
|
||||
item: Item;
|
||||
user: { title: string; thumb: string };
|
||||
player: { title: string; product: string; platform: string; device: string; state: string; local: boolean; address: string; secure: boolean };
|
||||
bandwidth: number;
|
||||
location: string;
|
||||
decision: { video: string; audio: string; container: string; transcodeHw: boolean; progress: number; speed: number; throttled: boolean; videoCodec: string; audioCodec: string; reason: string } | null;
|
||||
viewOffset: number;
|
||||
}
|
||||
|
||||
export async function sessions(s: PlexServer): Promise<Session[]> {
|
||||
const mc = await s.container('/status/sessions');
|
||||
return arr(mc.Metadata).map((m: any) => {
|
||||
const t = m.TranscodeSession;
|
||||
const sess = m.Session ?? {};
|
||||
return {
|
||||
sessionKey: str(m.sessionKey),
|
||||
sessionId: str(sess.id),
|
||||
item: parseItem(m),
|
||||
user: { title: str(m.User?.title), thumb: str(m.User?.thumb) },
|
||||
player: {
|
||||
title: str(m.Player?.title),
|
||||
product: str(m.Player?.product),
|
||||
platform: str(m.Player?.platform),
|
||||
device: str(m.Player?.device),
|
||||
state: str(m.Player?.state),
|
||||
local: bool(m.Player?.local),
|
||||
address: str(m.Player?.address),
|
||||
secure: bool(m.Player?.secure),
|
||||
},
|
||||
bandwidth: num(sess.bandwidth),
|
||||
location: str(sess.location),
|
||||
viewOffset: num(m.viewOffset),
|
||||
decision: t
|
||||
? {
|
||||
video: str(t.videoDecision),
|
||||
audio: str(t.audioDecision),
|
||||
container: str(t.container),
|
||||
transcodeHw: bool(t.transcodeHwRequested) || bool(t.transcodeHwFullPipeline),
|
||||
progress: num(t.progress),
|
||||
speed: num(t.speed),
|
||||
throttled: bool(t.throttled),
|
||||
videoCodec: str(t.videoCodec),
|
||||
audioCodec: str(t.audioCodec),
|
||||
reason: str(t.transcodeReason ?? ''),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export const terminateSession = (s: PlexServer, sessionId: string, reason: string) => s.get('/status/sessions/terminate', { sessionId, reason });
|
||||
|
||||
export interface HistoryEntry {
|
||||
id: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
thumb: string;
|
||||
viewedAt: number;
|
||||
accountId: number;
|
||||
deviceId: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export async function history(s: PlexServer, size = 30): Promise<HistoryEntry[]> {
|
||||
const mc = await s.container('/status/sessions/history/all', { sort: 'viewedAt:desc', 'X-Plex-Container-Size': size, 'X-Plex-Container-Start': 0 });
|
||||
return arr(mc.Metadata).map((m: any) => ({
|
||||
id: str(m.historyKey ?? m.ratingKey),
|
||||
title: str(m.grandparentTitle || m.title),
|
||||
subtitle: m.type === 'episode' ? `S${num(m.parentIndex)} · E${num(m.index)} ${str(m.title)}` : str(m.year ?? ''),
|
||||
thumb: str(m.grandparentThumb || m.thumb),
|
||||
viewedAt: num(m.viewedAt),
|
||||
accountId: num(m.accountID),
|
||||
deviceId: num(m.deviceID),
|
||||
type: str(m.type),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function accounts(s: PlexServer): Promise<Record<number, string>> {
|
||||
const mc = await s.container('/accounts');
|
||||
return Object.fromEntries(arr(mc.Account).map((a: any) => [num(a.id), str(a.name) || 'Owner']));
|
||||
}
|
||||
|
||||
export interface Device {
|
||||
id: number;
|
||||
name: string;
|
||||
platform: string;
|
||||
clientIdentifier: string;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export async function devices(s: PlexServer): Promise<Device[]> {
|
||||
const mc = await s.container('/devices');
|
||||
return arr(mc.Device).map((d: any) => ({ id: num(d.id), name: str(d.name), platform: str(d.platform), clientIdentifier: str(d.clientIdentifier), createdAt: num(d.createdAt) }));
|
||||
}
|
||||
|
||||
export const removeDevice = (s: PlexServer, id: number) => s.send('DELETE', `/devices/${id}`);
|
||||
|
||||
export interface BandwidthPoint {
|
||||
at: number;
|
||||
lan: number;
|
||||
wan: number;
|
||||
}
|
||||
|
||||
/** Bandwidth samples grouped by time (bytes per sample interval). */
|
||||
export async function bandwidth(s: PlexServer, timespan = 6): Promise<{ points: BandwidthPoint[]; devices: Record<number, string> }> {
|
||||
const mc = await s.container('/statistics/bandwidth', { timespan });
|
||||
const byAt = new Map<number, BandwidthPoint>();
|
||||
for (const b of arr(mc.StatisticsBandwidth)) {
|
||||
const at = num(b.at);
|
||||
const p = byAt.get(at) ?? { at, lan: 0, wan: 0 };
|
||||
if (bool(b.lan)) p.lan += num(b.bytes);
|
||||
else p.wan += num(b.bytes);
|
||||
byAt.set(at, p);
|
||||
}
|
||||
return {
|
||||
points: [...byAt.values()].sort((a, b) => a.at - b.at),
|
||||
devices: Object.fromEntries(arr(mc.Device).map((d: any) => [num(d.id), str(d.name)])),
|
||||
};
|
||||
}
|
||||
|
||||
export interface ResourcePoint {
|
||||
at: number;
|
||||
hostCpu: number;
|
||||
processCpu: number;
|
||||
hostMemory: number;
|
||||
processMemory: number;
|
||||
}
|
||||
|
||||
export async function resources(s: PlexServer, timespan = 6): Promise<ResourcePoint[]> {
|
||||
const mc = await s.container('/statistics/resources', { timespan });
|
||||
return arr(mc.StatisticsResources)
|
||||
.map((r: any) => ({
|
||||
at: num(r.at),
|
||||
hostCpu: num(r.hostCpuUtilization),
|
||||
processCpu: num(r.processCpuUtilization),
|
||||
hostMemory: num(r.hostMemoryUtilization),
|
||||
processMemory: num(r.processMemoryUtilization),
|
||||
}))
|
||||
.sort((a, b) => a.at - b.at);
|
||||
}
|
||||
|
||||
export interface Activity {
|
||||
uuid: string;
|
||||
type: string;
|
||||
title: string;
|
||||
subtitle: string;
|
||||
progress: number;
|
||||
cancellable: boolean;
|
||||
}
|
||||
|
||||
export async function activities(s: PlexServer): Promise<Activity[]> {
|
||||
const mc = await s.container('/activities');
|
||||
return arr(mc.Activity).map((a: any) => ({
|
||||
uuid: str(a.uuid),
|
||||
type: str(a.type),
|
||||
title: str(a.title),
|
||||
subtitle: str(a.subtitle),
|
||||
progress: num(a.progress),
|
||||
cancellable: bool(a.cancellable),
|
||||
}));
|
||||
}
|
||||
|
||||
export const cancelActivity = (s: PlexServer, uuid: string) => s.send('DELETE', `/activities/${uuid}`);
|
||||
|
||||
export interface ButlerTask {
|
||||
name: string;
|
||||
title: string;
|
||||
description: string;
|
||||
interval: number;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export async function butlerTasks(s: PlexServer): Promise<ButlerTask[]> {
|
||||
const j = await s.get('/butler');
|
||||
return arr(j?.ButlerTasks?.ButlerTask).map((t: any) => ({
|
||||
name: str(t.name),
|
||||
title: str(t.title) || str(t.name).replace(/^ButlerTask/, '').replace(/([a-z])([A-Z])/g, '$1 $2'),
|
||||
description: str(t.description),
|
||||
interval: num(t.interval),
|
||||
enabled: bool(t.enabled),
|
||||
}));
|
||||
}
|
||||
|
||||
export const runButlerTask = (s: PlexServer, name: string) => s.send('POST', `/butler/${name}`);
|
||||
export const stopButlerTasks = (s: PlexServer) => s.send('DELETE', '/butler');
|
||||
|
||||
export interface RemoteAccess {
|
||||
mappingState: string;
|
||||
mappingError: string;
|
||||
signInState: string;
|
||||
publicAddress: string;
|
||||
publicPort: number;
|
||||
privateAddress: string;
|
||||
privatePort: number;
|
||||
reachabilityPending: boolean;
|
||||
}
|
||||
|
||||
export async function remoteAccess(s: PlexServer): Promise<RemoteAccess> {
|
||||
const j = await s.get('/myplex/account');
|
||||
const m = j?.MyPlex ?? {};
|
||||
return {
|
||||
mappingState: str(m.mappingState),
|
||||
mappingError: str(m.mappingError),
|
||||
signInState: str(m.signInState),
|
||||
publicAddress: str(m.publicAddress),
|
||||
publicPort: num(m.publicPort),
|
||||
privateAddress: str(m.privateAddress),
|
||||
privatePort: num(m.privatePort),
|
||||
reachabilityPending: bool(m.reachabilityPending),
|
||||
};
|
||||
}
|
||||
|
||||
export const refreshReachability = (s: PlexServer) => s.send('PUT', '/myplex/refreshReachability');
|
||||
|
||||
// —— Libraries ——————————————————————————————————————————————————————
|
||||
|
||||
export const scanLibrary = (s: PlexServer, id: string, force = false) => s.get(`/library/sections/${id}/refresh`, force ? { force: 1 } : undefined);
|
||||
export const cancelScan = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}/refresh`);
|
||||
export const emptyTrash = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/emptyTrash`);
|
||||
export const analyzeLibrary = (s: PlexServer, id: string) => s.send('PUT', `/library/sections/${id}/analyze`);
|
||||
export const deleteLibrary = (s: PlexServer, id: string) => s.send('DELETE', `/library/sections/${id}`);
|
||||
export const cleanBundles = (s: PlexServer) => s.send('PUT', '/library/clean/bundles');
|
||||
export const optimizeDatabase = (s: PlexServer) => s.send('PUT', '/library/optimize', { async: 1 });
|
||||
export const scanAll = (s: PlexServer) => s.get('/library/sections/all/refresh');
|
||||
|
||||
export async function librarySize(s: PlexServer, sec: Section): Promise<number> {
|
||||
const mc = await s.container(`/library/sections/${sec.id}/all`, { 'X-Plex-Container-Size': 0, type: sec.type === 'show' ? 2 : sec.type === 'artist' ? 8 : undefined });
|
||||
return num(mc.totalSize ?? mc.size);
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
identifier: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export async function agents(s: PlexServer, mediaType: number): Promise<Agent[]> {
|
||||
const mc = await s.container('/system/agents', { mediaType });
|
||||
return arr(mc.Agent).map((a: any) => ({ identifier: str(a.identifier), name: str(a.name ?? a.title) }));
|
||||
}
|
||||
|
||||
export async function scanners(s: PlexServer, type: number): Promise<string[]> {
|
||||
const mc = await s.container(`/system/scanners/${type}`);
|
||||
return arr(mc.Scanner).map((x: any) => str(x.name));
|
||||
}
|
||||
|
||||
export interface BrowseEntry {
|
||||
key: string;
|
||||
path: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** The server's file system, for choosing library folders. */
|
||||
export async function browse(s: PlexServer, key?: string): Promise<BrowseEntry[]> {
|
||||
const mc = await s.container(key ?? '/services/browse', { includeFiles: 0 });
|
||||
return arr(mc.Path).map((p: any) => ({ key: str(p.key), path: str(p.path), title: str(p.title) }));
|
||||
}
|
||||
|
||||
export async function createLibrary(s: PlexServer, opts: { name: string; type: 'movie' | 'show'; agent: string; scanner: string; language: string; locations: string[] }) {
|
||||
const u = new URL(s.url('/library/sections'));
|
||||
u.searchParams.set('name', opts.name);
|
||||
u.searchParams.set('type', opts.type);
|
||||
u.searchParams.set('agent', opts.agent);
|
||||
u.searchParams.set('scanner', opts.scanner);
|
||||
u.searchParams.set('language', opts.language);
|
||||
for (const l of opts.locations) u.searchParams.append('location', l);
|
||||
await s.send('POST', u.toString());
|
||||
}
|
||||
|
||||
export async function updateLibrary(s: PlexServer, sec: Section, opts: { name: string; locations: string[] }) {
|
||||
const u = new URL(s.url(`/library/sections/${sec.id}`));
|
||||
u.searchParams.set('name', opts.name);
|
||||
u.searchParams.set('agent', sec.agent);
|
||||
u.searchParams.set('language', sec.language);
|
||||
for (const l of opts.locations) u.searchParams.append('location', l);
|
||||
await s.send('PUT', u.toString());
|
||||
}
|
||||
|
||||
export async function sectionDetail(s: PlexServer, id: string): Promise<Section> {
|
||||
const mc = await s.container('/library/sections');
|
||||
const d = arr(mc.Directory).find((x: any) => str(x.key) === id);
|
||||
return parseSection(d ?? {});
|
||||
}
|
||||
|
||||
// —— Updates & diagnostics ————————————————————————————————————————————
|
||||
|
||||
export interface UpdateStatus {
|
||||
canInstall: boolean;
|
||||
checkedAt: number;
|
||||
status: number;
|
||||
version: string;
|
||||
added: string;
|
||||
fixed: string;
|
||||
state: string;
|
||||
}
|
||||
|
||||
export async function updateStatus(s: PlexServer): Promise<UpdateStatus | null> {
|
||||
const mc = await s.container('/updater/status');
|
||||
const r = arr(mc.Release)[0];
|
||||
return {
|
||||
canInstall: bool(mc.canInstall),
|
||||
checkedAt: num(mc.checkedAt),
|
||||
status: num(mc.status),
|
||||
version: str(r?.version),
|
||||
added: str(r?.added),
|
||||
fixed: str(r?.fixed),
|
||||
state: str(r?.state),
|
||||
};
|
||||
}
|
||||
|
||||
export const checkForUpdates = (s: PlexServer) => s.send('PUT', '/updater/check', { download: 1 });
|
||||
export const applyUpdate = (s: PlexServer) => s.send('PUT', '/updater/apply');
|
||||
348
src/plex/api.ts
Normal file
348
src/plex/api.ts
Normal file
|
|
@ -0,0 +1,348 @@
|
|||
/** Library browsing and title operations against one server. */
|
||||
import type { PlexServer, Params } from './client';
|
||||
import { arr, num, parseHub, parseItem, parseSection, str } from './parse';
|
||||
import type { FilterOption, Hub, Item, Page, Section } from './types';
|
||||
|
||||
const items = (mc: any) => arr(mc.Metadata).map(parseItem);
|
||||
|
||||
export async function sections(s: PlexServer): Promise<Section[]> {
|
||||
const mc = await s.container('/library/sections');
|
||||
return arr(mc.Directory).map(parseSection);
|
||||
}
|
||||
|
||||
export async function serverInfo(s: PlexServer) {
|
||||
return s.container('/');
|
||||
}
|
||||
|
||||
const VIDEO_TYPES = new Set(['movie', 'show', 'season', 'episode', 'collection', 'clip']);
|
||||
|
||||
export async function homeHubs(s: PlexServer): Promise<Hub[]> {
|
||||
const mc = await s.container('/hubs', { count: 20, includeExternalMetadata: 1, includeLibraryPlaylists: 0 });
|
||||
return arr(mc.Hub)
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
||||
}
|
||||
|
||||
export async function sectionHubs(s: PlexServer, sectionId: string): Promise<Hub[]> {
|
||||
const mc = await s.container(`/hubs/sections/${sectionId}`, { count: 20, includeExternalMetadata: 1 });
|
||||
return arr(mc.Hub)
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type));
|
||||
}
|
||||
|
||||
/** Continue Watching across libraries (Plex's own hub honors removals). */
|
||||
export async function continueWatching(s: PlexServer, sectionId?: string): Promise<Item[]> {
|
||||
const path = sectionId ? `/hubs/sections/${sectionId}/continueWatching/items` : '/hubs/continueWatching/items';
|
||||
try {
|
||||
const mc = await s.container(path, { 'X-Plex-Container-Size': 40, includeExternalMetadata: 1 });
|
||||
return items(mc);
|
||||
} catch {
|
||||
const mc = await s.container('/library/onDeck', { 'X-Plex-Container-Size': 40 });
|
||||
return items(mc).filter((i) => !sectionId || i.librarySectionId === sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function hubItems(s: PlexServer, key: string, start = 0, size = 60): Promise<Page<Item>> {
|
||||
const mc = await s.container(key, { 'X-Plex-Container-Start': start, 'X-Plex-Container-Size': size, includeExternalMetadata: 1 });
|
||||
const list = items(mc).length ? items(mc) : arr(mc.Hub).flatMap((h: any) => arr(h.Metadata).map(parseItem));
|
||||
return { items: list, total: num(mc.totalSize ?? mc.size), offset: start };
|
||||
}
|
||||
|
||||
/** Metadata types used by library queries. */
|
||||
export const TYPE_ID: Record<string, number> = { movie: 1, show: 2, season: 3, episode: 4, collection: 18 };
|
||||
|
||||
export async function libraryPage(
|
||||
s: PlexServer,
|
||||
sectionId: string,
|
||||
opts: { type?: number; sort?: string; filters?: Record<string, string>; title?: string; start: number; size: number },
|
||||
): Promise<Page<Item>> {
|
||||
const params: Params = {
|
||||
'X-Plex-Container-Start': opts.start,
|
||||
'X-Plex-Container-Size': opts.size,
|
||||
type: opts.type,
|
||||
sort: opts.sort,
|
||||
includeGuids: 0,
|
||||
...opts.filters,
|
||||
};
|
||||
if (opts.title) params['title'] = opts.title;
|
||||
const mc = await s.container(`/library/sections/${sectionId}/all`, params);
|
||||
return { items: items(mc), total: num(mc.totalSize ?? mc.size), offset: opts.start };
|
||||
}
|
||||
|
||||
export interface LibraryMeta {
|
||||
filters: { filter: string; type: string; title: string; key: string }[];
|
||||
sorts: { key: string; title: string; defaultDirection: string }[];
|
||||
}
|
||||
|
||||
export async function libraryMeta(s: PlexServer, sectionId: string, type: number): Promise<LibraryMeta> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/all`, { includeMeta: 1, 'X-Plex-Container-Size': 0, type });
|
||||
const name = Object.entries(TYPE_ID).find(([, v]) => v === type)?.[0];
|
||||
const t = arr(mc.Meta?.Type).find((x: any) => x.type === name) ?? arr(mc.Meta?.Type)[0];
|
||||
return {
|
||||
filters: arr(t?.Filter).map((f: any) => ({ filter: str(f.filter), type: str(f.filterType), title: str(f.title), key: str(f.key) })),
|
||||
sorts: arr(t?.Sort).map((x: any) => ({ key: str(x.key), title: str(x.title), defaultDirection: str(x.defaultDirection) || 'asc' })),
|
||||
};
|
||||
}
|
||||
|
||||
export async function filterOptions(s: PlexServer, path: string, type?: number): Promise<FilterOption[]> {
|
||||
const mc = await s.container(path, { type });
|
||||
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title) }));
|
||||
}
|
||||
|
||||
export async function firstCharacters(s: PlexServer, sectionId: string, params: Params): Promise<{ key: string; title: string; size: number }[]> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/firstCharacter`, params);
|
||||
return arr(mc.Directory).map((d: any) => ({ key: str(d.key), title: str(d.title), size: num(d.size) }));
|
||||
}
|
||||
|
||||
export async function collections(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/sections/${sectionId}/collections`, { includeCollections: 1, sort: 'titleSort:asc' });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function metadata(s: PlexServer, id: string): Promise<Item> {
|
||||
const mc = await s.container(`/library/metadata/${id}`, {
|
||||
includeMarkers: 1,
|
||||
includeChapters: 1,
|
||||
includeExtras: 1,
|
||||
includeConcerts: 1,
|
||||
includeOnDeck: 1,
|
||||
includeReviews: 0,
|
||||
includePreferences: 1,
|
||||
includeExternalMedia: 0,
|
||||
checkFiles: 1,
|
||||
asyncAugmentMetadata: 0,
|
||||
});
|
||||
const first = arr(mc.Metadata)[0];
|
||||
if (!first) throw new Error('This title is unavailable.');
|
||||
const item = parseItem(first);
|
||||
item.raw.__librarySectionID = mc.librarySectionID;
|
||||
if (!item.librarySectionId) item.librarySectionId = str(mc.librarySectionID);
|
||||
return item;
|
||||
}
|
||||
|
||||
export async function children(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/children`, { includeMarkers: 0, excludeAllLeaves: 1 });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function allLeaves(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/allLeaves`);
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
/** The show's next episode (Plex's OnDeck), if any. */
|
||||
export async function onDeckFor(_s: PlexServer, item: Item): Promise<Item | null> {
|
||||
const od = arr(item.raw?.OnDeck?.Metadata)[0];
|
||||
if (od) return parseItem(od);
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function related(s: PlexServer, id: string): Promise<Hub[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/related`, { includeExternalMetadata: 1, count: 20 });
|
||||
return arr(mc.Hub).map(parseHub).filter((h) => h.items.length);
|
||||
}
|
||||
|
||||
export async function collectionItems(s: PlexServer, id: string): Promise<Item[]> {
|
||||
const mc = await s.container(`/library/collections/${id}/children`);
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
/** Titles featuring a person, across the server's movie and TV libraries. */
|
||||
export async function personTitles(s: PlexServer, personId: string, libs: Section[]): Promise<Item[]> {
|
||||
const video = libs.filter((l) => l.type === 'movie' || l.type === 'show');
|
||||
const results = await Promise.all(
|
||||
video.map(async (l) => {
|
||||
const out: Item[] = [];
|
||||
let start = 0;
|
||||
for (let guard = 0; guard < 10; guard++) {
|
||||
const mc = await s.container(`/library/sections/${l.id}/all`, {
|
||||
actor: personId,
|
||||
sort: 'originallyAvailableAt:desc',
|
||||
'X-Plex-Container-Start': start,
|
||||
'X-Plex-Container-Size': 100,
|
||||
});
|
||||
const batch = items(mc);
|
||||
out.push(...batch);
|
||||
start += batch.length;
|
||||
if (!batch.length || start >= num(mc.totalSize ?? mc.size)) break;
|
||||
}
|
||||
// Directors and writers too, when the person has no acting credits here.
|
||||
if (!out.length) {
|
||||
for (const tag of ['director', 'writer']) {
|
||||
const mc = await s.container(`/library/sections/${l.id}/all`, { [tag]: personId, sort: 'originallyAvailableAt:desc' });
|
||||
out.push(...items(mc));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}),
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
return results.flat().filter((i) => (seen.has(i.id) ? false : (seen.add(i.id), true)));
|
||||
}
|
||||
|
||||
export async function person(s: PlexServer, id: string): Promise<any> {
|
||||
try {
|
||||
const mc = await s.container(`/library/people/${id}`);
|
||||
return arr(mc.Directory)[0] ?? arr(mc.Metadata)[0] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
hubs: Hub[];
|
||||
people: { id: string; tag: string; thumb: string }[];
|
||||
}
|
||||
|
||||
export async function search(s: PlexServer, query: string, sectionId?: string): Promise<SearchResult> {
|
||||
const mc = await s.container('/hubs/search', { query, limit: 30, includeCollections: 1, sectionId, includeExternalMedia: 0 });
|
||||
const hubs = arr(mc.Hub);
|
||||
const people = hubs
|
||||
.filter((h: any) => h.type === 'actor' || h.type === 'director')
|
||||
.flatMap((h: any) => arr(h.Directory ?? h.Metadata))
|
||||
.map((p: any) => ({ id: str(p.id ?? p.ratingKey), tag: str(p.tag ?? p.title), thumb: str(p.thumb) }))
|
||||
.filter((p: any) => p.id && p.tag);
|
||||
const seenPeople = new Set<string>();
|
||||
return {
|
||||
hubs: hubs
|
||||
.map(parseHub)
|
||||
.filter((h) => h.items.length && VIDEO_TYPES.has(h.items[0].type)),
|
||||
people: people.filter((p) => (seenPeople.has(p.id) ? false : (seenPeople.add(p.id), true))),
|
||||
};
|
||||
}
|
||||
|
||||
// —— Watch state ————————————————————————————————————————————————
|
||||
|
||||
export async function setWatched(s: PlexServer, id: string, watched: boolean) {
|
||||
await s.get(watched ? '/:/scrobble' : '/:/unscrobble', { key: id, identifier: 'com.plexapp.plugins.library' });
|
||||
}
|
||||
|
||||
export async function removeFromContinueWatching(s: PlexServer, id: string) {
|
||||
await s.send('PUT', '/actions/removeFromContinueWatching', { ratingKey: id });
|
||||
}
|
||||
|
||||
export async function rate(s: PlexServer, id: string, rating: number) {
|
||||
await s.send('PUT', '/:/rate', { key: id, identifier: 'com.plexapp.plugins.library', rating: rating < 0 ? -1 : rating });
|
||||
}
|
||||
|
||||
export async function selectStreams(s: PlexServer, partId: string, sel: { audioStreamID?: string; subtitleStreamID?: string }) {
|
||||
await s.send('PUT', `/library/parts/${partId}`, { allParts: 1, ...sel });
|
||||
}
|
||||
|
||||
// —— Library management ——————————————————————————————————————————
|
||||
|
||||
export const refreshMetadata = (s: PlexServer, id: string, force = true) => s.send('PUT', `/library/metadata/${id}/refresh`, { force: force ? 1 : 0 });
|
||||
export const analyze = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/analyze`);
|
||||
export const unmatch = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/unmatch`);
|
||||
export const splitApart = (s: PlexServer, id: string) => s.send('PUT', `/library/metadata/${id}/split`);
|
||||
export const merge = (s: PlexServer, id: string, others: string[]) => s.send('PUT', `/library/metadata/${id}/merge`, { ids: others.join(',') });
|
||||
export const deleteItem = (s: PlexServer, id: string) => s.send('DELETE', `/library/metadata/${id}`);
|
||||
export const deleteMedia = (s: PlexServer, id: string, mediaId: string) => s.send('DELETE', `/library/metadata/${id}/media/${mediaId}`);
|
||||
|
||||
export interface MatchCandidate {
|
||||
guid: string;
|
||||
name: string;
|
||||
year: number;
|
||||
score: number;
|
||||
thumb: string;
|
||||
summary: string;
|
||||
matched: boolean;
|
||||
}
|
||||
|
||||
export async function matches(s: PlexServer, id: string, opts: { title?: string; year?: string; agent?: string; language?: string }): Promise<MatchCandidate[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/matches`, {
|
||||
manual: 1,
|
||||
title: opts.title,
|
||||
year: opts.year,
|
||||
agent: opts.agent,
|
||||
language: opts.language,
|
||||
});
|
||||
return arr(mc.SearchResult).map((r: any) => ({
|
||||
guid: str(r.guid),
|
||||
name: str(r.name),
|
||||
year: num(r.year),
|
||||
score: num(r.score),
|
||||
thumb: str(r.thumb),
|
||||
summary: str(r.summary),
|
||||
matched: r.matched === 1 || r.matched === true || r.matched === '1',
|
||||
}));
|
||||
}
|
||||
|
||||
export const applyMatch = (s: PlexServer, id: string, guid: string, name: string, year?: number) =>
|
||||
s.send('PUT', `/library/metadata/${id}/match`, { guid, name, year });
|
||||
|
||||
export async function artworkOptions(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos'): Promise<{ key: string; thumb: string; selected: boolean; provider: string }[]> {
|
||||
const mc = await s.container(`/library/metadata/${id}/${kind}`);
|
||||
return arr(mc.Metadata).map((m: any) => ({ key: str(m.key), thumb: str(m.thumb || m.key), selected: m.selected === true || m.selected === 1, provider: str(m.provider) }));
|
||||
}
|
||||
|
||||
export const selectArtwork = (s: PlexServer, id: string, kind: 'poster' | 'art' | 'clearLogo', url: string) =>
|
||||
s.send('PUT', `/library/metadata/${id}/${kind}`, { url });
|
||||
|
||||
export async function uploadArtwork(s: PlexServer, id: string, kind: 'posters' | 'arts' | 'clearLogos', data: Blob) {
|
||||
await s.send('POST', `/library/metadata/${id}/${kind}`, undefined, { body: data });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edits metadata through the section `all` endpoint, as Plex Web does. Field
|
||||
* values are locked so later refreshes keep them.
|
||||
*/
|
||||
export async function editMetadata(
|
||||
s: PlexServer,
|
||||
item: Item,
|
||||
fields: Record<string, string>,
|
||||
tagFields: Record<string, { add: string[]; remove: string[] }> = {},
|
||||
locks: Record<string, boolean> = {},
|
||||
) {
|
||||
const type = TYPE_ID[item.type] ?? 1;
|
||||
const params: Params = { type, id: item.id, includeExternalMedia: 1 };
|
||||
for (const [k, v] of Object.entries(fields)) {
|
||||
params[`${k}.value`] = v;
|
||||
params[`${k}.locked`] = locks[k] === false ? 0 : 1;
|
||||
}
|
||||
for (const [tag, change] of Object.entries(tagFields)) {
|
||||
change.add.forEach((v, i) => (params[`${tag}[${i}].tag.tag`] = v));
|
||||
if (change.remove.length) params[`${tag}[].tag.tag-`] = change.remove.join(',');
|
||||
params[`${tag}.locked`] = locks[tag] === false ? 0 : 1;
|
||||
}
|
||||
for (const [k, locked] of Object.entries(locks)) {
|
||||
if (!(k in fields) && !(k in tagFields)) params[`${k}.locked`] = locked ? 1 : 0;
|
||||
}
|
||||
const section = item.librarySectionId || str(item.raw?.__librarySectionID);
|
||||
await s.send('PUT', `/library/sections/${section}/all`, params);
|
||||
}
|
||||
|
||||
/** Collections: create, add, remove. */
|
||||
export async function addToCollection(s: PlexServer, item: Item, collection: string) {
|
||||
await editMetadata(s, item, {}, { collection: { add: [collection], remove: [] } });
|
||||
}
|
||||
|
||||
export async function removeFromCollection(s: PlexServer, collectionId: string, itemId: string) {
|
||||
await s.send('DELETE', `/library/collections/${collectionId}/items/${itemId}`);
|
||||
}
|
||||
|
||||
export async function playlists(s: PlexServer): Promise<Item[]> {
|
||||
const mc = await s.container('/playlists', { playlistType: 'video', smart: 0 });
|
||||
return items(mc);
|
||||
}
|
||||
|
||||
export async function addToPlaylist(s: PlexServer, playlistId: string, machineId: string, itemId: string) {
|
||||
await s.send('PUT', `/playlists/${playlistId}/items`, { uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}` });
|
||||
}
|
||||
|
||||
export async function createPlaylist(s: PlexServer, title: string, machineId: string, itemId: string) {
|
||||
await s.send('POST', '/playlists', {
|
||||
type: 'video',
|
||||
title,
|
||||
smart: 0,
|
||||
uri: `server://${machineId}/com.plexapp.plugins.library/library/metadata/${itemId}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** Library change detection: small response; compared every few seconds. */
|
||||
export async function libraryRevision(s: PlexServer): Promise<string> {
|
||||
const mc = await s.container('/library/sections');
|
||||
return arr(mc.Directory)
|
||||
.map((d: any) => [d.key, d.contentChangedAt, d.scannedAt, d.updatedAt].join(':'))
|
||||
.join('|');
|
||||
}
|
||||
183
src/plex/client.ts
Normal file
183
src/plex/client.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { httpFetch } from '../platform/native';
|
||||
|
||||
export const PRODUCT = 'Kaleido';
|
||||
export const PLATFORM = 'Windows';
|
||||
|
||||
export class PlexError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status = 0,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
let clientId = '';
|
||||
let version = '0.1.0';
|
||||
let deviceName = 'Windows PC';
|
||||
|
||||
/** A stable, random identifier for this installation (not secret). */
|
||||
export function clientIdentifier(): string {
|
||||
if (clientId) return clientId;
|
||||
clientId = localStorage.getItem('kaleido.clientId') ?? '';
|
||||
if (!clientId) {
|
||||
clientId = crypto.randomUUID();
|
||||
localStorage.setItem('kaleido.clientId', clientId);
|
||||
}
|
||||
return clientId;
|
||||
}
|
||||
|
||||
export function configureClient(opts: { version?: string; deviceName?: string }) {
|
||||
if (opts.version) version = opts.version;
|
||||
if (opts.deviceName) deviceName = opts.deviceName;
|
||||
}
|
||||
|
||||
export function plexHeaders(token?: string | null): Record<string, string> {
|
||||
const h: Record<string, string> = {
|
||||
Accept: 'application/json',
|
||||
'X-Plex-Product': PRODUCT,
|
||||
'X-Plex-Version': version,
|
||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||
'X-Plex-Platform': PLATFORM,
|
||||
'X-Plex-Platform-Version': '11',
|
||||
'X-Plex-Device': 'Windows',
|
||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
||||
'X-Plex-Model': 'Desktop',
|
||||
'X-Plex-Provides': 'player',
|
||||
'X-Plex-Language': navigator.language || 'en',
|
||||
};
|
||||
if (token) h['X-Plex-Token'] = token;
|
||||
return h;
|
||||
}
|
||||
|
||||
/** Query-string equivalents of the identification headers (for media URLs). */
|
||||
export function plexQuery(token?: string | null): Record<string, string> {
|
||||
const q: Record<string, string> = {
|
||||
'X-Plex-Product': PRODUCT,
|
||||
'X-Plex-Version': version,
|
||||
'X-Plex-Client-Identifier': clientIdentifier(),
|
||||
'X-Plex-Platform': PLATFORM,
|
||||
'X-Plex-Device': 'Windows',
|
||||
'X-Plex-Device-Name': `Kaleido (${deviceName})`,
|
||||
};
|
||||
if (token) q['X-Plex-Token'] = token;
|
||||
return q;
|
||||
}
|
||||
|
||||
export type Params = Record<string, string | number | boolean | undefined | null>;
|
||||
|
||||
export function withParams(url: string, params?: Params): string {
|
||||
if (!params) return url;
|
||||
const u = new URL(url);
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
u.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v));
|
||||
}
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
params?: Params;
|
||||
body?: BodyInit | null;
|
||||
headers?: Record<string, string>;
|
||||
timeout?: number;
|
||||
signal?: AbortSignal;
|
||||
/** Return raw text instead of parsed JSON. */
|
||||
text?: boolean;
|
||||
}
|
||||
|
||||
const statusMessage = (status: number) =>
|
||||
status === 401 || status === 403
|
||||
? 'Plex declined this request. Sign in again or check your access to this server.'
|
||||
: status === 404
|
||||
? 'This item is no longer available.'
|
||||
: status === 400
|
||||
? 'Plex could not process this request.'
|
||||
: status >= 500
|
||||
? `The Plex server reported an error (${status}).`
|
||||
: `Plex could not complete the request (${status}).`;
|
||||
|
||||
export async function plexRequest<T = any>(url: string, token: string | null | undefined, opts: RequestOptions = {}): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), opts.timeout ?? 30000);
|
||||
const onAbort = () => controller.abort();
|
||||
opts.signal?.addEventListener('abort', onAbort);
|
||||
let response: Response;
|
||||
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);
|
||||
} 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 {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text as unknown as T;
|
||||
}
|
||||
}
|
||||
|
||||
/** A connection to one Plex Media Server. */
|
||||
export class PlexServer {
|
||||
constructor(
|
||||
public readonly uri: string,
|
||||
public readonly token: string,
|
||||
public readonly machineId: string,
|
||||
public readonly name: string,
|
||||
public readonly owned: boolean,
|
||||
public readonly local: boolean,
|
||||
) {}
|
||||
|
||||
url(path: string, params?: Params): string {
|
||||
const base = path.startsWith('http') ? path : `${this.uri.replace(/\/$/, '')}/${path.replace(/^\//, '')}`;
|
||||
return withParams(base, params);
|
||||
}
|
||||
|
||||
/** URL including the token, for media loaded outside fetch (images, video). */
|
||||
signed(path: string, params?: Params): string {
|
||||
return this.url(path, { ...params, 'X-Plex-Token': this.token });
|
||||
}
|
||||
|
||||
async get<T = any>(path: string, params?: Params, opts: RequestOptions = {}): Promise<T> {
|
||||
return plexRequest<T>(this.url(path), this.token, { ...opts, params });
|
||||
}
|
||||
|
||||
async container(path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
|
||||
const j = await this.get(path, params, opts);
|
||||
return j?.MediaContainer ?? {};
|
||||
}
|
||||
|
||||
async send(method: 'POST' | 'PUT' | 'DELETE', path: string, params?: Params, opts: RequestOptions = {}): Promise<any> {
|
||||
return plexRequest(this.url(path), this.token, { ...opts, method, params });
|
||||
}
|
||||
|
||||
/** Photo transcoder URL, sized for the device pixel ratio. */
|
||||
image(path: string | undefined, width: number, height: number, opts: { blur?: number; quality?: number; format?: 'jpeg' | 'png' } = {}): string {
|
||||
if (!path) return '';
|
||||
const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
||||
const w = Math.round(width * dpr);
|
||||
const h = Math.round(height * dpr);
|
||||
return this.signed('/photo/:/transcode', {
|
||||
url: path,
|
||||
width: w,
|
||||
height: h,
|
||||
minSize: 1,
|
||||
upscale: 1,
|
||||
quality: opts.quality,
|
||||
blur: opts.blur,
|
||||
format: opts.format ?? 'jpeg',
|
||||
});
|
||||
}
|
||||
}
|
||||
248
src/plex/parse.ts
Normal file
248
src/plex/parse.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
import type { AudienceScore, Chapter, Hub, Item, Marker, Media, Part, Role, Section, Stream, Tag } from './types';
|
||||
|
||||
const arr = (v: any): any[] => (Array.isArray(v) ? v : v ? [v] : []);
|
||||
const str = (v: any): string => (v === undefined || v === null ? '' : String(v));
|
||||
const num = (v: any): number => {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
};
|
||||
const bool = (v: any): boolean => v === true || v === 1 || v === '1' || v === 'true';
|
||||
|
||||
const tags = (v: any): Tag[] =>
|
||||
arr(v).map((t) => ({ id: str(t.id), tag: str(t.tag), filter: str(t.filter) })).filter((t) => t.tag);
|
||||
|
||||
export function parseStream(s: any): Stream {
|
||||
return {
|
||||
id: str(s.id),
|
||||
streamType: num(s.streamType),
|
||||
codec: str(s.codec),
|
||||
index: s.index === undefined ? -1 : num(s.index),
|
||||
language: str(s.language),
|
||||
languageCode: str(s.languageCode ?? s.languageTag),
|
||||
displayTitle: str(s.displayTitle ?? s.title ?? s.language),
|
||||
extendedDisplayTitle: str(s.extendedDisplayTitle ?? s.displayTitle),
|
||||
title: str(s.title),
|
||||
selected: bool(s.selected),
|
||||
default: bool(s.default),
|
||||
forced: bool(s.forced),
|
||||
key: str(s.key),
|
||||
channels: num(s.channels),
|
||||
audioChannelLayout: str(s.audioChannelLayout),
|
||||
bitrate: num(s.bitrate),
|
||||
width: num(s.width),
|
||||
height: num(s.height),
|
||||
frameRate: num(s.frameRate),
|
||||
profile: str(s.profile),
|
||||
colorTrc: str(s.colorTrc),
|
||||
colorPrimaries: str(s.colorPrimaries),
|
||||
bitDepth: num(s.bitDepth),
|
||||
doviPresent: bool(s.DOVIPresent),
|
||||
hearingImpaired: bool(s.hearingImpaired),
|
||||
samplingRate: num(s.samplingRate),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePart(p: any): Part {
|
||||
return {
|
||||
id: str(p.id),
|
||||
key: str(p.key),
|
||||
file: str(p.file),
|
||||
size: num(p.size),
|
||||
duration: num(p.duration),
|
||||
container: str(p.container),
|
||||
indexes: str(p.indexes),
|
||||
streams: arr(p.Stream).map(parseStream),
|
||||
accessible: p.accessible === undefined ? true : bool(p.accessible),
|
||||
exists: p.exists === undefined ? true : bool(p.exists),
|
||||
};
|
||||
}
|
||||
|
||||
export function dynamicRange(video?: Stream): string {
|
||||
if (!video) return '';
|
||||
if (video.doviPresent) return 'Dolby Vision';
|
||||
if (video.colorTrc === 'smpte2084') return 'HDR10';
|
||||
if (video.colorTrc === 'arib-std-b67') return 'HLG';
|
||||
return '';
|
||||
}
|
||||
|
||||
function parseMedia(m: any): Media {
|
||||
const parts = arr(m.Part).map(parsePart);
|
||||
const streams = parts.flatMap((p) => p.streams);
|
||||
const video = streams.find((s) => s.streamType === 1);
|
||||
const audio = streams.filter((s) => s.streamType === 2);
|
||||
return {
|
||||
id: str(m.id),
|
||||
container: str(m.container),
|
||||
videoCodec: str(m.videoCodec),
|
||||
audioCodec: str(m.audioCodec),
|
||||
videoResolution: str(m.videoResolution),
|
||||
width: num(m.width),
|
||||
height: num(m.height),
|
||||
bitrate: num(m.bitrate),
|
||||
duration: num(m.duration),
|
||||
audioChannels: num(m.audioChannels),
|
||||
videoProfile: str(m.videoProfile),
|
||||
videoFrameRate: str(m.videoFrameRate),
|
||||
aspectRatio: num(m.aspectRatio),
|
||||
optimizedForStreaming: bool(m.optimizedForStreaming),
|
||||
title: str(m.title),
|
||||
parts,
|
||||
dynamicRange: dynamicRange(video) || (str(m.videoDynamicRange ?? '') === 'HDR' ? 'HDR10' : ''),
|
||||
atmos: audio.some((s) => /atmos/i.test(s.displayTitle + s.extendedDisplayTitle + s.title)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
|
||||
export function parseScores(j: any): AudienceScore[] {
|
||||
const out: AudienceScore[] = [];
|
||||
const add = (image: string, value: number, kind: 'audience' | 'critic') => {
|
||||
if (!Number.isFinite(value) || value < 0 || value > 10 || !image) return;
|
||||
let source: AudienceScore['source'] | null = null;
|
||||
if (image.startsWith('rottentomatoes://')) source = 'Rotten Tomatoes';
|
||||
else if (image.startsWith('imdb://')) source = 'IMDb';
|
||||
else if (image.startsWith('themoviedb://')) source = 'TMDB';
|
||||
else if (image.startsWith('thetvdb://') || image.startsWith('tvdb://')) source = 'TVDB';
|
||||
if (!source || out.some((s) => s.source === source && s.kind === kind)) return;
|
||||
out.push({ source, value, kind, image });
|
||||
};
|
||||
for (const r of arr(j.Rating)) add(str(r.image), num(r.value), r.type === 'critic' ? 'critic' : 'audience');
|
||||
if (j.audienceRatingImage) add(str(j.audienceRatingImage), num(j.audienceRating), 'audience');
|
||||
if (j.ratingImage) add(str(j.ratingImage), num(j.rating), 'critic');
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseUltraBlur(j: any): Item['ultraBlur'] {
|
||||
const u = arr(j.UltraBlurColors)[0];
|
||||
if (!u?.topLeft) return null;
|
||||
return { topLeft: str(u.topLeft), topRight: str(u.topRight), bottomRight: str(u.bottomRight), bottomLeft: str(u.bottomLeft) };
|
||||
}
|
||||
|
||||
export function parseItem(j: any): Item {
|
||||
const images = arr(j.Image);
|
||||
const image = (type: string) => str(images.find((i) => i.type === type)?.url);
|
||||
const roles: Role[] = arr(j.Role)
|
||||
.map((r) => ({
|
||||
id: str(r.id) || str(r.filter).replace(/^actor=/, ''),
|
||||
tag: str(r.tag),
|
||||
filter: str(r.filter),
|
||||
role: str(r.role),
|
||||
thumb: str(r.thumb),
|
||||
}))
|
||||
.filter((r) => r.tag);
|
||||
const type = str(j.type);
|
||||
return {
|
||||
id: str(j.ratingKey ?? j.key),
|
||||
key: str(j.key),
|
||||
guid: str(j.guid),
|
||||
guids: arr(j.Guid).map((g) => str(g.id)),
|
||||
type,
|
||||
subtype: str(j.subtype),
|
||||
title: str(j.title),
|
||||
titleSort: str(j.titleSort),
|
||||
originalTitle: str(j.originalTitle),
|
||||
summary: str(j.summary),
|
||||
tagline: str(j.tagline),
|
||||
year: num(j.year ?? j.parentYear),
|
||||
originallyAvailableAt: str(j.originallyAvailableAt),
|
||||
duration: num(j.duration),
|
||||
viewOffset: num(j.viewOffset),
|
||||
viewCount: num(j.viewCount),
|
||||
lastViewedAt: num(j.lastViewedAt),
|
||||
addedAt: num(j.addedAt),
|
||||
updatedAt: num(j.updatedAt),
|
||||
thumb: str(j.thumb),
|
||||
art: str(j.art ?? j.grandparentArt ?? j.parentArt),
|
||||
logo: image('clearLogo'),
|
||||
theme: str(j.theme ?? j.parentTheme ?? j.grandparentTheme),
|
||||
contentRating: str(j.contentRating),
|
||||
studio: str(j.studio),
|
||||
parentId: str(j.parentRatingKey),
|
||||
parentKey: str(j.parentKey),
|
||||
parentTitle: str(j.parentTitle),
|
||||
parentIndex: num(j.parentIndex),
|
||||
parentThumb: str(j.parentThumb),
|
||||
grandparentId: str(j.grandparentRatingKey),
|
||||
grandparentKey: str(j.grandparentKey),
|
||||
grandparentTitle: str(j.grandparentTitle),
|
||||
grandparentThumb: str(j.grandparentThumb),
|
||||
grandparentArt: str(j.grandparentArt),
|
||||
index: num(j.index),
|
||||
leafCount: num(j.leafCount),
|
||||
viewedLeafCount: num(j.viewedLeafCount),
|
||||
childCount: num(j.childCount),
|
||||
genres: tags(j.Genre),
|
||||
directors: tags(j.Director),
|
||||
writers: tags(j.Writer),
|
||||
producers: tags(j.Producer),
|
||||
countries: tags(j.Country),
|
||||
labels: tags(j.Label),
|
||||
collections: tags(j.Collection),
|
||||
roles,
|
||||
scores: parseScores(j),
|
||||
userRating: num(j.userRating),
|
||||
media: arr(j.Media).map(parseMedia),
|
||||
markers: arr(j.Marker).map(
|
||||
(m): Marker => ({
|
||||
id: str(m.id),
|
||||
type: str(m.type),
|
||||
start: num(m.startTimeOffset),
|
||||
end: num(m.endTimeOffset),
|
||||
final: bool(m.final),
|
||||
}),
|
||||
),
|
||||
chapters: arr(j.Chapter).map(
|
||||
(c, i): Chapter => ({
|
||||
index: num(c.index) || i + 1,
|
||||
title: str(c.tag ?? c.title) || `Chapter ${i + 1}`,
|
||||
start: num(c.startTimeOffset),
|
||||
end: num(c.endTimeOffset),
|
||||
thumb: str(c.thumb),
|
||||
}),
|
||||
),
|
||||
extras: arr(j.Extras?.Metadata).map(parseItem),
|
||||
librarySectionId: str(j.librarySectionID),
|
||||
librarySectionTitle: str(j.librarySectionTitle),
|
||||
librarySectionKey: str(j.librarySectionKey),
|
||||
smart: bool(j.smart),
|
||||
editionTitle: str(j.editionTitle),
|
||||
skipChildren: bool(j.skipChildren),
|
||||
ultraBlur: parseUltraBlur(j),
|
||||
raw: j,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseHub(h: any): Hub {
|
||||
return {
|
||||
id: str(h.hubIdentifier ?? h.key ?? h.title),
|
||||
key: str(h.key),
|
||||
title: str(h.title),
|
||||
type: str(h.type),
|
||||
context: str(h.context),
|
||||
size: num(h.size),
|
||||
more: bool(h.more),
|
||||
style: str(h.style),
|
||||
items: arr(h.Metadata).map(parseItem),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSection(d: any): Section {
|
||||
return {
|
||||
id: str(d.key),
|
||||
key: str(d.key),
|
||||
title: str(d.title),
|
||||
type: str(d.type),
|
||||
agent: str(d.agent),
|
||||
scanner: str(d.scanner),
|
||||
language: str(d.language),
|
||||
thumb: str(d.thumb),
|
||||
art: str(d.art),
|
||||
locations: arr(d.Location).map((l) => ({ id: str(l.id), path: str(l.path) })),
|
||||
scannedAt: num(d.scannedAt),
|
||||
updatedAt: num(d.updatedAt),
|
||||
contentChangedAt: num(d.contentChangedAt),
|
||||
refreshing: bool(d.refreshing),
|
||||
hidden: num(d.hidden) > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export { arr, str, num, bool };
|
||||
109
src/plex/playback.ts
Normal file
109
src/plex/playback.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/** Delivery decisions, stream URLs and progress reporting for playback. */
|
||||
import { plexQuery, type PlexServer } from './client';
|
||||
import type { Item, Media, Part } from './types';
|
||||
import { QUALITY_PROFILE, type Quality } from '../app/settings';
|
||||
|
||||
export interface Delivery {
|
||||
url: string;
|
||||
mode: 'direct' | 'transcode' | 'local';
|
||||
/** Plex transcode session; stopped when playback ends. */
|
||||
session?: string;
|
||||
label: string;
|
||||
/** Media timestamps are absolute (Plex HLS); don't rebase to zero. */
|
||||
absoluteTime: boolean;
|
||||
}
|
||||
|
||||
/** mpv EDL joins multi-part files (CD1/CD2) into one timeline. */
|
||||
function edl(urls: string[]): string {
|
||||
return 'edl://' + urls.map((u) => `%${new TextEncoder().encode(u).length}%${u}`).join(';');
|
||||
}
|
||||
|
||||
export function directUrl(server: PlexServer, media: Media): string {
|
||||
const urls = media.parts.map((p) => server.signed(p.key, plexQuery()));
|
||||
return urls.length > 1 ? edl(urls) : urls[0];
|
||||
}
|
||||
|
||||
export function transcodeUrl(
|
||||
server: PlexServer,
|
||||
item: Item,
|
||||
opts: { mediaIndex: number; quality: Exclude<Quality, 'original'> | 'remux'; offsetMs: number; session: string; local: boolean; audioStreamID?: string; subtitleStreamID?: string },
|
||||
): string {
|
||||
const media = item.media[opts.mediaIndex];
|
||||
const profile = opts.quality === 'remux' ? null : QUALITY_PROFILE[opts.quality];
|
||||
const extra = [
|
||||
'add-transcode-target(type=videoProfile&context=streaming&protocol=hls&container=mpegts&videoCodec=h264,hevc&audioCodec=aac,ac3,eac3,mp3,opus)',
|
||||
'add-limitation(scope=videoCodec&scopeName=hevc&type=upperBound&name=video.bitDepth&value=10)',
|
||||
].join('+');
|
||||
return server.signed('/video/:/transcode/universal/start.m3u8', {
|
||||
...plexQuery(),
|
||||
path: `/library/metadata/${item.id}`,
|
||||
mediaIndex: opts.mediaIndex,
|
||||
partIndex: 0,
|
||||
protocol: 'hls',
|
||||
session: opts.session,
|
||||
offset: (opts.offsetMs / 1000).toFixed(1),
|
||||
fastSeek: 1,
|
||||
directPlay: 0,
|
||||
directStream: profile ? 1 : 1,
|
||||
directStreamAudio: 1,
|
||||
copyts: 1,
|
||||
hasMDE: 1,
|
||||
mediaBufferSize: 102400,
|
||||
location: opts.local ? 'lan' : 'wan',
|
||||
videoQuality: 100,
|
||||
maxVideoBitrate: profile ? profile.kbps : Math.max(media?.bitrate ?? 0, 200000),
|
||||
videoResolution: profile ? `${profile.width}x${profile.height}` : `${media?.width || 3840}x${media?.height || 2160}`,
|
||||
subtitles: 'burn',
|
||||
subtitleSize: 100,
|
||||
audioBoost: 100,
|
||||
autoAdjustQuality: 0,
|
||||
'X-Plex-Session-Identifier': opts.session,
|
||||
'X-Plex-Client-Profile-Extra': extra,
|
||||
});
|
||||
}
|
||||
|
||||
export function partAt(media: Media, timeMs: number): { part: Part; local: number } {
|
||||
let start = 0;
|
||||
for (const p of media.parts) {
|
||||
if (!p.duration || timeMs < start + p.duration) return { part: p, local: timeMs - start };
|
||||
start += p.duration;
|
||||
}
|
||||
const last = media.parts[media.parts.length - 1];
|
||||
return { part: last, local: timeMs - (start - (last?.duration ?? 0)) };
|
||||
}
|
||||
|
||||
/** Server-generated preview thumbnail for a position, if the part has an index. */
|
||||
export function previewUrl(server: PlexServer, media: Media | undefined, timeMs: number): string {
|
||||
if (!media) return '';
|
||||
const { part, local } = partAt(media, timeMs);
|
||||
if (!part?.indexes.split(',').includes('sd')) return '';
|
||||
return server.signed(`/library/parts/${part.id}/indexes/sd/${Math.max(0, Math.floor(local / 5000) * 5000)}`);
|
||||
}
|
||||
|
||||
export async function reportTimeline(
|
||||
server: PlexServer,
|
||||
item: Item,
|
||||
state: 'playing' | 'paused' | 'buffering' | 'stopped',
|
||||
timeMs: number,
|
||||
session: string,
|
||||
extra: Record<string, string | number> = {},
|
||||
) {
|
||||
await server.get(
|
||||
'/:/timeline',
|
||||
{
|
||||
ratingKey: item.id,
|
||||
key: item.key || `/library/metadata/${item.id}`,
|
||||
state,
|
||||
time: Math.max(0, Math.round(timeMs)),
|
||||
duration: Math.round(item.duration),
|
||||
identifier: 'com.plexapp.plugins.library',
|
||||
hasMDE: 1,
|
||||
...extra,
|
||||
},
|
||||
{ headers: { 'X-Plex-Session-Identifier': session }, timeout: 10000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function stopTranscode(server: PlexServer, session: string) {
|
||||
await server.get('/video/:/transcode/universal/stop', { session }).catch(() => {});
|
||||
}
|
||||
114
src/plex/plex.test.ts
Normal file
114
src/plex/plex.test.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { parseItem, parseScores } from './parse';
|
||||
import { isLocalAddress } from './account';
|
||||
import { partAt } from './playback';
|
||||
import { duration, formatBadges, isWatched, remaining, washGradient } from '../app/format';
|
||||
import { buildFeatures } from '../screens/discover';
|
||||
import type { Hub } from './types';
|
||||
|
||||
const movie = (over: Record<string, unknown> = {}) =>
|
||||
parseItem({
|
||||
ratingKey: '9776',
|
||||
key: '/library/metadata/9776',
|
||||
type: 'movie',
|
||||
title: '2 Fast 2 Furious',
|
||||
summary: 'An ex-cop…',
|
||||
art: '/art',
|
||||
year: 2003,
|
||||
duration: 6000000,
|
||||
Image: [{ type: 'clearLogo', url: '/logo' }],
|
||||
UltraBlurColors: [{ topLeft: '162e4f', topRight: '30618f', bottomRight: '345e96', bottomLeft: '1c2c56' }],
|
||||
Media: [
|
||||
{
|
||||
id: '1',
|
||||
videoResolution: '4k',
|
||||
audioChannels: 8,
|
||||
Part: [
|
||||
{
|
||||
id: '10',
|
||||
key: '/library/parts/10/file.mkv',
|
||||
duration: 3000000,
|
||||
Stream: [
|
||||
{ id: 's1', streamType: 1, codec: 'hevc', DOVIPresent: true, index: 0 },
|
||||
{ id: 's2', streamType: 2, codec: 'truehd', displayTitle: 'English (TrueHD 7.1 Atmos)', index: 1 },
|
||||
],
|
||||
},
|
||||
{ id: '11', key: '/library/parts/11/file.mkv', duration: 3000000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('parsing', () => {
|
||||
it('reads logos, UltraBlur colors and format facts', () => {
|
||||
const m = movie();
|
||||
expect(m.logo).toBe('/logo');
|
||||
expect(m.ultraBlur?.topRight).toBe('30618f');
|
||||
expect(m.media[0].dynamicRange).toBe('Dolby Vision');
|
||||
expect(m.media[0].atmos).toBe(true);
|
||||
expect(formatBadges(m)).toEqual(['4K', 'DOLBY VISION', 'ATMOS']);
|
||||
});
|
||||
|
||||
it('keeps audience scores and never substitutes critic ratings', () => {
|
||||
const scores = parseScores({
|
||||
Rating: [
|
||||
{ image: 'rottentomatoes://image.rating.upright', value: 7.9, type: 'audience' },
|
||||
{ image: 'rottentomatoes://image.rating.ripe', value: 9.1, type: 'critic' },
|
||||
{ image: 'imdb://image.rating', value: 7.2, type: 'audience' },
|
||||
],
|
||||
});
|
||||
expect(scores.filter((s) => s.kind === 'audience').map((s) => s.source)).toEqual(['Rotten Tomatoes', 'IMDb']);
|
||||
expect(scores.find((s) => s.kind === 'critic')?.value).toBe(9.1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('watched rules', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
it('uses episode counts for shows', () => {
|
||||
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 10 }))).toBe(true);
|
||||
expect(isWatched(parseItem({ type: 'show', leafCount: 10, viewedLeafCount: 3 }))).toBe(false);
|
||||
});
|
||||
|
||||
it('formats durations and time left', () => {
|
||||
expect(duration(6000000)).toBe('1h 40m');
|
||||
expect(duration(45 * 60000)).toBe('45m');
|
||||
expect(remaining(movie({ viewOffset: 3000000 }))).toBe('50m left');
|
||||
});
|
||||
});
|
||||
|
||||
describe('connections', () => {
|
||||
it('recognizes local plex.direct and private addresses', () => {
|
||||
expect(isLocalAddress('https://192-168-50-81.abc.plex.direct:32400')).toBe(true);
|
||||
expect(isLocalAddress('http://10.0.0.5:32400')).toBe(true);
|
||||
expect(isLocalAddress('https://38-130-3-235.abc.plex.direct:27015')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('playback', () => {
|
||||
it('maps a position to the right part of a multi-part title', () => {
|
||||
const m = movie().media[0];
|
||||
expect(partAt(m, 1000).part.id).toBe('10');
|
||||
expect(partAt(m, 4000000)).toMatchObject({ local: 1000000 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('features', () => {
|
||||
it('interleaves sources, skips in-progress titles and needs artwork', () => {
|
||||
const hub = (id: string, items: Record<string, unknown>[]): Hub => ({ id, key: '', title: id, type: 'movie', context: '', size: items.length, more: false, style: '', items: items.map((i) => movie(i)) });
|
||||
const features = buildFeatures([
|
||||
hub('movie.recentlyreleased.1', [{ ratingKey: 'a' }, { ratingKey: 'b', viewOffset: 100 }]),
|
||||
hub('movie.topunwatched.1', [{ ratingKey: 'c' }, { ratingKey: 'd', art: '' }]),
|
||||
]);
|
||||
expect(features.map((f) => f.item.id).sort()).toEqual(['a', 'c']);
|
||||
});
|
||||
|
||||
it('builds an artwork wash from UltraBlur colors', () => {
|
||||
expect(washGradient(movie().ultraBlur)).toContain('rgba(48, 97, 143');
|
||||
});
|
||||
});
|
||||
277
src/plex/types.ts
Normal file
277
src/plex/types.ts
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
/** Normalized Plex models. Parsing lives in parse.ts; raw JSON is kept for editors. */
|
||||
|
||||
export type ItemType =
|
||||
| 'movie'
|
||||
| 'show'
|
||||
| 'season'
|
||||
| 'episode'
|
||||
| 'collection'
|
||||
| 'clip'
|
||||
| 'playlist'
|
||||
| 'person'
|
||||
| 'artist'
|
||||
| 'album'
|
||||
| 'track'
|
||||
| 'photo'
|
||||
| string;
|
||||
|
||||
export interface Stream {
|
||||
id: string;
|
||||
streamType: 1 | 2 | 3 | number; // video, audio, subtitle
|
||||
codec: string;
|
||||
index: number;
|
||||
language: string;
|
||||
languageCode: string;
|
||||
displayTitle: string;
|
||||
extendedDisplayTitle: string;
|
||||
title: string;
|
||||
selected: boolean;
|
||||
default: boolean;
|
||||
forced: boolean;
|
||||
key: string; // external subtitle path
|
||||
channels: number;
|
||||
audioChannelLayout: string;
|
||||
bitrate: number;
|
||||
width: number;
|
||||
height: number;
|
||||
frameRate: number;
|
||||
profile: string;
|
||||
colorTrc: string;
|
||||
colorPrimaries: string;
|
||||
bitDepth: number;
|
||||
doviPresent: boolean;
|
||||
hearingImpaired: boolean;
|
||||
samplingRate: number;
|
||||
}
|
||||
|
||||
export interface Part {
|
||||
id: string;
|
||||
key: string;
|
||||
file: string;
|
||||
size: number;
|
||||
duration: number;
|
||||
container: string;
|
||||
indexes: string;
|
||||
streams: Stream[];
|
||||
accessible: boolean;
|
||||
exists: boolean;
|
||||
}
|
||||
|
||||
export interface Media {
|
||||
id: string;
|
||||
container: string;
|
||||
videoCodec: string;
|
||||
audioCodec: string;
|
||||
videoResolution: string;
|
||||
width: number;
|
||||
height: number;
|
||||
bitrate: number;
|
||||
duration: number;
|
||||
audioChannels: number;
|
||||
videoProfile: string;
|
||||
videoFrameRate: string;
|
||||
aspectRatio: number;
|
||||
optimizedForStreaming: boolean;
|
||||
title: string;
|
||||
parts: Part[];
|
||||
dynamicRange: string; // 'Dolby Vision' | 'HDR10' | 'HLG' | ''
|
||||
atmos: boolean;
|
||||
}
|
||||
|
||||
export interface Marker {
|
||||
id: string;
|
||||
type: 'intro' | 'credits' | 'commercial' | string;
|
||||
start: number;
|
||||
end: number;
|
||||
final: boolean;
|
||||
}
|
||||
|
||||
export interface Chapter {
|
||||
index: number;
|
||||
title: string;
|
||||
start: number;
|
||||
end: number;
|
||||
thumb: string;
|
||||
}
|
||||
|
||||
export interface Tag {
|
||||
id: string;
|
||||
tag: string;
|
||||
filter: string;
|
||||
}
|
||||
|
||||
export interface Role extends Tag {
|
||||
role: string;
|
||||
thumb: string;
|
||||
}
|
||||
|
||||
export interface AudienceScore {
|
||||
source: 'Rotten Tomatoes' | 'IMDb' | 'TMDB' | 'TVDB';
|
||||
value: number; // 0–10
|
||||
kind: 'audience' | 'critic';
|
||||
image: string;
|
||||
}
|
||||
|
||||
export interface Item {
|
||||
id: string;
|
||||
key: string;
|
||||
guid: string;
|
||||
guids: string[];
|
||||
type: ItemType;
|
||||
subtype: string;
|
||||
title: string;
|
||||
titleSort: string;
|
||||
originalTitle: string;
|
||||
summary: string;
|
||||
tagline: string;
|
||||
year: number;
|
||||
originallyAvailableAt: string;
|
||||
duration: number;
|
||||
viewOffset: number;
|
||||
viewCount: number;
|
||||
lastViewedAt: number;
|
||||
addedAt: number;
|
||||
updatedAt: number;
|
||||
thumb: string;
|
||||
art: string;
|
||||
logo: string;
|
||||
theme: string;
|
||||
contentRating: string;
|
||||
studio: string;
|
||||
parentId: string;
|
||||
parentKey: string;
|
||||
parentTitle: string;
|
||||
parentIndex: number;
|
||||
parentThumb: string;
|
||||
grandparentId: string;
|
||||
grandparentKey: string;
|
||||
grandparentTitle: string;
|
||||
grandparentThumb: string;
|
||||
grandparentArt: string;
|
||||
index: number;
|
||||
leafCount: number;
|
||||
viewedLeafCount: number;
|
||||
childCount: number;
|
||||
genres: Tag[];
|
||||
directors: Tag[];
|
||||
writers: Tag[];
|
||||
producers: Tag[];
|
||||
countries: Tag[];
|
||||
labels: Tag[];
|
||||
collections: Tag[];
|
||||
roles: Role[];
|
||||
scores: AudienceScore[];
|
||||
userRating: number;
|
||||
media: Media[];
|
||||
markers: Marker[];
|
||||
chapters: Chapter[];
|
||||
extras: Item[];
|
||||
librarySectionId: string;
|
||||
librarySectionTitle: string;
|
||||
librarySectionKey: string;
|
||||
/** For collections: number of members. For people (search hubs): unused. */
|
||||
smart: boolean;
|
||||
editionTitle: string;
|
||||
skipChildren: boolean;
|
||||
/** Plex UltraBlur corner colors (hex without #), for artwork-led washes. */
|
||||
ultraBlur: { topLeft: string; topRight: string; bottomRight: string; bottomLeft: string } | null;
|
||||
raw: any;
|
||||
}
|
||||
|
||||
export interface Hub {
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
type: string;
|
||||
context: string;
|
||||
size: number;
|
||||
more: boolean;
|
||||
style: string;
|
||||
items: Item[];
|
||||
}
|
||||
|
||||
export interface Section {
|
||||
id: string;
|
||||
key: string;
|
||||
title: string;
|
||||
type: 'movie' | 'show' | 'artist' | 'photo' | string;
|
||||
agent: string;
|
||||
scanner: string;
|
||||
language: string;
|
||||
thumb: string;
|
||||
art: string;
|
||||
locations: { id: string; path: string }[];
|
||||
scannedAt: number;
|
||||
updatedAt: number;
|
||||
contentChangedAt: number;
|
||||
refreshing: boolean;
|
||||
hidden: boolean;
|
||||
}
|
||||
|
||||
export interface Page<T> {
|
||||
items: T[];
|
||||
total: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface PlexUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
username: string;
|
||||
title: string;
|
||||
email: string;
|
||||
thumb: string;
|
||||
home: boolean;
|
||||
homeAdmin: boolean;
|
||||
protected: boolean;
|
||||
subscription: boolean;
|
||||
}
|
||||
|
||||
export interface HomeUser {
|
||||
id: number;
|
||||
uuid: string;
|
||||
title: string;
|
||||
username: string;
|
||||
thumb: string;
|
||||
admin: boolean;
|
||||
protected: boolean;
|
||||
restricted: boolean;
|
||||
guest: boolean;
|
||||
}
|
||||
|
||||
export interface ServerConnection {
|
||||
uri: string;
|
||||
local: boolean;
|
||||
relay: boolean;
|
||||
protocol: string;
|
||||
address: string;
|
||||
port: number;
|
||||
IPv6: boolean;
|
||||
}
|
||||
|
||||
export interface ServerResource {
|
||||
id: string; // clientIdentifier / machineIdentifier
|
||||
name: string;
|
||||
owned: boolean;
|
||||
accessToken: string;
|
||||
productVersion: string;
|
||||
platform: string;
|
||||
presence: boolean;
|
||||
publicAddress: string;
|
||||
connections: ServerConnection[];
|
||||
sourceTitle: string;
|
||||
httpsRequired: boolean;
|
||||
}
|
||||
|
||||
export interface FilterOption {
|
||||
key: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export interface LibraryQuery {
|
||||
sectionId: string;
|
||||
type?: number; // 1 movie, 2 show, 3 season, 4 episode
|
||||
sort: string; // e.g. titleSort:asc
|
||||
filters: Record<string, string>; // e.g. genre=12, unwatched=1
|
||||
title?: string;
|
||||
}
|
||||
222
src/screens/Downloads.tsx
Normal file
222
src/screens/Downloads.tsx
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useDownloads, type Download } from '../downloads/store';
|
||||
import { useSession } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { duration, episodeLabel, fileSize } from '../app/format';
|
||||
import { usePlayer } from '../player/store';
|
||||
import { invoke, isNative, localFileUrl, revealPath } from '../platform/native';
|
||||
import { Button, EmptyState, IconButton } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { confirmDialog, openMenu } from '../ui/overlays';
|
||||
|
||||
function useLocalArt(d: Download, key: string) {
|
||||
const [url, setUrl] = useState('');
|
||||
const path = d.meta.localAssets?.[key];
|
||||
useEffect(() => {
|
||||
if (path) localFileUrl(path).then(setUrl);
|
||||
}, [path]);
|
||||
return url;
|
||||
}
|
||||
|
||||
function DownloadRow({ d }: { d: Download }) {
|
||||
const store = useDownloads();
|
||||
const server = useSession((s) => s.server);
|
||||
const item = store.itemOf(d);
|
||||
const still = useLocalArt(d, item.type === 'episode' ? 'still' : 'art');
|
||||
const poster = useLocalArt(d, 'poster');
|
||||
const pct = d.total ? Math.min(100, (d.received / d.total) * 100) : 0;
|
||||
const isEp = item.type === 'episode';
|
||||
const onServer = server?.machineId === d.meta.serverId;
|
||||
const play = () => usePlayer.getState().play(item, { localFile: d.filePath, resume: true });
|
||||
const remove = async () => {
|
||||
if (await confirmDialog({ title: 'Remove download?', message: `“${item.title}” will be deleted from this computer. It stays available on your Plex server.`, confirm: 'Remove', danger: true })) store.remove(d.id);
|
||||
};
|
||||
const status =
|
||||
d.status === 'completed'
|
||||
? fileSize(d.total || d.received)
|
||||
: d.status === 'downloading'
|
||||
? `${fileSize(d.received)} of ${fileSize(d.total)}${d.speed ? ` · ${fileSize(d.speed)}/s` : ''}`
|
||||
: d.status === 'queued'
|
||||
? 'Waiting…'
|
||||
: d.status === 'paused'
|
||||
? `Paused · ${fileSize(d.received)} of ${fileSize(d.total)}`
|
||||
: (d.error ?? 'Failed');
|
||||
return (
|
||||
<div className={`download-row ${d.status}`}>
|
||||
<button className="dl-thumb" onClick={d.status === 'completed' ? play : undefined} aria-label={`Play ${item.title}`}>
|
||||
{(still || poster) && <img src={still || poster} alt="" draggable={false} className={still ? '' : 'poster'} />}
|
||||
{d.status === 'completed' && (
|
||||
<span className="dl-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
<div className="dl-details">
|
||||
<h3>{isEp ? item.grandparentTitle : item.title}</h3>
|
||||
<p>
|
||||
{isEp ? `${episodeLabel(item)} · ${item.title}` : [item.year, duration(item.duration)].filter(Boolean).join(' · ')}
|
||||
{d.meta.serverName && <span className="dim"> · {d.meta.serverName}</span>}
|
||||
</p>
|
||||
{d.status !== 'completed' ? (
|
||||
<div className="dl-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="dl-status">{status}</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="file-status">
|
||||
<Icon name="check" size={14} /> Ready offline · {status}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="dl-actions">
|
||||
{d.status === 'completed' && (
|
||||
<Button variant="ghost" size="sm" icon="play" onClick={play}>
|
||||
Play
|
||||
</Button>
|
||||
)}
|
||||
{d.status === 'downloading' || d.status === 'queued' ? (
|
||||
<IconButton icon="pause" label="Pause" onClick={() => store.pause(d.id)} />
|
||||
) : d.status === 'paused' || d.status === 'failed' ? (
|
||||
<IconButton icon="refresh" label="Resume" onClick={() => store.resume(d.id)} />
|
||||
) : null}
|
||||
<IconButton
|
||||
icon="dots"
|
||||
label="More"
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
[
|
||||
...(onServer ? [{ label: 'Details', icon: 'info', onSelect: () => navigate({ name: 'item', id: item.id }) }] : []),
|
||||
...(d.status === 'completed' ? [{ label: 'Show in folder', icon: 'folder', onSelect: () => revealPath(d.filePath) }] : []),
|
||||
{ divider: true },
|
||||
{ label: 'Remove download', icon: 'trash', danger: true, onSelect: remove },
|
||||
],
|
||||
e.currentTarget,
|
||||
{ align: 'end' },
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Downloads({ offline }: { offline?: boolean }) {
|
||||
const store = useDownloads();
|
||||
const [space, setSpace] = useState<{ free: number; total: number } | null>(null);
|
||||
useEffect(() => {
|
||||
store.init();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
if (isNative && store.dir) invoke<{ free: number; total: number }>('disk_space', { path: store.dir }).then(setSpace).catch(() => {});
|
||||
}, [store.dir, store.items.length]);
|
||||
|
||||
const active = store.items.filter((d) => d.status !== 'completed');
|
||||
const done = store.items.filter((d) => d.status === 'completed');
|
||||
const used = store.items.reduce((a, d) => a + (d.status === 'completed' ? d.total || d.received : d.received), 0);
|
||||
const movies = done.filter((d) => d.meta.raw?.type !== 'episode');
|
||||
const episodes = done.filter((d) => d.meta.raw?.type === 'episode');
|
||||
const shows = new Map<string, Download[]>();
|
||||
for (const e of episodes) {
|
||||
const k = e.meta.raw?.grandparentTitle ?? 'Episodes';
|
||||
shows.set(k, [...(shows.get(k) ?? []), e]);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`downloads-page page-pad${offline ? '' : ' top'}`}>
|
||||
<div className="download-intro">
|
||||
<div>
|
||||
<div className="micro">Offline · This computer</div>
|
||||
<h1 className="page-title">Downloads</h1>
|
||||
<p className="page-subtitle">Movies and episodes saved to this computer play without a connection. Progress syncs to Plex when you’re back online.</p>
|
||||
</div>
|
||||
{isNative && (
|
||||
<div className="storage-card">
|
||||
<div className="storage-head">
|
||||
<b>Storage</b>
|
||||
<span>{space ? `${fileSize(space.free)} free` : ''}</span>
|
||||
</div>
|
||||
<div className="storage-bar">
|
||||
{space && (
|
||||
<>
|
||||
<span className="other" style={{ width: `${Math.max(0, ((space.total - space.free - used) / space.total) * 100)}%` }} />
|
||||
<span className="mine" style={{ width: `${(used / space.total) * 100}%` }} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="storage-caption">
|
||||
{fileSize(used) || '0 MB'} used by Kaleido
|
||||
{store.dir && (
|
||||
<button className="inline-link" onClick={() => revealPath(store.dir)} title={store.dir}>
|
||||
Open folder
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isNative && (
|
||||
<EmptyState icon="download" title="Downloads need the desktop app">
|
||||
Install Kaleido for Windows to save movies and episodes for offline viewing.
|
||||
</EmptyState>
|
||||
)}
|
||||
{isNative && !store.items.length && (
|
||||
<EmptyState icon="download" title="Nothing downloaded yet" action={!offline && <Button variant="ghost" icon="film" onClick={() => navigate({ name: 'section', kind: 'movie', tab: 'library' })}>Browse movies</Button>}>
|
||||
Choose Download on a movie or episode, or download a whole season from its page.
|
||||
</EmptyState>
|
||||
)}
|
||||
|
||||
{active.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
In progress <small>{active.length}</small>
|
||||
</h2>
|
||||
<div className="actions">
|
||||
{active.some((d) => d.status === 'downloading' || d.status === 'queued') ? (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => (d.status === 'downloading' || d.status === 'queued') && store.pause(d.id))}>
|
||||
Pause all
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="text" onClick={() => active.forEach((d) => store.resume(d.id))}>
|
||||
Resume all
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{active.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="dl-section">
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
Movies <small>{movies.length}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{movies.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{[...shows.entries()].map(([show, list]) => (
|
||||
<section className="dl-section" key={show}>
|
||||
<div className="dl-section-head">
|
||||
<h2>
|
||||
{show} <small>{list.length} episode{list.length === 1 ? '' : 's'}</small>
|
||||
</h2>
|
||||
</div>
|
||||
{list
|
||||
.sort((a, b) => (a.meta.raw.parentIndex - b.meta.raw.parentIndex) * 1000 + (a.meta.raw.index - b.meta.raw.index))
|
||||
.map((d) => (
|
||||
<DownloadRow key={d.id} d={d} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
53
src/screens/Home.tsx
Normal file
53
src/screens/Home.tsx
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { navigate } from '../app/router';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf } from '../ui/media';
|
||||
import { ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS } from './discover';
|
||||
|
||||
export function Home() {
|
||||
const server = useServer();
|
||||
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 });
|
||||
// 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(',')],
|
||||
queryFn: async () => (await Promise.all(video.map((s) => api.sectionHubs(server, s.id).catch(() => [])))).flat(),
|
||||
enabled: video.length > 0,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const features = useMemo(() => buildFeatures(sectionHubs.data ?? [], 8), [sectionHubs.data]);
|
||||
const extra = (sectionHubs.data ?? []).filter((h) => /recentlyreleased|recentlyaired|topunwatched|toprated/.test(h.id));
|
||||
|
||||
if (home.isError && !home.data) return <ErrorState error={home.error} onRetry={() => home.refetch()} />;
|
||||
if (!home.data || sections.isLoading) return <PageLoader />;
|
||||
|
||||
const hubs = home.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
const cw = continueWatching.data ?? [];
|
||||
const homeIds = new Set(hubs.map((h) => h.title));
|
||||
|
||||
return (
|
||||
<div className="home">
|
||||
<Hero features={features} variant="home" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title="Continue Watching" items={cw} continueWatching />
|
||||
{hubs.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={h.more ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
{extra
|
||||
.filter((h) => !homeIds.has(h.title))
|
||||
.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} onViewAll={() => navigate({ name: 'hub', key: h.key, title: h.title })} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
43
src/screens/HubScreen.tsx
Normal file
43
src/screens/HubScreen.tsx
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServer } from '../app/session';
|
||||
import { LandscapeCard, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Spinner } from '../ui/primitives';
|
||||
|
||||
/** "View all" for a hub, paged as it scrolls. */
|
||||
export default function HubScreen({ hubKey, title }: { hubKey: string; title: string }) {
|
||||
const server = useServer();
|
||||
const q = useInfiniteQuery({
|
||||
queryKey: [server.machineId, 'hubAll', hubKey],
|
||||
queryFn: ({ pageParam }) => api.hubItems(server, hubKey, pageParam, 72),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (last, pages) => {
|
||||
const loaded = pages.reduce((a, p) => a + p.items.length, 0);
|
||||
return last.items.length && loaded < last.total ? loaded : undefined;
|
||||
},
|
||||
});
|
||||
const sentinel = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
const el = sentinel.current;
|
||||
if (!el) return;
|
||||
const io = new IntersectionObserver(([e]) => e.isIntersecting && q.hasNextPage && !q.isFetchingNextPage && q.fetchNextPage(), { rootMargin: '800px' });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, [q.hasNextPage, q.isFetchingNextPage]);
|
||||
|
||||
const items = q.data?.pages.flatMap((p) => p.items) ?? [];
|
||||
const wide = items.length > 0 && items.every((i) => i.type === 'episode');
|
||||
return (
|
||||
<div className="page-pad top hub-page">
|
||||
<h1 className="page-title">{title}</h1>
|
||||
{q.isError && <ErrorState error={q.error} onRetry={() => q.refetch()} />}
|
||||
{q.isLoading && <PageLoader />}
|
||||
{q.data && !items.length && <EmptyState title="Nothing here yet" />}
|
||||
<div className={`poster-grid auto${wide ? ' wide' : ''}`}>{items.map((i) => (wide ? <LandscapeCard key={i.id} item={i} /> : <PosterCard key={i.id} item={i} />))}</div>
|
||||
<div ref={sentinel} className="grid-sentinel">
|
||||
{q.isFetchingNextPage && <Spinner />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
616
src/screens/Item.tsx
Normal file
616
src/screens/Item.tsx
Normal file
|
|
@ -0,0 +1,616 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item } from '../plex/types';
|
||||
import { invalidateLibrary, useChildren, useItem, useRelated, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
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 { 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, toastError } from '../ui/overlays';
|
||||
import { useDownloads } from '../downloads/store';
|
||||
import { playThemeMusic, stopThemeMusic } from '../player/theme';
|
||||
|
||||
export function ItemScreen({ id }: { id: string }) {
|
||||
const q = useItem(id);
|
||||
const item = q.data;
|
||||
useEffect(() => {
|
||||
if (item?.theme && item.type !== 'collection') playThemeMusic(item.theme);
|
||||
}, [item?.theme]);
|
||||
useEffect(() => () => stopThemeMusic(), []);
|
||||
if (q.isError) return <div className="page-pad top"><ErrorState error={q.error} onRetry={() => q.refetch()} /></div>;
|
||||
if (!item) return <PageLoader />;
|
||||
switch (item.type) {
|
||||
case 'show':
|
||||
return <ShowDetail item={item} />;
|
||||
case 'season':
|
||||
return <SeasonDetail item={item} />;
|
||||
case 'episode':
|
||||
return <EpisodeDetail item={item} />;
|
||||
case 'collection':
|
||||
return <CollectionDetail item={item} />;
|
||||
default:
|
||||
return <MovieDetail item={item} />;
|
||||
}
|
||||
}
|
||||
|
||||
// —— Shared pieces ————————————————————————————————————————————————
|
||||
|
||||
function Synopsis({ item, text }: { item: Item; text: string }) {
|
||||
const [clamped, setClamped] = useState(false);
|
||||
if (!text) return null;
|
||||
return (
|
||||
<div className="synopsis-wrap">
|
||||
<p
|
||||
className="synopsis"
|
||||
ref={(el) => {
|
||||
if (el) setClamped(el.scrollHeight > el.clientHeight + 2);
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</p>
|
||||
{clamped && (
|
||||
<button className="btn text synopsis-more" onClick={() => openDialog({ kind: 'synopsis', item })}>
|
||||
More
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WatchedButton({ item }: { item: Item }) {
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(item, percent);
|
||||
return (
|
||||
<Button variant="ghost" icon={watched ? 'check' : 'plus'} onClick={() => setWatched(item, !watched)} className={watched ? 'is-on' : ''}>
|
||||
{watched ? 'Watched' : 'Mark watched'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DownloadButton({ item }: { item: Item }) {
|
||||
const downloads = useDownloads();
|
||||
const isSeries = item.type === 'show' || item.type === 'season';
|
||||
const dl = downloads.items.find((d) => d.id === downloads.idFor(item.id));
|
||||
if (isSeries) return <IconButton round icon="download" label={item.type === 'show' ? 'Download unwatched episodes' : 'Download season'} onClick={() => downloads.startAll(item)} />;
|
||||
if (dl?.status === 'completed') return <IconButton round icon="downloaded" label="Downloaded" className="on" onClick={() => navigate({ name: 'downloads' })} />;
|
||||
if (dl) {
|
||||
const pct = dl.total ? Math.round((dl.received / dl.total) * 100) : 0;
|
||||
return (
|
||||
<button className="circle-btn download-progress" aria-label={`Downloading ${pct}%`} title={`Downloading ${pct}%`} onClick={() => navigate({ name: 'downloads' })}>
|
||||
<svg viewBox="0 0 36 36" width="42" height="42">
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="rgba(255,255,255,.2)" strokeWidth="2.4" />
|
||||
<circle cx="18" cy="18" r="15" fill="none" stroke="currentColor" strokeWidth="2.4" strokeDasharray={`${pct * 0.94} 100`} transform="rotate(-90 18 18)" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return <IconButton round icon="download" label="Download" onClick={() => downloads.start(item)} />;
|
||||
}
|
||||
|
||||
function MoreButton({ item, onDeleted }: { item: Item; onDeleted?: () => void }) {
|
||||
return <IconButton round icon="dots" label="More actions" onClick={(e) => openMenu(itemMenu(item, { detail: true, onDeleted }), e.currentTarget)} />;
|
||||
}
|
||||
|
||||
function TrailerButton({ item }: { item: Item }) {
|
||||
const trailer = item.extras.find((e) => e.subtype === 'trailer' && e.media.length);
|
||||
if (!trailer) return null;
|
||||
return (
|
||||
<Button variant="ghost" icon="film" onClick={() => playItem(trailer, { resume: false })}>
|
||||
Trailer
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailHero({ item, backdropItem, children, title, below }: { item: Item; backdropItem?: Item; children: ReactNode; title?: ReactNode; below?: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<Backdrop item={backdropItem ?? item} className="detail-backdrop" />
|
||||
<header className="detail-hero">
|
||||
<div className="detail-head">
|
||||
{title ?? <TitleArt item={item} maxWidth={440} maxHeight={140} />}
|
||||
{children}
|
||||
</div>
|
||||
{below}
|
||||
</header>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CastRow({ item, title = 'Cast & Crew' }: { item: Item; title?: string }) {
|
||||
const people = [
|
||||
...item.roles.map((r) => ({ id: r.id, name: r.tag, role: r.role, thumb: r.thumb })),
|
||||
...item.directors.map((d) => ({ id: d.id, name: d.tag, role: 'Director', thumb: (d as any).thumb ?? item.raw?.Director?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
...item.writers.slice(0, 3).map((d) => ({ id: d.id, name: d.tag, role: 'Writer', thumb: item.raw?.Writer?.find((x: any) => x.tag === d.tag)?.thumb })),
|
||||
];
|
||||
if (!people.length) return null;
|
||||
return (
|
||||
<Shelf title={title} kind="people">
|
||||
{people.map((p, i) => (
|
||||
<PersonCard key={`${p.id}-${i}`} name={p.name} role={p.role} thumb={p.thumb} onClick={p.id ? () => navigate({ name: 'person', id: p.id, title: p.name, thumb: p.thumb }) : undefined} />
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtrasRow({ item }: { item: Item }) {
|
||||
const extras = item.extras.filter((e) => e.media.length);
|
||||
if (!extras.length) return null;
|
||||
return (
|
||||
<Shelf title="Trailers & Extras" kind="landscape">
|
||||
{extras.map((e) => (
|
||||
<article key={e.id} className="card landscape extra" role="button" tabIndex={0} onClick={() => playItem(e, { resume: false })} onKeyDown={(ev) => ev.key === 'Enter' && playItem(e, { resume: false })}>
|
||||
<ExtraCover item={e} />
|
||||
<div className="card-caption">
|
||||
<div className="card-title">{e.title}</div>
|
||||
<div className="card-meta">{[extraLabel(e), duration(e.duration)].filter(Boolean).join(' · ')}</div>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
|
||||
function ExtraCover({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
return (
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(item.thumb, 400, 225)} />
|
||||
<div className="card-hover" />
|
||||
<span className="extra-play">
|
||||
<Icon name="play" size={18} />
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RelatedRows({ item }: { item: Item }) {
|
||||
const related = useRelated(item.id);
|
||||
const hubs = (related.data ?? []).map((h) => ({ ...h, items: h.items.filter((i) => i.id !== item.id && ['movie', 'show'].includes(i.type)) })).filter((h) => h.items.length);
|
||||
return (
|
||||
<>
|
||||
{hubs.slice(0, 3).map((h) => (
|
||||
<HubShelf key={h.id} title={h.title} items={h.items} landscape={false} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function StarRating({ item }: { item: Item }) {
|
||||
const server = useServer();
|
||||
const [value, setValue] = useState(item.userRating);
|
||||
const [hover, setHover] = useState(0);
|
||||
useEffect(() => setValue(item.userRating), [item.userRating]);
|
||||
const set = async (stars: number) => {
|
||||
const rating = stars * 2 === value ? -1 : stars * 2;
|
||||
setValue(Math.max(0, rating));
|
||||
try {
|
||||
await api.rate(server, item.id, rating);
|
||||
invalidateLibrary();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
const shown = hover || value / 2;
|
||||
return (
|
||||
<span className="star-rating" onMouseLeave={() => setHover(0)} aria-label="Your rating">
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button key={n} onMouseEnter={() => setHover(n)} onClick={() => set(n)} aria-label={`${n} star${n > 1 ? 's' : ''}`}>
|
||||
<Icon name={n <= shown ? 'starFill' : 'star'} size={15} />
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function AboutPanel({ item }: { item: Item }) {
|
||||
const m = item.media[0];
|
||||
const rows: [string, ReactNode][] = [];
|
||||
const tags = (list: { tag: string; id: string }[], filter: string, limit = 3) =>
|
||||
list.slice(0, limit).map((t, i) => (
|
||||
<span key={t.tag}>
|
||||
{i > 0 && ', '}
|
||||
{filter === 'person' ? (
|
||||
<button className="inline-link" onClick={() => t.id && navigate({ name: 'person', id: t.id, title: t.tag })}>
|
||||
{t.tag}
|
||||
</button>
|
||||
) : (
|
||||
t.tag
|
||||
)}
|
||||
</span>
|
||||
));
|
||||
if (item.directors.length) rows.push([item.directors.length > 1 ? 'Directors' : 'Director', tags(item.directors, 'person')]);
|
||||
if (item.writers.length) rows.push(['Writers', tags(item.writers, 'person')]);
|
||||
if (item.studio) rows.push([item.type === 'show' || item.type === 'episode' ? 'Network' : 'Studio', item.studio]);
|
||||
if (item.originallyAvailableAt) rows.push([item.type === 'show' ? 'Premiered' : 'Released', date(item.originallyAvailableAt)]);
|
||||
if (item.genres.length) rows.push(['Genres', item.genres.map((g) => g.tag).join(', ')]);
|
||||
if (item.countries.length) rows.push(['Country', item.countries.map((c) => c.tag).join(', ')]);
|
||||
if (item.contentRating) rows.push(['Rated', item.contentRating]);
|
||||
if (item.duration && item.type !== 'show') rows.push(['Runtime', duration(item.duration)]);
|
||||
for (const s of item.scores) rows.push([`${s.source}${s.kind === 'critic' ? ' critics' : ''}`, s.source === 'Rotten Tomatoes' ? `${Math.round(s.value * 10)}%` : `${s.value.toFixed(1)} / 10`]);
|
||||
if (item.collections.length) rows.push(['Collections', item.collections.map((c) => c.tag).join(', ')]);
|
||||
if (item.labels.length) rows.push(['Labels', item.labels.map((c) => c.tag).join(', ')]);
|
||||
if (item.editionTitle) rows.push(['Edition', item.editionTitle]);
|
||||
if (m) {
|
||||
rows.push(['Video', [resolutionLabel(m), m.dynamicRange, m.videoCodec.toUpperCase(), m.videoFrameRate].filter(Boolean).join(' · ')]);
|
||||
rows.push(['Audio', [m.audioCodec.toUpperCase(), channelLabel(m.audioChannels), m.atmos ? 'Atmos' : ''].filter(Boolean).join(' · ')]);
|
||||
if (m.bitrate) rows.push(['Bitrate', bitrate(m.bitrate)]);
|
||||
const size = m.parts.reduce((a, p) => a + p.size, 0);
|
||||
if (size) rows.push(['File size', fileSize(size)]);
|
||||
if (item.media.length > 1) rows.push(['Versions', `${item.media.length} available`]);
|
||||
}
|
||||
if (item.addedAt) rows.push(['Added', date(item.addedAt)]);
|
||||
return (
|
||||
<aside className="about-panel">
|
||||
<div className="about-head">
|
||||
<h3>About</h3>
|
||||
{['movie', 'show', 'episode', 'season'].includes(item.type) && <StarRating item={item} />}
|
||||
</div>
|
||||
{item.tagline && <p className="about-tagline">“{item.tagline}”</p>}
|
||||
{rows.map(([k, v]) => (
|
||||
<div className="about-line" key={k}>
|
||||
<span>{k}</span>
|
||||
<strong>{v}</strong>
|
||||
</div>
|
||||
))}
|
||||
{(m || canManage()) && (
|
||||
<div className="about-actions">
|
||||
{m && (
|
||||
<Button variant="outline" size="sm" icon="info" onClick={() => openDialog({ kind: 'info', item })}>
|
||||
Media info
|
||||
</Button>
|
||||
)}
|
||||
{canManage() && (
|
||||
<Button variant="outline" size="sm" icon="edit" onClick={() => openDialog({ kind: 'edit', item })}>
|
||||
Edit
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Movie ——————————————————————————————————————————————————————————
|
||||
|
||||
function MovieDetail({ item }: { item: Item }) {
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
return (
|
||||
<div className="detail movie">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{resume && (
|
||||
<div className="detail-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${(item.viewOffset / item.duration) * 100}%` }} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Shows and seasons ————————————————————————————————————————————
|
||||
|
||||
function EpisodeRow({ ep }: { ep: Item }) {
|
||||
const server = useServer();
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const watched = isWatched(ep, percent);
|
||||
const p = ep.viewOffset && ep.duration ? ep.viewOffset / ep.duration : 0;
|
||||
return (
|
||||
<div
|
||||
className="episode-row"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => openItem(ep)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && openItem(ep)}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
openMenu(itemMenu(ep), { x: e.clientX, y: e.clientY });
|
||||
}}
|
||||
>
|
||||
<div className="episode-index">{ep.index || '–'}</div>
|
||||
<div className="episode-pic">
|
||||
<Artwork src={server.image(ep.thumb, 320, 180)} />
|
||||
<button
|
||||
className="episode-play"
|
||||
aria-label={`Play ${ep.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
playWithVersion(ep);
|
||||
}}
|
||||
>
|
||||
<Icon name="play" size={18} />
|
||||
</button>
|
||||
{p > 0 && !watched && (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${p * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="episode-text">
|
||||
<h3>
|
||||
{ep.title}
|
||||
{watched && <Icon name="check" size={15} className="episode-watched" />}
|
||||
</h3>
|
||||
<div className="episode-meta">
|
||||
{[duration(ep.duration), ep.originallyAvailableAt ? date(ep.originallyAvailableAt) : '', ep.viewOffset && !watched ? remaining(ep) : ''].filter(Boolean).join(' · ')}
|
||||
</div>
|
||||
{ep.summary && <p>{ep.summary}</p>}
|
||||
</div>
|
||||
<button
|
||||
className="icon-btn episode-more"
|
||||
aria-label="More"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openMenu(itemMenu(ep), e.currentTarget);
|
||||
}}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<section className="episodes">
|
||||
<div className="episodes-head">
|
||||
<h2>Episodes</h2>
|
||||
{showPicker && seasons.length > 1 && (
|
||||
<Select
|
||||
value={seasonId!}
|
||||
label="Season"
|
||||
options={seasons.map((s) => ({ value: s.id, label: s.title, hint: s.leafCount ? `${s.leafCount} ep` : undefined }))}
|
||||
onChange={(v) => {
|
||||
setSeasonId(v);
|
||||
useRouter.getState().setState({ season: v });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{season && (
|
||||
<span className="episodes-sub">
|
||||
{season.leafCount} episodes{season.year ? ` · ${season.year}` : ''}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{season?.summary && <p className="season-summary">{season.summary}</p>}
|
||||
<div className="episode-list">
|
||||
{episodes.isLoading && <PageLoader />}
|
||||
{episodes.data?.map((ep) => <EpisodeRow key={ep.id} ep={ep} />)}
|
||||
{episodes.data && !episodes.data.length && <EmptyState icon="tv" title="No episodes" />}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
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 nextEp = next.data;
|
||||
const seasonList = (seasons.data ?? []).filter((s) => s.type === 'season');
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const playLabel = nextEp ? (nextEp.viewOffset ? `Resume ${episodeLabel(nextEp)}` : isWatched(item, percent) ? 'Play' : item.viewedLeafCount ? `Watch ${episodeLabel(nextEp)}` : 'Play') : 'Play';
|
||||
void server;
|
||||
return (
|
||||
<div className="detail show">
|
||||
<DetailHero item={item}>
|
||||
<Facts item={item} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => (nextEp ? playWithVersion(nextEp) : playItem(item))}>
|
||||
{playLabel}
|
||||
</Button>
|
||||
<Button variant="ghost" icon="shuffle" onClick={() => shuffleItem(item)}>
|
||||
Shuffle
|
||||
</Button>
|
||||
<TrailerButton item={item} />
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
{nextEp && (
|
||||
<div className="detail-tech">
|
||||
Up next: {episodeLabel(nextEp)} · {nextEp.title}
|
||||
</div>
|
||||
)}
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{seasonList.length > 1 && (
|
||||
<Shelf title="Seasons">
|
||||
{seasonList.map((s) => (
|
||||
<PosterCard key={s.id} item={s} caption="episodes" />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{seasons.isLoading ? <PageLoader /> : <Episodes seasons={seasonList} initialSeason={nextEp?.parentId} />}
|
||||
<CastRow item={item} />
|
||||
<ExtrasRow item={item} />
|
||||
<RelatedRows item={item} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SeasonDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.parentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const seasonList = (siblings.data ?? []).filter((s) => s.type === 'season');
|
||||
const episodes = useChildren(item.id);
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
const next = (episodes.data ?? []).find((e) => !isWatched(e, percent)) ?? episodes.data?.[0];
|
||||
const showItem = show.data;
|
||||
return (
|
||||
<div className="detail season">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={showItem ?? item}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={340} maxHeight={96} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.parentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: showItem?.contentRating ?? item.contentRating, genres: [] }} />
|
||||
<Synopsis item={item} text={item.summary || showItem?.summary || ''} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!next} onClick={() => next && playWithVersion(next)}>
|
||||
{next ? (next.viewOffset ? `Resume ${episodeLabel(next)}` : `Play ${episodeLabel(next)}`) : 'Play'}
|
||||
</Button>
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
<Episodes seasons={seasonList.length ? seasonList : [item]} initialSeason={item.id} />
|
||||
{showItem && <CastRow item={showItem} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EpisodeDetail({ item }: { item: Item }) {
|
||||
const show = useItem(item.grandparentId);
|
||||
const siblings = useChildren(item.parentId);
|
||||
const resume = item.viewOffset > 0 && !isWatched(item);
|
||||
const showItem = show.data;
|
||||
const others = (siblings.data ?? []).filter((e) => e.id !== item.id);
|
||||
const startIndex = Math.max(0, (siblings.data ?? []).findIndex((e) => e.id === item.id));
|
||||
const ordered = useMemo(() => [...others.slice(startIndex), ...others.slice(0, startIndex)], [siblings.data, item.id]);
|
||||
return (
|
||||
<div className="detail episode">
|
||||
<DetailHero
|
||||
item={item}
|
||||
backdropItem={{ ...item, art: item.thumb, grandparentArt: item.thumb, ultraBlur: showItem?.ultraBlur ?? item.ultraBlur }}
|
||||
title={
|
||||
<>
|
||||
{showItem ? (
|
||||
<button className="title-link" onClick={() => navigate({ name: 'item', id: showItem.id })}>
|
||||
<TitleArt item={showItem} maxWidth={300} maxHeight={84} as="h2" />
|
||||
</button>
|
||||
) : (
|
||||
<h2 className="title-text small">{item.grandparentTitle}</h2>
|
||||
)}
|
||||
<h1 className="detail-subtitle">{item.title}</h1>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Facts item={{ ...item, contentRating: item.contentRating || showItem?.contentRating || '' }} />
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? `Resume · ${remaining(item)}` : 'Play'}
|
||||
</Button>
|
||||
{resume && (
|
||||
<Button variant="ghost" icon="replay10" onClick={() => playWithVersion(item, { offsetMs: 0, resume: false })}>
|
||||
From beginning
|
||||
</Button>
|
||||
)}
|
||||
<WatchedButton item={item} />
|
||||
<DownloadButton item={item} />
|
||||
<MoreButton item={item} onDeleted={goBack} />
|
||||
</div>
|
||||
<div className="detail-tech">{technicalLine(item.media[0])}</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body">
|
||||
<div className="detail-main">
|
||||
{ordered.length > 0 && (
|
||||
<Shelf title={`More from ${item.parentTitle || `Season ${item.parentIndex}`}`} kind="landscape" onViewAll={() => navigate({ name: 'item', id: item.parentId })}>
|
||||
{ordered.map((e) => (
|
||||
<LandscapeCard key={e.id} item={e} episodeStyle />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
<CastRow item={item.roles.length ? item : (showItem ?? item)} title={item.roles.length ? 'Cast & Guest Stars' : 'Cast & Crew'} />
|
||||
</div>
|
||||
<AboutPanel item={item} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Collections ——————————————————————————————————————————————————
|
||||
|
||||
function CollectionDetail({ item }: { item: Item }) {
|
||||
const members = useServerQuery(['collectionItems', item.id], (s) => api.collectionItems(s, item.id));
|
||||
const list = members.data ?? [];
|
||||
const backdropItem = item.art ? item : list.find((m) => m.art);
|
||||
return (
|
||||
<div className="detail collection">
|
||||
<DetailHero item={item} backdropItem={backdropItem} title={<h1 className="title-text">{item.title}</h1>}>
|
||||
<div className="facts">
|
||||
<span className="fact">{list.length ? `${list.length} titles` : 'Collection'}</span>
|
||||
{item.contentRating && <span className="badge">{item.contentRating}</span>}
|
||||
</div>
|
||||
<Synopsis item={item} text={item.summary} />
|
||||
<div className="actions detail-actions">
|
||||
<Button variant="primary" icon="play" disabled={!list.length} onClick={() => list[0] && playWithVersion(list.find((m) => !isWatched(m)) ?? list[0])}>
|
||||
Play
|
||||
</Button>
|
||||
<MoreButton item={item} />
|
||||
</div>
|
||||
</DetailHero>
|
||||
<div className="detail-body single">
|
||||
<div className="detail-main">
|
||||
{members.isLoading && <PageLoader />}
|
||||
<div className="poster-grid auto">
|
||||
{list.map((m) => (
|
||||
<PosterCard key={m.id} item={m} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
328
src/screens/LibraryBrowser.tsx
Normal file
328
src/screens/LibraryBrowser.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import * as api from '../plex/api';
|
||||
import type { Item, Section } from '../plex/types';
|
||||
import { queryClient, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { SectionKind } from '../app/router';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { EmptyState, ErrorState, IconButton, PageLoader, Select, Spinner } from '../ui/primitives';
|
||||
import { openMenu, type MenuItem } from '../ui/overlays';
|
||||
|
||||
const PAGE = 120;
|
||||
const CARD_WIDTH = { compact: 148, comfortable: 182, large: 228 } as const;
|
||||
const BOOLEAN_LABELS: Record<string, string> = {
|
||||
unwatched: 'Unwatched',
|
||||
inProgress: 'In progress',
|
||||
hdr: 'HDR',
|
||||
dovi: 'Dolby Vision',
|
||||
hdr10plus: 'HDR10+',
|
||||
atmos: 'Dolby Atmos',
|
||||
unmatched: 'Unmatched',
|
||||
};
|
||||
const QUICK_FILTERS = ['genre', 'year', 'decade', 'contentRating', 'resolution', 'collection', 'studio', 'country', 'audioLanguage', 'subtitleLanguage', 'label', 'editionTitle', 'network'];
|
||||
|
||||
function useDebounced<T>(value: T, ms: number) {
|
||||
const [v, setV] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setV(value), ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, ms]);
|
||||
return v;
|
||||
}
|
||||
|
||||
export function LibraryBrowser({ section, kind }: { section: Section; kind: SectionKind }) {
|
||||
const server = useServer();
|
||||
const type = kind === 'movie' ? 1 : 2;
|
||||
const views = useSettings((s) => s.libraryViews);
|
||||
const setSetting = useSettings((s) => s.set);
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const view = views[section.id] ?? { sort: 'titleSort:asc', filters: {} };
|
||||
const [query, setQuery] = useState('');
|
||||
const title = useDebounced(query.trim(), 300);
|
||||
const meta = useServerQuery(['libraryMeta', section.id, type], (s) => api.libraryMeta(s, section.id, type), { staleTime: 30 * 60_000 });
|
||||
|
||||
const saveView = (next: Partial<typeof view>) => setSetting('libraryViews', { ...views, [section.id]: { ...view, ...next } });
|
||||
const [sortKey, sortDir] = view.sort.split(':') as [string, 'asc' | 'desc'];
|
||||
const sortTitle = meta.data?.sorts.find((s) => s.key === sortKey)?.title ?? 'Title';
|
||||
|
||||
const filterLabel = (filter: string) => meta.data?.filters.find((f) => f.filter === filter)?.title ?? BOOLEAN_LABELS[filter] ?? filter;
|
||||
|
||||
// Option titles for active filter chips (values are Plex keys).
|
||||
const [chipTitles, setChipTitles] = useState<Record<string, string>>({});
|
||||
|
||||
const loadOptions = async (f: { filter: string; key: string }) =>
|
||||
queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'filterOptions', f.key, type],
|
||||
queryFn: () => api.filterOptions(server, f.key, type),
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
|
||||
const openFilters = async (anchor: HTMLElement) => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
const bools = filters.filter((f) => f.type === 'boolean');
|
||||
const strings = filters.filter((f) => f.type !== 'boolean' && QUICK_FILTERS.includes(f.filter));
|
||||
const options = await Promise.all(strings.map((f) => loadOptions(f).catch(() => [])));
|
||||
const items: MenuItem[] = [
|
||||
...bools.map((f) => ({
|
||||
label: BOOLEAN_LABELS[f.filter] ?? f.title,
|
||||
checked: view.filters[f.filter] === '1',
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === '1') delete next[f.filter];
|
||||
else next[f.filter] = '1';
|
||||
saveView({ filters: next });
|
||||
},
|
||||
})),
|
||||
{ divider: true },
|
||||
...strings
|
||||
.map((f, i): MenuItem => ({
|
||||
label: f.title,
|
||||
hint: view.filters[f.filter] ? chipTitles[`${f.filter}=${view.filters[f.filter]}`] ?? '1 selected' : undefined,
|
||||
submenu: options[i].length
|
||||
? options[i].slice(0, 400).map((o) => ({
|
||||
label: o.title,
|
||||
checked: view.filters[f.filter] === o.key,
|
||||
onSelect: () => {
|
||||
const next = { ...view.filters };
|
||||
if (next[f.filter] === o.key) delete next[f.filter];
|
||||
else next[f.filter] = o.key;
|
||||
setChipTitles((c) => ({ ...c, [`${f.filter}=${o.key}`]: o.title }));
|
||||
saveView({ filters: next });
|
||||
},
|
||||
}))
|
||||
: [{ label: 'No options', disabled: true }],
|
||||
}))
|
||||
.filter((m) => m.submenu!.length),
|
||||
];
|
||||
openMenu(items, anchor, { minWidth: 230 });
|
||||
};
|
||||
|
||||
// Resolve chip titles for remembered filters.
|
||||
useEffect(() => {
|
||||
const filters = meta.data?.filters ?? [];
|
||||
for (const [k, v] of Object.entries(view.filters)) {
|
||||
const f = filters.find((x) => x.filter === k);
|
||||
if (!f || f.type === 'boolean' || chipTitles[`${k}=${v}`]) continue;
|
||||
loadOptions(f)
|
||||
.then((opts) => {
|
||||
const o = opts.find((x) => x.key === v);
|
||||
if (o) setChipTitles((c) => ({ ...c, [`${k}=${v}`]: o.title }));
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
}, [meta.data, view.filters]);
|
||||
|
||||
if (meta.isError && !meta.data) return <ErrorState error={meta.error} onRetry={() => meta.refetch()} />;
|
||||
|
||||
const activeFilters = Object.entries(view.filters);
|
||||
return (
|
||||
<div className="library">
|
||||
<div className="lib-toolbar">
|
||||
<div className="lib-search">
|
||||
<Icon name="search" size={16} />
|
||||
<input value={query} placeholder={`Search ${section.title}`} onChange={(e) => setQuery(e.target.value)} onKeyDown={(e) => e.key === 'Escape' && (e.stopPropagation(), setQuery(''))} />
|
||||
{query && (
|
||||
<button aria-label="Clear" onClick={() => setQuery('')}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button className="select" onClick={(e) => openFilters(e.currentTarget)} disabled={!meta.data}>
|
||||
<Icon name="sliders" size={15} />
|
||||
<span className="select-value">Filter{activeFilters.length ? ` · ${activeFilters.length}` : ''}</span>
|
||||
</button>
|
||||
<div className="sort-group">
|
||||
<Select
|
||||
value={sortKey}
|
||||
prefix="Sort"
|
||||
label="Sort by"
|
||||
options={(meta.data?.sorts ?? [{ key: 'titleSort', title: 'Title', defaultDirection: 'asc' }]).map((s) => ({ value: s.key, label: s.title }))}
|
||||
onChange={(k) => {
|
||||
const s = meta.data?.sorts.find((x) => x.key === k);
|
||||
saveView({ sort: `${k}:${s?.defaultDirection ?? 'asc'}` });
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
icon={sortDir === 'asc' ? 'chevronUp' : 'chevronDown'}
|
||||
label={sortDir === 'asc' ? 'Ascending' : 'Descending'}
|
||||
className="sort-dir"
|
||||
onClick={() => saveView({ sort: `${sortKey}:${sortDir === 'asc' ? 'desc' : 'asc'}` })}
|
||||
/>
|
||||
</div>
|
||||
<div className="toolbar-spacer" />
|
||||
<div className="density" role="group" aria-label="Poster size">
|
||||
{(['compact', 'comfortable', 'large'] as const).map((s, i) => (
|
||||
<button key={s} className={posterSize === s ? 'on' : ''} aria-label={`${s} posters`} title={`${s[0].toUpperCase()}${s.slice(1)} posters`} onClick={() => setSetting('posterSize', s)}>
|
||||
<span style={{ width: 8 + i * 3, height: 11 + i * 4 }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{activeFilters.length > 0 && (
|
||||
<div className="filter-chips">
|
||||
{activeFilters.map(([k, v]) => (
|
||||
<button
|
||||
key={k}
|
||||
className="chip"
|
||||
onClick={() => {
|
||||
const next = { ...view.filters };
|
||||
delete next[k];
|
||||
saveView({ filters: next });
|
||||
}}
|
||||
>
|
||||
{v === '1' && BOOLEAN_LABELS[k] ? BOOLEAN_LABELS[k] : `${filterLabel(k)}: ${chipTitles[`${k}=${v}`] ?? v}`}
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
))}
|
||||
<button className="btn text" onClick={() => saveView({ filters: {} })}>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<LibraryGrid key={`${section.id}|${view.sort}|${JSON.stringify(view.filters)}|${title}`} section={section} type={type} sort={view.sort} filters={view.filters} title={title} sortTitle={sortTitle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryGrid({ section, type, sort, filters, title, sortTitle }: { section: Section; type: number; sort: string; filters: Record<string, string>; title: string; sortTitle: string }) {
|
||||
const server = useServer();
|
||||
const posterSize = useSettings((s) => s.posterSize);
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);
|
||||
const [pages, setPages] = useState<Record<number, Item[]>>({});
|
||||
const [total, setTotal] = useState<number | null>(null);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
const inflight = useRef(new Set<number>());
|
||||
const params = { type, sort, filters, title };
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = gridRef.current;
|
||||
if (!el) return;
|
||||
setScrollEl(el.closest('.main-scroll') as HTMLElement);
|
||||
const ro = new ResizeObserver(() => setWidth(el.clientWidth));
|
||||
ro.observe(el);
|
||||
setWidth(el.clientWidth);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const loadPage = useCallback(
|
||||
async (p: number) => {
|
||||
if (inflight.current.has(p)) return;
|
||||
inflight.current.add(p);
|
||||
try {
|
||||
const page = await queryClient.fetchQuery({
|
||||
queryKey: [server.machineId, 'libraryPage', section.id, params, p],
|
||||
queryFn: () => api.libraryPage(server, section.id, { ...params, start: p * PAGE, size: PAGE }),
|
||||
staleTime: 60_000,
|
||||
});
|
||||
setPages((prev) => ({ ...prev, [p]: page.items }));
|
||||
setTotal(page.total);
|
||||
} catch (e) {
|
||||
setError(e);
|
||||
} finally {
|
||||
inflight.current.delete(p);
|
||||
}
|
||||
},
|
||||
[server, section.id, JSON.stringify(params)],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
loadPage(0);
|
||||
}, [loadPage]);
|
||||
|
||||
const gap = 16;
|
||||
const target = CARD_WIDTH[posterSize];
|
||||
const cols = Math.max(2, Math.floor((width + gap) / (target + gap)));
|
||||
const cardW = width ? (width - gap * (cols - 1)) / cols : target;
|
||||
const rowH = cardW * 1.5 + 52 + 22;
|
||||
const rows = total === null ? 0 : Math.ceil(total / cols);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows,
|
||||
getScrollElement: () => scrollEl,
|
||||
estimateSize: () => rowH,
|
||||
overscan: 3,
|
||||
scrollMargin: gridRef.current?.offsetTop ?? 0,
|
||||
// Keep jump targets clear of the sticky top bar and toolbar.
|
||||
scrollPaddingStart: 150,
|
||||
});
|
||||
useEffect(() => virtualizer.measure(), [rowH, cols]);
|
||||
|
||||
const vrows = virtualizer.getVirtualItems();
|
||||
useEffect(() => {
|
||||
if (!vrows.length) return;
|
||||
const first = vrows[0].index * cols;
|
||||
const last = (vrows[vrows.length - 1].index + 1) * cols;
|
||||
for (let p = Math.floor(first / PAGE); p <= Math.floor(Math.min(last, (total ?? 1) - 1) / PAGE); p++) if (!pages[p]) loadPage(p);
|
||||
}, [vrows.map((r) => r.index).join(','), cols, total]);
|
||||
|
||||
const itemAt = (i: number) => pages[Math.floor(i / PAGE)]?.[i % PAGE];
|
||||
|
||||
// A–Z jumps for title order.
|
||||
const alpha = sort.startsWith('titleSort') && !title;
|
||||
const letters = useServerQuery(['firstCharacter', section.id, type, filters], (s) => api.firstCharacters(s, section.id, { type, ...filters }), { enabled: alpha, staleTime: 120_000 });
|
||||
const jump = (char: string) => {
|
||||
if (!letters.data) return;
|
||||
const list = sort.endsWith(':desc') ? [...letters.data].reverse() : letters.data;
|
||||
let offset = 0;
|
||||
for (const l of list) {
|
||||
if (l.title === char) break;
|
||||
offset += l.size;
|
||||
}
|
||||
virtualizer.scrollToIndex(Math.floor(offset / cols), { align: 'start' });
|
||||
};
|
||||
|
||||
if (error && total === null) return <ErrorState error={error} onRetry={() => (setError(null), loadPage(0))} />;
|
||||
return (
|
||||
<div className="library-body">
|
||||
<div className="grid-count">
|
||||
{total === null ? <Spinner size={14} /> : `${total.toLocaleString()} ${total === 1 ? 'title' : 'titles'}`}
|
||||
{total !== null && sortTitle && <span className="dim"> · by {sortTitle.toLowerCase()}</span>}
|
||||
</div>
|
||||
<div className="lib-grid-wrap">
|
||||
<div ref={gridRef} className="lib-grid" style={{ height: virtualizer.getTotalSize() }}>
|
||||
{total === 0 && (
|
||||
<EmptyState icon="search" title="Nothing matches">
|
||||
Try a different search or remove a filter.
|
||||
</EmptyState>
|
||||
)}
|
||||
{vrows.map((row) => (
|
||||
<div
|
||||
key={row.key}
|
||||
className="lib-row"
|
||||
style={{ transform: `translateY(${row.start - virtualizer.options.scrollMargin}px)`, gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap }}
|
||||
>
|
||||
{Array.from({ length: cols }, (_, c) => {
|
||||
const i = row.index * cols + c;
|
||||
if (total !== null && i >= total) return <div key={c} />;
|
||||
const item = itemAt(i);
|
||||
return item ? (
|
||||
<PosterCard key={item.id} item={item} />
|
||||
) : (
|
||||
<div key={c} className="card poster placeholder">
|
||||
<div className="card-cover skeleton" />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{alpha && letters.data && letters.data.length > 3 && (
|
||||
<div className="alpha-rail" aria-label="Jump to letter">
|
||||
{letters.data.map((l) => (
|
||||
<button key={l.title} onClick={() => jump(l.title)} title={`${l.title} · ${l.size}`}>
|
||||
{l.title}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{total === null && <PageLoader />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
61
src/screens/Person.tsx
Normal file
61
src/screens/Person.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import * as api from '../plex/api';
|
||||
import { useSections, useServerQuery } from '../app/queries';
|
||||
import { useServer } from '../app/session';
|
||||
import { PosterCard } from '../ui/media';
|
||||
import { Artwork, EmptyState, ErrorState, PageLoader } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
export default function Person({ id, title, thumb }: { id: string; title: string; thumb?: string }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const titles = useServerQuery(['person', id], (s) => api.personTitles(s, id, sections.data ?? []), { enabled: !!sections.data });
|
||||
const list = titles.data ?? [];
|
||||
const movies = list.filter((i) => i.type === 'movie');
|
||||
const shows = list.filter((i) => i.type === 'show');
|
||||
const years = list.map((i) => i.year).filter(Boolean);
|
||||
return (
|
||||
<div className="person-page page-pad top">
|
||||
<header className="person-header">
|
||||
<div className="person-portrait">{thumb ? <Artwork src={server.image(thumb, 240, 240)} /> : <Icon name="person" size={52} />}</div>
|
||||
<div>
|
||||
<div className="micro">Filmography in your library</div>
|
||||
<h1>{title}</h1>
|
||||
{titles.data && (
|
||||
<p className="muted">
|
||||
{[movies.length ? `${movies.length} movie${movies.length === 1 ? '' : 's'}` : '', shows.length ? `${shows.length} show${shows.length === 1 ? '' : 's'}` : '', years.length ? `${Math.min(...years)}–${Math.max(...years)}` : '']
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
{titles.isError && <ErrorState error={titles.error} onRetry={() => titles.refetch()} />}
|
||||
{titles.isLoading && <PageLoader />}
|
||||
{titles.data && !list.length && (
|
||||
<EmptyState icon="person" title="Nothing in your library">
|
||||
{title} doesn’t appear in any movie or show on this server.
|
||||
</EmptyState>
|
||||
)}
|
||||
{movies.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>Movies</h2>
|
||||
<div className="poster-grid auto">
|
||||
{movies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{shows.length > 0 && (
|
||||
<section className="person-section">
|
||||
<h2>TV Shows</h2>
|
||||
<div className="poster-grid auto">
|
||||
{shows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
src/screens/Search.tsx
Normal file
191
src/screens/Search.tsx
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useServerQuery } from '../app/queries';
|
||||
import { navigate, useRouter } from '../app/router';
|
||||
import type { Item } from '../plex/types';
|
||||
import { LandscapeCard, PersonCard, PosterCard, Shelf } from '../ui/media';
|
||||
import { EmptyState, ErrorState, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
const RECENT_KEY = 'kaleido.recentSearches';
|
||||
const loadRecent = (): string[] => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]');
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
/** Plex search ranks per hub; float exact and prefix title matches to the top. */
|
||||
function rank(query: string, items: Item[]): Item[] {
|
||||
const q = query.toLowerCase();
|
||||
const score = (i: Item) => {
|
||||
const t = (i.type === 'episode' ? i.title : i.title).toLowerCase();
|
||||
if (t === q) return 0;
|
||||
if (t.startsWith(q)) return 1;
|
||||
if (t.split(/\W+/).some((w) => w.startsWith(q))) return 2;
|
||||
return 3;
|
||||
};
|
||||
return [...items].sort((a, b) => score(a) - score(b));
|
||||
}
|
||||
|
||||
export default function Search({ initial }: { initial?: string }) {
|
||||
const saved = useRouter((s) => s.current.state.query as string | undefined);
|
||||
const [query, setQuery] = useState(saved ?? initial ?? '');
|
||||
const [debounced, setDebounced] = useState(query);
|
||||
const [recent, setRecent] = useState(loadRecent);
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
input.current?.focus();
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setDebounced(query.trim()), 250);
|
||||
useRouter.getState().setState({ query });
|
||||
return () => clearTimeout(t);
|
||||
}, [query]);
|
||||
|
||||
const results = useServerQuery(['search', debounced], (s) => api.search(s, debounced), { enabled: debounced.length > 0, staleTime: 60_000 });
|
||||
const recentlyAdded = useServerQuery(['homeHubs'], (s) => api.homeHubs(s), { enabled: !debounced });
|
||||
|
||||
const remember = (q: string) => {
|
||||
const next = [q, ...recent.filter((r) => r.toLowerCase() !== q.toLowerCase())].slice(0, 8);
|
||||
setRecent(next);
|
||||
localStorage.setItem(RECENT_KEY, JSON.stringify(next));
|
||||
};
|
||||
|
||||
const hubs = results.data?.hubs ?? [];
|
||||
const all = hubs.flatMap((h) => h.items);
|
||||
const movies = rank(debounced, all.filter((i) => i.type === 'movie'));
|
||||
const shows = rank(debounced, all.filter((i) => i.type === 'show'));
|
||||
const episodes = rank(debounced, all.filter((i) => i.type === 'episode'));
|
||||
const collections = all.filter((i) => i.type === 'collection');
|
||||
const people = results.data?.people ?? [];
|
||||
const top = rank(debounced, [...movies, ...shows]).slice(0, 6);
|
||||
const inTop = new Set(top.map((i) => i.id));
|
||||
const moreMovies = movies.filter((i) => !inTop.has(i.id));
|
||||
const moreShows = shows.filter((i) => !inTop.has(i.id));
|
||||
|
||||
return (
|
||||
<div className="search-page page-pad top">
|
||||
<div className="search-hero">
|
||||
<div className="search-field">
|
||||
<Icon name="search" size={22} />
|
||||
<input
|
||||
ref={input}
|
||||
value={query}
|
||||
placeholder="Search movies, shows, episodes and people"
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && query.trim()) remember(query.trim());
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
if (query) setQuery('');
|
||||
else useRouter.getState().back();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{results.isFetching && <Spinner size={18} />}
|
||||
{query && (
|
||||
<button className="icon-btn" aria-label="Clear search" onClick={() => (setQuery(''), input.current?.focus())}>
|
||||
<Icon name="x" size={17} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!debounced && (
|
||||
<div className="search-idle">
|
||||
{recent.length > 0 && (
|
||||
<div className="recent-searches">
|
||||
<h3>Recent searches</h3>
|
||||
<div className="chips">
|
||||
{recent.map((r) => (
|
||||
<button key={r} className="chip" onClick={() => setQuery(r)}>
|
||||
<Icon name="clock" size={13} />
|
||||
{r}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="btn text"
|
||||
onClick={() => {
|
||||
setRecent([]);
|
||||
localStorage.removeItem(RECENT_KEY);
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{recentlyAdded.data
|
||||
?.filter((h) => /recent/.test(h.id))
|
||||
.slice(0, 2)
|
||||
.map((h) => (
|
||||
<Shelf key={h.id} title={h.title} className="flush">
|
||||
{h.items.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{debounced && results.isError && <ErrorState error={results.error} onRetry={() => results.refetch()} />}
|
||||
{debounced && results.data && !all.length && !people.length && (
|
||||
<EmptyState icon="search" title={`No results for “${debounced}”`}>
|
||||
Check the spelling, or search for an actor, director or episode title.
|
||||
</EmptyState>
|
||||
)}
|
||||
{debounced && results.data && (
|
||||
<div className="search-results" onClick={() => remember(debounced)}>
|
||||
{top.length > 0 && (
|
||||
<section className="search-top">
|
||||
<h3>Top results</h3>
|
||||
<div className="poster-grid auto">
|
||||
{top.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{moreMovies.length > 0 && (
|
||||
<Shelf title="More movies" className="flush">
|
||||
{moreMovies.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{moreShows.length > 0 && (
|
||||
<Shelf title="More TV shows" className="flush">
|
||||
{moreShows.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{episodes.length > 0 && (
|
||||
<Shelf title="Episodes" kind="landscape" className="flush">
|
||||
{episodes.map((i) => (
|
||||
<LandscapeCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{people.length > 0 && (
|
||||
<Shelf title="People" kind="people" className="flush">
|
||||
{people.map((p) => (
|
||||
<PersonCard key={p.id} name={p.tag} thumb={p.thumb} onClick={() => navigate({ name: 'person', id: p.id, title: p.tag, thumb: p.thumb })} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
{collections.length > 0 && (
|
||||
<Shelf title="Collections" className="flush">
|
||||
{collections.map((i) => (
|
||||
<PosterCard key={i.id} item={i} />
|
||||
))}
|
||||
</Shelf>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
111
src/screens/Section.tsx
Normal file
111
src/screens/Section.tsx
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as api from '../plex/api';
|
||||
import { useSectionFor, useServerQuery } from '../app/queries';
|
||||
import { navigate, type SectionKind, type SectionTab } from '../app/router';
|
||||
import { useSettings } from '../app/settings';
|
||||
import type { Section } from '../plex/types';
|
||||
import { Hero } from '../ui/Hero';
|
||||
import { HubShelf, PosterCard } from '../ui/media';
|
||||
import { EmptyState, ErrorState, PageLoader, Select } from '../ui/primitives';
|
||||
import { buildFeatures, HIDDEN_HUBS, recentSeasons } from './discover';
|
||||
import { LibraryBrowser } from './LibraryBrowser';
|
||||
|
||||
const TABS: { id: SectionTab; label: string }[] = [
|
||||
{ id: 'discover', label: 'Discover' },
|
||||
{ id: 'library', label: 'Library' },
|
||||
{ id: 'collections', label: 'Collections' },
|
||||
];
|
||||
|
||||
function SectionHeader({ kind, tab, section, all, overlay }: { kind: SectionKind; tab: SectionTab; section: Section; all: Section[]; overlay: boolean }) {
|
||||
const set = useSettings((s) => s.set);
|
||||
return (
|
||||
<div className={`section-header${overlay ? ' overlay' : ''}`}>
|
||||
<h1>{kind === 'movie' ? 'Movies' : 'TV Shows'}</h1>
|
||||
<nav className="section-tabs" role="tablist">
|
||||
{TABS.map((t) => (
|
||||
<button key={t.id} role="tab" aria-selected={t.id === tab} className={t.id === tab ? 'active' : ''} onClick={() => navigate({ name: 'section', kind, tab: t.id }, { replace: true })}>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
{all.length > 1 && (
|
||||
<Select
|
||||
className="section-picker"
|
||||
value={section.id}
|
||||
label="Library"
|
||||
options={all.map((s) => ({ value: s.id, label: s.title }))}
|
||||
onChange={(v) => set(kind === 'movie' ? 'movieSection' : 'showSection', v)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 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]);
|
||||
|
||||
if (hubs.isError && !hubs.data) return <ErrorState error={hubs.error} onRetry={() => hubs.refetch()} />;
|
||||
if (!hubs.data) return <PageLoader />;
|
||||
const rest = hubs.data.filter((h) => !HIDDEN_HUBS.test(h.id));
|
||||
// TV: episodes lead; redundant episode hubs are skipped when they repeat Continue Watching.
|
||||
const cwIds = new Set((cw.data ?? []).map((i) => i.id));
|
||||
const shelves = rest.filter((h) => !(h.items.length && h.items.every((i) => cwIds.has(i.id))));
|
||||
return (
|
||||
<>
|
||||
<Hero features={features} variant="section" />
|
||||
<div className="shelves over-hero">
|
||||
<HubShelf title={kind === 'show' ? 'Next Episodes' : 'Continue Watching'} items={cw.data ?? []} continueWatching />
|
||||
{kind === 'show' && <HubShelf title="New Seasons" items={seasons.data ?? []} landscape={false} />}
|
||||
{shelves.map((h) => (
|
||||
<HubShelf key={h.id} title={h.title.replace(/ in (Movies|TV Shows)$/, '')} items={h.items} onViewAll={h.more || h.key.includes('/all') ? () => navigate({ name: 'hub', key: h.key, title: h.title }) : undefined} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Collections({ section }: { section: Section }) {
|
||||
const q = useServerQuery(['collections', section.id], (s) => api.collections(s, section.id));
|
||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
||||
if (!q.data) return <PageLoader />;
|
||||
if (!q.data.length)
|
||||
return (
|
||||
<EmptyState icon="collection" title="No collections yet">
|
||||
Collections created in Plex for {section.title} appear here.
|
||||
</EmptyState>
|
||||
);
|
||||
return (
|
||||
<div className="page-pad">
|
||||
<div className="grid-count">{q.data.length.toLocaleString()} collections</div>
|
||||
<div className="poster-grid auto">
|
||||
{q.data.map((c) => (
|
||||
<PosterCard key={c.id} item={c} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SectionScreen({ kind, tab }: { kind: SectionKind; tab: SectionTab }) {
|
||||
const { section, all, loading } = useSectionFor(kind);
|
||||
if (loading) return <PageLoader />;
|
||||
if (!section)
|
||||
return (
|
||||
<div className="page-pad top">
|
||||
<EmptyState icon={kind === 'movie' ? 'film' : 'tv'} title={`No ${kind === 'movie' ? 'movie' : 'TV'} libraries`}>
|
||||
This server has no {kind === 'movie' ? 'movie' : 'TV show'} libraries you can access.
|
||||
</EmptyState>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<div className={`section-screen tab-${tab}`} key={section.id}>
|
||||
<SectionHeader kind={kind} tab={tab} section={section} all={all} overlay={tab === 'discover'} />
|
||||
{tab === 'discover' && <Discover kind={kind} section={section} />}
|
||||
{tab === 'library' && <LibraryBrowser section={section} kind={kind} />}
|
||||
{tab === 'collections' && <Collections section={section} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
102
src/screens/ServerPicker.tsx
Normal file
102
src/screens/ServerPicker.tsx
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSession } from '../app/session';
|
||||
import type { ServerResource } from '../plex/types';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
import { useRouter } from '../app/router';
|
||||
|
||||
export function ServerPicker() {
|
||||
const resources = useSession((s) => s.resources);
|
||||
const status = useSession((s) => s.status);
|
||||
const error = useSession((s) => s.error);
|
||||
const user = useSession((s) => s.user);
|
||||
const current = useSession((s) => s.server);
|
||||
const choose = useSession((s) => s.chooseServer);
|
||||
const refresh = useSession((s) => s.refreshResources);
|
||||
const signOut = useSession((s) => s.signOut);
|
||||
const [pending, setPending] = useState('');
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!resources.length) {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const pick = async (r: ServerResource) => {
|
||||
setPending(r.id);
|
||||
await choose(r);
|
||||
setPending('');
|
||||
useRouter.getState().reset({ name: 'home' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card wide">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={40} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
<h1>Choose a server</h1>
|
||||
<p className="auth-lede">{user ? `Signed in as ${user.title}.` : 'Pick the Plex Media Server to browse.'}</p>
|
||||
<div className="server-list">
|
||||
{refreshing && !resources.length && (
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Finding your servers…
|
||||
</div>
|
||||
)}
|
||||
{resources.map((r) => (
|
||||
<button key={r.id} className={`server-row${current?.machineId === r.id ? ' current' : ''}`} onClick={() => pick(r)} disabled={!!pending}>
|
||||
<div className="server-glyph">
|
||||
<Icon name="server" size={20} />
|
||||
</div>
|
||||
<div className="server-text">
|
||||
<strong>{r.name}</strong>
|
||||
<small>
|
||||
{r.owned ? 'Your server' : `Shared by ${r.sourceTitle || 'a friend'}`} · {r.platform || 'Plex Media Server'}
|
||||
{r.productVersion ? ` · ${r.productVersion.split('-')[0]}` : ''}
|
||||
</small>
|
||||
</div>
|
||||
<span className={`presence${r.presence ? ' on' : ''}`}>{r.presence ? 'Online' : 'Offline'}</span>
|
||||
{pending === r.id && status === 'connecting' ? <Spinner size={18} /> : <Icon name="next" size={18} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
<div className="auth-actions spread">
|
||||
<Button
|
||||
variant="ghost"
|
||||
icon="refresh"
|
||||
busy={refreshing}
|
||||
onClick={() => {
|
||||
setRefreshing(true);
|
||||
refresh()
|
||||
.catch(() => {})
|
||||
.finally(() => setRefreshing(false));
|
||||
}}
|
||||
>
|
||||
Refresh
|
||||
</Button>
|
||||
{current && (
|
||||
<Button variant="ghost" onClick={() => useSession.setState({ status: 'ready', error: '' })}>
|
||||
Keep {current.name}
|
||||
</Button>
|
||||
)}
|
||||
<button className="auth-link" onClick={signOut}>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
193
src/screens/SignIn.tsx
Normal file
193
src/screens/SignIn.tsx
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { authUrl, checkPin, createPin, type Pin } from '../plex/account';
|
||||
import { useSession } from '../app/session';
|
||||
import { openExternal } from '../platform/native';
|
||||
import { Button, KaleidoMark, Spinner } from '../ui/primitives';
|
||||
import { Icon } from '../ui/Icon';
|
||||
import { WindowDrag } from './WindowDrag';
|
||||
|
||||
type Mode = 'start' | 'browser' | 'code' | 'manual';
|
||||
|
||||
export function SignIn() {
|
||||
const completeSignIn = useSession((s) => s.completeSignIn);
|
||||
const connectManual = useSession((s) => s.connectManual);
|
||||
const sessionError = useSession((s) => s.error);
|
||||
const [mode, setMode] = useState<Mode>('start');
|
||||
const [pin, setPin] = useState<Pin | null>(null);
|
||||
const [error, setError] = useState(sessionError);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [url, setUrl] = useState('');
|
||||
const [token, setToken] = useState('');
|
||||
const poll = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const stopPolling = () => {
|
||||
if (poll.current) clearInterval(poll.current);
|
||||
poll.current = null;
|
||||
};
|
||||
useEffect(() => stopPolling, []);
|
||||
|
||||
const begin = async (strong: boolean) => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
stopPolling();
|
||||
try {
|
||||
const p = await createPin(strong);
|
||||
setPin(p);
|
||||
setMode(strong ? 'browser' : 'code');
|
||||
if (strong) await openExternal(authUrl(p));
|
||||
const started = Date.now();
|
||||
poll.current = setInterval(async () => {
|
||||
if (Date.now() - started > 15 * 60_000) {
|
||||
stopPolling();
|
||||
setError('The sign-in request expired. Try again.');
|
||||
setMode('start');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const t = await checkPin(p);
|
||||
if (t) {
|
||||
stopPolling();
|
||||
await completeSignIn(t);
|
||||
}
|
||||
} catch {
|
||||
/* keep polling */
|
||||
}
|
||||
}, 1500);
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const manual = async () => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
try {
|
||||
let u = url.trim();
|
||||
if (!/^https?:\/\//.test(u)) u = `http://${u}`;
|
||||
if (!/:\d+/.test(u.replace(/^https?:\/\//, ''))) u = `${u.replace(/\/$/, '')}:32400`;
|
||||
await connectManual(u, token.trim());
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="auth-screen">
|
||||
<WindowDrag />
|
||||
<div className="auth-backdrop" />
|
||||
<div className="auth-card">
|
||||
<div className="auth-brand">
|
||||
<KaleidoMark size={46} />
|
||||
<span>KALEIDO</span>
|
||||
</div>
|
||||
{mode === 'start' && (
|
||||
<>
|
||||
<h1>Your Plex library, front and center.</h1>
|
||||
<p className="auth-lede">Sign in with your Plex account to browse and play everything on your servers.</p>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" size="lg" icon="external" busy={busy} onClick={() => begin(true)}>
|
||||
Sign in with Plex
|
||||
</Button>
|
||||
<button className="auth-link" onClick={() => begin(false)}>
|
||||
Use a code at plex.tv/link instead
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'browser' && (
|
||||
<>
|
||||
<h1>Continue in your browser</h1>
|
||||
<p className="auth-lede">We opened Plex’s sign-in page. Kaleido continues automatically once you approve it.</p>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => pin && openExternal(authUrl(pin))}>
|
||||
Open the page again
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'code' && pin && (
|
||||
<>
|
||||
<h1>Link Kaleido</h1>
|
||||
<p className="auth-lede">
|
||||
On any device, go to <b>plex.tv/link</b> and enter this code.
|
||||
</p>
|
||||
<div className="auth-code selectable">{pin.code}</div>
|
||||
<div className="auth-waiting">
|
||||
<Spinner size={18} /> Waiting for Plex…
|
||||
</div>
|
||||
<div className="auth-actions">
|
||||
<Button variant="ghost" icon="external" onClick={() => openExternal('https://plex.tv/link')}>
|
||||
Open plex.tv/link
|
||||
</Button>
|
||||
<button
|
||||
className="auth-link"
|
||||
onClick={() => {
|
||||
stopPolling();
|
||||
setMode('start');
|
||||
}}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{mode === 'manual' && (
|
||||
<>
|
||||
<h1>Connect to a server</h1>
|
||||
<p className="auth-lede">Enter a Plex Media Server address and an access token. Account features such as profiles need a full sign-in.</p>
|
||||
<form
|
||||
className="auth-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
manual();
|
||||
}}
|
||||
>
|
||||
<label className="field">
|
||||
<span>Server address</span>
|
||||
<input autoFocus value={url} placeholder="192.168.1.20:32400" onChange={(e) => setUrl(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Access token</span>
|
||||
<input type="password" value={token} onChange={(e) => setToken(e.target.value)} />
|
||||
</label>
|
||||
<div className="auth-actions">
|
||||
<Button variant="primary" busy={busy} disabled={!url || !token} type="submit">
|
||||
Connect
|
||||
</Button>
|
||||
<button type="button" className="auth-link" onClick={() => setMode('start')}>
|
||||
Back
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
{error && (
|
||||
<div className="auth-error">
|
||||
<Icon name="alert" size={16} /> {error}
|
||||
</div>
|
||||
)}
|
||||
{mode === 'start' && (
|
||||
<button className="auth-manual" onClick={() => setMode('manual')}>
|
||||
Connect to a server manually
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
src/screens/Splash.tsx
Normal file
44
src/screens/Splash.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings } from '../app/settings';
|
||||
|
||||
const FACETS = [
|
||||
{ fill: '#C3E8D3', d: 'M33,4 L55.5,17 L42.5,24.5 L33,19 Z' },
|
||||
{ fill: '#71B9B0', d: 'M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z' },
|
||||
{ fill: '#3D7C7B', d: 'M55.5,47 L33,60 L33,45 L42.5,39.5 Z' },
|
||||
{ fill: '#D0A977', d: 'M31,60 L8.5,47 L21.5,39.5 L31,45 Z' },
|
||||
{ fill: '#E9D8AE', d: 'M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z' },
|
||||
{ fill: '#EEF2DD', d: 'M8.5,17 L31,4 L31,19 L21.5,24.5 Z' },
|
||||
];
|
||||
|
||||
/**
|
||||
* The cold-start aperture: the six facets twist open around the dark center,
|
||||
* hold until startup data is ready, then the view flies through the aperture.
|
||||
*/
|
||||
export function Splash({ ready, onDone }: { ready: boolean; onDone: () => void }) {
|
||||
const reduced = useSettings((s) => s.reducedMotion);
|
||||
const [phase, setPhase] = useState<'opening' | 'held' | 'leaving'>('opening');
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setPhase('held'), reduced ? 0 : 1100);
|
||||
return () => clearTimeout(t);
|
||||
}, [reduced]);
|
||||
useEffect(() => {
|
||||
if (phase === 'held' && ready) setPhase('leaving');
|
||||
}, [phase, ready]);
|
||||
useEffect(() => {
|
||||
if (phase !== 'leaving') return;
|
||||
const t = setTimeout(onDone, reduced ? 0 : 620);
|
||||
return () => clearTimeout(t);
|
||||
}, [phase]);
|
||||
return (
|
||||
<div className={`splash ${phase}`} data-tauri-drag-region>
|
||||
<div className="splash-mark">
|
||||
<svg viewBox="0 0 64 64" width="92" height="92" aria-hidden="true">
|
||||
{FACETS.map((f, i) => (
|
||||
<path key={i} d={f.d} fill={f.fill} style={{ ['--i' as string]: i }} />
|
||||
))}
|
||||
</svg>
|
||||
<span className="splash-word">KALEIDO</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
22
src/screens/WindowDrag.tsx
Normal file
22
src/screens/WindowDrag.tsx
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { isNative, win } from '../platform/native';
|
||||
import { Icon } from '../ui/Icon';
|
||||
|
||||
/** A draggable strip with window controls for full-screen states without the top bar. */
|
||||
export function WindowDrag() {
|
||||
if (!isNative) return null;
|
||||
return (
|
||||
<div className="window-drag" data-tauri-drag-region>
|
||||
<div className="window-controls">
|
||||
<button aria-label="Minimize" onClick={() => win.minimize()}>
|
||||
<Icon name="minimize" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Maximize" onClick={() => win.toggleMaximize()}>
|
||||
<Icon name="maximize" size={13} strokeWidth={1.4} />
|
||||
</button>
|
||||
<button aria-label="Close" className="close" onClick={() => win.close()}>
|
||||
<Icon name="x" size={15} strokeWidth={1.4} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
96
src/screens/dialogs/Artwork.tsx
Normal file
96
src/screens/dialogs/Artwork.tsx
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, promptDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
const KIND = { poster: 'posters', art: 'arts', clearLogo: 'clearLogos' } as const;
|
||||
const LABEL = { poster: 'poster', art: 'background', clearLogo: 'logo' } as const;
|
||||
|
||||
export function ArtworkDialog({ item, type, onClose }: { item: Item; type: 'poster' | 'art' | 'clearLogo'; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const options = useServerQuery(['artwork', item.id, type], (s) => api.artworkOptions(s, item.id, KIND[type]), { staleTime: 0 });
|
||||
const [busy, setBusy] = useState('');
|
||||
|
||||
const choose = async (key: string) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await api.selectArtwork(server, item.id, type, key);
|
||||
toast(`Updated the ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
|
||||
const upload = () => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/webp';
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
setBusy('upload');
|
||||
try {
|
||||
await api.uploadArtwork(server, item.id, KIND[type], file);
|
||||
toast(`Uploaded a new ${LABEL[type]}`, 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
};
|
||||
|
||||
const fromUrl = async () => {
|
||||
const url = await promptDialog({ title: `Use an image from the web`, message: `Plex downloads the image and uses it as the ${LABEL[type]}.`, confirm: 'Use image', input: { label: 'Image URL', placeholder: 'https://…' } });
|
||||
if (url) choose(url);
|
||||
};
|
||||
|
||||
const shape = type === 'poster' ? 'poster' : type === 'art' ? 'landscape' : 'logo';
|
||||
return (
|
||||
<Dialog
|
||||
title={`Choose ${LABEL[type]}`}
|
||||
subtitle={item.title}
|
||||
onClose={onClose}
|
||||
width={880}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" icon="link" onClick={fromUrl}>
|
||||
From URL
|
||||
</Button>
|
||||
<Button variant="ghost" icon="upload" busy={busy === 'upload'} onClick={upload}>
|
||||
Upload image
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{options.isLoading && <PageLoader />}
|
||||
{options.data && !options.data.length && <EmptyState icon="image" title="No alternatives">Upload an image or use one from the web.</EmptyState>}
|
||||
<div className={`artwork-grid ${shape}`}>
|
||||
{options.data?.map((o) => (
|
||||
<button key={o.key} className={`artwork-option${o.selected ? ' selected' : ''}`} onClick={() => choose(o.key)} disabled={!!busy}>
|
||||
<img src={server.image(o.thumb, shape === 'poster' ? 180 : 320, shape === 'poster' ? 270 : 180, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" loading="lazy" />
|
||||
{o.selected && (
|
||||
<span className="artwork-selected">
|
||||
<Icon name="check" size={14} strokeWidth={2.4} />
|
||||
</span>
|
||||
)}
|
||||
{o.provider && <span className="artwork-provider">{o.provider.replace(/^com\.plexapp\.agents\.|^tv\.plex\.agents\./, '')}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
60
src/screens/dialogs/DialogHost.tsx
Normal file
60
src/screens/dialogs/DialogHost.tsx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import { useDialogs } from '../../app/actions';
|
||||
import { useSession } from '../../app/session';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { EditMetadataDialog } from './EditMetadata';
|
||||
import { FixMatchDialog } from './FixMatch';
|
||||
import { ArtworkDialog } from './Artwork';
|
||||
import { MediaInfoDialog } from './MediaInfo';
|
||||
import { CollectionDialog, PlaylistDialog } from './Lists';
|
||||
import { channelLabel, resolutionLabel } from '../../app/format';
|
||||
|
||||
export function DialogHost() {
|
||||
const dialog = useDialogs((s) => s.dialog);
|
||||
const close = useDialogs((s) => s.close);
|
||||
const server = useSession((s) => s.server);
|
||||
if (!dialog || !server) return null;
|
||||
switch (dialog.kind) {
|
||||
case 'edit':
|
||||
return <EditMetadataDialog item={dialog.item} onClose={close} />;
|
||||
case 'match':
|
||||
return <FixMatchDialog item={dialog.item} onClose={close} />;
|
||||
case 'artwork':
|
||||
return <ArtworkDialog item={dialog.item} type={dialog.type} onClose={close} />;
|
||||
case 'info':
|
||||
return <MediaInfoDialog item={dialog.item} onClose={close} />;
|
||||
case 'collection':
|
||||
return <CollectionDialog item={dialog.item} onClose={close} />;
|
||||
case 'playlist':
|
||||
return <PlaylistDialog item={dialog.item} onClose={close} />;
|
||||
case 'synopsis':
|
||||
return (
|
||||
<Dialog title={dialog.item.title} subtitle={[dialog.item.year, dialog.item.tagline].filter(Boolean).join(' · ')} onClose={close} width={620}>
|
||||
<p className="synopsis-full selectable">{dialog.item.summary}</p>
|
||||
</Dialog>
|
||||
);
|
||||
case 'versions':
|
||||
return (
|
||||
<Dialog title="Choose a version" subtitle={dialog.item.title} onClose={close} width={520}>
|
||||
<div className="version-list">
|
||||
{dialog.item.media.map((m, i) => (
|
||||
<button
|
||||
key={m.id}
|
||||
className="version-row"
|
||||
onClick={() => {
|
||||
close();
|
||||
dialog.onPick(i);
|
||||
}}
|
||||
>
|
||||
<b>{m.title || [resolutionLabel(m), m.dynamicRange].filter(Boolean).join(' ')}</b>
|
||||
<span>
|
||||
{[m.videoCodec.toUpperCase(), `${m.audioCodec.toUpperCase()} ${channelLabel(m.audioChannels)}`, m.bitrate ? `${Math.round(m.bitrate / 1000)} Mbps` : '', m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
208
src/screens/dialogs/EditMetadata.tsx
Normal file
208
src/screens/dialogs/EditMetadata.tsx
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useItem } from '../../app/queries';
|
||||
import { openDialog } from '../../app/actions';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader, Segmented } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
type Tab = 'general' | 'tags' | 'artwork';
|
||||
|
||||
const FIELDS: { key: string; label: string; types: string[]; multiline?: boolean; type?: string }[] = [
|
||||
{ key: 'title', label: 'Title', types: ['movie', 'show', 'season', 'episode', 'collection'] },
|
||||
{ key: 'titleSort', label: 'Sort title', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'originalTitle', label: 'Original title', types: ['movie', 'show'] },
|
||||
{ key: 'originallyAvailableAt', label: 'Release date', types: ['movie', 'show', 'episode'], type: 'date' },
|
||||
{ key: 'contentRating', label: 'Content rating', types: ['movie', 'show', 'collection'] },
|
||||
{ key: 'studio', label: 'Studio', types: ['movie', 'show'] },
|
||||
{ key: 'tagline', label: 'Tagline', types: ['movie', 'show'] },
|
||||
{ key: 'summary', label: 'Summary', types: ['movie', 'show', 'season', 'episode', 'collection'], multiline: true },
|
||||
];
|
||||
|
||||
const TAGS: { key: string; label: string; source: keyof Item; types: string[] }[] = [
|
||||
{ key: 'genre', label: 'Genres', source: 'genres', types: ['movie', 'show'] },
|
||||
{ key: 'collection', label: 'Collections', source: 'collections', types: ['movie', 'show'] },
|
||||
{ key: 'label', label: 'Labels', source: 'labels', types: ['movie', 'show', 'episode', 'season', 'collection'] },
|
||||
{ key: 'director', label: 'Directors', source: 'directors', types: ['movie', 'episode'] },
|
||||
{ key: 'writer', label: 'Writers', source: 'writers', types: ['movie', 'episode'] },
|
||||
{ key: 'country', label: 'Countries', source: 'countries', types: ['movie', 'show'] },
|
||||
];
|
||||
|
||||
function TagEditor({ label, values, onChange, locked, onLock }: { label: string; values: string[]; onChange: (v: string[]) => void; locked: boolean; onLock: () => void }) {
|
||||
const [draft, setDraft] = useState('');
|
||||
const add = () => {
|
||||
const v = draft.trim();
|
||||
if (v && !values.includes(v)) onChange([...values, v]);
|
||||
setDraft('');
|
||||
};
|
||||
return (
|
||||
<div className="field">
|
||||
<span>
|
||||
{label}
|
||||
<LockToggle locked={locked} onClick={onLock} />
|
||||
</span>
|
||||
<div className="tag-editor">
|
||||
{values.map((v) => (
|
||||
<span key={v} className="chip">
|
||||
{v}
|
||||
<button aria-label={`Remove ${v}`} onClick={() => onChange(values.filter((x) => x !== v))}>
|
||||
<Icon name="x" size={12} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
<input
|
||||
value={draft}
|
||||
placeholder="Add…"
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ',') {
|
||||
e.preventDefault();
|
||||
add();
|
||||
} else if (e.key === 'Backspace' && !draft && values.length) onChange(values.slice(0, -1));
|
||||
}}
|
||||
onBlur={add}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LockToggle({ locked, onClick }: { locked: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button type="button" className={`lock-toggle${locked ? ' on' : ''}`} onClick={onClick} title={locked ? 'Locked: refreshes keep this value' : 'Unlocked: refreshes may replace this value'}>
|
||||
<Icon name={locked ? 'lock' : 'unlock'} size={12} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EditMetadataDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const full = useItem(initial.id);
|
||||
const item = full.data ?? initial;
|
||||
const [tab, setTab] = useState<Tab>('general');
|
||||
const [values, setValues] = useState<Record<string, string> | null>(null);
|
||||
const [tags, setTags] = useState<Record<string, string[]> | null>(null);
|
||||
const [locks, setLocks] = useState<Record<string, boolean>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const fields = FIELDS.filter((f) => f.types.includes(item.type));
|
||||
const tagFields = TAGS.filter((t) => t.types.includes(item.type));
|
||||
const lockedFields: Record<string, boolean> = Object.fromEntries((item.raw?.Field ?? []).map((f: any) => [f.name, !!f.locked]));
|
||||
|
||||
if (full.data && !values) {
|
||||
setValues(Object.fromEntries(fields.map((f) => [f.key, String(item.raw?.[f.key] ?? '')])));
|
||||
setTags(Object.fromEntries(tagFields.map((t) => [t.key, ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag)])));
|
||||
setLocks(lockedFields);
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
if (!values || !tags) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const changed: Record<string, string> = {};
|
||||
for (const f of fields) if ((values[f.key] ?? '') !== String(item.raw?.[f.key] ?? '')) changed[f.key] = values[f.key];
|
||||
const tagChanges: Record<string, { add: string[]; remove: string[] }> = {};
|
||||
for (const t of tagFields) {
|
||||
const before = ((item[t.source] as { tag: string }[]) ?? []).map((x) => x.tag);
|
||||
const after = tags[t.key];
|
||||
if (before.join('\u0000') !== after.join('\u0000')) tagChanges[t.key] = { add: after, remove: before.filter((b) => !after.includes(b)) };
|
||||
}
|
||||
const lockChanges: Record<string, boolean> = {};
|
||||
for (const [k, v] of Object.entries(locks)) if (!!lockedFields[k] !== v) lockChanges[k] = v;
|
||||
for (const k of [...Object.keys(changed), ...Object.keys(tagChanges)]) if (!(k in lockChanges)) lockChanges[k] = true;
|
||||
if (!Object.keys(changed).length && !Object.keys(tagChanges).length && !Object.keys(lockChanges).length) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
await api.editMetadata(server, item, changed, tagChanges, lockChanges);
|
||||
toast('Metadata saved', 'success');
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
title="Edit metadata"
|
||||
subtitle={`${item.title}${item.librarySectionTitle ? ` · ${item.librarySectionTitle}` : ''}`}
|
||||
onClose={onClose}
|
||||
width={760}
|
||||
className="edit-dialog"
|
||||
footer={
|
||||
<>
|
||||
<span className="dialog-note">
|
||||
<Icon name="lock" size={13} /> Edited fields are locked so metadata refreshes keep them.
|
||||
</span>
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" icon="check" busy={busy} onClick={save} disabled={!values}>
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<Segmented
|
||||
value={tab}
|
||||
onChange={setTab}
|
||||
options={[
|
||||
{ value: 'general', label: 'General' },
|
||||
...(tagFields.length ? [{ value: 'tags' as Tab, label: 'Tags' }] : []),
|
||||
{ value: 'artwork', label: 'Artwork' },
|
||||
]}
|
||||
className="dialog-tabs"
|
||||
/>
|
||||
{!values || !tags ? (
|
||||
<PageLoader />
|
||||
) : tab === 'general' ? (
|
||||
<div className="field-grid">
|
||||
{fields.map((f) => (
|
||||
<label key={f.key} className="field" style={f.multiline || f.key === 'title' || f.key === 'tagline' ? { gridColumn: '1 / -1' } : undefined}>
|
||||
<span>
|
||||
{f.label}
|
||||
<LockToggle locked={!!locks[f.key]} onClick={() => setLocks((l) => ({ ...l, [f.key]: !l[f.key] }))} />
|
||||
</span>
|
||||
{f.multiline ? (
|
||||
<textarea value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} rows={6} />
|
||||
) : (
|
||||
<input type={f.type ?? 'text'} value={values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
|
||||
)}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : tab === 'tags' ? (
|
||||
<div>
|
||||
{tagFields.map((t) => (
|
||||
<TagEditor key={t.key} label={t.label} values={tags[t.key]} onChange={(v) => setTags({ ...tags, [t.key]: v })} locked={!!locks[t.key]} onLock={() => setLocks((l) => ({ ...l, [t.key]: !l[t.key] }))} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="artwork-tab">
|
||||
{(
|
||||
[
|
||||
['poster', 'Poster', item.thumb, 'poster'],
|
||||
['art', 'Background', item.art, 'landscape'],
|
||||
['clearLogo', 'Logo', item.logo, 'logo'],
|
||||
] as const
|
||||
).map(([type, label, path, shape]) => (
|
||||
<button key={type} className={`artwork-choice ${shape}`} onClick={() => openDialog({ kind: 'artwork', item, type })}>
|
||||
<div className="artwork-choice-img">{path ? <img src={server.image(path, shape === 'poster' ? 200 : 360, shape === 'poster' ? 300 : 200, { format: shape === 'logo' ? 'png' : 'jpeg' })} alt="" /> : <Icon name="image" size={24} />}</div>
|
||||
<span>
|
||||
{label} <Icon name="next" size={13} />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
91
src/screens/dialogs/FixMatch.tsx
Normal file
91
src/screens/dialogs/FixMatch.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateItem, invalidateLibrary, useSections } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, EmptyState, Spinner } from '../../ui/primitives';
|
||||
|
||||
export function FixMatchDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const sections = useSections();
|
||||
const section = sections.data?.find((s) => s.id === item.librarySectionId);
|
||||
const [title, setTitle] = useState(item.title);
|
||||
const [year, setYear] = useState(item.year ? String(item.year) : '');
|
||||
const [results, setResults] = useState<api.MatchCandidate[] | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [applying, setApplying] = useState('');
|
||||
|
||||
const search = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setResults(await api.matches(server, item.id, { title, year, agent: section?.agent, language: section?.language }));
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
search();
|
||||
}, [section?.agent]);
|
||||
|
||||
const apply = async (m: api.MatchCandidate) => {
|
||||
setApplying(m.guid);
|
||||
try {
|
||||
await api.applyMatch(server, item.id, m.guid, m.name, m.year);
|
||||
toast(`Matched to “${m.name}”. Plex is updating its metadata.`, 'success');
|
||||
setTimeout(() => {
|
||||
invalidateItem(item.id);
|
||||
invalidateLibrary();
|
||||
}, 2500);
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setApplying('');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog title="Fix match" subtitle={`Choose the correct ${item.type === 'show' ? 'series' : 'movie'} for ${item.raw?.Media?.[0]?.Part?.[0]?.file?.split(/[\\/]/).pop() ?? item.title}`} onClose={onClose} width={720}>
|
||||
<form
|
||||
className="match-search"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
search();
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Title" />
|
||||
<input className="text-input year" value={year} onChange={(e) => setYear(e.target.value.replace(/\D/g, '').slice(0, 4))} placeholder="Year" />
|
||||
<Button variant="ghost" icon="search" busy={busy} type="submit">
|
||||
Search
|
||||
</Button>
|
||||
</form>
|
||||
<div className="match-results">
|
||||
{busy && !results && (
|
||||
<div className="center-pad">
|
||||
<Spinner />
|
||||
</div>
|
||||
)}
|
||||
{results && !results.length && <EmptyState icon="search" title="No matches found">Try a different title or year.</EmptyState>}
|
||||
{results?.map((m) => (
|
||||
<button key={m.guid} className="match-row" onClick={() => apply(m)} disabled={!!applying}>
|
||||
<div className="match-thumb">{m.thumb && <img src={m.thumb.startsWith('http') ? m.thumb : server.image(m.thumb, 80, 120)} alt="" />}</div>
|
||||
<div className="match-text">
|
||||
<b>
|
||||
{m.name} {m.year ? <span className="dim">({m.year})</span> : null}
|
||||
</b>
|
||||
{m.summary && <p>{m.summary}</p>}
|
||||
<small>
|
||||
{m.matched ? 'Current match · ' : ''}
|
||||
{m.score}% confidence
|
||||
</small>
|
||||
</div>
|
||||
{applying === m.guid && <Spinner size={18} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
101
src/screens/dialogs/Lists.tsx
Normal file
101
src/screens/dialogs/Lists.tsx
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { useState } from 'react';
|
||||
import * as api from '../../plex/api';
|
||||
import type { Item } from '../../plex/types';
|
||||
import { useServer } from '../../app/session';
|
||||
import { invalidateLibrary, useServerQuery } from '../../app/queries';
|
||||
import { Dialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Button, PageLoader } from '../../ui/primitives';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
|
||||
export function CollectionDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const collections = useServerQuery(['collections', item.librarySectionId], (s) => api.collections(s, item.librarySectionId), { enabled: !!item.librarySectionId });
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const current = new Set(item.collections.map((c) => c.tag));
|
||||
const add = async (title: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.addToCollection(server, item, title);
|
||||
toast(`Added to “${title}”`, 'success');
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to collection" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) add(name.trim());
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New collection name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{collections.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{collections.data?.map((c) => (
|
||||
<button key={c.id} className="list-pick-row" disabled={busy || current.has(c.title)} onClick={() => add(c.title)}>
|
||||
<Icon name="collection" size={17} />
|
||||
<span>{c.title}</span>
|
||||
{current.has(c.title) && <Icon name="check" size={15} className="dim" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlaylistDialog({ item, onClose }: { item: Item; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const playlists = useServerQuery(['playlists'], (s) => api.playlists(s));
|
||||
const [name, setName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Dialog title="Add to playlist" subtitle={item.title} onClose={onClose} width={480}>
|
||||
<form
|
||||
className="inline-create"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) run(() => api.createPlaylist(server, name.trim(), server.machineId, item.id), `Created “${name.trim()}”`);
|
||||
}}
|
||||
>
|
||||
<input className="text-input" value={name} onChange={(e) => setName(e.target.value)} placeholder="New playlist name" />
|
||||
<Button variant="ghost" icon="plus" type="submit" disabled={!name.trim() || busy}>
|
||||
Create
|
||||
</Button>
|
||||
</form>
|
||||
{playlists.isLoading && <PageLoader />}
|
||||
<div className="list-pick">
|
||||
{playlists.data?.map((p) => (
|
||||
<button key={p.id} className="list-pick-row" disabled={busy} onClick={() => run(() => api.addToPlaylist(server, p.id, server.machineId, item.id), `Added to “${p.title}”`)}>
|
||||
<Icon name="queue" size={17} />
|
||||
<span>{p.title}</span>
|
||||
<small className="dim">{p.leafCount ? `${p.leafCount} items` : ''}</small>
|
||||
</button>
|
||||
))}
|
||||
{playlists.data && !playlists.data.length && <p className="muted">No video playlists yet. Create one above.</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
109
src/screens/dialogs/MediaInfo.tsx
Normal file
109
src/screens/dialogs/MediaInfo.tsx
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
import type { Item, Stream } from '../../plex/types';
|
||||
import { useItem } from '../../app/queries';
|
||||
import { bitrate, channelLabel, date, duration, fileSize, resolutionLabel } from '../../app/format';
|
||||
import { Dialog } from '../../ui/overlays';
|
||||
import { PageLoader } from '../../ui/primitives';
|
||||
|
||||
function streamLine(s: Stream): string {
|
||||
if (s.streamType === 1)
|
||||
return [s.codec.toUpperCase(), s.profile, s.width && s.height ? `${s.width}×${s.height}` : '', s.frameRate ? `${s.frameRate} fps` : '', s.bitDepth ? `${s.bitDepth}-bit` : '', s.doviPresent ? 'Dolby Vision' : s.colorTrc === 'smpte2084' ? 'HDR10' : '', bitrate(s.bitrate)]
|
||||
.filter(Boolean)
|
||||
.join(' · ');
|
||||
if (s.streamType === 2) return [s.extendedDisplayTitle || s.displayTitle, s.samplingRate ? `${(s.samplingRate / 1000).toFixed(1)} kHz` : '', bitrate(s.bitrate)].filter(Boolean).join(' · ');
|
||||
return [s.extendedDisplayTitle || s.displayTitle, s.key ? 'External file' : 'Embedded'].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
export function MediaInfoDialog({ item: initial, onClose }: { item: Item; onClose: () => void }) {
|
||||
const q = useItem(initial.id);
|
||||
const item = q.data ?? initial;
|
||||
return (
|
||||
<Dialog title="Media info" subtitle={item.type === 'episode' ? `${item.grandparentTitle} · ${item.title}` : item.title} onClose={onClose} width={760}>
|
||||
{q.isLoading && <PageLoader />}
|
||||
<div className="media-info selectable">
|
||||
{item.media.map((m, mi) => (
|
||||
<section key={m.id} className="media-version">
|
||||
<h3>
|
||||
{item.media.length > 1 ? `Version ${mi + 1} · ` : ''}
|
||||
{[resolutionLabel(m), m.dynamicRange, m.container.toUpperCase()].filter(Boolean).join(' · ')}
|
||||
</h3>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Duration</span>
|
||||
<b>{duration(m.duration || item.duration)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Bitrate</span>
|
||||
<b>{bitrate(m.bitrate) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Video</span>
|
||||
<b>{[m.videoCodec.toUpperCase(), m.videoProfile, m.videoFrameRate].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Audio</span>
|
||||
<b>{[m.audioCodec.toUpperCase(), channelLabel(m.audioChannels)].filter(Boolean).join(' · ')}</b>
|
||||
</div>
|
||||
</div>
|
||||
{m.parts.map((p) => (
|
||||
<div key={p.id} className="media-part">
|
||||
<div className="media-file">
|
||||
<span>File</span>
|
||||
<code>{p.file || p.key}</code>
|
||||
</div>
|
||||
<div className="info-grid">
|
||||
<div>
|
||||
<span>Size</span>
|
||||
<b>{fileSize(p.size) || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Availability</span>
|
||||
<b>{p.exists === false ? 'Missing' : p.accessible === false ? 'Not accessible' : 'Available'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Previews</span>
|
||||
<b>{p.indexes.includes('sd') ? 'Generated' : 'Not generated'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<table className="stream-table">
|
||||
<tbody>
|
||||
{p.streams.map((s) => (
|
||||
<tr key={s.id}>
|
||||
<td>{s.streamType === 1 ? 'Video' : s.streamType === 2 ? 'Audio' : s.streamType === 3 ? 'Subtitle' : 'Other'}</td>
|
||||
<td>{streamLine(s)}</td>
|
||||
<td>{s.selected ? 'Selected' : s.default ? 'Default' : ''}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
<div className="info-grid footer">
|
||||
<div>
|
||||
<span>Library</span>
|
||||
<b>{item.librarySectionTitle || '—'}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Added</span>
|
||||
<b>{date(item.addedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Updated</span>
|
||||
<b>{date(item.updatedAt)}</b>
|
||||
</div>
|
||||
<div>
|
||||
<span>Plex ID</span>
|
||||
<b>{item.id}</b>
|
||||
</div>
|
||||
{item.guids.length > 0 && (
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
<span>External IDs</span>
|
||||
<b>{item.guids.join(' · ')}</b>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
81
src/screens/discover.ts
Normal file
81
src/screens/discover.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import * as api from '../plex/api';
|
||||
import type { Hub, Item } from '../plex/types';
|
||||
import type { Feature } from '../ui/Hero';
|
||||
import type { PlexServer } from '../plex/client';
|
||||
|
||||
/** One shuffle per app session keeps features stable while browsing. */
|
||||
const seed = Math.floor(Math.random() * 1e9);
|
||||
function shuffled<T>(list: T[], salt = 0): T[] {
|
||||
const out = [...list];
|
||||
let s = (seed + salt) % 2147483647 || 1;
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
s = (s * 48271) % 2147483647;
|
||||
const j = s % (i + 1);
|
||||
[out[i], out[j]] = [out[j], out[i]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const FEATURE_SOURCES: [RegExp, string][] = [
|
||||
[/recentlyreleased|recentlyaired/, 'Recently released'],
|
||||
[/topunwatched|toprated/, 'Highly rated'],
|
||||
[/recentlyadded/, 'Recently added'],
|
||||
[/startwatching/, 'Start watching'],
|
||||
[/curated|genre|by\.actor|moreingenre/, 'Recommended'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Features interleave recently released, highly rated unwatched and
|
||||
* Plex-recommended titles; they need artwork and skip in-progress titles.
|
||||
*/
|
||||
export function buildFeatures(hubs: Hub[], limit = 8, salt = 0): Feature[] {
|
||||
const pools: Feature[][] = FEATURE_SOURCES.map(([re, eyebrow]) =>
|
||||
shuffled(
|
||||
hubs
|
||||
.filter((h) => re.test(h.id))
|
||||
.flatMap((h) => h.items)
|
||||
.filter((i) => (i.type === 'movie' || i.type === 'show') && i.art && !i.viewOffset && i.summary)
|
||||
.map((item) => ({ item, eyebrow })),
|
||||
salt,
|
||||
),
|
||||
);
|
||||
const out: Feature[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (let round = 0; out.length < limit && round < 20; round++) {
|
||||
for (const pool of pools) {
|
||||
const f = pool[round];
|
||||
if (f && !seen.has(f.item.id) && out.length < limit) {
|
||||
seen.add(f.item.id);
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* New seasons, one card per show. Samples many seasons so a single series
|
||||
* import cannot fill the row.
|
||||
*/
|
||||
export async function recentSeasons(s: PlexServer, sectionId: string): Promise<Item[]> {
|
||||
const page = await api.libraryPage(s, sectionId, { type: 3, sort: 'addedAt:desc', start: 0, size: 100 });
|
||||
const byShow = new Map<string, Item[]>();
|
||||
for (const season of page.items) {
|
||||
if (!season.parentId) continue;
|
||||
const list = byShow.get(season.parentId) ?? [];
|
||||
list.push(season);
|
||||
byShow.set(season.parentId, list);
|
||||
}
|
||||
const out: Item[] = [];
|
||||
for (const [, seasons] of byShow) {
|
||||
if (out.length >= 18) break;
|
||||
// Several new seasons: show the series; one: the season itself.
|
||||
if (seasons.length > 1) {
|
||||
const first = seasons[0];
|
||||
out.push({ ...first, id: first.parentId, type: 'show', title: first.parentTitle, thumb: first.parentThumb || first.thumb, key: `/library/metadata/${first.parentId}/children` });
|
||||
} else out.push(seasons[0]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const HIDDEN_HUBS = /continue|ondeck|inprogress|playlists|music|photos|videos\.recent/;
|
||||
331
src/screens/settings/AppSettings.tsx
Normal file
331
src/screens/settings/AppSettings.tsx
Normal file
|
|
@ -0,0 +1,331 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useSettings, QUALITY_LABEL, type Quality, type SkipMode, type SubtitleMode } from '../../app/settings';
|
||||
import { useSession } from '../../app/session';
|
||||
import { useSections } from '../../app/queries';
|
||||
import { useDownloads } from '../../downloads/store';
|
||||
import { appInfo, isNative, openExternal, pickFolder, revealPath, type AppInfo } from '../../platform/native';
|
||||
import { checkForUpdate, installUpdate, useUpdater } from '../../app/updater';
|
||||
import { Button, Select, Switch } from '../../ui/primitives';
|
||||
import { confirmDialog } from '../../ui/overlays';
|
||||
import { Pref, SettingsSection } from './parts';
|
||||
import { KaleidoMark } from '../../ui/primitives';
|
||||
|
||||
const LANGUAGES: [string, string][] = [
|
||||
['', 'Automatic'],
|
||||
['eng', 'English'],
|
||||
['spa', 'Spanish'],
|
||||
['fre', 'French'],
|
||||
['ger', 'German'],
|
||||
['ita', 'Italian'],
|
||||
['por', 'Portuguese'],
|
||||
['jpn', 'Japanese'],
|
||||
['kor', 'Korean'],
|
||||
['chi', 'Chinese'],
|
||||
['rus', 'Russian'],
|
||||
['hin', 'Hindi'],
|
||||
['ara', 'Arabic'],
|
||||
['dut', 'Dutch'],
|
||||
['swe', 'Swedish'],
|
||||
['nor', 'Norwegian'],
|
||||
['dan', 'Danish'],
|
||||
['fin', 'Finnish'],
|
||||
['pol', 'Polish'],
|
||||
['tur', 'Turkish'],
|
||||
];
|
||||
|
||||
const qualityOptions = (Object.keys(QUALITY_LABEL) as Quality[]).map((q) => ({ value: q, label: QUALITY_LABEL[q] }));
|
||||
const skipOptions: { value: SkipMode; label: string }[] = [
|
||||
{ value: 'button', label: 'Show a button' },
|
||||
{ value: 'auto', label: 'Skip automatically' },
|
||||
{ value: 'off', label: 'Off' },
|
||||
];
|
||||
|
||||
const SHORTCUTS: [string, string][][] = [
|
||||
[
|
||||
['Ctrl + K', 'Search'],
|
||||
['Alt + ← / Mouse back', 'Go back'],
|
||||
['Alt + → / Mouse forward', 'Go forward'],
|
||||
['Esc', 'Go back or close a dialog'],
|
||||
['F11', 'Full screen'],
|
||||
['Ctrl + ,', 'Settings'],
|
||||
['Right-click a title', 'Title actions'],
|
||||
],
|
||||
[
|
||||
['Space or K', 'Play / pause'],
|
||||
['← / →', 'Seek back / forward'],
|
||||
['Shift + ← / →', 'Seek one minute'],
|
||||
['J / L', 'Seek 10 seconds'],
|
||||
['↑ / ↓ or scroll', 'Volume'],
|
||||
['M', 'Mute'],
|
||||
['F or double-click', 'Full screen'],
|
||||
['C', 'Next subtitle track'],
|
||||
['Shift + N', 'Next episode'],
|
||||
['0–9', 'Jump to 0–90%'],
|
||||
['Esc', 'Exit full screen, then the player'],
|
||||
],
|
||||
];
|
||||
|
||||
export function AppSettings({ tab }: { tab: string }) {
|
||||
const s = useSettings();
|
||||
const set = s.set;
|
||||
const session = useSession();
|
||||
const sections = useSections();
|
||||
const downloads = useDownloads();
|
||||
const [info, setInfo] = useState<AppInfo | null>(null);
|
||||
const updater = useUpdater();
|
||||
useEffect(() => {
|
||||
appInfo().then(setInfo);
|
||||
}, []);
|
||||
const movieLibs = (sections.data ?? []).filter((x) => x.type === 'movie');
|
||||
const showLibs = (sections.data ?? []).filter((x) => x.type === 'show');
|
||||
|
||||
switch (tab) {
|
||||
case 'general':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Account" description="Your Plex account and the server Kaleido is browsing.">
|
||||
<Pref label={session.user?.title ?? 'Signed in with a server token'} description={session.user?.email || 'Manual connection'}>
|
||||
<Button variant="ghost" size="sm" icon="logout" onClick={() => confirmDialog({ title: 'Sign out of Plex?', message: 'Downloads stay on this computer. You can sign in again at any time.', confirm: 'Sign out' }).then((ok) => void (ok && session.signOut()))}>
|
||||
Sign out
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref
|
||||
label="Server"
|
||||
description={
|
||||
session.server
|
||||
? `${session.server.name} · ${session.connection?.relay ? 'Plex Relay' : session.connection?.local ? 'Local network' : 'Remote'} · ${session.server.uri.replace(/X-Plex-Token=[^&]+/, '')}`
|
||||
: ''
|
||||
}
|
||||
>
|
||||
<Button variant="ghost" size="sm" icon="swap" onClick={session.showServerPicker} disabled={!session.accountToken}>
|
||||
Change
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Browsing">
|
||||
<Pref label="Start on" description="The page Kaleido opens to.">
|
||||
<Select
|
||||
value={s.startPage}
|
||||
onChange={(v) => set('startPage', v)}
|
||||
options={[
|
||||
{ value: 'home', label: 'Home' },
|
||||
{ value: 'movies', label: 'Movies' },
|
||||
{ value: 'shows', label: 'TV Shows' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
{movieLibs.length > 1 && (
|
||||
<Pref label="Movies library" description="The library shown in Movies.">
|
||||
<Select value={s.movieSection || movieLibs[0].id} onChange={(v) => set('movieSection', v)} options={movieLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
{showLibs.length > 1 && (
|
||||
<Pref label="TV Shows library" description="The library shown in TV Shows.">
|
||||
<Select value={s.showSection || showLibs[0].id} onChange={(v) => set('showSection', v)} options={showLibs.map((l) => ({ value: l.id, label: l.title }))} />
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Mark as watched at" description="How far into a title playback counts as watched. This belongs to Kaleido and doesn’t change your server.">
|
||||
<Select value={s.watchedPercent} onChange={(v) => set('watchedPercent', v)} options={[70, 75, 80, 85, 90, 95].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'playback':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Quality" description="Original quality plays the source file directly; Kaleido decodes nearly every format, so Plex rarely needs to convert.">
|
||||
<Pref label="On your local network">
|
||||
<Select value={s.quality} onChange={(v) => set('quality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Away from home" description="Used when the server is reached remotely or through Plex Relay.">
|
||||
<Select value={s.remoteQuality} onChange={(v) => set('remoteQuality', v)} options={qualityOptions} />
|
||||
</Pref>
|
||||
<Pref label="Hardware decoding" description="Uses your graphics card to decode video. Turn off only if you see artifacts. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hwdec} onChange={(v) => set('hwdec', v)} />
|
||||
</Pref>
|
||||
<Pref label="HDR passthrough" description="Sends HDR video to HDR-capable displays when Windows HDR is on. Applies after restarting Kaleido.">
|
||||
<Switch checked={s.hdrPassthrough} onChange={(v) => set('hdrPassthrough', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Episodes and markers" description="Intro and credits markers come from your Plex server’s analysis.">
|
||||
<Pref label="Skip intros">
|
||||
<Select value={s.skipIntro} onChange={(v) => set('skipIntro', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Skip credits">
|
||||
<Select value={s.skipCredits} onChange={(v) => set('skipCredits', v)} options={skipOptions} />
|
||||
</Pref>
|
||||
<Pref label="Play the next episode automatically">
|
||||
<Switch checked={s.autoplayNext} onChange={(v) => set('autoplayNext', v)} />
|
||||
</Pref>
|
||||
<Pref label="Countdown" description="Seconds before the next episode starts.">
|
||||
<Select value={s.countdownSeconds} disabled={!s.autoplayNext} onChange={(v) => set('countdownSeconds', v)} options={[5, 8, 10, 15, 20, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
<Pref label="Arrow-key seek">
|
||||
<Select value={s.seekStep} onChange={(v) => set('seekStep', v)} options={[5, 10, 15, 30].map((v) => ({ value: v, label: `${v} seconds` }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'subtitles':
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Audio">
|
||||
<Pref label="Preferred audio language" description="Automatic follows the track Plex selects for each title.">
|
||||
<Select value={s.audioLanguage} onChange={(v) => set('audioLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Subtitles">
|
||||
<Pref label="Show subtitles">
|
||||
<Select<SubtitleMode>
|
||||
value={s.subtitleMode}
|
||||
onChange={(v) => set('subtitleMode', v)}
|
||||
options={[
|
||||
{ value: 'auto', label: 'As chosen in Plex' },
|
||||
{ value: 'forced', label: 'Forced subtitles only' },
|
||||
{ value: 'always', label: 'Always' },
|
||||
{ value: 'off', label: 'Never' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Subtitle language" description="Automatic uses the language of the audio track.">
|
||||
<Select value={s.subtitleLanguage} onChange={(v) => set('subtitleLanguage', v)} options={LANGUAGES.map(([value, label]) => ({ value, label }))} />
|
||||
</Pref>
|
||||
<Pref label="Size">
|
||||
<Select
|
||||
value={s.subtitleScale}
|
||||
onChange={(v) => set('subtitleScale', v)}
|
||||
options={[
|
||||
{ value: 0.8, label: 'Small' },
|
||||
{ value: 1, label: 'Normal' },
|
||||
{ value: 1.25, label: 'Large' },
|
||||
{ value: 1.5, label: 'Extra large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Background box" description="Draws text subtitles on a dark box for contrast.">
|
||||
<Switch checked={s.subtitleBackground} onChange={(v) => set('subtitleBackground', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
case 'interface':
|
||||
return (
|
||||
<SettingsSection title="Interface" description="Kaleido keeps the same artwork-led look as its TV app.">
|
||||
<Pref label="Artwork colour wash" description="Tints pages with colors from the title’s artwork.">
|
||||
<Switch checked={s.colorWash} onChange={(v) => set('colorWash', v)} />
|
||||
</Pref>
|
||||
<Pref label="Rotate featured titles" description="Cycles the featured title on Home and Discover every 12 seconds.">
|
||||
<Switch checked={s.heroRotation} onChange={(v) => set('heroRotation', v)} />
|
||||
</Pref>
|
||||
<Pref label="Poster size" description="Card size in library grids.">
|
||||
<Select
|
||||
value={s.posterSize}
|
||||
onChange={(v) => set('posterSize', v)}
|
||||
options={[
|
||||
{ value: 'compact', label: 'Compact' },
|
||||
{ value: 'comfortable', label: 'Comfortable' },
|
||||
{ value: 'large', label: 'Large' },
|
||||
]}
|
||||
/>
|
||||
</Pref>
|
||||
<Pref label="Theme music" description="Plays a show or movie’s theme on its page.">
|
||||
<Switch checked={s.themeMusic} onChange={(v) => set('themeMusic', v)} />
|
||||
</Pref>
|
||||
<Pref label="Theme music volume">
|
||||
<Select value={s.themeVolume} disabled={!s.themeMusic} onChange={(v) => set('themeVolume', v)} options={[15, 30, 50, 75, 100].map((v) => ({ value: v, label: `${v}%` }))} />
|
||||
</Pref>
|
||||
<Pref label="Reduce motion" description="Turns off transitions and animations.">
|
||||
<Switch checked={s.reducedMotion} onChange={(v) => set('reducedMotion', v)} />
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'downloads':
|
||||
return (
|
||||
<SettingsSection title="Offline media" description="Downloads keep the original file, so they play exactly as on your server.">
|
||||
<Pref label="Download folder" description={downloads.dir || info?.defaultDownloadDir || 'Not set'}>
|
||||
<Button variant="ghost" size="sm" icon="folder" disabled={!isNative} onClick={async () => {
|
||||
const dir = await pickFolder(downloads.dir);
|
||||
if (dir) await downloads.setDir(dir);
|
||||
}}>
|
||||
Change
|
||||
</Button>
|
||||
{downloads.dir && (
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(downloads.dir)}>
|
||||
Open
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
<Pref label="Resume interrupted downloads" description="Downloads in progress when Kaleido closed continue automatically when it reconnects.">
|
||||
<span className="muted">Always</span>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
);
|
||||
case 'shortcuts':
|
||||
return (
|
||||
<div className="shortcut-columns">
|
||||
{SHORTCUTS.map((group, i) => (
|
||||
<SettingsSection key={i} title={i === 0 ? 'Browsing' : 'Player'}>
|
||||
{group.map(([k, label]) => (
|
||||
<Pref key={label} label={label}>
|
||||
<span className="kbd">{k}</span>
|
||||
</Pref>
|
||||
))}
|
||||
</SettingsSection>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
case 'about':
|
||||
return (
|
||||
<>
|
||||
<div className="about-app">
|
||||
<KaleidoMark size={56} />
|
||||
<div>
|
||||
<h2>Kaleido</h2>
|
||||
<p className="muted">
|
||||
Version {info?.version ?? '—'} · {info?.platform === 'windows' ? 'Windows' : info?.platform}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<SettingsSection title="Updates" description="Kaleido checks for new versions when it starts and installs them with your permission.">
|
||||
<Pref
|
||||
label={updater.available ? `Kaleido ${updater.available.version} is available` : updater.checking ? 'Checking…' : 'You’re up to date'}
|
||||
description={updater.error || (updater.available?.notes ? updater.available.notes : updater.checkedAt ? `Last checked ${new Date(updater.checkedAt).toLocaleTimeString()}` : '')}
|
||||
>
|
||||
{updater.available ? (
|
||||
<Button variant="primary" size="sm" icon="download" busy={updater.installing} onClick={installUpdate}>
|
||||
{updater.installing ? `Installing ${Math.round(updater.progress * 100)}%` : 'Install and restart'}
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={updater.checking} disabled={!isNative} onClick={() => checkForUpdate(true)}>
|
||||
Check now
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Information">
|
||||
<Pref label="Plex client identifier" description={localStorage.getItem('kaleido.clientId') ?? ''} />
|
||||
{info?.dataDir && (
|
||||
<Pref label="App data" description={info.dataDir}>
|
||||
<Button variant="ghost" size="sm" onClick={() => revealPath(info.dataDir)}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
)}
|
||||
<Pref label="Source code" description="git.elijahkuntz.com/Elijah/Kaleido-Desktop">
|
||||
<Button variant="ghost" size="sm" icon="external" onClick={() => openExternal('https://git.elijahkuntz.com/Elijah/Kaleido-Desktop')}>
|
||||
Open
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Reset preferences" description="Restores Kaleido’s settings. Your sign-in and downloads are kept.">
|
||||
<Button variant="ghost" size="sm" onClick={() => confirmDialog({ title: 'Reset preferences?', message: 'Playback, subtitle and interface settings return to their defaults.', confirm: 'Reset' }).then((ok) => ok && s.reset())}>
|
||||
Reset
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<p className="legal">Kaleido is an independent project and is not affiliated with Plex. Video playback uses mpv (libmpv), licensed under the LGPL.</p>
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
255
src/screens/settings/ServerDashboard.tsx
Normal file
255
src/screens/settings/ServerDashboard.tsx
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
import { useMemo } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import * as api from '../../plex/api';
|
||||
import { useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { bitrate, clock, episodeLabel, relativeTime } from '../../app/format';
|
||||
import { Artwork, Button, EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { promptDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, StatTile } from './parts';
|
||||
|
||||
function AreaChart({ series, height = 150, max, format }: { series: { values: number[]; color: string; label: string }[]; height?: number; max?: number; format: (v: number) => string }) {
|
||||
const n = Math.max(...series.map((s) => s.values.length), 2);
|
||||
const top = Math.max(max ?? 0, ...series.flatMap((s) => s.values), 1);
|
||||
const W = 920;
|
||||
const path = (values: number[]) => values.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (n - 1)) * W).toFixed(1)} ${(height - 6 - (v / top) * (height - 16)).toFixed(1)}`).join(' ');
|
||||
return (
|
||||
<div className="chart">
|
||||
<svg viewBox={`0 0 ${W} ${height}`} preserveAspectRatio="none" className="chart-svg" role="img">
|
||||
<defs>
|
||||
{series.map((s, i) => (
|
||||
<linearGradient key={i} id={`g${i}${s.label}`} x1="0" x2="0" y1="0" y2="1">
|
||||
<stop stopColor={s.color} stopOpacity=".28" />
|
||||
<stop offset="1" stopColor={s.color} stopOpacity="0" />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
{[0.25, 0.5, 0.75, 1].map((f) => (
|
||||
<path key={f} d={`M0 ${(height - 6 - f * (height - 16)).toFixed(1)} H${W}`} stroke="rgba(255,255,255,.08)" strokeWidth="1" vectorEffect="non-scaling-stroke" />
|
||||
))}
|
||||
{series.map((s, i) =>
|
||||
s.values.length > 1 ? (
|
||||
<g key={i}>
|
||||
<path d={`${path(s.values)} L${(((s.values.length - 1) / (n - 1)) * W).toFixed(1)} ${height} L0 ${height} Z`} fill={`url(#g${i}${s.label})`} />
|
||||
<path d={path(s.values)} stroke={s.color} strokeWidth="2" fill="none" vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
|
||||
</g>
|
||||
) : null,
|
||||
)}
|
||||
</svg>
|
||||
<div className="chart-footer">
|
||||
<div className="legend">
|
||||
{series.map((s) => (
|
||||
<span key={s.label}>
|
||||
<i style={{ background: s.color }} />
|
||||
{s.label} {s.values.length ? format(s.values[s.values.length - 1]) : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<span>Peak {format(top)}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NowPlaying({ session, onStop }: { session: admin.Session; onStop: () => void }) {
|
||||
const server = useServer();
|
||||
const item = session.item;
|
||||
const poster = item.type === 'episode' ? item.grandparentThumb : item.thumb;
|
||||
const pct = item.duration ? (session.viewOffset / item.duration) * 100 : 0;
|
||||
const d = session.decision;
|
||||
const mode = !d ? 'Direct play' : d.video === 'transcode' ? 'Transcoding video' : d.audio === 'transcode' ? 'Transcoding audio' : 'Direct stream';
|
||||
return (
|
||||
<div className="now-playing">
|
||||
<div className="np-poster">
|
||||
<Artwork src={server.image(poster, 90, 135)} />
|
||||
</div>
|
||||
<div className="np-body">
|
||||
<h3>{item.type === 'episode' ? item.grandparentTitle : item.title}</h3>
|
||||
<p>{item.type === 'episode' ? `${episodeLabel(item)} · ${item.title}` : item.year || ''}</p>
|
||||
<p className="dim">
|
||||
{session.user.title} · {session.player.title || session.player.product} ({session.player.platform}) · {session.player.local ? 'Local' : 'Remote'} {session.player.address}
|
||||
</p>
|
||||
<div className="np-progress">
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
<span className="dim">
|
||||
{session.player.state === 'paused' ? 'Paused · ' : session.player.state === 'buffering' ? 'Buffering · ' : ''}
|
||||
{clock(session.viewOffset / 1000)} / {clock(item.duration / 1000)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="np-pills">
|
||||
<span className={`stream-pill${d?.video === 'transcode' ? ' warn' : ''}`}>
|
||||
<Icon name={d ? 'cpu' : 'check'} size={13} />
|
||||
{mode}
|
||||
{d?.transcodeHw ? ' (hw)' : ''}
|
||||
</span>
|
||||
{session.bandwidth > 0 && <span className="stream-pill neutral">{bitrate(session.bandwidth)}</span>}
|
||||
{d && d.speed > 0 && <span className="stream-pill neutral">{d.speed.toFixed(1)}× {d.throttled ? 'throttled' : ''}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="x" onClick={onStop}>
|
||||
Stop
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Dashboard() {
|
||||
const server = useServer();
|
||||
const sessions = useServerQuery(['sessions'], (s) => admin.sessions(s), { refetchInterval: 5000, staleTime: 0 });
|
||||
const bw = useServerQuery(['bandwidth'], (s) => admin.bandwidth(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
||||
const res = useServerQuery(['resources'], (s) => admin.resources(s, 6), { refetchInterval: 6000, staleTime: 0 });
|
||||
const info = useServerQuery(['serverInfo'], (s) => api.serverInfo(s), { staleTime: 60_000 });
|
||||
const sections = useServerQuery(['sections'], (s) => api.sections(s));
|
||||
const remote = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { staleTime: 60_000 });
|
||||
|
||||
const list = sessions.data ?? [];
|
||||
const transcodes = list.filter((s) => s.decision?.video === 'transcode').length;
|
||||
const points = (bw.data?.points ?? []).slice(-40);
|
||||
const toMbps = (bytes: number) => (bytes * 8) / 6 / 1e6;
|
||||
const lan = points.map((p) => toMbps(p.lan));
|
||||
const wan = points.map((p) => toMbps(p.wan));
|
||||
const r = (res.data ?? []).slice(-40);
|
||||
const cpu = r[r.length - 1];
|
||||
const totalBandwidth = list.reduce((a, s) => a + s.bandwidth, 0);
|
||||
|
||||
const stop = async (s: admin.Session) => {
|
||||
const reason = await promptDialog({
|
||||
title: 'Stop this stream?',
|
||||
message: `${s.user.title} will see this message on ${s.player.title || s.player.product}.`,
|
||||
confirm: 'Stop stream',
|
||||
danger: true,
|
||||
input: { label: 'Message', value: 'The server owner has ended this stream.' },
|
||||
});
|
||||
if (reason === null) return;
|
||||
try {
|
||||
await admin.terminateSession(server, s.sessionId, reason);
|
||||
toast('Stream stopped', 'success');
|
||||
sessions.refetch();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
|
||||
const mc = info.data ?? {};
|
||||
return (
|
||||
<>
|
||||
<div className="stats-grid">
|
||||
<StatTile label="Active streams" value={list.length} detail={list.length ? `${list.length - transcodes} direct · ${transcodes} transcoding` : 'Nothing playing'} />
|
||||
<StatTile label="Streaming bandwidth" value={totalBandwidth ? bitrate(totalBandwidth) : '0 Mbps'} detail={`${list.filter((s) => !s.player.local).length} remote`} />
|
||||
<StatTile label="Server CPU" value={cpu ? `${Math.round(cpu.hostCpu)}%` : '—'} detail={cpu ? `Plex ${cpu.processCpu.toFixed(1)}%` : ''} tone={cpu && cpu.hostCpu > 85 ? 'warn' : undefined} />
|
||||
<StatTile label="Remote access" value={remote.data?.mappingState === 'mapped' ? 'Online' : 'Limited'} detail={remote.data?.publicAddress ?? ''} tone={remote.data?.mappingState === 'mapped' ? 'good' : 'warn'} />
|
||||
</div>
|
||||
<Card title="Now playing" actions={<span className="status-tag"><i className="dot" />{list.length} active</span>}>
|
||||
{sessions.isLoading && <PageLoader />}
|
||||
{sessions.data && !list.length && <p className="muted np-empty">No one is watching right now.</p>}
|
||||
{list.map((s) => (
|
||||
<NowPlaying key={s.sessionKey} session={s} onStop={() => stop(s)} />
|
||||
))}
|
||||
</Card>
|
||||
<div className="admin-2-col">
|
||||
<Card title="Bandwidth" actions={<span className="note">Last few minutes · live</span>}>
|
||||
<AreaChart
|
||||
series={[
|
||||
{ values: wan, color: '#6797f5', label: 'Remote' },
|
||||
{ values: lan, color: '#e0ad5d', label: 'Local' },
|
||||
]}
|
||||
format={(v) => `${v.toFixed(1)} Mbps`}
|
||||
/>
|
||||
</Card>
|
||||
<Card title="Resources" actions={<span className="note">Host CPU and memory</span>}>
|
||||
<AreaChart
|
||||
series={[
|
||||
{ values: r.map((p) => p.hostCpu), color: '#8fc7a8', label: 'CPU' },
|
||||
{ values: r.map((p) => p.hostMemory), color: '#b49ae8', label: 'Memory' },
|
||||
]}
|
||||
max={100}
|
||||
format={(v) => `${Math.round(v)}%`}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
<Card title="Server">
|
||||
<div className="server-info">
|
||||
{[
|
||||
['Name', mc.friendlyName],
|
||||
['Version', String(mc.version ?? '').split('-')[0]],
|
||||
['Platform', [mc.platform, mc.platformVersion].filter(Boolean).join(' ')],
|
||||
['Libraries', (sections.data ?? []).map((s) => s.title).join(', ')],
|
||||
['Plex Pass', mc.myPlexSubscription ? 'Active' : 'Not active'],
|
||||
['Signed in as', mc.myPlexUsername],
|
||||
['Transcoder', mc.transcoderVideo ? 'Video, audio' : 'Available'],
|
||||
['Connection', server.uri.replace(/^https?:\/\//, '')],
|
||||
].map(([k, v]) => (
|
||||
<div key={k as string}>
|
||||
<span>{k}</span>
|
||||
<b>{(v as string) || '—'}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Activity() {
|
||||
const server = useServer();
|
||||
const activities = useServerQuery(['activities'], (s) => admin.activities(s), { refetchInterval: 3000, staleTime: 0 });
|
||||
const history = useServerQuery(['history'], (s) => admin.history(s, 40), { staleTime: 15_000 });
|
||||
const accounts = useServerQuery(['accounts'], (s) => admin.accounts(s), { staleTime: 10 * 60_000 });
|
||||
const devices = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 10 * 60_000 });
|
||||
const deviceName = useMemo(() => Object.fromEntries((devices.data ?? []).map((d) => [d.id, d.name])), [devices.data]);
|
||||
return (
|
||||
<>
|
||||
<Card title="Running now" actions={<span className="note">Scans, analysis and maintenance</span>}>
|
||||
{activities.data && !activities.data.length && <p className="muted np-empty">The server is idle.</p>}
|
||||
{activities.data?.map((a) => (
|
||||
<div key={a.uuid} className="activity-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name={a.type.includes('library') ? 'refresh' : a.type.includes('media') ? 'film' : 'activity'} size={17} />
|
||||
</div>
|
||||
<div className="activity-text">
|
||||
<strong>{a.title}</strong>
|
||||
<small>{a.subtitle}</small>
|
||||
{a.progress > 0 && (
|
||||
<span className="progress-bar">
|
||||
<i style={{ width: `${a.progress}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{a.cancellable && (
|
||||
<Button variant="ghost" size="sm" onClick={() => admin.cancelActivity(server, a.uuid).then(() => activities.refetch(), toastError)}>
|
||||
Cancel
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
<Card title="Watch history">
|
||||
{history.isLoading && <PageLoader />}
|
||||
{history.data && !history.data.length && <EmptyState icon="clock" title="No history yet" />}
|
||||
<div className="history-list">
|
||||
{history.data?.map((h) => (
|
||||
<div key={h.id + h.viewedAt} className="history-row">
|
||||
<div className="history-thumb">
|
||||
<Artwork src={server.image(h.thumb, 60, 90)} />
|
||||
</div>
|
||||
<div>
|
||||
<strong>{h.title}</strong>
|
||||
<small>{h.subtitle}</small>
|
||||
</div>
|
||||
<span className="dim">{accounts.data?.[h.accountId] ?? 'Owner'}</span>
|
||||
<span className="dim">{deviceName[h.deviceId] ?? ''}</span>
|
||||
<span className="dim">{relativeTime(h.viewedAt)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerDashboard({ tab }: { tab: 'dashboard' | 'activity' }) {
|
||||
return tab === 'dashboard' ? <Dashboard /> : <Activity />;
|
||||
}
|
||||
258
src/screens/settings/ServerLibraries.tsx
Normal file
258
src/screens/settings/ServerLibraries.tsx
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import type { Section } from '../../plex/types';
|
||||
import { invalidateLibrary, queryClient, useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { relativeTime } from '../../app/format';
|
||||
import { Button, PageLoader, Segmented, Select, Spinner } from '../../ui/primitives';
|
||||
import { confirmDialog, Dialog, openMenu, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card } from './parts';
|
||||
|
||||
function FolderPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) {
|
||||
const [stack, setStack] = useState<{ key?: string; title: string; path: string }[]>([{ title: 'Computer', path: '' }]);
|
||||
const current = stack[stack.length - 1];
|
||||
const q = useServerQuery(['browse', current.key ?? 'root'], (s) => admin.browse(s, current.key), { staleTime: 30_000 });
|
||||
return (
|
||||
<Dialog
|
||||
title="Choose a folder"
|
||||
subtitle={current.path || 'Folders on the server'}
|
||||
onClose={onClose}
|
||||
width={560}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" disabled={!current.path} onClick={() => (onPick(current.path), onClose())}>
|
||||
Use this folder
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="folder-crumbs">
|
||||
{stack.map((c, i) => (
|
||||
<button key={i} onClick={() => setStack(stack.slice(0, i + 1))}>
|
||||
{c.title}
|
||||
{i < stack.length - 1 && <Icon name="next" size={12} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="folder-list">
|
||||
{q.isLoading && <Spinner />}
|
||||
{q.data?.map((p) => (
|
||||
<button key={p.key} className="list-pick-row" onClick={() => setStack([...stack, { key: p.key, title: p.title, path: p.path }])}>
|
||||
<Icon name="folder" size={17} />
|
||||
<span>{p.title}</span>
|
||||
<Icon name="next" size={14} className="dim" />
|
||||
</button>
|
||||
))}
|
||||
{q.data && !q.data.length && <p className="muted">No subfolders.</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryDialog({ section, onClose }: { section?: Section; onClose: () => void }) {
|
||||
const server = useServer();
|
||||
const [type, setType] = useState<'movie' | 'show'>(section?.type === 'show' ? 'show' : 'movie');
|
||||
const [name, setName] = useState(section?.title ?? 'Movies');
|
||||
const [locations, setLocations] = useState<string[]>(section?.locations.map((l) => l.path) ?? []);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const agents = useServerQuery(['agents', type], (s) => admin.agents(s, type === 'movie' ? 1 : 2), { enabled: !section });
|
||||
const scanners = useServerQuery(['scanners', type], (s) => admin.scanners(s, type === 'movie' ? 1 : 2), { enabled: !section });
|
||||
const [agent, setAgent] = useState('');
|
||||
const [scanner, setScanner] = useState('');
|
||||
useEffect(() => {
|
||||
if (section) return;
|
||||
setName(type === 'movie' ? 'Movies' : 'TV Shows');
|
||||
setAgent('');
|
||||
setScanner('');
|
||||
}, [type]);
|
||||
const agentValue = agent || agents.data?.find((a) => a.identifier.startsWith('tv.plex.agents'))?.identifier || agents.data?.[0]?.identifier || '';
|
||||
const scannerValue = scanner || scanners.data?.find((s) => s.startsWith('Plex'))?.toString() || scanners.data?.[0] || '';
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
if (section) await admin.updateLibrary(server, section, { name, locations });
|
||||
else await admin.createLibrary(server, { name, type, agent: agentValue, scanner: scannerValue, language: navigator.language || 'en-US', locations });
|
||||
toast(section ? 'Library updated' : `Created “${name}”. Plex is scanning it now.`, 'success');
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'sections'] });
|
||||
invalidateLibrary();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
title={section ? `Edit ${section.title}` : 'Add a library'}
|
||||
onClose={onClose}
|
||||
width={600}
|
||||
footer={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" busy={busy} disabled={!name.trim() || !locations.length} onClick={save}>
|
||||
{section ? 'Save' : 'Add library'}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{!section && (
|
||||
<Segmented
|
||||
className="dialog-tabs"
|
||||
value={type}
|
||||
onChange={setType}
|
||||
options={[
|
||||
{ value: 'movie', label: 'Movies' },
|
||||
{ value: 'show', label: 'TV Shows' },
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<label className="field">
|
||||
<span>Name</span>
|
||||
<input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
{!section && (
|
||||
<div className="field-grid">
|
||||
<div className="field">
|
||||
<span>Metadata agent</span>
|
||||
<Select value={agentValue} options={(agents.data ?? []).map((a) => ({ value: a.identifier, label: a.name }))} onChange={setAgent} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<span>Scanner</span>
|
||||
<Select value={scannerValue} options={(scanners.data ?? []).map((s) => ({ value: s, label: s }))} onChange={setScanner} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="field">
|
||||
<span>Folders</span>
|
||||
<div className="folder-chosen">
|
||||
{locations.map((l) => (
|
||||
<div key={l} className="folder-row">
|
||||
<Icon name="folder" size={16} />
|
||||
<code>{l}</code>
|
||||
<button aria-label="Remove folder" onClick={() => setLocations(locations.filter((x) => x !== l))}>
|
||||
<Icon name="x" size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<Button variant="ghost" size="sm" icon="plus" onClick={() => setPicking(true)}>
|
||||
Add folder
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
{picking && <FolderPicker onClose={() => setPicking(false)} onPick={(p) => setLocations((l) => (l.includes(p) ? l : [...l, p]))} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryRow({ section }: { section: Section }) {
|
||||
const server = useServer();
|
||||
const size = useServerQuery(['librarySize', section.id], (s) => admin.librarySize(s, section), { staleTime: 60_000 });
|
||||
const [editing, setEditing] = useState(false);
|
||||
const act = async (fn: () => Promise<unknown>, done: string) => {
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
setTimeout(() => queryClient.invalidateQueries({ queryKey: [server.machineId, 'sections'] }), 1500);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
}
|
||||
};
|
||||
const icon = section.type === 'movie' ? 'film' : section.type === 'show' ? 'tv' : section.type === 'artist' ? 'audio' : 'image';
|
||||
const unit = section.type === 'movie' ? 'movies' : section.type === 'show' ? 'shows' : section.type === 'artist' ? 'artists' : 'items';
|
||||
return (
|
||||
<div className="library-manage-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name={icon} size={18} />
|
||||
</div>
|
||||
<div className="library-manage-text">
|
||||
<strong>
|
||||
{section.title}
|
||||
{section.refreshing && (
|
||||
<span className="scanning">
|
||||
<Spinner size={12} /> Scanning
|
||||
</span>
|
||||
)}
|
||||
</strong>
|
||||
<small>
|
||||
{size.data !== undefined ? `${size.data.toLocaleString()} ${unit}` : '…'} · Scanned {relativeTime(section.scannedAt) || 'never'}
|
||||
</small>
|
||||
<small className="dim">{section.locations.map((l) => l.path).join(' · ')}</small>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="refresh" onClick={() => act(() => admin.scanLibrary(server, section.id), `Scanning ${section.title}`)}>
|
||||
Scan
|
||||
</Button>
|
||||
<button
|
||||
className="icon-btn"
|
||||
aria-label="More"
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
[
|
||||
{ label: 'Scan library files', icon: 'scan', onSelect: () => act(() => admin.scanLibrary(server, section.id), `Scanning ${section.title}`) },
|
||||
{ label: 'Refresh all metadata', icon: 'refresh', onSelect: () => act(() => admin.scanLibrary(server, section.id, true), `Refreshing metadata for ${section.title}`) },
|
||||
{ label: 'Analyze', icon: 'activity', onSelect: () => act(() => admin.analyzeLibrary(server, section.id), `Analyzing ${section.title}`) },
|
||||
{ label: 'Empty trash', icon: 'trash', onSelect: () => act(() => admin.emptyTrash(server, section.id), 'Trash emptied') },
|
||||
...(section.refreshing ? [{ label: 'Cancel scan', icon: 'x', onSelect: () => act(() => admin.cancelScan(server, section.id), 'Scan cancelled') }] : []),
|
||||
{ divider: true },
|
||||
...(section.type === 'movie' || section.type === 'show' ? [{ label: 'Edit…', icon: 'edit', onSelect: () => setEditing(true) }] : []),
|
||||
{
|
||||
label: 'Delete library…',
|
||||
icon: 'trash',
|
||||
danger: true,
|
||||
onSelect: async () => {
|
||||
if (await confirmDialog({ title: `Delete “${section.title}”?`, message: 'The library and its metadata are removed from Plex. Your media files are not deleted.', confirm: 'Delete library', danger: true }))
|
||||
act(() => admin.deleteLibrary(server, section.id), 'Library deleted');
|
||||
},
|
||||
},
|
||||
],
|
||||
e.currentTarget,
|
||||
{ align: 'end' },
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
{editing && <LibraryDialog section={section} onClose={() => setEditing(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerLibraries() {
|
||||
const server = useServer();
|
||||
const sections = useServerQuery(['sections'], (s) => import('../../plex/api').then((m) => m.sections(s)), { refetchInterval: 5000, staleTime: 0 });
|
||||
const [adding, setAdding] = useState(false);
|
||||
if (!sections.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<Card
|
||||
title="Libraries"
|
||||
actions={
|
||||
<div className="actions">
|
||||
<Button variant="ghost" size="sm" icon="refresh" onClick={() => admin.scanAll(server).then(() => toast('Scanning all libraries', 'success'), toastError)}>
|
||||
Scan all
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" icon="plus" onClick={() => setAdding(true)}>
|
||||
Add library
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{sections.data.map((s) => (
|
||||
<LibraryRow key={s.id} section={s} />
|
||||
))}
|
||||
</Card>
|
||||
{adding && <LibraryDialog onClose={() => setAdding(false)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
218
src/screens/settings/ServerManage.tsx
Normal file
218
src/screens/settings/ServerManage.tsx
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import { useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { date } from '../../app/format';
|
||||
import { invoke, isNative, saveFile } from '../../platform/native';
|
||||
import { Button, PageLoader, Switch } from '../../ui/primitives';
|
||||
import { confirmDialog, toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, Pref, SettingsSection } from './parts';
|
||||
|
||||
function Devices() {
|
||||
const server = useServer();
|
||||
const q = useServerQuery(['devices'], (s) => admin.devices(s), { staleTime: 0 });
|
||||
const [filter, setFilter] = useState('');
|
||||
if (!q.data) return <PageLoader />;
|
||||
const list = q.data.filter((d) => !filter || `${d.name} ${d.platform}`.toLowerCase().includes(filter.toLowerCase())).sort((a, b) => b.createdAt - a.createdAt);
|
||||
return (
|
||||
<Card
|
||||
title={`Devices · ${q.data.length}`}
|
||||
actions={<input className="text-input compact" placeholder="Filter devices" value={filter} onChange={(e) => setFilter(e.target.value)} />}
|
||||
>
|
||||
<p className="muted card-lede">Apps and devices that have connected to this server. Removing one signs it out of this server.</p>
|
||||
{list.map((d) => (
|
||||
<div key={d.id} className="library-manage-row">
|
||||
<div className="lib-ico">
|
||||
<Icon name="monitor" size={17} />
|
||||
</div>
|
||||
<div className="library-manage-text">
|
||||
<strong>{d.name || 'Unnamed device'}</strong>
|
||||
<small>
|
||||
{d.platform || 'Unknown platform'} · First seen {date(d.createdAt)}
|
||||
</small>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={async () => {
|
||||
if (!(await confirmDialog({ title: `Remove ${d.name || 'this device'}?`, message: 'It will need to sign in again to use this server.', confirm: 'Remove', danger: true }))) return;
|
||||
admin.removeDevice(server, d.id).then(() => (toast('Device removed', 'success'), q.refetch()), toastError);
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Troubleshooting() {
|
||||
const server = useServer();
|
||||
const [busy, setBusy] = useState('');
|
||||
const run = async (key: string, fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(key);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy('');
|
||||
}
|
||||
};
|
||||
const download = async (key: string, path: string, name: string) => {
|
||||
if (!isNative) return toast('Saving files needs the desktop app.', 'error');
|
||||
const target = await saveFile(name);
|
||||
if (!target) return;
|
||||
await run(key, async () => {
|
||||
const bytes = await invoke<number>('save_url', { url: server.signed(path), path: target });
|
||||
return bytes;
|
||||
}, `Saved ${name}`);
|
||||
};
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
return (
|
||||
<>
|
||||
<SettingsSection title="Diagnostics" description="Share these with Plex support or keep them for your records.">
|
||||
<Pref label="Download logs" description="A zip of the server’s recent log files.">
|
||||
<Button variant="ghost" size="sm" icon="download" busy={busy === 'logs'} onClick={() => download('logs', '/diagnostics/logs', `Plex Media Server Logs ${stamp}.zip`)}>
|
||||
Download
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Download database" description="A copy of the library database (it can be large).">
|
||||
<Button variant="ghost" size="sm" icon="download" busy={busy === 'db'} onClick={() => download('db', '/diagnostics/databases', `Plex Media Server Databases ${stamp}.zip`)}>
|
||||
Download
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
<SettingsSection title="Maintenance">
|
||||
<Pref label="Clean bundles" description="Removes leftover metadata for media that no longer exists.">
|
||||
<Button variant="ghost" size="sm" busy={busy === 'bundles'} onClick={() => run('bundles', () => admin.cleanBundles(server), 'Cleaning bundles')}>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Optimize database" description="Compacts the database. Plex may be slow while this runs.">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
busy={busy === 'optimize'}
|
||||
onClick={async () =>
|
||||
(await confirmDialog({ title: 'Optimize the database?', message: 'Browsing may be slow until it finishes.', confirm: 'Optimize' })) && run('optimize', () => admin.optimizeDatabase(server), 'Optimizing the database')
|
||||
}
|
||||
>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
<Pref label="Empty trash in every library" description="Removes items whose files are gone.">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
busy={busy === 'trash'}
|
||||
onClick={() =>
|
||||
run(
|
||||
'trash',
|
||||
async () => {
|
||||
const secs = await import('../../plex/api').then((m) => m.sections(server));
|
||||
await Promise.all(secs.map((s) => admin.emptyTrash(server, s.id)));
|
||||
},
|
||||
'Emptied trash',
|
||||
)
|
||||
}
|
||||
>
|
||||
Run
|
||||
</Button>
|
||||
</Pref>
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface LogLine {
|
||||
level: number;
|
||||
message: string;
|
||||
at: number;
|
||||
}
|
||||
|
||||
const LEVELS = ['Error', 'Warning', 'Info', 'Debug', 'Verbose'];
|
||||
|
||||
function Console() {
|
||||
const server = useServer();
|
||||
const [lines, setLines] = useState<LogLine[]>([]);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [state, setState] = useState<'connecting' | 'live' | 'closed'>('connecting');
|
||||
const [verbose, setVerbose] = useState(false);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const pausedRef = useRef(paused);
|
||||
pausedRef.current = paused;
|
||||
|
||||
useEffect(() => {
|
||||
const url = server.signed('/:/websockets/notifications', { filters: 'log' }).replace(/^http/, 'ws');
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => setState('live');
|
||||
ws.onclose = () => setState('closed');
|
||||
ws.onerror = () => setState('closed');
|
||||
ws.onmessage = (e) => {
|
||||
if (pausedRef.current) return;
|
||||
try {
|
||||
const c = JSON.parse(e.data)?.NotificationContainer;
|
||||
const logs = (c?.LogSentNotification ?? c?.Log ?? []) as any[];
|
||||
if (!logs.length) return;
|
||||
setLines((prev) =>
|
||||
[...prev, ...logs.map((l) => ({ level: Number(l.level ?? 2), message: String(l.message ?? ''), at: Date.parse(l.time) || Date.now() }))].slice(-1500),
|
||||
);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
};
|
||||
return () => ws.close();
|
||||
}, [server]);
|
||||
|
||||
useEffect(() => {
|
||||
const el = box.current;
|
||||
if (el && !paused) el.scrollTop = el.scrollHeight;
|
||||
}, [lines, paused]);
|
||||
|
||||
const shown = lines.filter((l) => verbose || l.level <= 2);
|
||||
return (
|
||||
<Card
|
||||
title="Server console"
|
||||
actions={
|
||||
<div className="actions">
|
||||
<span className={`status-tag${state === 'live' ? '' : ' off'}`}>
|
||||
<i className="dot" />
|
||||
{state === 'live' ? 'Live' : state === 'connecting' ? 'Connecting' : 'Disconnected'}
|
||||
</span>
|
||||
<label className="inline-toggle">
|
||||
Debug
|
||||
<Switch checked={verbose} onChange={setVerbose} />
|
||||
</label>
|
||||
<Button variant="ghost" size="sm" icon={paused ? 'play' : 'pause'} onClick={() => setPaused(!paused)}>
|
||||
{paused ? 'Resume' : 'Pause'}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setLines([])}>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="console selectable" ref={box}>
|
||||
{!shown.length && <div className="dim">Waiting for server log messages…</div>}
|
||||
{shown.map((l, i) => (
|
||||
<div key={i} className={`console-line l${l.level}`}>
|
||||
<span className="console-time">{new Date(l.at).toLocaleTimeString()}</span>
|
||||
<span className="console-level">{LEVELS[l.level] ?? l.level}</span>
|
||||
<span>{l.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="note">Shows messages as the server writes them.</p>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerManage({ tab }: { tab: 'devices' | 'troubleshooting' | 'console' }) {
|
||||
if (tab === 'devices') return <Devices />;
|
||||
if (tab === 'troubleshooting') return <Troubleshooting />;
|
||||
return <Console />;
|
||||
}
|
||||
287
src/screens/settings/ServerPrefs.tsx
Normal file
287
src/screens/settings/ServerPrefs.tsx
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
import { useMemo, useState } from 'react';
|
||||
import * as admin from '../../plex/admin';
|
||||
import { queryClient, useServerQuery } from '../../app/queries';
|
||||
import { useServer } from '../../app/session';
|
||||
import { relativeTime } from '../../app/format';
|
||||
import { Button, ErrorState, PageLoader, Select, Switch } from '../../ui/primitives';
|
||||
import { toast, toastError } from '../../ui/overlays';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { Card, Pref, SettingsSection } from './parts';
|
||||
|
||||
/** Which Plex preference groups each page shows; Live TV/DVR and online sources are excluded. */
|
||||
const GROUPS: Record<string, { groups: string[]; title: string; description: string; exclude?: RegExp; include?: RegExp }> = {
|
||||
general: { groups: ['general'], title: 'Server identity', description: 'How this server identifies itself and reports problems.' },
|
||||
remote: { groups: [], title: 'Remote access', description: '' },
|
||||
library: { groups: ['library'], title: 'Library', description: 'How Plex watches folders, scans media and generates previews and markers.', exclude: /^Music|Photo|Camera/ },
|
||||
network: { groups: ['network'], title: 'Network', description: 'Connections, security and the networks treated as local.', exclude: /RemoteAccess|PublishServer|ManualPortMapping/ },
|
||||
transcoder: { groups: ['transcoder'], title: 'Transcoder', description: 'How the server converts video for devices that can’t play it directly.' },
|
||||
extras: { groups: ['extras'], title: 'Extras', description: 'Trailers and extras before movies, for clients that support cinema trailers.' },
|
||||
scheduled: { groups: ['butler'], title: 'Maintenance window', description: 'Plex runs background maintenance during these hours.' },
|
||||
dlna: { groups: ['dlna'], title: 'DLNA', description: 'Lets DLNA devices on your network browse and play this server’s media.' },
|
||||
};
|
||||
|
||||
function hourLabel(h: number) {
|
||||
const d = new Date();
|
||||
d.setHours(h, 0, 0, 0);
|
||||
return d.toLocaleTimeString([], { hour: 'numeric' });
|
||||
}
|
||||
|
||||
function SettingControl({ setting, value, onChange }: { setting: admin.ServerSetting; value: unknown; onChange: (v: string | number | boolean) => void }) {
|
||||
if (setting.type === 'bool') return <Switch checked={value === true || value === 'true' || value === 1} onChange={onChange} label={setting.label} />;
|
||||
if (setting.options) {
|
||||
return (
|
||||
<Select
|
||||
value={String(value)}
|
||||
options={setting.options.map((o) => ({ value: o.value, label: o.label }))}
|
||||
onChange={(v) => onChange(setting.type === 'int' ? Number(v) : v)}
|
||||
minWidth={200}
|
||||
className="pref-select"
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (/StartHour|EndHour/.test(setting.id)) {
|
||||
return <Select value={Number(value)} options={Array.from({ length: 24 }, (_, h) => ({ value: h, label: hourLabel(h) }))} onChange={onChange} />;
|
||||
}
|
||||
return (
|
||||
<input
|
||||
className="text-input pref-input"
|
||||
type={setting.type === 'int' || setting.type === 'double' ? 'number' : setting.id.toLowerCase().includes('password') ? 'password' : 'text'}
|
||||
value={String(value ?? '')}
|
||||
placeholder={setting.default !== undefined && setting.default !== '' ? String(setting.default) : ''}
|
||||
onChange={(e) => onChange(setting.type === 'int' || setting.type === 'double' ? (e.target.value === '' ? '' : Number(e.target.value)) as number : e.target.value)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function PrefsEditor({ tab }: { tab: string }) {
|
||||
const server = useServer();
|
||||
const cfg = GROUPS[tab];
|
||||
const q = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
||||
const [advanced, setAdvanced] = useState(false);
|
||||
const [edits, setEdits] = useState<Record<string, string | number | boolean>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const settings = useMemo(
|
||||
() => (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && (advanced || !x.advanced) && !(cfg.exclude && cfg.exclude.test(x.id))),
|
||||
[q.data, tab, advanced],
|
||||
);
|
||||
const advancedCount = (q.data ?? []).filter((x) => cfg.groups.includes(x.group) && !x.hidden && x.advanced).length;
|
||||
const dirty = Object.keys(edits).length > 0;
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await admin.setPrefs(server, edits);
|
||||
toast('Server settings saved', 'success');
|
||||
setEdits({});
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'serverPrefs'] });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (q.isError) return <ErrorState error={q.error} onRetry={() => q.refetch()} />;
|
||||
if (!q.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<SettingsSection
|
||||
title={cfg.title}
|
||||
description={cfg.description}
|
||||
actions={
|
||||
advancedCount > 0 && (
|
||||
<label className="inline-toggle">
|
||||
Show advanced
|
||||
<Switch checked={advanced} onChange={setAdvanced} />
|
||||
</label>
|
||||
)
|
||||
}
|
||||
>
|
||||
{settings.map((s) => (
|
||||
<Pref key={s.id} label={s.label} description={s.summary}>
|
||||
<SettingControl setting={s} value={s.id in edits ? edits[s.id] : s.value} onChange={(v) => setEdits((e) => (v === s.value ? (({ [s.id]: _, ...rest }) => rest)(e) : { ...e, [s.id]: v }))} />
|
||||
</Pref>
|
||||
))}
|
||||
{!settings.length && <p className="muted">No settings in this group.</p>}
|
||||
</SettingsSection>
|
||||
<div className={`save-bar${dirty ? ' show' : ''}`}>
|
||||
<span>
|
||||
{Object.keys(edits).length} unsaved change{Object.keys(edits).length === 1 ? '' : 's'}
|
||||
</span>
|
||||
<Button variant="ghost" size="sm" onClick={() => setEdits({})}>
|
||||
Discard
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" icon="check" busy={busy} onClick={save}>
|
||||
Save changes
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoteAccess() {
|
||||
const server = useServer();
|
||||
const status = useServerQuery(['remoteAccess'], (s) => admin.remoteAccess(s), { refetchInterval: 10000, staleTime: 0 });
|
||||
const prefs = useServerQuery(['serverPrefs'], (s) => admin.prefs(s), { staleTime: 0 });
|
||||
const get = (id: string) => prefs.data?.find((p) => p.id === id);
|
||||
const enabled = get('PublishServerOnPlexOnlineKey')?.value === true;
|
||||
const manual = get('ManualPortMappingMode')?.value === true || get('ManualPortMappingMode')?.value === 1;
|
||||
const [port, setPort] = useState<string>('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const r = status.data;
|
||||
const mapped = r?.mappingState === 'mapped';
|
||||
|
||||
const run = async (fn: () => Promise<unknown>, done?: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
if (done) toast(done, 'success');
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'serverPrefs'] });
|
||||
await queryClient.invalidateQueries({ queryKey: [server.machineId, 'remoteAccess'] });
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!r || !prefs.data) return <PageLoader />;
|
||||
return (
|
||||
<>
|
||||
<Card className={`remote-status ${mapped && enabled ? 'good' : 'warn'}`}>
|
||||
<div className="remote-status-row">
|
||||
<div className="remote-icon">
|
||||
<Icon name={mapped && enabled ? 'globe' : 'alert'} size={22} />
|
||||
</div>
|
||||
<div>
|
||||
<h2>{!enabled ? 'Remote access is off' : mapped ? 'Fully accessible outside your network' : r.reachabilityPending ? 'Checking reachability…' : 'Not reachable outside your network'}</h2>
|
||||
<p className="muted">
|
||||
{enabled
|
||||
? `Public ${r.publicAddress || '—'}:${r.publicPort || '—'} → private ${r.privateAddress || '—'}:${r.privatePort || '—'}`
|
||||
: 'Turn on remote access to stream away from home without Plex Relay limits.'}
|
||||
{r.mappingError && ` · ${r.mappingError}`}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={busy} disabled={!enabled} onClick={() => run(() => admin.refreshReachability(server), 'Retrying remote access')}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
<SettingsSection title="Remote access">
|
||||
<Pref label="Enable remote access" description="Publishes this server to plex.tv so your devices can reach it from anywhere.">
|
||||
<Switch checked={enabled} disabled={busy} onChange={(v) => run(() => admin.setPrefs(server, { PublishServerOnPlexOnlineKey: v }), v ? 'Remote access enabled' : 'Remote access disabled')} />
|
||||
</Pref>
|
||||
<Pref label="Manually specify public port" description="Use when your router doesn’t support UPnP/NAT-PMP; forward this port to the server.">
|
||||
<Switch checked={!!manual} disabled={busy || !enabled} onChange={(v) => run(() => admin.setPrefs(server, { ManualPortMappingMode: v }))} />
|
||||
</Pref>
|
||||
{manual && (
|
||||
<Pref label="Public port">
|
||||
<input className="text-input pref-input" type="number" value={port || String(get('ManualPortMappingPort')?.value ?? '')} onChange={(e) => setPort(e.target.value)} />
|
||||
<Button variant="ghost" size="sm" disabled={!port} onClick={() => run(() => admin.setPrefs(server, { ManualPortMappingPort: Number(port) }), 'Port saved')}>
|
||||
Apply
|
||||
</Button>
|
||||
</Pref>
|
||||
)}
|
||||
{get('WanPerStreamMaxUploadRate') && (
|
||||
<Pref label={get('WanPerStreamMaxUploadRate')!.label} description={get('WanPerStreamMaxUploadRate')!.summary}>
|
||||
<SettingControl setting={get('WanPerStreamMaxUploadRate')!} value={get('WanPerStreamMaxUploadRate')!.value} onChange={(v) => run(() => admin.setPrefs(server, { WanPerStreamMaxUploadRate: v }), 'Saved')} />
|
||||
</Pref>
|
||||
)}
|
||||
{get('WanTotalMaxUploadRate') && (
|
||||
<Pref label={get('WanTotalMaxUploadRate')!.label} description={get('WanTotalMaxUploadRate')!.summary}>
|
||||
<input className="text-input pref-input" type="number" defaultValue={String(get('WanTotalMaxUploadRate')!.value ?? '')} onBlur={(e) => run(() => admin.setPrefs(server, { WanTotalMaxUploadRate: Number(e.target.value) }), 'Saved')} />
|
||||
</Pref>
|
||||
)}
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ScheduledTasks() {
|
||||
const server = useServer();
|
||||
const tasks = useServerQuery(['butlerTasks'], (s) => admin.butlerTasks(s));
|
||||
const [running, setRunning] = useState('');
|
||||
const run = async (t: admin.ButlerTask) => {
|
||||
setRunning(t.name);
|
||||
try {
|
||||
await admin.runButlerTask(server, t.name);
|
||||
toast(`Started “${t.title}”`, 'success');
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setRunning('');
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<PrefsEditor tab="scheduled" />
|
||||
<SettingsSection
|
||||
title="Tasks"
|
||||
description="Run maintenance now instead of waiting for the window."
|
||||
actions={
|
||||
<Button variant="ghost" size="sm" icon="x" onClick={() => admin.stopButlerTasks(server).then(() => toast('Stopped running tasks', 'success'), toastError)}>
|
||||
Stop all
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
{tasks.data?.map((t) => (
|
||||
<Pref key={t.name} label={t.title} description={[t.description, `Every ${t.interval} day${t.interval === 1 ? '' : 's'}`, t.enabled ? '' : 'Disabled'].filter(Boolean).join(' · ')}>
|
||||
<Button variant="ghost" size="sm" icon="play" busy={running === t.name} onClick={() => run(t)}>
|
||||
Run now
|
||||
</Button>
|
||||
</Pref>
|
||||
))}
|
||||
</SettingsSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ServerUpdates() {
|
||||
const server = useServer();
|
||||
const status = useServerQuery(['serverUpdate'], (s) => admin.updateStatus(s), { staleTime: 0 });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const u = status.data;
|
||||
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await fn();
|
||||
toast(done, 'success');
|
||||
setTimeout(() => status.refetch(), 3000);
|
||||
} catch (e) {
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<SettingsSection title="Plex Media Server updates">
|
||||
<Pref
|
||||
label={u?.version ? `Version ${u.version} is ${u.state === 'downloaded' ? 'ready to install' : 'available'}` : 'No update pending'}
|
||||
description={u?.checkedAt ? `Checked ${relativeTime(u.checkedAt)}` : 'Plex checks for updates automatically.'}
|
||||
>
|
||||
{u?.version && u.canInstall ? (
|
||||
<Button variant="primary" size="sm" busy={busy} onClick={() => run(() => admin.applyUpdate(server), 'Installing the update; the server will restart')}>
|
||||
Install now
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="ghost" size="sm" icon="refresh" busy={busy} onClick={() => run(() => admin.checkForUpdates(server), 'Checking for server updates')}>
|
||||
Check now
|
||||
</Button>
|
||||
)}
|
||||
</Pref>
|
||||
{u?.added && <p className="release-notes selectable">{u.added}</p>}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ServerPrefs({ tab }: { tab: string }) {
|
||||
if (tab === 'remote') return <RemoteAccess />;
|
||||
if (tab === 'scheduled') return <ScheduledTasks />;
|
||||
if (!GROUPS[tab]) return null;
|
||||
return (
|
||||
<>
|
||||
<PrefsEditor tab={tab} />
|
||||
{tab === 'general' && <ServerUpdates />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
140
src/screens/settings/Settings.tsx
Normal file
140
src/screens/settings/Settings.tsx
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
import { lazy, Suspense, type ReactNode } from 'react';
|
||||
import { navigate } from '../../app/router';
|
||||
import { useSession } from '../../app/session';
|
||||
import { Icon } from '../../ui/Icon';
|
||||
import { EmptyState, PageLoader } from '../../ui/primitives';
|
||||
import { AppSettings } from './AppSettings';
|
||||
|
||||
const ServerDashboard = lazy(() => import('./ServerDashboard'));
|
||||
const ServerPrefs = lazy(() => import('./ServerPrefs'));
|
||||
const ServerLibraries = lazy(() => import('./ServerLibraries'));
|
||||
const ServerManage = lazy(() => import('./ServerManage'));
|
||||
|
||||
type NavGroup = { group: string; items: { id: string; label: string; icon: string }[] };
|
||||
|
||||
export const APP_NAV: NavGroup[] = [
|
||||
{
|
||||
group: 'Preferences',
|
||||
items: [
|
||||
{ id: 'general', label: 'General', icon: 'settings' },
|
||||
{ id: 'playback', label: 'Playback', icon: 'playCircle' },
|
||||
{ id: 'subtitles', label: 'Audio & subtitles', icon: 'captions' },
|
||||
{ id: 'interface', label: 'Interface', icon: 'palette' },
|
||||
{ id: 'downloads', label: 'Downloads', icon: 'download' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Help',
|
||||
items: [
|
||||
{ id: 'shortcuts', label: 'Keyboard shortcuts', icon: 'keyboard' },
|
||||
{ id: 'about', label: 'About & updates', icon: 'info' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const SERVER_NAV: NavGroup[] = [
|
||||
{
|
||||
group: 'Status',
|
||||
items: [
|
||||
{ id: 'dashboard', label: 'Dashboard', icon: 'activity' },
|
||||
{ id: 'activity', label: 'Activity & history', icon: 'clock' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Settings',
|
||||
items: [
|
||||
{ id: 'general', label: 'General', icon: 'settings' },
|
||||
{ id: 'remote', label: 'Remote access', icon: 'globe' },
|
||||
{ id: 'library', label: 'Library', icon: 'film' },
|
||||
{ id: 'network', label: 'Network', icon: 'network' },
|
||||
{ id: 'transcoder', label: 'Transcoder', icon: 'cpu' },
|
||||
{ id: 'extras', label: 'Extras', icon: 'sparkle' },
|
||||
{ id: 'scheduled', label: 'Scheduled tasks', icon: 'calendar' },
|
||||
{ id: 'dlna', label: 'DLNA', icon: 'tv' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Manage',
|
||||
items: [
|
||||
{ id: 'libraries', label: 'Libraries', icon: 'folder' },
|
||||
{ id: 'devices', label: 'Devices', icon: 'monitor' },
|
||||
{ id: 'troubleshooting', label: 'Troubleshooting', icon: 'tool' },
|
||||
{ id: 'console', label: 'Console', icon: 'terminal' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function serverContent(tab: string): ReactNode {
|
||||
switch (tab) {
|
||||
case 'dashboard':
|
||||
case 'activity':
|
||||
return <ServerDashboard tab={tab} />;
|
||||
case 'libraries':
|
||||
return <ServerLibraries />;
|
||||
case 'devices':
|
||||
case 'troubleshooting':
|
||||
case 'console':
|
||||
return <ServerManage tab={tab} />;
|
||||
default:
|
||||
return <ServerPrefs tab={tab} />;
|
||||
}
|
||||
}
|
||||
|
||||
export default function Settings({ mode, tab }: { mode: 'app' | 'server'; tab: string }) {
|
||||
const server = useSession((s) => s.server);
|
||||
const owned = !!server?.owned;
|
||||
const nav = mode === 'app' ? APP_NAV : SERVER_NAV;
|
||||
const label = nav.flatMap((g) => g.items).find((i) => i.id === tab)?.label ?? 'Settings';
|
||||
const go = (m: 'app' | 'server', t: string) => navigate({ name: 'settings', mode: m, tab: t }, { replace: true });
|
||||
|
||||
return (
|
||||
<div className="settings-shell">
|
||||
<aside className="settings-nav">
|
||||
<h3>Settings</h3>
|
||||
<div className="seg settings-mode">
|
||||
<button className={mode === 'app' ? 'selected' : ''} onClick={() => go('app', 'general')}>
|
||||
Kaleido
|
||||
</button>
|
||||
<button className={mode === 'server' ? 'selected' : ''} onClick={() => go('server', 'dashboard')}>
|
||||
Plex server
|
||||
</button>
|
||||
</div>
|
||||
{nav.map((g) => (
|
||||
<div key={g.group}>
|
||||
<div className="settings-group">{g.group}</div>
|
||||
{g.items.map((i) => (
|
||||
<button key={i.id} className={`settings-link${i.id === tab ? ' selected' : ''}`} onClick={() => go(mode, i.id)}>
|
||||
<Icon name={i.icon} size={16} />
|
||||
{i.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
<div className="settings-main">
|
||||
<div className="settings-inner" key={`${mode}-${tab}`}>
|
||||
<div className="settings-header">
|
||||
<div>
|
||||
<div className="micro">{mode === 'server' ? `Plex server / ${server?.name ?? ''}` : 'Kaleido / This computer'}</div>
|
||||
<h1 className="page-title">{label}</h1>
|
||||
</div>
|
||||
{mode === 'server' && server && (
|
||||
<span className="status-tag">
|
||||
<i className="dot" /> {server.name}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{mode === 'app' ? (
|
||||
<AppSettings tab={tab} />
|
||||
) : !owned ? (
|
||||
<EmptyState icon="lock" title="Server management needs the owner">
|
||||
{server?.name ?? 'This server'} is shared with you. Only its owner can view the dashboard and change server settings.
|
||||
</EmptyState>
|
||||
) : (
|
||||
<Suspense fallback={<PageLoader />}>{serverContent(tab)}</Suspense>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
52
src/screens/settings/parts.tsx
Normal file
52
src/screens/settings/parts.tsx
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import type { ReactNode } from 'react';
|
||||
|
||||
export function SettingsSection({ title, description, children, actions }: { title: string; description?: ReactNode; children: ReactNode; actions?: ReactNode }) {
|
||||
return (
|
||||
<section className="settings-section">
|
||||
<div className="settings-section-head">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function Pref({ label, description, children, wide }: { label: ReactNode; description?: ReactNode; children?: ReactNode; wide?: boolean }) {
|
||||
return (
|
||||
<div className={`pref${wide ? ' wide' : ''}`}>
|
||||
<div className="pref-text">
|
||||
<strong>{label}</strong>
|
||||
{description && <p>{description}</p>}
|
||||
</div>
|
||||
{children && <div className="pref-control">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function StatTile({ label, value, detail, tone }: { label: string; value: ReactNode; detail?: ReactNode; tone?: 'good' | 'warn' }) {
|
||||
return (
|
||||
<div className={`stat-tile${tone ? ` ${tone}` : ''}`}>
|
||||
<label>{label}</label>
|
||||
<strong>{value}</strong>
|
||||
{detail && <small>{detail}</small>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ title, children, actions, className = '' }: { title?: ReactNode; children: ReactNode; actions?: ReactNode; className?: string }) {
|
||||
return (
|
||||
<div className={`admin-card ${className}`}>
|
||||
{(title || actions) && (
|
||||
<div className="admin-card-head">
|
||||
{title && <h2>{title}</h2>}
|
||||
{actions}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
1251
src/styles/app.css
Normal file
1251
src/styles/app.css
Normal file
File diff suppressed because it is too large
Load diff
232
src/styles/base.css
Normal file
232
src/styles/base.css
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
:root {
|
||||
--bg: #090a0c;
|
||||
--bg-raised: #0d0f11;
|
||||
--panel: #17191c;
|
||||
--panel-2: #202328;
|
||||
--panel-3: #2a2e33;
|
||||
--line: rgba(255, 255, 255, 0.105);
|
||||
--line-soft: rgba(255, 255, 255, 0.06);
|
||||
--muted: #9da3aa;
|
||||
--dim: #777d83;
|
||||
--white: #f5f6f7;
|
||||
--text: #e6e8e9;
|
||||
--accent: #a9c7c0;
|
||||
--accent-strong: #c1ded7;
|
||||
--accent-ink: #12201c;
|
||||
--danger: #e59a9a;
|
||||
--success: #8fc7a8;
|
||||
--warning: #e3c27c;
|
||||
--gutter: clamp(22px, 3.4vw, 64px);
|
||||
--nav-h: 64px;
|
||||
--r-sm: 5px;
|
||||
--r: 8px;
|
||||
--r-lg: 12px;
|
||||
--ease: cubic-bezier(0.2, 0.7, 0.1, 1);
|
||||
--ease-out: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
--t-fast: 140ms;
|
||||
--t: 220ms;
|
||||
--t-slow: 420ms;
|
||||
--shadow-pop: 0 24px 80px rgba(0, 0, 0, 0.62), 0 2px 10px rgba(0, 0, 0, 0.35);
|
||||
font-family: 'Inter Variable', 'Segoe UI Variable Text', 'Segoe UI', system-ui, sans-serif;
|
||||
font-feature-settings: 'cv11', 'ss01';
|
||||
color: var(--white);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
html.reduced-motion {
|
||||
--t-fast: 0ms;
|
||||
--t: 0ms;
|
||||
--t-slow: 0ms;
|
||||
}
|
||||
html.reduced-motion *,
|
||||
html.reduced-motion *::before,
|
||||
html.reduced-motion *::after {
|
||||
animation-duration: 0ms !important;
|
||||
transition-duration: 0ms !important;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
html {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--white);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* While video plays, the page is transparent so the native surface shows through. */
|
||||
html.video-active body {
|
||||
background: transparent;
|
||||
}
|
||||
html.video-active .app-shell {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
select {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
border: 0;
|
||||
background: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
user-select: text;
|
||||
-webkit-user-select: text;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
svg {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--accent-strong);
|
||||
outline-offset: 3px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: rgba(169, 199, 192, 0.35);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
border-radius: 10px;
|
||||
border: 3px solid transparent;
|
||||
background-clip: padding-box;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background-color: rgba(255, 255, 255, 0.28);
|
||||
}
|
||||
::-webkit-scrollbar-corner {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.micro {
|
||||
color: #b2c8c2;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.18em;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.dim {
|
||||
color: var(--dim);
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.selectable {
|
||||
user-select: text;
|
||||
-webkit-user-select: text;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes rise-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(14px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pop-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-4px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% {
|
||||
background-position: -400px 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 400px 0;
|
||||
}
|
||||
}
|
||||
603
src/styles/player.css
Normal file
603
src/styles/player.css
Normal file
|
|
@ -0,0 +1,603 @@
|
|||
.player {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 600;
|
||||
color: #fff;
|
||||
cursor: default;
|
||||
user-select: none;
|
||||
}
|
||||
.player.idle {
|
||||
cursor: none;
|
||||
}
|
||||
.player.loading {
|
||||
background: #000;
|
||||
}
|
||||
.player-cover {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #000;
|
||||
}
|
||||
.player-cover img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
opacity: 0.35;
|
||||
filter: blur(2px);
|
||||
animation: fade-in 500ms;
|
||||
}
|
||||
.player-cover-scrim {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: radial-gradient(ellipse at center, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.75) 80%);
|
||||
}
|
||||
.player-gradient {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 400ms var(--ease);
|
||||
}
|
||||
.player-gradient.top {
|
||||
top: 0;
|
||||
height: 160px;
|
||||
background: linear-gradient(180deg, rgba(0, 0, 0, 0.7), transparent);
|
||||
}
|
||||
.player-gradient.bottom {
|
||||
bottom: 0;
|
||||
height: 300px;
|
||||
background: linear-gradient(0deg, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.45) 45%, transparent 100%);
|
||||
}
|
||||
.player.idle .player-gradient,
|
||||
.player.idle .player-top,
|
||||
.player.idle .player-bottom {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
.player.idle .player-bottom {
|
||||
transform: translateY(10px);
|
||||
}
|
||||
.player-top {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 72px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
padding: 0 28px;
|
||||
transition: opacity 400ms var(--ease);
|
||||
}
|
||||
.player-back {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
transition: background var(--t-fast);
|
||||
}
|
||||
.player-back:hover {
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
.player-top-title {
|
||||
font-size: 14px;
|
||||
color: #d9dddf;
|
||||
pointer-events: none;
|
||||
}
|
||||
.player-top-title b {
|
||||
color: #fff;
|
||||
font-weight: 650;
|
||||
margin-right: 8px;
|
||||
}
|
||||
.player-center {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
.player-flash {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
margin: -42px 0 0 -42px;
|
||||
border-radius: 50%;
|
||||
background: rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(8px);
|
||||
display: grid;
|
||||
place-items: center;
|
||||
pointer-events: none;
|
||||
animation: flash 600ms var(--ease-out) forwards;
|
||||
}
|
||||
@keyframes flash {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.7);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: scale(1.25);
|
||||
}
|
||||
}
|
||||
.player-bottom {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
padding: 0 clamp(24px, 3.5vw, 56px) 22px;
|
||||
transition:
|
||||
opacity 400ms var(--ease),
|
||||
transform 400ms var(--ease);
|
||||
}
|
||||
.player-bottom-head {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 20px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.player-title {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.player-title .title-text {
|
||||
font-size: 26px;
|
||||
}
|
||||
.player-episode {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #eef0f0;
|
||||
}
|
||||
.player-title .facts {
|
||||
font-size: 12px;
|
||||
color: #c8ced0;
|
||||
}
|
||||
.player-delivery {
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
color: #b9c2c3;
|
||||
}
|
||||
|
||||
/* Timeline */
|
||||
.timeline {
|
||||
position: relative;
|
||||
height: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
touch-action: none;
|
||||
}
|
||||
.timeline-track {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 4px;
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
overflow: hidden;
|
||||
transition: height 140ms var(--ease);
|
||||
}
|
||||
.timeline:hover .timeline-track,
|
||||
.timeline.dragging .timeline-track {
|
||||
height: 7px;
|
||||
}
|
||||
.timeline-buffered {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: rgba(255, 255, 255, 0.28);
|
||||
}
|
||||
.timeline-played {
|
||||
position: absolute;
|
||||
inset: 0 auto 0 0;
|
||||
background: #f1f4f3;
|
||||
}
|
||||
.timeline-marker {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
background: rgba(169, 199, 192, 0.45);
|
||||
mix-blend-mode: screen;
|
||||
}
|
||||
.timeline-chapter {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: 2px;
|
||||
background: rgba(0, 0, 0, 0.55);
|
||||
}
|
||||
.timeline-thumb {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
margin: -7.5px 0 0 -7.5px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
|
||||
transform: scale(0);
|
||||
transition: transform 140ms var(--ease);
|
||||
pointer-events: none;
|
||||
}
|
||||
.timeline:hover .timeline-thumb,
|
||||
.timeline.dragging .timeline-thumb {
|
||||
transform: scale(1);
|
||||
}
|
||||
.timeline-preview {
|
||||
position: absolute;
|
||||
bottom: 30px;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.timeline-preview img {
|
||||
width: 220px;
|
||||
aspect-ratio: 16 / 9;
|
||||
object-fit: cover;
|
||||
border-radius: 6px;
|
||||
background: #000;
|
||||
box-shadow:
|
||||
0 10px 30px rgba(0, 0, 0, 0.6),
|
||||
0 0 0 1.5px rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
.timeline-preview-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
font-size: 12px;
|
||||
text-shadow: 0 1px 6px rgba(0, 0, 0, 0.8);
|
||||
}
|
||||
.timeline-preview-text span {
|
||||
color: #d2d7d8;
|
||||
font-size: 11px;
|
||||
}
|
||||
.timeline-preview-text b {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* Controls */
|
||||
.player-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.player-controls-left,
|
||||
.player-controls-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.player-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 50%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #f2f4f4;
|
||||
transition:
|
||||
background var(--t-fast),
|
||||
transform var(--t-fast);
|
||||
}
|
||||
.player-icon:hover {
|
||||
background: rgba(255, 255, 255, 0.13);
|
||||
}
|
||||
.player-icon:active {
|
||||
transform: scale(0.92);
|
||||
}
|
||||
.player-icon.on {
|
||||
background: rgba(255, 255, 255, 0.18);
|
||||
}
|
||||
.player-icon.lit {
|
||||
color: var(--accent-strong);
|
||||
}
|
||||
.player-icon.big {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
}
|
||||
.player-time {
|
||||
margin-left: 12px;
|
||||
font-size: 13px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #f0f2f2;
|
||||
}
|
||||
.player-time .dim {
|
||||
color: #a5acaf;
|
||||
}
|
||||
.volume {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.volume input {
|
||||
width: 0;
|
||||
opacity: 0;
|
||||
transition:
|
||||
width var(--t) var(--ease-out),
|
||||
opacity var(--t);
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
height: 4px;
|
||||
border-radius: 4px;
|
||||
background: linear-gradient(90deg, #fff var(--v), rgba(255, 255, 255, 0.25) var(--v));
|
||||
cursor: pointer;
|
||||
}
|
||||
.volume:hover input,
|
||||
.volume input:focus {
|
||||
width: 90px;
|
||||
opacity: 1;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.volume input::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
/* Panels */
|
||||
.player-panel {
|
||||
position: absolute;
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
bottom: 84px;
|
||||
min-width: 300px;
|
||||
max-height: min(60vh, 520px);
|
||||
overflow-y: auto;
|
||||
padding: 14px 8px 8px;
|
||||
border-radius: 14px;
|
||||
background: rgba(22, 25, 27, 0.9);
|
||||
backdrop-filter: blur(28px) saturate(1.3);
|
||||
box-shadow:
|
||||
0 24px 70px rgba(0, 0, 0, 0.6),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
|
||||
animation: pop-in 180ms var(--ease-out);
|
||||
}
|
||||
.player-panel.tracks {
|
||||
width: min(620px, calc(100vw - 48px));
|
||||
}
|
||||
.player-panel-title {
|
||||
font-size: 11px;
|
||||
font-weight: 750;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: #9aa4a6;
|
||||
padding: 0 12px 10px;
|
||||
}
|
||||
.panel-columns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
.panel-columns h4 {
|
||||
margin: 4px 12px 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.panel-option {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 9px 10px;
|
||||
border-radius: 8px;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
color: #d9dedf;
|
||||
}
|
||||
.panel-option:hover {
|
||||
background: rgba(255, 255, 255, 0.09);
|
||||
}
|
||||
.panel-option.selected {
|
||||
color: #fff;
|
||||
font-weight: 620;
|
||||
}
|
||||
.panel-check {
|
||||
width: 18px;
|
||||
flex: none;
|
||||
color: var(--accent-strong);
|
||||
padding-top: 1px;
|
||||
}
|
||||
.panel-label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.panel-label small {
|
||||
font-size: 11px;
|
||||
color: #8f989b;
|
||||
font-weight: 400;
|
||||
}
|
||||
.panel-empty {
|
||||
padding: 8px 12px;
|
||||
color: var(--dim);
|
||||
font-size: 12px;
|
||||
}
|
||||
.panel-delay {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin: 10px 10px 4px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
font-size: 12px;
|
||||
color: #a5adb0;
|
||||
}
|
||||
.panel-delay span {
|
||||
margin-right: auto;
|
||||
}
|
||||
.panel-delay button {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 7px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
font-size: 15px;
|
||||
}
|
||||
.panel-delay b {
|
||||
min-width: 50px;
|
||||
text-align: center;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: #fff;
|
||||
}
|
||||
.panel-row {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 11px 12px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.panel-row:hover {
|
||||
background: rgba(255, 255, 255, 0.09);
|
||||
}
|
||||
.panel-row span {
|
||||
margin-right: auto;
|
||||
}
|
||||
.panel-row b {
|
||||
font-weight: 500;
|
||||
color: #a9b2b5;
|
||||
}
|
||||
.panel-info {
|
||||
padding: 10px 12px 6px;
|
||||
margin-top: 6px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||
font-size: 11px;
|
||||
color: #899295;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.player-panel.chapters {
|
||||
min-width: 340px;
|
||||
}
|
||||
|
||||
/* Skip & post-play */
|
||||
.skip-button {
|
||||
position: absolute;
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
bottom: 170px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 46px;
|
||||
padding: 0 22px;
|
||||
border-radius: 8px;
|
||||
background: rgba(20, 22, 24, 0.82);
|
||||
backdrop-filter: blur(14px);
|
||||
box-shadow:
|
||||
0 10px 30px rgba(0, 0, 0, 0.5),
|
||||
inset 0 0 0 1.5px rgba(255, 255, 255, 0.55);
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
color: #fff;
|
||||
animation: rise-in 300ms var(--ease-out);
|
||||
transition:
|
||||
background var(--t-fast),
|
||||
color var(--t-fast);
|
||||
}
|
||||
.skip-button:hover {
|
||||
background: #f3f5f4;
|
||||
color: #111;
|
||||
}
|
||||
.post-play {
|
||||
position: absolute;
|
||||
right: clamp(24px, 3.5vw, 56px);
|
||||
bottom: 150px;
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: center;
|
||||
width: min(520px, calc(100vw - 48px));
|
||||
padding: 14px;
|
||||
border-radius: 14px;
|
||||
background: rgba(20, 22, 24, 0.88);
|
||||
backdrop-filter: blur(20px);
|
||||
box-shadow:
|
||||
0 24px 70px rgba(0, 0, 0, 0.6),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
|
||||
animation: rise-in 360ms var(--ease-out);
|
||||
}
|
||||
.post-play-art {
|
||||
position: relative;
|
||||
width: 180px;
|
||||
aspect-ratio: 16 / 9;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
flex: none;
|
||||
background: #000;
|
||||
}
|
||||
.post-play-art img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.post-play-ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: auto;
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
.post-play-ring circle {
|
||||
fill: rgba(0, 0, 0, 0.45);
|
||||
stroke: #fff;
|
||||
stroke-width: 3;
|
||||
stroke-dasharray: 107;
|
||||
animation: ring 8s linear forwards;
|
||||
}
|
||||
@keyframes ring {
|
||||
from {
|
||||
stroke-dashoffset: 107;
|
||||
}
|
||||
to {
|
||||
stroke-dashoffset: 0;
|
||||
}
|
||||
}
|
||||
.post-play-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.post-play-text b {
|
||||
font-size: 14px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.post-play-text .actions {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.player-error {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: min(480px, calc(100vw - 48px));
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: #f2c4c3;
|
||||
}
|
||||
.player-error h2 {
|
||||
margin: 4px 0 0;
|
||||
color: #fff;
|
||||
font-size: 20px;
|
||||
}
|
||||
.player-error p {
|
||||
color: #c4cacc;
|
||||
margin: 0 0 14px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
1860
src/styles/screens.css
Normal file
1860
src/styles/screens.css
Normal file
File diff suppressed because it is too large
Load diff
570
src/styles/ui.css
Normal file
570
src/styles/ui.css
Normal file
|
|
@ -0,0 +1,570 @@
|
|||
/* —— Buttons ———————————————————————————————————————————————— */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 9px;
|
||||
height: 40px;
|
||||
padding: 0 20px;
|
||||
border-radius: 7px;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background var(--t-fast) var(--ease),
|
||||
color var(--t-fast) var(--ease),
|
||||
transform var(--t-fast) var(--ease),
|
||||
box-shadow var(--t-fast) var(--ease);
|
||||
}
|
||||
.btn:active:not(:disabled) {
|
||||
transform: scale(0.975);
|
||||
}
|
||||
.btn.sm {
|
||||
height: 32px;
|
||||
padding: 0 13px;
|
||||
font-size: 12px;
|
||||
gap: 7px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.btn.lg {
|
||||
height: 46px;
|
||||
padding: 0 26px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.btn.primary {
|
||||
background: #f6f7f7;
|
||||
color: #121415;
|
||||
}
|
||||
.btn.primary:hover:not(:disabled) {
|
||||
background: #dfe8e4;
|
||||
}
|
||||
.btn.muted {
|
||||
background: rgba(255, 255, 255, 0.17);
|
||||
color: #fff;
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
.btn.muted:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.27);
|
||||
}
|
||||
.btn.ghost {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: #e3e6e7;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.09);
|
||||
}
|
||||
.btn.ghost:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.13);
|
||||
}
|
||||
.btn.outline {
|
||||
background: transparent;
|
||||
color: #eceeef;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
.btn.outline:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.btn.danger {
|
||||
background: #b9504f;
|
||||
color: #fff;
|
||||
}
|
||||
.btn.danger:hover:not(:disabled) {
|
||||
background: #c95e5c;
|
||||
}
|
||||
.btn.text {
|
||||
background: none;
|
||||
height: auto;
|
||||
padding: 6px 4px;
|
||||
color: var(--accent);
|
||||
font-weight: 650;
|
||||
font-size: 12px;
|
||||
}
|
||||
.btn.text:hover:not(:disabled) {
|
||||
color: var(--accent-strong);
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
height: 36px;
|
||||
width: 36px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
border-radius: 8px;
|
||||
color: #d6dadb;
|
||||
transition:
|
||||
background var(--t-fast),
|
||||
color var(--t-fast);
|
||||
}
|
||||
.icon-btn:hover:not(:disabled),
|
||||
.icon-btn.on {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.circle-btn {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
border-radius: 50%;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
color: #fff;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.42);
|
||||
backdrop-filter: blur(8px);
|
||||
transition:
|
||||
background var(--t-fast),
|
||||
transform var(--t-fast),
|
||||
box-shadow var(--t-fast);
|
||||
}
|
||||
.circle-btn:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
box-shadow: inset 0 0 0 1.5px rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
.circle-btn:active:not(:disabled) {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
.circle-btn.on {
|
||||
color: var(--accent-strong);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.actions.end {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* —— Spinner, artwork ———————————————————————————————————————— */
|
||||
.spinner {
|
||||
display: inline-block;
|
||||
border-radius: 50%;
|
||||
border: 2px solid rgba(255, 255, 255, 0.16);
|
||||
border-top-color: rgba(255, 255, 255, 0.85);
|
||||
animation: spin 0.8s linear infinite;
|
||||
flex: none;
|
||||
}
|
||||
.page-loader {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: 50vh;
|
||||
animation: fade-in 400ms 200ms both;
|
||||
}
|
||||
|
||||
.artwork {
|
||||
opacity: 0;
|
||||
transition: opacity 360ms var(--ease);
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
.artwork.ready {
|
||||
opacity: 1;
|
||||
}
|
||||
.artwork.empty {
|
||||
opacity: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
background: linear-gradient(135deg, #1d2125, #15181b);
|
||||
}
|
||||
|
||||
/* —— Switch, select, segmented ——————————————————————————————— */
|
||||
.switch {
|
||||
width: 38px;
|
||||
height: 22px;
|
||||
border-radius: 20px;
|
||||
background: #3b3f44;
|
||||
position: relative;
|
||||
flex: none;
|
||||
transition: background var(--t);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.switch span {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
left: 3px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: #c6cacb;
|
||||
transition:
|
||||
transform var(--t) var(--ease-out),
|
||||
background var(--t);
|
||||
}
|
||||
.switch.on {
|
||||
background: #8fb8aa;
|
||||
}
|
||||
.switch.on span {
|
||||
transform: translateX(16px);
|
||||
background: #0f1916;
|
||||
}
|
||||
|
||||
.select {
|
||||
height: 34px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 11px 0 13px;
|
||||
border-radius: 7px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.11);
|
||||
font-size: 12px;
|
||||
color: #dfe2e3;
|
||||
max-width: 100%;
|
||||
transition: background var(--t-fast);
|
||||
}
|
||||
.select:hover:not(:disabled) {
|
||||
background: rgba(255, 255, 255, 0.11);
|
||||
}
|
||||
.select-prefix {
|
||||
color: var(--muted);
|
||||
}
|
||||
.select-value {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 560;
|
||||
}
|
||||
.select svg {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.seg {
|
||||
display: inline-flex;
|
||||
gap: 3px;
|
||||
padding: 3px;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-radius: 8px;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.seg button {
|
||||
padding: 7px 14px;
|
||||
border-radius: 6px;
|
||||
color: #a3a8ad;
|
||||
font-size: 12px;
|
||||
font-weight: 560;
|
||||
transition:
|
||||
background var(--t-fast),
|
||||
color var(--t-fast);
|
||||
}
|
||||
.seg button:hover {
|
||||
color: #fff;
|
||||
}
|
||||
.seg button.selected {
|
||||
background: #3a403f;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* —— Fields ——————————————————————————————————————————————————— */
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.field > span {
|
||||
font-size: 11px;
|
||||
color: #b7c0c3;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.field input,
|
||||
.field textarea,
|
||||
.text-input {
|
||||
width: 100%;
|
||||
min-height: 38px;
|
||||
background: #101315;
|
||||
border: 1px solid rgba(255, 255, 255, 0.14);
|
||||
border-radius: 7px;
|
||||
padding: 9px 11px;
|
||||
font-size: 13px;
|
||||
transition:
|
||||
border-color var(--t-fast),
|
||||
background var(--t-fast);
|
||||
}
|
||||
.field textarea {
|
||||
min-height: 110px;
|
||||
resize: vertical;
|
||||
line-height: 1.55;
|
||||
}
|
||||
.field input:focus,
|
||||
.field textarea:focus,
|
||||
.text-input:focus {
|
||||
border-color: rgba(169, 199, 192, 0.65);
|
||||
background: #12171a;
|
||||
}
|
||||
.field-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
/* —— Menus ———————————————————————————————————————————————————— */
|
||||
.menu-layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 900;
|
||||
}
|
||||
.menu-panel {
|
||||
position: fixed;
|
||||
max-height: calc(100vh - 24px);
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
border-radius: 11px;
|
||||
background: rgba(31, 34, 37, 0.985);
|
||||
backdrop-filter: blur(24px) saturate(1.3);
|
||||
box-shadow:
|
||||
var(--shadow-pop),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.12);
|
||||
animation: pop-in 150ms var(--ease-out);
|
||||
transition: opacity 80ms;
|
||||
}
|
||||
.menu-item {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 10px 8px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 12.5px;
|
||||
color: #dde0e2;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.menu-item:hover:not(:disabled),
|
||||
.menu-item.open {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
}
|
||||
.menu-item.danger {
|
||||
color: var(--danger);
|
||||
}
|
||||
.menu-icon {
|
||||
width: 18px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: #a7b5b3;
|
||||
}
|
||||
.menu-label {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.menu-hint {
|
||||
color: var(--dim);
|
||||
font-size: 11px;
|
||||
margin-left: 14px;
|
||||
}
|
||||
.menu-chev {
|
||||
color: var(--dim);
|
||||
}
|
||||
.menu-sep {
|
||||
height: 1px;
|
||||
background: rgba(255, 255, 255, 0.09);
|
||||
margin: 5px 6px;
|
||||
}
|
||||
.menu-heading {
|
||||
padding: 9px 10px 5px;
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.12em;
|
||||
text-transform: uppercase;
|
||||
color: var(--dim);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* —— Dialogs —————————————————————————————————————————————————— */
|
||||
.dialog-layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 800;
|
||||
background: rgba(5, 6, 8, 0.72);
|
||||
backdrop-filter: blur(14px);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: 9vh 16px 16px;
|
||||
overflow-y: auto;
|
||||
animation: fade-in 180ms var(--ease);
|
||||
}
|
||||
.dialog {
|
||||
max-height: calc(100vh - 12vh - 16px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-radius: 14px;
|
||||
background: #1a1d20;
|
||||
box-shadow:
|
||||
var(--shadow-pop),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.11);
|
||||
animation: rise-in 240ms var(--ease-out);
|
||||
overflow: hidden;
|
||||
}
|
||||
.dialog-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
padding: 22px 22px 16px 26px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.dialog-header h2 {
|
||||
margin: 0;
|
||||
font-size: 19px;
|
||||
letter-spacing: -0.025em;
|
||||
font-weight: 720;
|
||||
}
|
||||
.dialog-header p {
|
||||
margin: 6px 0 0;
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.dialog-body {
|
||||
padding: 20px 26px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.dialog-bare {
|
||||
overflow-y: auto;
|
||||
}
|
||||
.dialog-footer {
|
||||
padding: 15px 22px;
|
||||
border-top: 1px solid var(--line);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.dialog-footer > .actions {
|
||||
margin-left: auto;
|
||||
}
|
||||
.confirm-message {
|
||||
color: #c9cfd1;
|
||||
font-size: 13px;
|
||||
line-height: 1.65;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
/* —— Toasts —————————————————————————————————————————————————— */
|
||||
.toast-stack {
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
bottom: 26px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.toast {
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
max-width: min(560px, 90vw);
|
||||
padding: 11px 16px;
|
||||
border-radius: 10px;
|
||||
background: rgba(40, 46, 47, 0.96);
|
||||
backdrop-filter: blur(18px);
|
||||
box-shadow:
|
||||
0 14px 40px rgba(0, 0, 0, 0.55),
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.13);
|
||||
font-size: 12.5px;
|
||||
color: #e9eeee;
|
||||
animation: rise-in 260ms var(--ease-out);
|
||||
}
|
||||
.toast.success svg {
|
||||
color: var(--success);
|
||||
}
|
||||
.toast.error svg {
|
||||
color: var(--danger);
|
||||
}
|
||||
.toast-action {
|
||||
color: var(--accent-strong);
|
||||
font-weight: 650;
|
||||
margin-left: 6px;
|
||||
}
|
||||
|
||||
/* —— Empty / error ——————————————————————————————————————————— */
|
||||
.empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
padding: 70px 24px;
|
||||
gap: 4px;
|
||||
animation: fade-in 300ms;
|
||||
}
|
||||
.empty-icon {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
border-radius: 16px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
color: #a9b6b4;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
.empty-state h3 {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 680;
|
||||
}
|
||||
.empty-state p {
|
||||
margin: 6px 0 16px;
|
||||
max-width: 440px;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.kbd {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
color: #b9c0c3;
|
||||
padding: 3px 7px;
|
||||
border-radius: 5px;
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.14),
|
||||
inset 0 -1px 0 rgba(255, 255, 255, 0.08);
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
border-radius: 4px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.04em;
|
||||
color: #e7eaea;
|
||||
box-shadow: inset 0 0 0 1.2px rgba(255, 255, 255, 0.45);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge.solid {
|
||||
box-shadow: none;
|
||||
background: rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 4px;
|
||||
border-radius: 4px;
|
||||
background: rgba(255, 255, 255, 0.16);
|
||||
overflow: hidden;
|
||||
}
|
||||
.progress-bar > i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--accent);
|
||||
border-radius: inherit;
|
||||
transition: width 300ms var(--ease);
|
||||
}
|
||||
|
||||
.skeleton {
|
||||
background: linear-gradient(90deg, #17191c 0, #1e2124 40%, #17191c 80%) 0 0 / 800px 100%;
|
||||
animation: shimmer 1.4s linear infinite;
|
||||
}
|
||||
62
src/ui/Backdrop.tsx
Normal file
62
src/ui/Backdrop.tsx
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useServer } from '../app/session';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { art, washGradient } from '../app/format';
|
||||
|
||||
interface Layer {
|
||||
key: number;
|
||||
src: string;
|
||||
wash: string;
|
||||
ready: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. Changes crossfade; the outgoing layer stays until the new
|
||||
* image has decoded.
|
||||
*/
|
||||
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();
|
||||
const colorWash = useSettings((s) => s.colorWash);
|
||||
const [layers, setLayers] = useState<Layer[]>([]);
|
||||
const counter = useRef(0);
|
||||
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) : '';
|
||||
|
||||
useEffect(() => {
|
||||
if (!src && !wash) 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 }];
|
||||
});
|
||||
}, [src, wash]);
|
||||
|
||||
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)), 700);
|
||||
return next;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={`backdrop ${className}`} aria-hidden="true">
|
||||
{layers.map((l) => (
|
||||
<div key={l.key} className={`backdrop-layer${l.ready ? ' ready' : ''}`}>
|
||||
{l.wash && <div className="backdrop-wash" style={{ background: l.wash }} />}
|
||||
{l.src && <img className="backdrop-art" src={l.src} alt="" draggable={false} decoding="async" onLoad={() => onReady(l.key)} onError={() => onReady(l.key)} />}
|
||||
</div>
|
||||
))}
|
||||
<div className="backdrop-scrim" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
92
src/ui/Hero.tsx
Normal file
92
src/ui/Hero.tsx
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useSettings } from '../app/settings';
|
||||
import { itemMenu, openItem, playWithVersion } from '../app/actions';
|
||||
import { Backdrop } from './Backdrop';
|
||||
import { Facts, TitleArt } from './media';
|
||||
import { Button, IconButton } from './primitives';
|
||||
import { openMenu } from './overlays';
|
||||
import { episodeLabel } from '../app/format';
|
||||
|
||||
export interface Feature {
|
||||
item: Item;
|
||||
eyebrow: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cinematic feature at the top of Home and the Discover pages. Features
|
||||
* rotate every 12 seconds while the pointer is away, crossfading artwork
|
||||
* while the copy lifts out and rises into place.
|
||||
*/
|
||||
export function Hero({ features, variant = 'home' }: { features: Feature[]; variant?: 'home' | 'section' }) {
|
||||
const rotate = useSettings((s) => s.heroRotation);
|
||||
const reduced = useSettings((s) => s.reducedMotion);
|
||||
const [index, setIndex] = useState(0);
|
||||
const [hover, setHover] = useState(false);
|
||||
const [copyKey, setCopyKey] = useState(0);
|
||||
const root = useRef<HTMLElement>(null);
|
||||
const count = features.length;
|
||||
const feature = features[Math.min(index, count - 1)];
|
||||
|
||||
useEffect(() => {
|
||||
if (!rotate || reduced || count < 2 || hover) return;
|
||||
const t = setTimeout(() => go(index + 1), 12000);
|
||||
return () => clearTimeout(t);
|
||||
}, [index, rotate, reduced, count, hover]);
|
||||
|
||||
// Pause rotation when the hero is scrolled away.
|
||||
const [visible, setVisible] = useState(true);
|
||||
useEffect(() => {
|
||||
const el = root.current;
|
||||
if (!el) return;
|
||||
const io = new IntersectionObserver(([e]) => setVisible(e.intersectionRatio > 0.4), { threshold: [0, 0.4, 1] });
|
||||
io.observe(el);
|
||||
return () => io.disconnect();
|
||||
}, []);
|
||||
|
||||
const go = (i: number) => {
|
||||
if (!visible && i !== index) return;
|
||||
setIndex(((i % count) + count) % count);
|
||||
setCopyKey((k) => k + 1);
|
||||
};
|
||||
|
||||
if (!feature) return <section className={`hero ${variant} empty`} />;
|
||||
const item = feature.item;
|
||||
const resume = item.viewOffset > 0;
|
||||
const summary = item.summary || item.tagline;
|
||||
|
||||
return (
|
||||
<section ref={root} className={`hero ${variant}`} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}>
|
||||
<Backdrop item={item} className="hero-backdrop" />
|
||||
<div className="hero-content" key={copyKey}>
|
||||
<div className="micro hero-eyebrow">{feature.eyebrow}</div>
|
||||
<TitleArt item={item} className="hero-title" maxWidth={variant === 'home' ? 420 : 380} maxHeight={variant === 'home' ? 128 : 108} />
|
||||
{item.type === 'episode' && (
|
||||
<div className="hero-episode">
|
||||
{episodeLabel(item)} · {item.title}
|
||||
</div>
|
||||
)}
|
||||
<Facts item={item} />
|
||||
{summary && <p className="hero-summary">{summary}</p>}
|
||||
<div className="actions hero-actions">
|
||||
<Button variant="primary" icon="play" onClick={() => playWithVersion(item)}>
|
||||
{resume ? 'Resume' : 'Play'}
|
||||
</Button>
|
||||
<Button variant="muted" icon="info" onClick={() => openItem(item.type === 'episode' ? { ...item, id: item.grandparentId || item.id } : item)}>
|
||||
More info
|
||||
</Button>
|
||||
<IconButton round icon="dots" label="More actions" onClick={(e) => openMenu(itemMenu(item), e.currentTarget)} />
|
||||
</div>
|
||||
</div>
|
||||
{count > 1 && (
|
||||
<div className="hero-dots" role="tablist" aria-label="Featured titles">
|
||||
{features.map((f, i) => (
|
||||
<button key={f.item.id} role="tab" aria-selected={i === index} aria-label={f.item.title} className={i === index ? 'active' : ''} onClick={() => go(i)}>
|
||||
{i === index && rotate && !reduced && !hover && visible && <i key={copyKey} className="hero-dot-progress" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
114
src/ui/HoverPreview.tsx
Normal file
114
src/ui/HoverPreview.tsx
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { create } from 'zustand';
|
||||
import { useRouter } from '../app/router';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useSession } from '../app/session';
|
||||
import { art, duration, episodeLabel } from '../app/format';
|
||||
import { Ratings } from './media';
|
||||
|
||||
/**
|
||||
* A quiet preview shown after the pointer rests on a poster: artwork, facts
|
||||
* and synopsis, without opening the title. It never captures the pointer.
|
||||
*/
|
||||
const usePreview = create<{ item: Item | null; rect: DOMRect | null; anchor: HTMLElement | null; show(item: Item, anchor: HTMLElement): void; hide(): void }>((set) => ({
|
||||
item: null,
|
||||
rect: null,
|
||||
anchor: null,
|
||||
show: (item, anchor) => set({ item, anchor, rect: anchor.getBoundingClientRect() }),
|
||||
hide: () => set({ item: null, rect: null, anchor: null }),
|
||||
}));
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
const DELAY = 650;
|
||||
|
||||
export function previewHandlers(item: Item) {
|
||||
return {
|
||||
onMouseEnter: (e: React.MouseEvent) => {
|
||||
const el = e.currentTarget as HTMLElement;
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
if (el.matches(':hover') && !document.querySelector('.menu-layer')) usePreview.getState().show(item, el);
|
||||
}, DELAY);
|
||||
},
|
||||
onMouseLeave: () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = null;
|
||||
usePreview.getState().hide();
|
||||
},
|
||||
onMouseDown: () => {
|
||||
if (timer) clearTimeout(timer);
|
||||
usePreview.getState().hide();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function HoverPreviewHost() {
|
||||
const { item, rect } = usePreview();
|
||||
const server = useSession((s) => s.server);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [pos, setPos] = useState<{ left: number; top: number; side: 'right' | 'left' } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const close = () => usePreview.getState().hide();
|
||||
// The anchor card can disappear (navigation, re-render) without a mouseleave.
|
||||
const check = () => {
|
||||
const a = usePreview.getState().anchor;
|
||||
if (a && (!a.isConnected || !a.matches(':hover'))) close();
|
||||
};
|
||||
const unsub = useRouter.subscribe(close);
|
||||
window.addEventListener('wheel', close, { passive: true });
|
||||
window.addEventListener('keydown', close);
|
||||
window.addEventListener('input', close, true);
|
||||
window.addEventListener('mousemove', check, { passive: true });
|
||||
return () => {
|
||||
unsub();
|
||||
window.removeEventListener('wheel', close);
|
||||
window.removeEventListener('keydown', close);
|
||||
window.removeEventListener('input', close, true);
|
||||
window.removeEventListener('mousemove', check);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!rect || !ref.current) return setPos(null);
|
||||
const w = ref.current.offsetWidth;
|
||||
const h = ref.current.offsetHeight;
|
||||
const side = rect.right + 14 + w < window.innerWidth - 12 ? 'right' : 'left';
|
||||
const left = side === 'right' ? rect.right + 14 : rect.left - 14 - w;
|
||||
const top = Math.min(Math.max(76, rect.top + rect.height / 2 - h / 2), window.innerHeight - h - 12);
|
||||
setPos({ left, top, side });
|
||||
}, [rect, item]);
|
||||
|
||||
if (!item || !rect || !server) return null;
|
||||
const backdrop = art.backdrop(item);
|
||||
const summary = item.summary || item.tagline;
|
||||
const facts = [
|
||||
item.type === 'episode' ? episodeLabel(item) : item.year || '',
|
||||
item.type === 'show' ? (item.childCount ? `${item.childCount} season${item.childCount === 1 ? '' : 's'}` : '') : duration(item.duration),
|
||||
item.genres.slice(0, 2).map((g) => g.tag).join(', '),
|
||||
].filter(Boolean);
|
||||
|
||||
return createPortal(
|
||||
<div ref={ref} className={`hover-preview ${pos?.side ?? 'right'}`} style={{ left: pos?.left ?? -9999, top: pos?.top ?? -9999 }} aria-hidden="true">
|
||||
{backdrop && (
|
||||
<div className="hover-preview-art">
|
||||
<img src={server.image(backdrop, 360, 202)} alt="" />
|
||||
{item.logo && <img className="hover-preview-logo" src={server.image(item.logo, 200, 64, { format: 'png' })} alt="" />}
|
||||
</div>
|
||||
)}
|
||||
<div className="hover-preview-body">
|
||||
{!item.logo && <b className="hover-preview-title">{item.type === 'episode' ? item.grandparentTitle : item.title}</b>}
|
||||
<div className="hover-preview-facts">
|
||||
{item.contentRating && <span className="badge">{item.contentRating}</span>}
|
||||
{facts.map((f) => (
|
||||
<span key={f}>{f}</span>
|
||||
))}
|
||||
</div>
|
||||
<Ratings item={item} compact />
|
||||
{summary && <p>{summary}</p>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
119
src/ui/Icon.tsx
Normal file
119
src/ui/Icon.tsx
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import type { CSSProperties } from 'react';
|
||||
|
||||
/** Stroke icons in the Kaleido style (1.8px, rounded), drawn on a 24px grid. */
|
||||
const PATHS: Record<string, string> = {
|
||||
home: '<path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1Z"/>',
|
||||
film: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M7 3v18M17 3v18M3 8h4m-4 8h4m10-8h4m-4 8h4"/>',
|
||||
tv: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m8 22 1-3m7 0 1 3M8 2l4 3 4-3"/>',
|
||||
search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>',
|
||||
settings:
|
||||
'<path d="M12 15.2a3.2 3.2 0 1 0 0-6.4 3.2 3.2 0 0 0 0 6.4Z"/><path d="M19.4 13.5a7.7 7.7 0 0 0 0-3l2-1.6-2-3.4-2.4 1a7.5 7.5 0 0 0-2.6-1.5L14 2.5h-4l-.4 2.5A7.5 7.5 0 0 0 7 6.5l-2.4-1-2 3.4 2 1.6a7.7 7.7 0 0 0 0 3l-2 1.6 2 3.4 2.4-1a7.5 7.5 0 0 0 2.6 1.5l.4 2.5h4l.4-2.5a7.5 7.5 0 0 0 2.6-1.5l2.4 1 2-3.4Z"/>',
|
||||
back: '<path d="m14 18-6-6 6-6"/>',
|
||||
next: '<path d="m9 18 6-6-6-6"/>',
|
||||
arrowLeft: '<path d="M19 12H5m6-6-6 6 6 6"/>',
|
||||
play: '<path d="M7 4.8v14.4a.8.8 0 0 0 1.2.7l11.6-7.2a.8.8 0 0 0 0-1.4L8.2 4.1a.8.8 0 0 0-1.2.7Z" fill="currentColor" stroke="none"/>',
|
||||
pause: '<rect x="6" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/><rect x="14" y="4.5" width="4" height="15" rx="1.2" fill="currentColor" stroke="none"/>',
|
||||
plus: '<path d="M12 5v14M5 12h14"/>',
|
||||
minus: '<path d="M5 12h14"/>',
|
||||
check: '<path d="m5 12.5 4.2 4.2L19 7"/>',
|
||||
info: '<circle cx="12" cy="12" r="9.2"/><path d="M12 11v5.5M12 7.6h.01"/>',
|
||||
grid: '<rect x="3.5" y="3.5" width="7" height="7" rx="1.4"/><rect x="13.5" y="3.5" width="7" height="7" rx="1.4"/><rect x="3.5" y="13.5" width="7" height="7" rx="1.4"/><rect x="13.5" y="13.5" width="7" height="7" rx="1.4"/>',
|
||||
list: '<path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01"/>',
|
||||
sliders: '<path d="M4 7h10m4 0h2M4 17h2m4 0h10"/><circle cx="16" cy="7" r="2"/><circle cx="8" cy="17" r="2"/>',
|
||||
chevronDown: '<path d="m6 9 6 6 6-6"/>',
|
||||
chevronUp: '<path d="m6 15 6-6 6 6"/>',
|
||||
expand: '<path d="M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5"/>',
|
||||
collapse: '<path d="M3 8h5V3m8 0v5h5M8 21v-5H3m13 5v-5h5"/>',
|
||||
external: '<path d="M14 3h7v7M21 3l-9 9M19 14v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5"/>',
|
||||
user: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
|
||||
users: '<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0M16 4.6a3.5 3.5 0 0 1 0 6.8M21.5 20a6.5 6.5 0 0 0-4-6"/>',
|
||||
volume: '<path d="M11 5 6 9H3v6h3l5 4Z"/><path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13"/>',
|
||||
volumeLow: '<path d="M11 5 6 9H3v6h3l5 4Z"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/>',
|
||||
mute: '<path d="M11 5 6 9H3v6h3l5 4Z"/><path d="m16 9 6 6m0-6-6 6"/>',
|
||||
captions: '<rect x="2.5" y="5" width="19" height="14" rx="2.5"/><path d="M10.5 10.2a2.2 2.2 0 1 0 0 3.6m7-3.6a2.2 2.2 0 1 0 0 3.6"/>',
|
||||
audio: '<path d="M3 12h2m3-5v10m4-13v16m4-11v6m4-4v2"/>',
|
||||
rewind: '<path d="M11 18 4 12l7-6v12Zm9 0-7-6 7-6v12Z"/>',
|
||||
forward: '<path d="m13 6 7 6-7 6V6ZM4 6l7 6-7 6V6Z"/>',
|
||||
replay10: '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.7"/><path d="M4 4v4.7h4.7"/><text x="12" y="15.6" font-size="7.4" text-anchor="middle" fill="currentColor" stroke="none" font-weight="700" font-family="Inter Variable,Segoe UI">10</text>',
|
||||
forward10: '<path d="M20 12a8 8 0 1 1-2.4-5.7L20 8.7"/><path d="M20 4v4.7h-4.7"/><text x="12" y="15.6" font-size="7.4" text-anchor="middle" fill="currentColor" stroke="none" font-weight="700" font-family="Inter Variable,Segoe UI">10</text>',
|
||||
skipNext: '<path d="M5 5.5v13l9-6.5-9-6.5Z" fill="currentColor"/><path d="M18 5v14"/>',
|
||||
skipPrev: '<path d="M19 5.5v13l-9-6.5 9-6.5Z" fill="currentColor"/><path d="M6 5v14"/>',
|
||||
monitor: '<rect x="3" y="3.5" width="18" height="13" rx="2"/><path d="M8 21h8m-4-4.5V21"/>',
|
||||
heart: '<path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8Z"/>',
|
||||
star: '<path d="m12 2.8 2.8 5.8 6.3.9-4.6 4.4 1.1 6.3L12 17.2l-5.6 3 1.1-6.3-4.6-4.4 6.3-.9Z"/>',
|
||||
starFill: '<path d="m12 2.8 2.8 5.8 6.3.9-4.6 4.4 1.1 6.3L12 17.2l-5.6 3 1.1-6.3-4.6-4.4 6.3-.9Z" fill="currentColor"/>',
|
||||
shuffle: '<path d="m18 14 4 4-4 4M2 18h3c5 0 7-12 12-12h5m-4-4 4 4-4 4M2 6h3c2.2 0 3.8 2.3 5.1 5M14 15.6c1 1.5 2.2 2.4 3.9 2.4H22"/>',
|
||||
clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>',
|
||||
folder: '<path d="M3 7a2 2 0 0 1 2-2h4.6l2 2H19a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/>',
|
||||
dots: '<circle cx="5" cy="12" r="1.4" fill="currentColor"/><circle cx="12" cy="12" r="1.4" fill="currentColor"/><circle cx="19" cy="12" r="1.4" fill="currentColor"/>',
|
||||
dotsV: '<circle cx="12" cy="5" r="1.4" fill="currentColor"/><circle cx="12" cy="12" r="1.4" fill="currentColor"/><circle cx="12" cy="19" r="1.4" fill="currentColor"/>',
|
||||
x: '<path d="m6 6 12 12M18 6 6 18"/>',
|
||||
download: '<path d="M12 3v12m-5-5 5 5 5-5M4 19h16"/>',
|
||||
downloaded: '<path d="M12 3v12m-5-5 5 5 5-5M4 19h16" opacity=".35"/><circle cx="18" cy="18" r="5" fill="currentColor" stroke="none"/><path d="m15.8 18 1.5 1.5 2.9-3" stroke="#0b0d0e" stroke-width="1.6"/>',
|
||||
trash: '<path d="M4 7h16M10 11v6m4-6v6M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12M9 7V4h6v3"/>',
|
||||
edit: '<path d="M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16Z"/><path d="m13.5 6.5 4 4"/>',
|
||||
refresh: '<path d="M20 11a8 8 0 0 0-14.8-4M4 4v4h4M4 13a8 8 0 0 0 14.8 4M20 20v-4h-4"/>',
|
||||
wand: '<path d="m4 20 11-11m2-6v2m0 4v2m-4-4h2m4 0h2M15 9l2 2"/>',
|
||||
scan: '<path d="M4 8V5a1 1 0 0 1 1-1h3m8 0h3a1 1 0 0 1 1 1v3m0 8v3a1 1 0 0 1-1 1h-3m-8 0H5a1 1 0 0 1-1-1v-3M7 12h10"/>',
|
||||
link: '<path d="M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1"/><path d="M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"/>',
|
||||
unlink: '<path d="M10 14a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1M14 10a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1M4 4l16 16"/>',
|
||||
split: '<path d="M6 3v6a6 6 0 0 0 6 6h0a6 6 0 0 1 6 6M18 3v6a6 6 0 0 1-6 6"/>',
|
||||
image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5-9 9"/>',
|
||||
layers: '<path d="m12 3 9 5-9 5-9-5 9-5Z"/><path d="m3 13 9 5 9-5"/>',
|
||||
stack: '<rect x="4" y="8" width="16" height="12" rx="2"/><path d="M7 5h10M9 2h6"/>',
|
||||
activity: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
|
||||
server: '<rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/>',
|
||||
globe: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18 14 14 0 0 1 0-18Z"/>',
|
||||
network: '<rect x="9" y="3" width="6" height="5" rx="1"/><rect x="3" y="16" width="6" height="5" rx="1"/><rect x="15" y="16" width="6" height="5" rx="1"/><path d="M12 8v4M6 16v-2h12v2"/>',
|
||||
cpu: '<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4m6-4v4M9 18v4m6-4v4M2 9h4m-4 6h4m12-6h4m-4 6h4"/>',
|
||||
language: '<path d="M4 5h9M8.5 3v2c0 4-2.5 7-5 8.5M6 9c1.4 2.2 3.4 3.8 6 4.6M13 21l4-9 4 9m-6.8-3h5.6"/>',
|
||||
calendar: '<rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 10h18M8 3v4m8-4v4"/>',
|
||||
sparkle: '<path d="M12 3c.6 4.2 2.8 6.4 7 7-4.2.6-6.4 2.8-7 7-.6-4.2-2.8-6.4-7-7 4.2-.6 6.4-2.8 7-7Z"/>',
|
||||
tool: '<path d="M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.6 2.6-2.4-.6-.6-2.4Z"/>',
|
||||
terminal: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m7 9 3 3-3 3m5 0h5"/>',
|
||||
shield: '<path d="M12 3 4.5 6v6c0 4.5 3.2 7.8 7.5 9 4.3-1.2 7.5-4.5 7.5-9V6Z"/>',
|
||||
bell: '<path d="M6 8a6 6 0 0 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0"/>',
|
||||
keyboard: '<rect x="2.5" y="6" width="19" height="12" rx="2"/><path d="M6 10h.01M9 10h.01M12 10h.01M15 10h.01M18 10h.01M7 14h10"/>',
|
||||
palette: '<path d="M12 3a9 9 0 1 0 0 18c1.2 0 2-.8 2-1.8 0-.5-.2-.9-.5-1.3-.3-.3-.5-.8-.5-1.3 0-1 .8-1.8 1.8-1.8H17a4 4 0 0 0 4-4C21 6.4 17 3 12 3Z"/><circle cx="7.5" cy="11.5" r="1" fill="currentColor"/><circle cx="10.5" cy="7.5" r="1" fill="currentColor"/><circle cx="15.5" cy="7.5" r="1" fill="currentColor"/>',
|
||||
logout: '<path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3M10 17l-5-5 5-5M5 12h11"/>',
|
||||
swap: '<path d="M7 4 3 8l4 4M3 8h14M17 20l4-4-4-4M21 16H7"/>',
|
||||
pip: '<rect x="2.5" y="4.5" width="19" height="15" rx="2"/><rect x="12" y="11.5" width="7" height="5" rx="1" fill="currentColor" stroke="none"/>',
|
||||
speed: '<path d="M12 14l4-4M3.5 17a9 9 0 1 1 17 0"/>',
|
||||
chapters: '<path d="M4 6h16M4 12h10M4 18h13"/>',
|
||||
hd: '<rect x="2.5" y="5" width="19" height="14" rx="2"/><path d="M7 9v6m0-3h4m0-3v6m3-6h2a3 3 0 0 1 0 6h-2Z"/>',
|
||||
window: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 9h18"/>',
|
||||
lock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>',
|
||||
unlock: '<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 7.8-1.3"/>',
|
||||
queue: '<path d="M3 6h12M3 12h12M3 18h8m6-3v6m-3-3h6"/>',
|
||||
collection: '<rect x="7" y="3" width="13" height="16" rx="2"/><path d="M4 7v12a2 2 0 0 0 2 2h10"/>',
|
||||
person: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
|
||||
upload: '<path d="M12 16V4m-5 5 5-5 5 5M4 20h16"/>',
|
||||
pauseCircle: '<circle cx="12" cy="12" r="9"/><path d="M10 9v6m4-6v6"/>',
|
||||
playCircle: '<circle cx="12" cy="12" r="9"/><path d="m10 8.5 5 3.5-5 3.5Z" fill="currentColor"/>',
|
||||
alert: '<path d="M12 3 2 20h20Z"/><path d="M12 10v4m0 3h.01"/>',
|
||||
wifiOff: '<path d="m3 3 18 18M8.5 16.5a5 5 0 0 1 7 0M5 12.5a10 10 0 0 1 4.5-2.4M19 12.5a10 10 0 0 0-2.4-1.6M2 8.8a15 15 0 0 1 4.3-2.6M22 8.8A15 15 0 0 0 11 5M12 20h.01"/>',
|
||||
restore: '<rect x="4" y="8" width="12" height="12" rx="1.5"/><path d="M8 8V5.5A1.5 1.5 0 0 1 9.5 4h9A1.5 1.5 0 0 1 20 5.5v9a1.5 1.5 0 0 1-1.5 1.5H16"/>',
|
||||
maximize: '<rect x="4.5" y="4.5" width="15" height="15" rx="1.5"/>',
|
||||
minimize: '<path d="M5 12h14"/>',
|
||||
};
|
||||
|
||||
export type IconName = keyof typeof PATHS | string;
|
||||
|
||||
export function Icon({ name, size = 20, className, style, strokeWidth = 1.8 }: { name: IconName; size?: number; className?: string; style?: CSSProperties; strokeWidth?: number }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={strokeWidth}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
className={className}
|
||||
style={style}
|
||||
dangerouslySetInnerHTML={{ __html: PATHS[name] ?? PATHS.info }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
350
src/ui/media.tsx
Normal file
350
src/ui/media.tsx
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
import { memo, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { Item } from '../plex/types';
|
||||
import { useServer } 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';
|
||||
import { Artwork } from './primitives';
|
||||
import { Icon } from './Icon';
|
||||
import { openMenu } from './overlays';
|
||||
import { previewHandlers } from './HoverPreview';
|
||||
import rtHot from '../assets/rt-hot.svg';
|
||||
import rtStale from '../assets/rt-stale.svg';
|
||||
import imdb from '../assets/imdb.svg';
|
||||
|
||||
// —— Ratings and facts ————————————————————————————————————————————
|
||||
|
||||
export function Ratings({ item, compact }: { item: Item; compact?: boolean }) {
|
||||
const audience = item.scores.filter((s) => s.kind === 'audience');
|
||||
const rt = audience.find((s) => s.source === 'Rotten Tomatoes');
|
||||
const im = audience.find((s) => s.source === 'IMDb');
|
||||
const fallback = !rt && !im ? audience.find((s) => s.source === 'TVDB' || s.source === 'TMDB') : null;
|
||||
if (!rt && !im && !fallback) return null;
|
||||
return (
|
||||
<span className={`ratings${compact ? ' compact' : ''}`}>
|
||||
{rt && (
|
||||
<span className="rating" title="Rotten Tomatoes audience score">
|
||||
<img src={rt.value >= 6 ? rtHot : rtStale} alt="Rotten Tomatoes" />
|
||||
{Math.round(rt.value * 10)}%
|
||||
</span>
|
||||
)}
|
||||
{im && (
|
||||
<span className="rating" title="IMDb rating">
|
||||
<img src={imdb} alt="IMDb" className="imdb" />
|
||||
{im.value.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
{fallback && (
|
||||
<span className="rating" title={`${fallback.source} rating`}>
|
||||
<Icon name="starFill" size={13} style={{ color: '#e9c46a' }} />
|
||||
{fallback.value.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function FormatBadges({ item }: { item: Item }) {
|
||||
const badges = formatBadges(item);
|
||||
if (!badges.length) return null;
|
||||
return (
|
||||
<span className="format-badges">
|
||||
{badges.map((b) => (
|
||||
<span key={b} className="badge">
|
||||
{b}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** "TV-MA · 2014 · Drama / Mystery · 1h 58m · [RT] [IMDb] · 4K HDR" */
|
||||
export function Facts({ item, withFormats = true, episode = true, children }: { item: Item; withFormats?: boolean; episode?: boolean; children?: ReactNode }) {
|
||||
const parts: ReactNode[] = [];
|
||||
if (item.type === 'episode') {
|
||||
if (episode) parts.push(<span key="ep">{episodeLabel(item)}</span>);
|
||||
if (item.originallyAvailableAt) parts.push(<span key="date">{new Date(item.originallyAvailableAt).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' })}</span>);
|
||||
} else if (item.year) parts.push(<span key="y">{item.year}</span>);
|
||||
if (item.genres.length && item.type !== 'episode') parts.push(<span key="g">{item.genres.slice(0, 2).map((g) => g.tag).join(' / ')}</span>);
|
||||
if (item.type === 'show') {
|
||||
if (item.childCount) parts.push(<span key="s">{item.childCount} season{item.childCount === 1 ? '' : 's'}</span>);
|
||||
} else if (item.type === 'season') {
|
||||
if (item.leafCount) parts.push(<span key="e">{item.leafCount} episodes</span>);
|
||||
} else if (item.viewOffset && item.duration) parts.push(<span key="r">{remaining(item)}</span>);
|
||||
else if (item.duration) parts.push(<span key="d">{duration(item.duration)}</span>);
|
||||
return (
|
||||
<div className="facts">
|
||||
{item.contentRating && <span className="badge">{item.contentRating.replace(/^gb\//, '')}</span>}
|
||||
{parts.map((p, i) => (
|
||||
<span key={i} className="fact">
|
||||
{i > 0 && <span className="fact-sep">·</span>}
|
||||
{p}
|
||||
</span>
|
||||
))}
|
||||
<Ratings item={item} />
|
||||
{withFormats && <FormatBadges item={item} />}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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();
|
||||
const path = logo ?? item.logo;
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [ready, setReady] = useState(false);
|
||||
useEffect(() => {
|
||||
setFailed(false);
|
||||
setReady(false);
|
||||
}, [path]);
|
||||
const title = item.type === 'episode' ? item.grandparentTitle : item.type === 'season' ? item.parentTitle || item.title : item.title;
|
||||
if (!path || failed)
|
||||
return (
|
||||
<As className={`title-text ${className}`} style={{ maxWidth: maxWidth * 1.4 }}>
|
||||
{title}
|
||||
</As>
|
||||
);
|
||||
return (
|
||||
<As className={`title-art ${className}`} style={{ maxWidth, height: maxHeight }}>
|
||||
<img
|
||||
src={server.image(path, maxWidth, maxHeight, { format: 'png' })}
|
||||
alt={title}
|
||||
draggable={false}
|
||||
className={ready ? 'ready' : ''}
|
||||
onLoad={() => setReady(true)}
|
||||
onError={() => setFailed(true)}
|
||||
style={{ maxWidth, maxHeight }}
|
||||
/>
|
||||
</As>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Card decorations —————————————————————————————————————————————
|
||||
|
||||
function WatchBadge({ item }: { item: Item }) {
|
||||
const percent = useSettings((s) => s.watchedPercent);
|
||||
if (isWatched(item, percent))
|
||||
return (
|
||||
<span className="watch-badge" title="Watched">
|
||||
<Icon name="check" size={13} strokeWidth={2.4} />
|
||||
</span>
|
||||
);
|
||||
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount > 0)
|
||||
return (
|
||||
<span className="watch-badge count" title={`${remainingEpisodes(item)} episodes left`}>
|
||||
{remainingEpisodes(item)}
|
||||
</span>
|
||||
);
|
||||
if ((item.type === 'show' || item.type === 'season') && item.leafCount && item.viewedLeafCount === 0) return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function ProgressLine({ item }: { item: Item }) {
|
||||
const p = progress(item);
|
||||
if (!p || p > 0.995) return null;
|
||||
return (
|
||||
<span className="progress-line">
|
||||
<i style={{ width: `${Math.max(3, p * 100)}%` }} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function useCardHandlers(item: Item, ctx: { continueWatching?: boolean } = {}) {
|
||||
return {
|
||||
onClick: () => openItem(item),
|
||||
onContextMenu: (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
openMenu(itemMenu(item, ctx), { x: e.clientX, y: e.clientY });
|
||||
},
|
||||
onKeyDown: (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') openItem(item);
|
||||
if (e.key === ' ') {
|
||||
e.preventDefault();
|
||||
playWithVersion(item);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function CardActions({ item, ctx }: { item: Item; ctx?: { continueWatching?: boolean } }) {
|
||||
const playable = ['movie', 'episode', 'show', 'season', 'clip'].includes(item.type);
|
||||
return (
|
||||
<div className="card-actions">
|
||||
{playable && (
|
||||
<button
|
||||
className="card-play"
|
||||
aria-label={`Play ${item.title}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
playWithVersion(item);
|
||||
}}
|
||||
>
|
||||
<Icon name="play" size={18} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="card-more"
|
||||
aria-label="More"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openMenu(itemMenu(item, ctx), e.currentTarget as HTMLElement);
|
||||
}}
|
||||
>
|
||||
<Icon name="dots" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Cards ——————————————————————————————————————————————————————————
|
||||
|
||||
export const PosterCard = memo(function PosterCard({ item, caption = 'year', className = '' }: { item: Item; caption?: 'year' | 'none' | 'episodes' | 'role'; className?: string }) {
|
||||
const server = useServer();
|
||||
const handlers = useCardHandlers(item);
|
||||
const path = art.poster(item);
|
||||
let meta: ReactNode = null;
|
||||
if (caption === 'year') meta = item.type === 'episode' ? episodeLabel(item) : item.type === 'season' ? (item.leafCount ? `${item.leafCount} episodes` : '') : item.type === 'collection' ? (item.childCount ? `${item.childCount} titles` : 'Collection') : item.year || '';
|
||||
if (caption === 'episodes') meta = item.leafCount ? `${item.leafCount} episodes` : '';
|
||||
if (caption === 'role') meta = (item as any).roleName ?? item.year;
|
||||
return (
|
||||
<article className={`card poster ${className}`} role="button" tabIndex={0} aria-label={item.title} {...handlers} {...previewHandlers(item)}>
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(path, 240, 360)} alt="" fallback={<span className="cover-fallback">{displayTitle(item)}</span>} />
|
||||
<div className="card-hover" />
|
||||
<CardActions item={item} />
|
||||
<WatchBadge item={item} />
|
||||
<ProgressLine item={item} />
|
||||
</div>
|
||||
{caption !== 'none' && (
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={item.type === 'season' ? item.title : displayTitle(item)}>
|
||||
{item.type === 'season' ? item.title : displayTitle(item)}
|
||||
</div>
|
||||
{meta ? <div className="card-meta">{meta}</div> : null}
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
});
|
||||
|
||||
export const LandscapeCard = memo(function LandscapeCard({ item, continueWatching, showTitle = true, episodeStyle = false }: { item: Item; continueWatching?: boolean; showTitle?: boolean; episodeStyle?: boolean }) {
|
||||
const server = useServer();
|
||||
const handlers = useCardHandlers(item, { continueWatching });
|
||||
const isEp = item.type === 'episode';
|
||||
const path = isEp ? item.thumb || item.grandparentArt : art.landscape(item);
|
||||
const title = episodeStyle && isEp ? `${item.index}. ${item.title}` : displayTitle(item);
|
||||
const meta = isEp
|
||||
? episodeStyle
|
||||
? [duration(item.duration), item.viewOffset ? remaining(item) : ''].filter(Boolean).join(' · ')
|
||||
: `${episodeLabel(item)} ${item.title}`
|
||||
: item.viewOffset
|
||||
? remaining(item)
|
||||
: [item.year, duration(item.duration)].filter(Boolean).join(' · ');
|
||||
return (
|
||||
<article className="card landscape" role="button" tabIndex={0} aria-label={title} {...handlers}>
|
||||
<div className="card-cover">
|
||||
<Artwork src={server.image(path, 400, 225)} alt="" fallback={<span className="cover-fallback">{title}</span>} />
|
||||
{!isEp && item.logo && continueWatching && (
|
||||
<div className="card-logo">
|
||||
<img src={server.image(item.logo, 220, 70, { format: 'png' })} alt="" draggable={false} />
|
||||
</div>
|
||||
)}
|
||||
<div className="card-hover" />
|
||||
<CardActions item={item} ctx={{ continueWatching }} />
|
||||
{episodeStyle && <WatchBadge item={item} />}
|
||||
<ProgressLine item={item} />
|
||||
</div>
|
||||
{showTitle && (
|
||||
<div className="card-caption">
|
||||
<div className="card-title" title={title}>
|
||||
{title}
|
||||
</div>
|
||||
<div className="card-meta">{meta}</div>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
});
|
||||
|
||||
export function PersonCard({ name, role, thumb, onClick }: { name: string; role?: string; thumb?: string; onClick?: () => void }) {
|
||||
const server = useServer();
|
||||
const initials = name
|
||||
.split(/\s+/)
|
||||
.map((x) => x[0])
|
||||
.slice(0, 2)
|
||||
.join('');
|
||||
return (
|
||||
<button className="person-card" onClick={onClick} disabled={!onClick}>
|
||||
<div className="person-photo">
|
||||
{thumb ? <Artwork src={server.image(thumb, 160, 160)} alt="" fallback={<span>{initials}</span>} /> : <span>{initials}</span>}
|
||||
</div>
|
||||
<b>{name}</b>
|
||||
{role && <small>{role}</small>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// —— Shelf ——————————————————————————————————————————————————————————
|
||||
|
||||
export function Shelf({ title, subtitle, onViewAll, children, className = '', kind = 'poster' }: { title: ReactNode; subtitle?: ReactNode; onViewAll?: () => void; children: ReactNode; className?: string; kind?: 'poster' | 'landscape' | 'people' | 'wide' }) {
|
||||
const row = useRef<HTMLDivElement>(null);
|
||||
const [edges, setEdges] = useState({ start: true, end: false });
|
||||
const update = () => {
|
||||
const el = row.current;
|
||||
if (!el) return;
|
||||
setEdges({ start: el.scrollLeft < 8, end: el.scrollLeft + el.clientWidth >= el.scrollWidth - 8 });
|
||||
};
|
||||
useEffect(() => {
|
||||
update();
|
||||
const el = row.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [children]);
|
||||
const page = (dir: number) => {
|
||||
const el = row.current;
|
||||
if (!el) return;
|
||||
el.scrollBy({ left: dir * (el.clientWidth - 120), behavior: 'smooth' });
|
||||
};
|
||||
return (
|
||||
<section className={`shelf-section ${className}`}>
|
||||
<div className="shelf-head">
|
||||
<h2>
|
||||
{onViewAll ? (
|
||||
<button className="shelf-title-link" onClick={onViewAll}>
|
||||
{title}
|
||||
<Icon name="next" size={16} />
|
||||
</button>
|
||||
) : (
|
||||
title
|
||||
)}
|
||||
{subtitle && <small>{subtitle}</small>}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="shelf-wrap">
|
||||
<button className={`shelf-paddle prev${edges.start ? ' hidden' : ''}`} aria-label="Scroll left" onClick={() => page(-1)} tabIndex={-1}>
|
||||
<Icon name="back" size={26} />
|
||||
</button>
|
||||
<div className={`shelf ${kind}`} ref={row} onScroll={update}>
|
||||
{children}
|
||||
</div>
|
||||
<button className={`shelf-paddle next${edges.end ? ' hidden' : ''}`} aria-label="Scroll right" onClick={() => page(1)} tabIndex={-1}>
|
||||
<Icon name="next" size={26} />
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** A hub shelf with the right card style for its contents. */
|
||||
export function HubShelf({ title, items, onViewAll, continueWatching, landscape }: { title: string; items: Item[]; onViewAll?: () => void; continueWatching?: boolean; landscape?: boolean }) {
|
||||
if (!items.length) return null;
|
||||
const wide = landscape ?? (continueWatching || items.every((i) => i.type === 'episode' || i.type === 'clip'));
|
||||
return (
|
||||
<Shelf title={title} onViewAll={onViewAll} kind={wide ? 'landscape' : 'poster'}>
|
||||
{items.map((i) => (wide ? <LandscapeCard key={i.id} item={i} continueWatching={continueWatching} /> : <PosterCard key={i.id} item={i} />))}
|
||||
</Shelf>
|
||||
);
|
||||
}
|
||||
329
src/ui/overlays.tsx
Normal file
329
src/ui/overlays.tsx
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
/** App-wide floating UI: menus, dialogs, confirmations and toasts. */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { create } from 'zustand';
|
||||
import { Icon } from './Icon';
|
||||
|
||||
// —— Menus ————————————————————————————————————————————————————————————
|
||||
|
||||
export interface MenuItem {
|
||||
label?: string;
|
||||
icon?: string;
|
||||
hint?: string;
|
||||
onSelect?: () => void;
|
||||
danger?: boolean;
|
||||
disabled?: boolean;
|
||||
checked?: boolean;
|
||||
divider?: boolean;
|
||||
heading?: string;
|
||||
submenu?: MenuItem[];
|
||||
}
|
||||
|
||||
interface MenuRequest {
|
||||
items: MenuItem[];
|
||||
x: number;
|
||||
y: number;
|
||||
/** Anchor rectangle; the menu prefers to open beneath it. */
|
||||
anchor?: DOMRect;
|
||||
align?: 'start' | 'end';
|
||||
minWidth?: number;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
const useMenuStore = create<{ menu: MenuRequest | null; open(m: MenuRequest): void; close(): void }>((set, get) => ({
|
||||
menu: null,
|
||||
open: (m) => {
|
||||
get().menu?.onClose?.();
|
||||
set({ menu: m });
|
||||
},
|
||||
close: () => {
|
||||
get().menu?.onClose?.();
|
||||
set({ menu: null });
|
||||
},
|
||||
}));
|
||||
|
||||
export function openMenu(items: MenuItem[], at: { x: number; y: number } | HTMLElement, opts: { align?: 'start' | 'end'; minWidth?: number; onClose?: () => void } = {}) {
|
||||
if (at instanceof HTMLElement) {
|
||||
const r = at.getBoundingClientRect();
|
||||
useMenuStore.getState().open({ items, x: opts.align === 'end' ? r.right : r.left, y: r.bottom + 6, anchor: r, ...opts });
|
||||
} else {
|
||||
useMenuStore.getState().open({ items, x: at.x, y: at.y, ...opts });
|
||||
}
|
||||
}
|
||||
export const closeMenu = () => useMenuStore.getState().close();
|
||||
|
||||
function MenuPanel({ req, items, x, y, altX, level = 0, onClose }: { req: MenuRequest; items: MenuItem[]; x: number; y: number; altX?: number; level?: number; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [pos, setPos] = useState({ left: x, top: y, ready: false });
|
||||
const [sub, setSub] = useState<{ index: number; x: number; y: number; altX: number } | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const w = el.offsetWidth;
|
||||
const h = el.offsetHeight;
|
||||
let left = req.align === 'end' && level === 0 ? x - w : x;
|
||||
let top = y;
|
||||
const vw = window.innerWidth;
|
||||
const vh = window.innerHeight;
|
||||
if (left + w > vw - 8) left = level && altX !== undefined ? altX - w : vw - w - 8;
|
||||
if (left < 8) left = 8;
|
||||
if (top + h > vh - 8) top = req.anchor && level === 0 ? Math.max(8, req.anchor.top - h - 6) : Math.max(8, vh - h - 8);
|
||||
setPos({ left, top, ready: true });
|
||||
}, [x, y, altX, req, level]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={ref}
|
||||
className="menu-panel"
|
||||
role="menu"
|
||||
style={{ left: pos.left, top: pos.top, minWidth: req.minWidth ?? 220, opacity: pos.ready ? 1 : 0 }}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{items.map((it, i) => {
|
||||
if (it.divider) return <div key={i} className="menu-sep" />;
|
||||
if (it.heading) return <div key={i} className="menu-heading">{it.heading}</div>;
|
||||
return (
|
||||
<button
|
||||
key={i}
|
||||
role="menuitem"
|
||||
className={`menu-item${it.danger ? ' danger' : ''}${sub?.index === i ? ' open' : ''}`}
|
||||
disabled={it.disabled}
|
||||
onMouseEnter={(e) => {
|
||||
if (it.submenu) {
|
||||
const r = (e.currentTarget as HTMLElement).getBoundingClientRect();
|
||||
setSub({ index: i, x: r.right + 4, y: r.top - 6, altX: r.left - 4 });
|
||||
} else setSub(null);
|
||||
}}
|
||||
onClick={() => {
|
||||
if (it.submenu) return;
|
||||
onClose();
|
||||
it.onSelect?.();
|
||||
}}
|
||||
>
|
||||
<span className="menu-icon">{it.checked !== undefined ? it.checked ? <Icon name="check" size={16} /> : null : it.icon ? <Icon name={it.icon} size={16} /> : null}</span>
|
||||
<span className="menu-label">{it.label}</span>
|
||||
{it.hint && <span className="menu-hint">{it.hint}</span>}
|
||||
{it.submenu && <Icon name="next" size={14} className="menu-chev" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{sub && items[sub.index]?.submenu && <MenuPanel req={req} items={items[sub.index].submenu!} x={sub.x} y={sub.y} altX={sub.altX} level={level + 1} onClose={onClose} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function MenuHost() {
|
||||
const menu = useMenuStore((s) => s.menu);
|
||||
const close = useMenuStore((s) => s.close);
|
||||
useEffect(() => {
|
||||
if (!menu) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
close();
|
||||
}
|
||||
};
|
||||
const onScroll = () => close();
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
window.addEventListener('resize', onScroll);
|
||||
window.addEventListener('wheel', onScroll, { passive: true });
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey, true);
|
||||
window.removeEventListener('resize', onScroll);
|
||||
window.removeEventListener('wheel', onScroll);
|
||||
};
|
||||
}, [menu, close]);
|
||||
if (!menu) return null;
|
||||
return createPortal(
|
||||
<div
|
||||
className="menu-layer"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) close();
|
||||
}}
|
||||
onContextMenu={(e) => {
|
||||
e.preventDefault();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<MenuPanel req={menu} items={menu.items} x={menu.x} y={menu.y} onClose={close} />
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
// —— Toasts ——————————————————————————————————————————————————————————
|
||||
|
||||
interface Toast {
|
||||
id: number;
|
||||
message: string;
|
||||
tone: 'info' | 'success' | 'error';
|
||||
action?: { label: string; onClick: () => void };
|
||||
}
|
||||
|
||||
const useToasts = create<{ toasts: Toast[]; push(t: Omit<Toast, 'id'>): void; dismiss(id: number): void }>((set) => ({
|
||||
toasts: [],
|
||||
push: (t) => {
|
||||
const id = Date.now() + Math.random();
|
||||
set((s) => ({ toasts: [...s.toasts.slice(-2), { ...t, id }] }));
|
||||
setTimeout(() => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })), t.tone === 'error' ? 6000 : 3400);
|
||||
},
|
||||
dismiss: (id) => set((s) => ({ toasts: s.toasts.filter((x) => x.id !== id) })),
|
||||
}));
|
||||
|
||||
export const toast = (message: string, tone: Toast['tone'] = 'info', action?: Toast['action']) => useToasts.getState().push({ message, tone, action });
|
||||
export const toastError = (e: unknown) => toast(e instanceof Error ? e.message : String(e), 'error');
|
||||
|
||||
export function ToastHost() {
|
||||
const toasts = useToasts((s) => s.toasts);
|
||||
const dismiss = useToasts((s) => s.dismiss);
|
||||
return createPortal(
|
||||
<div className="toast-stack" aria-live="polite">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={`toast ${t.tone}`}>
|
||||
{t.tone === 'success' && <Icon name="check" size={16} />}
|
||||
{t.tone === 'error' && <Icon name="alert" size={16} />}
|
||||
<span>{t.message}</span>
|
||||
{t.action && (
|
||||
<button
|
||||
className="toast-action"
|
||||
onClick={() => {
|
||||
t.action!.onClick();
|
||||
dismiss(t.id);
|
||||
}}
|
||||
>
|
||||
{t.action.label}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
// —— Dialogs ——————————————————————————————————————————————————————————
|
||||
|
||||
export function Dialog({
|
||||
title,
|
||||
subtitle,
|
||||
onClose,
|
||||
children,
|
||||
footer,
|
||||
width = 640,
|
||||
className = '',
|
||||
bare = false,
|
||||
}: {
|
||||
title?: ReactNode;
|
||||
subtitle?: ReactNode;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
footer?: ReactNode;
|
||||
width?: number;
|
||||
className?: string;
|
||||
bare?: boolean;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [onClose]);
|
||||
return createPortal(
|
||||
<div
|
||||
className="dialog-layer"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<div className={`dialog ${className}`} role="dialog" aria-modal="true" style={{ width: `min(${width}px, calc(100vw - 32px))` }}>
|
||||
{!bare && (
|
||||
<div className="dialog-header">
|
||||
<div>
|
||||
{title && <h2>{title}</h2>}
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
<button className="icon-btn" onClick={onClose} aria-label="Close">
|
||||
<Icon name="x" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className={bare ? 'dialog-bare' : 'dialog-body'}>{children}</div>
|
||||
{footer && <div className="dialog-footer">{footer}</div>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
|
||||
interface ConfirmRequest {
|
||||
title: string;
|
||||
message: ReactNode;
|
||||
confirm: string;
|
||||
danger?: boolean;
|
||||
input?: { label: string; placeholder?: string; type?: string; value?: string };
|
||||
resolve(v: string | boolean | null): void;
|
||||
}
|
||||
|
||||
const useConfirm = create<{ req: ConfirmRequest | null; set(r: ConfirmRequest | null): void }>((set) => ({ req: null, set: (req) => set({ req }) }));
|
||||
|
||||
export function confirmDialog(opts: Omit<ConfirmRequest, 'resolve' | 'input'>): Promise<boolean> {
|
||||
return new Promise((resolve) => useConfirm.getState().set({ ...opts, resolve: (v) => resolve(v === true) }));
|
||||
}
|
||||
|
||||
export function promptDialog(opts: Omit<ConfirmRequest, 'resolve'> & { input: NonNullable<ConfirmRequest['input']> }): Promise<string | null> {
|
||||
return new Promise((resolve) => useConfirm.getState().set({ ...opts, resolve: (v) => resolve(typeof v === 'string' ? v : null) }));
|
||||
}
|
||||
|
||||
export function ConfirmHost() {
|
||||
const req = useConfirm((s) => s.req);
|
||||
const set = useConfirm((s) => s.set);
|
||||
const [value, setValue] = useState('');
|
||||
useEffect(() => setValue(req?.input?.value ?? ''), [req]);
|
||||
if (!req) return null;
|
||||
const done = (v: string | boolean | null) => {
|
||||
req.resolve(v);
|
||||
set(null);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
title={req.title}
|
||||
onClose={() => done(null)}
|
||||
width={460}
|
||||
footer={
|
||||
<div className="actions end">
|
||||
<button className="btn ghost" onClick={() => done(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className={`btn ${req.danger ? 'danger' : 'primary'}`} onClick={() => done(req.input ? value : true)} autoFocus={!req.input}>
|
||||
{req.confirm}
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="confirm-message">{req.message}</div>
|
||||
{req.input && (
|
||||
<label className="field">
|
||||
<span>{req.input.label}</span>
|
||||
<input
|
||||
autoFocus
|
||||
type={req.input.type ?? 'text'}
|
||||
value={value}
|
||||
placeholder={req.input.placeholder}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') done(value);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
202
src/ui/primitives.tsx
Normal file
202
src/ui/primitives.tsx
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
import { useEffect, useRef, useState, type ButtonHTMLAttributes, type CSSProperties, type ReactNode } from 'react';
|
||||
import { Icon } from './Icon';
|
||||
import { openMenu, type MenuItem } from './overlays';
|
||||
|
||||
type Variant = 'primary' | 'muted' | 'ghost' | 'outline' | 'danger' | 'text';
|
||||
|
||||
export function Button({
|
||||
variant = 'muted',
|
||||
icon,
|
||||
iconRight,
|
||||
children,
|
||||
className = '',
|
||||
busy,
|
||||
size,
|
||||
...rest
|
||||
}: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: Variant; icon?: string; iconRight?: string; busy?: boolean; size?: 'sm' | 'lg' }) {
|
||||
return (
|
||||
<button className={`btn ${variant}${size ? ` ${size}` : ''} ${className}`} {...rest} disabled={rest.disabled || busy}>
|
||||
{busy ? <Spinner size={16} /> : icon ? <Icon name={icon} size={size === 'sm' ? 15 : 17} /> : null}
|
||||
{children && <span>{children}</span>}
|
||||
{iconRight && <Icon name={iconRight} size={15} />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function IconButton({
|
||||
icon,
|
||||
label,
|
||||
className = '',
|
||||
size = 19,
|
||||
round,
|
||||
...rest
|
||||
}: ButtonHTMLAttributes<HTMLButtonElement> & { icon: string; label: string; size?: number; round?: boolean }) {
|
||||
return (
|
||||
<button className={`${round ? 'circle-btn' : 'icon-btn'} ${className}`} aria-label={label} title={label} {...rest}>
|
||||
<Icon name={icon} size={size} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Spinner({ size = 22, className = '' }: { size?: number; className?: string }) {
|
||||
return <span className={`spinner ${className}`} style={{ width: size, height: size }} aria-label="Loading" />;
|
||||
}
|
||||
|
||||
/** An image that fades in once decoded, keeping its box stable. */
|
||||
export function Artwork({
|
||||
src,
|
||||
alt = '',
|
||||
className = '',
|
||||
style,
|
||||
fit = 'cover',
|
||||
eager,
|
||||
onLoad,
|
||||
fallback,
|
||||
}: {
|
||||
src?: string;
|
||||
alt?: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
fit?: 'cover' | 'contain';
|
||||
eager?: boolean;
|
||||
onLoad?: () => void;
|
||||
fallback?: ReactNode;
|
||||
}) {
|
||||
const [state, setState] = useState<'loading' | 'ready' | 'error'>('loading');
|
||||
const ref = useRef<HTMLImageElement>(null);
|
||||
useEffect(() => {
|
||||
setState('loading');
|
||||
const img = ref.current;
|
||||
if (img?.complete && img.naturalWidth) setState('ready');
|
||||
}, [src]);
|
||||
if (!src || state === 'error') return <div className={`artwork empty ${className}`} style={style}>{fallback}</div>;
|
||||
return (
|
||||
<img
|
||||
ref={ref}
|
||||
src={src}
|
||||
alt={alt}
|
||||
draggable={false}
|
||||
loading={eager ? 'eager' : 'lazy'}
|
||||
decoding="async"
|
||||
className={`artwork ${state === 'ready' ? 'ready' : ''} ${className}`}
|
||||
style={{ objectFit: fit, ...style }}
|
||||
onLoad={() => {
|
||||
setState('ready');
|
||||
onLoad?.();
|
||||
}}
|
||||
onError={() => setState('error')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function Switch({ checked, onChange, label, disabled }: { checked: boolean; onChange: (v: boolean) => void; label?: string; disabled?: boolean }) {
|
||||
return (
|
||||
<button role="switch" aria-checked={checked} aria-label={label} disabled={disabled} className={`switch${checked ? ' on' : ''}`} onClick={() => onChange(!checked)}>
|
||||
<span />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export interface Option<T extends string | number> {
|
||||
value: T;
|
||||
label: string;
|
||||
hint?: string;
|
||||
}
|
||||
|
||||
/** A dropdown that opens a Kaleido menu (not a native select). */
|
||||
export function Select<T extends string | number>({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
label,
|
||||
prefix,
|
||||
className = '',
|
||||
minWidth,
|
||||
disabled,
|
||||
placeholder,
|
||||
}: {
|
||||
value: T;
|
||||
options: Option<T>[];
|
||||
onChange: (v: T) => void;
|
||||
label?: string;
|
||||
prefix?: string;
|
||||
className?: string;
|
||||
minWidth?: number;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
}) {
|
||||
const current = options.find((o) => o.value === value);
|
||||
return (
|
||||
<button
|
||||
className={`select ${className}`}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
onClick={(e) =>
|
||||
openMenu(
|
||||
options.map((o): MenuItem => ({ label: o.label, hint: o.hint, checked: o.value === value, onSelect: () => onChange(o.value) })),
|
||||
e.currentTarget,
|
||||
{ minWidth: Math.max(minWidth ?? 0, (e.currentTarget as HTMLElement).offsetWidth) },
|
||||
)
|
||||
}
|
||||
>
|
||||
{prefix && <span className="select-prefix">{prefix}</span>}
|
||||
<span className="select-value">{current?.label ?? placeholder ?? 'Choose'}</span>
|
||||
<Icon name="chevronDown" size={15} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Segmented<T extends string>({ value, options, onChange, className = '' }: { value: T; options: Option<T>[]; onChange: (v: T) => void; className?: string }) {
|
||||
return (
|
||||
<div className={`seg ${className}`} role="tablist">
|
||||
{options.map((o) => (
|
||||
<button key={o.value} role="tab" aria-selected={o.value === value} className={o.value === value ? 'selected' : ''} onClick={() => onChange(o.value)}>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyState({ icon = 'info', title, children, action }: { icon?: string; title: string; children?: ReactNode; action?: ReactNode }) {
|
||||
return (
|
||||
<div className="empty-state">
|
||||
<div className="empty-icon">
|
||||
<Icon name={icon} size={26} />
|
||||
</div>
|
||||
<h3>{title}</h3>
|
||||
{children && <p>{children}</p>}
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorState({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
|
||||
const message = error instanceof Error ? error.message : String(error ?? 'Something went wrong.');
|
||||
return (
|
||||
<EmptyState icon="alert" title="Couldn’t load this" action={onRetry && <Button icon="refresh" onClick={onRetry}>Try again</Button>}>
|
||||
{message}
|
||||
</EmptyState>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageLoader() {
|
||||
return (
|
||||
<div className="page-loader">
|
||||
<Spinner size={28} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function KaleidoMark({ size = 26, className = '' }: { size?: number; className?: string }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 64 64" className={className} aria-hidden="true">
|
||||
<path fill="#C3E8D3" d="M33,4 L55.5,17 L42.5,24.5 L33,19 Z" />
|
||||
<path fill="#71B9B0" d="M56.5,19 L56.5,45 L43.5,37.5 L43.5,26.5 Z" />
|
||||
<path fill="#3D7C7B" d="M55.5,47 L33,60 L33,45 L42.5,39.5 Z" />
|
||||
<path fill="#D0A977" d="M31,60 L8.5,47 L21.5,39.5 L31,45 Z" />
|
||||
<path fill="#E9D8AE" d="M7.5,45 L7.5,19 L20.5,26.5 L20.5,37.5 Z" />
|
||||
<path fill="#EEF2DD" d="M8.5,17 L31,4 L31,19 L21.5,24.5 Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue