import { useState, type ReactNode } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, ApiError, type CollectionStatus, type HandshakeResult, type PendingEdits, type RemoteForm, type RemoteInUse, type RemoteSettings, } from '../api' import { askConfirm } from '../lib/confirm' import { Icon } from '../lib/icons' import { remoteHolder } from '../lib/platformCopy' import { Modal } from './Modal' import { OptionCard } from './OptionCard' /** * The picker's "Remote" step: the Konduktor servers this computer knows, and * a form to add one. * * A remote is saved only once the server has answered — the backend handshakes * every address and refuses a wrong password or a version that cannot talk, so * a saved remote is one that worked. Connecting can meet two things the user * has to decide, and both are asked here, before the library is shown: * * * another computer holds the library — take over (its edits stay with the * library), or leave it; * * the library holds edits another computer left unsaved — save them, * discard them, or decide later (they stay unsaved, and Save shows them). */ interface Props { onOpened: (status: CollectionStatus) => void } const input = 'w-full rounded-lg well px-3 py-2 text-sm text-text outline-none placeholder:text-faint focus:ring-1 focus:ring-accent' function addressLine(r: RemoteSettings): string { const main = r.port ? `${r.host}:${r.port}` : r.host if (!r.fallback_host) return main const fb = r.fallback_port ? `${r.fallback_host}:${r.fallback_port}` : r.fallback_host return `${main} · fallback ${fb}` } export function RemotePicker({ onOpened }: Props) { const qc = useQueryClient() const remotes = useQuery({ queryKey: ['remotes'], queryFn: api.remotes }) const [editing, setEditing] = useState(null) const [connecting, setConnecting] = useState(null) const [error, setError] = useState(null) const [pending, setPending] = useState<{ status: CollectionStatus; edits: PendingEdits } | null>(null) const connect = async (r: RemoteSettings, takeover = false): Promise => { setConnecting(r.id) setError(null) try { const status = await api.openRemote(r.id, takeover) if (status.pending_edits) setPending({ status, edits: status.pending_edits }) else onOpened(status) } catch (e) { const inUse = e instanceof ApiError && e.status === 409 ? (e.detail as RemoteInUse | null) : null if (inUse?.code === 'in_use') { const ok = await askConfirm({ title: `${r.name} is open on another computer`, body: ( <>

{remoteHolder(inUse.machine, inUse.since, inUse.batch)}

Taking over makes it read-only there. Any edits it has not saved stay with the library, and you are asked what to do with them.

), confirmLabel: 'Take over', tone: 'primary', }) if (ok) return connect(r, true) } else { setError((e as Error).message) } } finally { setConnecting(null) } } const remove = async (r: RemoteSettings) => { const ok = await askConfirm({ title: `Forget ${r.name}?`, body: 'Konduktor forgets this server and its saved password. Nothing on the server changes.', confirmLabel: 'Forget', }) if (!ok) return try { await api.deleteRemote(r.id) qc.invalidateQueries({ queryKey: ['remotes'] }) qc.invalidateQueries({ queryKey: ['platforms'] }) } catch (e) { setError((e as Error).message) } } if (editing) { return ( setEditing(null)} onSaved={() => { setEditing(null) qc.invalidateQueries({ queryKey: ['remotes'] }) qc.invalidateQueries({ queryKey: ['platforms'] }) }} /> ) } const list = remotes.data ?? [] return (
{remotes.isLoading &&
Loading…
} {list.map((r) => (
} title={r.name} subtitle={connecting === r.id ? 'Connecting…' : addressLine(r)} busy={connecting !== null} onClick={() => void connect(r)} />
))} } title="Add a remote library" subtitle="The address of a Konduktor server, and the account it was set up with" onClick={() => setEditing('new')} /> {error && (
{error}
)} {pending && ( { if (choice === 'save') await api.save() if (choice === 'discard') await api.discard() onOpened(pending.status) }} onError={(msg) => setError(msg)} /> )}
) } function RemoteFormView({ initial, onCancel, onSaved, }: { initial: RemoteSettings | null onCancel: () => void onSaved: () => void }) { const [name, setName] = useState(initial?.name ?? '') const [host, setHost] = useState(initial ? (initial.port ? `${initial.host}:${initial.port}` : initial.host) : '') const [fallback, setFallback] = useState( initial?.fallback_host ? initial.fallback_port ? `${initial.fallback_host}:${initial.fallback_port}` : initial.fallback_host : '', ) const [username, setUsername] = useState(initial?.username ?? '') const [password, setPassword] = useState('') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const [results, setResults] = useState(null) const ready = name.trim() && host.trim() && username.trim() && (password || initial?.has_password) const save = async () => { setBusy(true) setError(null) setResults(null) const form: RemoteForm = { name: name.trim(), host: host.trim(), fallback_host: fallback.trim() || null, username: username.trim(), ...(password ? { password } : {}), } try { const r = initial ? await api.editRemote(initial.id, form) : await api.addRemote(form) setResults(r.results) if (r.results.every((x) => x.ok)) onSaved() // A fallback that did not answer is saved anyway — a VPN address is often // unreachable at home — but the user is shown it before going back. } catch (e) { setError((e as Error).message) const detail = e instanceof ApiError ? (e.detail as { results?: HandshakeResult[] } | null) : null if (detail?.results) setResults(detail.results) } finally { setBusy(false) } } const saved = results !== null && error === null const field = (label: string, el: ReactNode, hint?: string) => ( ) return (
{field('Name', setName(e.target.value)} placeholder="NAS" autoFocus />)} {field( 'Address', setHost(e.target.value)} placeholder="192.168.1.20 or nas.local:8765" />, 'The server’s address on your network. Add :port if it is not 8765, or enter a full https://… address if it sits behind a reverse proxy.', )} {field( 'Fallback address', setFallback(e.target.value)} placeholder="Optional — e.g. https://konduktor.example.net" />, 'Tried when the first one does not answer — away from home, for instance. Same rules: host[:port] for the server itself (8765 if no port), or a full https://… address used exactly as typed.', )} {field('Username', setUsername(e.target.value)} autoComplete="username" />)} {field( 'Password', setPassword(e.target.value)} placeholder={initial?.has_password ? 'Unchanged' : ''} autoComplete="current-password" />, 'Kept in this computer’s keychain.', )} {results && (
{results.map((r) => (
{r.address === 'primary' ? 'Address' : 'Fallback'}{' '} {r.url} {!r.ok && {r.error}}
))}
)} {error && (
{error}
)}
{saved ? ( ) : ( <> )}
) } /** The edits another computer left unsaved in the library: save, discard, or * decide later. Esc is "later" — never a discard. */ function PendingEditsDialog({ edits, onChoose, onError, }: { edits: PendingEdits onChoose: (choice: 'save' | 'discard' | 'later') => Promise onError: (msg: string) => void }) { const [busy, setBusy] = useState(false) const choose = async (choice: 'save' | 'discard' | 'later') => { setBusy(true) try { await onChoose(choice) } catch (e) { onError((e as Error).message) setBusy(false) } } return ( void choose('later')}>
Unsaved edits from {edits.machine || 'another computer'}

This library has edits that were never saved: {edits.summary}.

Save them, or discard them to start from the library as it was last saved.

) }