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:
Elijah 2026-10-30 16:26:37 -07:00
commit 00d72e70f4
121 changed files with 25315 additions and 0 deletions

62
src/ui/Backdrop.tsx Normal file
View 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
View 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
View 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
View 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
View 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
View 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
View 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>
);
}