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('start'); const [pin, setPin] = useState(null); const [error, setError] = useState(sessionError); const [busy, setBusy] = useState(false); const [url, setUrl] = useState(''); const [token, setToken] = useState(''); const poll = useRef | 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 (
KALEIDO
{mode === 'start' && ( <>

Your Plex library, front and center.

Sign in with your Plex account to browse and play everything on your servers.

)} {mode === 'browser' && ( <>

Continue in your browser

We opened Plex’s sign-in page. Kaleido continues automatically once you approve it.

Waiting for Plex…
)} {mode === 'code' && pin && ( <>

Link Kaleido

On any device, go to plex.tv/link and enter this code.

{pin.code}
Waiting for Plex…
)} {mode === 'manual' && ( <>

Connect to a server

Enter a Plex Media Server address and an access token. Account features such as profiles need a full sign-in.

{ e.preventDefault(); manual(); }} >
)} {error && (
{error}
)} {mode === 'start' && ( )}
); }