Initial implementation of remote library system

This commit is contained in:
patben8 committed 2026-10-04 17:13:24 +02:00
1 parent e8a53eee07
commit e5fb0f0dbb
65 files changed
+6000 -183

No files matched your search

+39 -1
View File
@@ -646,7 +646,44 @@ export default function App() {
notify(n ? 'success' : 'error', text, details)
}
// A conversion keeps running if the page reloads; find it again.
const editState = useQuery({ queryKey: ['state'], queryFn: api.state, enabled: loaded, retry: false })
const isRemote = !!collection.data?.library?.remote
const editState = useQuery({
queryKey: ['state'],
queryFn: api.state,
enabled: loaded,
retry: false,
// A remote library's connection changes on its own (another computer
// takes over, the server drops off the network), so it is polled; a local
// library's state changes only when this app changes it.
refetchInterval: isRemote ? 5000 : false,
})
const remoteState = editState.data?.remote?.state ?? null
const remoteShown = useRef<string | null>(null)
useEffect(() => {
const previous = remoteShown.current
remoteShown.current = remoteState
if (!remoteState || previous === remoteState || previous === null) return
// What the library will accept changed with it: re-read, so the UI gates
// itself (read-only while taken over or offline) — never offers an edit.
qc.invalidateQueries({ queryKey: ['capabilities'] })
const who = editState.data?.remote?.machine
if (remoteState === 'taken_over')
notify('warning', `${who || 'Another computer'} took over this library — it is read-only here now`)
else if (remoteState === 'offline') notify('warning', 'The server cannot be reached — read-only until it is back')
else if (remoteState === 'connected' && previous !== 'reconnecting') notify('success', 'Reconnected to the server')
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteState])
const remoteNotices = editState.data?.remote?.notices ?? 0
const noticesShown = useRef(0)
useEffect(() => {
if (remoteNotices <= noticesShown.current) return
noticesShown.current = remoteNotices
const text = editState.data?.remote?.notice
if (text) notify('warning', text)
// Re-read: the server's library is what it is now, not what this tab holds.
qc.invalidateQueries()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remoteNotices])
useEffect(() => {
const id = editState.data?.stem_job
if (id && !batchJob) setBatchJob({ id, kind: 'stems' })
@@ -1510,6 +1547,7 @@ export default function App() {
: null
}
loading={loading}
connection={editState.data?.remote ?? null}
collectionName={capabilities.data ? libraryName : null}
onChangeCollection={() => {
// The same question the sidebar header asks: this button used to
+124 -5
View File
@@ -227,7 +227,10 @@ export interface SaveCapabilities {
}
/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */
export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
export type ReadonlyCause =
| 'platform_incomplete' | 'cloud_synced' | 'not_in_library' | 'browsing'
/** A library held by a server: another computer took it over / the server is unreachable. */
| 'taken_over' | 'offline'
export interface Capabilities {
platform: Platform
@@ -261,8 +264,15 @@ export interface Capabilities {
audio_formats: string[]
artwork: boolean
artwork_note: string | null
/** Whose filesystem an import destination is on: this computer's ('host'),
* or the machine holding the library ('library' — audio is uploaded). */
audio_destination: 'host' | 'library'
/** Added files can be left where they are rather than copied. */
reference: boolean
}
playlists: { folders: boolean; smart: 'none' | 'read_only'; reorder: boolean }
/** Path mapping / rewriting / the missing-files check apply to this library. */
paths: { remappable: boolean }
save: SaveCapabilities
}
@@ -273,6 +283,8 @@ export interface LibraryInfo {
path: string
display_name: string
version: string | null
/** Set when the library is held by a server (a saved remote). */
remote: { id: string; name: string; via: string | null } | null
}
export interface PlatformOption {
@@ -280,7 +292,7 @@ export interface PlatformOption {
name: string
library_label: string
/** Whether picking this platform's library means picking a file or a folder. */
selects: 'file' | 'directory'
selects: 'file' | 'directory' | 'remote'
installed: boolean
/** How many libraries this platform has right now; `installed` is `found > 0`. */
found: number
@@ -302,6 +314,22 @@ export interface EditState {
stem_job: string | null
/** What this open's crash recovery did about an interrupted conversion. */
stem_recovery: { committed: number; restored: number; kept: number } | null
/** A remote library's connection, null for a local one. */
remote: RemoteConnection | null
}
/** How this computer stands with a remote library's server. `taken_over`:
* another computer holds the session, so this one is read-only. */
export interface RemoteConnection {
state: 'connected' | 'reconnecting' | 'offline' | 'taken_over'
/** The address in use ('primary' / 'fallback'), when connected. */
via: 'primary' | 'fallback' | null
/** Who took it over, when `taken_over`. */
machine: string | null
/** Something to tell the user once ("the server restarted"), with a counter
* that changes each time there is a new one. */
notice: string | null
notices: number
}
export interface CollectionStatus {
@@ -310,6 +338,61 @@ export interface CollectionStatus {
library: LibraryInfo | null
tracks: number | null
playlists: number | null
/** Opening a remote: the unsaved edits another computer left there. */
pending_edits?: PendingEdits | null
}
/** Unsaved edits a remote library holds that another computer made. */
export interface PendingEdits {
machine: string | null
summary: string
}
/** A saved remote — a Konduktor server this computer knows how to reach. The
* password is in the OS keychain, never here. */
export interface RemoteSettings {
id: string
name: string
host: string
port: number | null
fallback_host: string | null
fallback_port: number | null
username: string
has_password: boolean
}
export interface RemoteForm {
name: string
/** `host` or `host:port`. */
host: string
fallback_host?: string | null
username: string
/** Omitted on an edit: keep the saved one. */
password?: string
}
/** One address's answer to a handshake. */
export interface HandshakeResult {
address: 'primary' | 'fallback'
url: string
ok: boolean
error: string | null
kind: 'ok' | 'unreachable' | 'auth' | 'version' | 'other'
}
/** Someone else holds a remote's session (409 from open-remote). */
export interface RemoteInUse {
code: 'in_use'
machine: string
since: string
batch: string | null
}
export interface RemoteCacheUsage {
bytes: number
files: number
cap: number
free: number
}
export interface CollectionCandidate {
@@ -515,6 +598,9 @@ export interface StemPlan {
bytes: number
/** The originals' size — what Save deletes in Replace mode. */
original_bytes: number
/** A remote library: what must cross the network (bytes; `speed` in
* bytes/s, `measured` false while it is still a default). */
transfer?: { download: number; upload: number; speed: number; measured: boolean }
}
/** A stem conversion job's `result`. */
@@ -743,6 +829,19 @@ async function getJSON<T>(url: string): Promise<T> {
return res.json() as Promise<T>
}
/** A refusal from the backend. `message` is always a sentence; `detail` keeps
* a structured answer (e.g. `{code: 'in_use', machine, since}`) for the few
* callers that act on it rather than just showing it. */
export class ApiError extends Error {
status: number
detail: unknown
constructor(status: number, message: string, detail: unknown) {
super(message)
this.status = status
this.detail = detail
}
}
async function send<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await fetch(API_BASE + url, {
method,
@@ -750,14 +849,19 @@ async function send<T>(method: string, url: string, body?: unknown): Promise<T>
body: body ? JSON.stringify(body) : undefined,
})
if (!res.ok) {
let detail = `${res.status} ${res.statusText}`
let message = `${res.status} ${res.statusText}`
let detail: unknown = null
try {
const j = await res.json()
if (j.detail) detail = j.detail
if (j.detail) {
detail = j.detail
if (typeof j.detail === 'string') message = j.detail
else if (typeof j.detail?.message === 'string') message = j.detail.message
}
} catch {
/* ignore */
}
throw new Error(detail)
throw new ApiError(res.status, message, detail)
}
return res.json() as Promise<T>
}
@@ -782,6 +886,21 @@ export const api = {
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
/** Folders on the machine that HOLDS the library (a remote's server),
* confined to its content folder — `home` is that folder. */
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
// ---- remote libraries ----
remotes: () => getJSON<RemoteSettings[]>('/api/remotes'),
addRemote: (form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('POST', '/api/remotes', form),
editRemote: (id: string, form: RemoteForm) =>
send<{ remote: RemoteSettings; results: HandshakeResult[] }>('PATCH', `/api/remotes/${id}`, form),
deleteRemote: (id: string) => send<{ status: string }>('DELETE', `/api/remotes/${id}`),
openRemote: (id: string, takeover = false) =>
send<CollectionStatus>('POST', '/api/library/open-remote', { remote_id: id, takeover }),
remoteCache: () => getJSON<RemoteCacheUsage>('/api/remote-cache'),
clearRemoteCache: () => send<{ freed: number }>('DELETE', '/api/remote-cache'),
// Re-asked rather than cached: drives come and go while a dialog is open.
places: (platform?: string) => getJSON<FsPlace[]>(`/api/fs/places${qs({ platform })}`),
+63 -6
View File
@@ -18,6 +18,10 @@ import { FolderPicker } from './FolderPicker'
* how the DJ keeps their music, and a remembered default would quietly apply
* last week's answer to a different drive.
*
* A library held by a server (`tracks.audio_destination === 'library'`) is the
* other exception: it cannot see this computer's files, so the only choice is
* which folder ON THE SERVER they are uploaded into.
*
* A playlist or export target still needs the files in the collection first —
* both hold collection track ids — so the dialog says so rather than doing it
* silently. Files the collection already holds are not added again, but still
@@ -53,8 +57,11 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
// decides copy vs in place itself, so there is nothing to ask.
const caps = useCaps()
const places = caps.tracks.places_audio
const [mode, setMode] = useState<'copy' | 'reference' | null>(null)
// Uploaded into a folder on the server: nothing to ask but where.
const uploads = !places && caps.tracks.audio_destination === 'library'
const [mode, setMode] = useState<'copy' | 'reference' | null>(uploads ? 'copy' : null)
const [folder, setFolder] = useState('')
const remote = useServerImportFolder(uploads)
const [browsing, setBrowsing] = useState(false)
const [job, setJob] = useState<JobStatus | null>(null)
const [starting, setStarting] = useState(false)
@@ -65,9 +72,13 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
const prefsLoaded = prefs.isSuccess
useEffect(() => {
if (!prefsLoaded || folder) return
if (uploads) {
if (remote.folder) setFolder(remote.folder)
return
}
const p = prefs.data as { importFolder?: string }
setFolder(p?.importFolder || '~/Music/Konduktor Imports')
}, [prefsLoaded, prefs.data, folder])
}, [prefsLoaded, prefs.data, folder, uploads, remote.folder])
const body: FolderAddRequest = {
track_ids: trackIds,
@@ -192,9 +203,11 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
{browsing && (
<FolderPicker
value={folder}
listing={uploads ? 'library' : 'host'}
onChange={(path) => {
setFolder(path)
api.patchPrefs({ importFolder: path }).catch(() => {})
if (uploads) remote.remember(path)
else api.patchPrefs({ importFolder: path }).catch(() => {})
}}
onClose={() => setBrowsing(false)}
/>
@@ -224,7 +237,21 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
</div>
)}
{!places && (
{uploads && (
<div className="rounded well px-3 py-2 text-xs text-muted">
<div>Uploaded to {remote.serverName} into</div>
<div className="mt-1 flex items-center gap-2">
<span className="min-w-0 truncate font-mono text-text" dir="rtl" title={folder}>
{folder ? `\u200E${folder}\u200E` : 'Loading…'}
</span>
<button onClick={() => setBrowsing(true)} className="shrink-0 text-accent hover:underline">
Change…
</button>
</div>
</div>
)}
{!places && !uploads && (
<div className="space-y-1">
{option(
'copy',
@@ -270,12 +297,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
<div className="text-text">
{newCount} new to {libraryName}
{shown !== 'reference' && p.total_bytes > 0 && (
<span className="text-muted"> · {gb(p.total_bytes)} to copy</span>
<span className="text-muted"> · {gb(p.total_bytes)} to {uploads ? 'upload' : 'copy'}</span>
)}
</div>
{shown !== 'reference' && p.free_bytes != null && (
<div className={p.enough_space === false ? 'text-pink' : 'text-faint'}>
{gb(p.free_bytes)} free
{gb(p.free_bytes)} free{uploads ? ' on the server' : ''}
{p.enough_space === false && ' — not enough space'}
</div>
)}
@@ -369,3 +396,33 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
document.body,
)
}
/**
* A folder ON THE SERVER of a remote library — where uploads go, or where stem
* files are written: the one last chosen for THIS remote (remembered per remote
* under `key`, since each server has its own folders), else its content folder
* (plus `sub`). `serverName` names it in the dialog.
*/
export function useServerFolder(
enabled: boolean,
key: 'remoteImportFolders' | 'remoteStemFolders' = 'remoteImportFolders',
sub = '',
) {
const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection, enabled })
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs, enabled })
const root = useQuery({ queryKey: ['fs', 'library', '~', null], queryFn: () => api.libraryListDir(), enabled })
const remoteId = collection.data?.library?.remote?.id ?? null
const saved = (prefs.data as Record<string, Record<string, string> | undefined> | undefined)?.[key]
const home = root.data?.home
const folder = (remoteId && saved?.[remoteId]) || (home ? (sub ? `${home}/${sub}` : home) : '')
return {
folder,
serverName: collection.data?.library?.display_name ?? 'the server',
remember: (path: string) => {
if (!remoteId) return
api.patchPrefs({ [key]: { ...(saved ?? {}), [remoteId]: path } }).catch(() => {})
},
}
}
export const useServerImportFolder = (enabled: boolean) => useServerFolder(enabled)
+17 -48
View File
@@ -1,10 +1,12 @@
import { useState, type ReactNode } from 'react'
import { useState } from 'react'
import { useMutation, useQuery } from '@tanstack/react-query'
import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api'
import { FileBrowser, useFsListing } from './FileBrowser'
import { browsePrompt, platformAvailability } from '../lib/platformCopy'
import { Icon } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons'
import { OptionCard } from './OptionCard'
import { RemotePicker } from './RemotePicker'
/**
* Choose a library to open, in two steps: WHICH PLATFORM, then which library.
@@ -35,50 +37,6 @@ function formatWhen(sec: number | null): string {
})
}
function OptionCard({
icon,
lit,
title,
subtitle,
disabled,
busy,
onClick,
}: {
icon: ReactNode
/** A small lit dot on the icon tile: "something is here". */
lit?: boolean
title: string
subtitle: string
disabled?: boolean
busy?: boolean
onClick: () => void
}) {
return (
<button
disabled={disabled || busy}
onClick={onClick}
className="btn-glass group flex w-full items-center gap-3.5 rounded-2xl px-3 py-3 text-left disabled:cursor-not-allowed disabled:opacity-40"
>
<span className="well relative flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-text">
{icon}
{lit && (
<span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-mint shadow-[0_0_8px_var(--color-mint)] ring-2 ring-[rgb(12_14_24)]" />
)}
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-text">{title}</div>
<div className="truncate text-xs text-faint">{subtitle}</div>
</div>
<Icon
name="chevronRight"
size={14}
strokeWidth={2.2}
className="text-faint transition-colors group-hover:text-text"
/>
</button>
)
}
export function CollectionPicker({ onOpened, onCancel }: Props) {
const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform')
const [platform, setPlatform] = useState<PlatformOption | null>(null)
@@ -89,10 +47,12 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
// /api/platforms is the pre-load equivalent, and it is the whole of step one.
const platforms = useQuery({ queryKey: ['platforms'], queryFn: api.platforms })
// A remote is not found on this computer; its step lists saved servers.
const remote = platform?.selects === 'remote'
const options = useQuery({
queryKey: ['collectionOptions', platform?.platform],
queryFn: () => api.collectionOptions(platform!.platform),
enabled: !!platform,
enabled: !!platform && !remote,
})
// Shares FileBrowser's query, so the confirm row below cannot disagree with
@@ -126,7 +86,9 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
const subtitle =
step === 'platform'
? 'Konduktor opens libraries from each of these.'
: step === 'library'
: step === 'library' && remote
? 'A library held by a Konduktor server, played and prepared from here.'
: step === 'library'
? 'Open automatically, resume your last one, or browse.'
: platform
? browsePrompt(platform)
@@ -146,7 +108,11 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
)}
<div className="min-w-0 flex-1">
<div className="text-[15px] font-semibold tracking-tight">
{platform ? `Select your ${platform.name} library` : 'Select your DJ platform'}
{remote
? 'Open a remote library'
: platform
? `Select your ${platform.name} library`
: 'Select your DJ platform'}
</div>
<div className="truncate text-xs text-muted">{subtitle}</div>
</div>
@@ -199,6 +165,9 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
/>
))}
</div>
) : step === 'library' && remote ? (
/* ---- Step 2, remote: which server ---- */
<RemotePicker onOpened={onOpened} />
) : step === 'library' ? (
/* ---- Step 2: which library of that platform ---- */
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
+43 -4
View File
@@ -10,6 +10,8 @@ import {
type StemTarget,
} from '../api'
import { FolderPicker } from './FolderPicker'
import { useServerFolder } from './AddFilesDialog'
import { useCaps } from '../lib/capabilities'
/**
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
@@ -89,6 +91,12 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
const [showSkipped, setShowSkipped] = useState(false)
const [starting, setStarting] = useState(false)
const [target, setTarget] = useState<StemTarget | null>(null)
// A remote library: its stem files are written ON THE SERVER, so the
// destination is one of its folders (remembered per remote), never the
// local one `stemConvert` remembers for this computer's libraries.
const remote = useCaps().tracks.audio_destination === 'library'
const server = useServerFolder(remote, 'remoteStemFolders', 'Stems')
const [serverDest, setServerDest] = useState<string | null>(null)
useEffect(() => {
if (opts || !prefs.isSuccess) return
@@ -114,9 +122,10 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists })
const choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data])
const destination = remote ? (serverDest ?? server.folder) : (opts?.destination ?? '')
const body: StemConvertOptions | null = opts && {
mode: opts.mode,
destination: opts.mode === 'destination' ? opts.destination : null,
destination: opts.mode === 'destination' ? destination : null,
collection: opts.mode === 'replace' ? 'repoint' : opts.collection,
playlist_id:
opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing'
@@ -218,7 +227,17 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
return createPortal(
<>
{browsing && opts && (
<FolderPicker value={opts.destination} onChange={(path) => set({ destination: path })} onClose={() => setBrowsing(false)} />
<FolderPicker
value={destination}
listing={remote ? 'library' : 'host'}
onChange={(path) => {
if (remote) {
setServerDest(path)
server.remember(path)
} else set({ destination: path })
}}
onClose={() => setBrowsing(false)}
/>
)}
<div
aria-modal="true"
@@ -260,8 +279,8 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
() => set({ mode: 'destination' }),
'Save to a folder',
<span className="flex items-center gap-2">
<span className="min-w-0 truncate font-mono" dir="rtl" title={opts.destination}>
{`‎${opts.destination}‎`}
<span className="min-w-0 truncate font-mono" dir="rtl" title={destination}>
{`‎${destination}‎`}
</span>
<button
onClick={(e) => {
@@ -414,6 +433,26 @@ export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading
{size(plan.bytes)} of stem files
</div>
)}
{/* A remote library: the sources come down and the stem
files go up — said, with the time it adds. */}
{n > 0 && plan.transfer && plan.transfer.download + plan.transfer.upload > 0 && (
<div className="text-faint">
{size(plan.transfer.download)} to download and {size(plan.transfer.upload)} to upload
{' · about '}
{duration((plan.transfer.download + plan.transfer.upload) / plan.transfer.speed)}
{plan.transfer.measured ? '' : ' (estimated)'} more
</div>
)}
{n > 0 && plan.transfer && (
<ul className="space-y-0.5 text-faint">
{plan.space.map((sp) => (
<li key={`${sp.volume}-${sp.folder}`}>
{sp.volume}: {size(sp.bytes)} needed
{sp.free != null ? `, ${size(sp.free)} free` : ''}
</li>
))}
</ul>
)}
{plan.blocked && <div className="text-pink">{plan.blocked}</div>}
</section>
)}
+19 -6
View File
@@ -26,13 +26,17 @@ import { Icon, type IconName } from '../lib/icons'
* the cache key. Passing it back up through a callback would mean an effect
* firing on every navigation to tell the parent what it already asked for.
*/
export function useFsListing(path: string | undefined, platform?: string) {
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host') {
return useQuery({
queryKey: ['fs', path ?? '~', platform ?? null],
queryFn: () => api.listDir(path, platform),
queryKey: ['fs', listing, path ?? '~', platform ?? null],
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform)),
})
}
/** Whose folders: this computer's (`host`), or those of the machine holding the
* library — a remote's server, confined to its content folder (`library`). */
export type Listing = 'host' | 'library'
// Volumes come and go while a dialog is open, so the rail polls. Slower than
// the sidebar's device poll: this is a shortcut list, not the thing you came for.
const PLACES_POLL_MS = 5000
@@ -59,19 +63,28 @@ interface Props {
onPickFile?: (path: string) => void
/** The caller's confirm row, pinned under the listing. */
footer?: ReactNode
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
listing?: Listing
}
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer }: Props) {
const listing = useFsListing(path, platform)
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) {
const listing = useFsListing(path, platform, whose)
const places = useQuery({
queryKey: ['fs-places', platform ?? null],
queryFn: () => api.places(platform),
refetchInterval: PLACES_POLL_MS,
// A server's folders have one place worth a shortcut: its content folder.
enabled: whose === 'host',
})
const data: FsListing | undefined = listing.data
const here = data?.path ?? ''
const rows = places.data ?? []
const rows: FsPlace[] =
whose === 'library'
? data
? [{ name: 'Library folder', path: data.home, kind: 'library' } as FsPlace]
: []
: (places.data ?? [])
// Volatile section LAST: a drive appearing or vanishing must not shift the
// rows above it under a cursor that is already moving towards one.
+6 -3
View File
@@ -1,6 +1,6 @@
import { createPortal } from 'react-dom'
import { useState } from 'react'
import { FileBrowser, useFsListing } from './FileBrowser'
import { FileBrowser, useFsListing, type Listing } from './FileBrowser'
/**
* Pick a FOLDER, by browsing.
@@ -15,16 +15,18 @@ interface Props {
value: string
onChange: (path: string) => void
onClose: () => void
/** Whose folders: this computer's, or the server's holding a remote library. */
listing?: Listing
}
export function FolderPicker({ value, onChange, onClose }: Props) {
export function FolderPicker({ value, onChange, onClose, listing = 'host' }: Props) {
// `undefined` means "wherever the server thinks home is" — the picker does not
// need to know that path to open on it.
const [dir, setDir] = useState<string | undefined>(value || undefined)
const [newFolder, setNewFolder] = useState('')
// Shares FileBrowser's query, so "where am I" cannot disagree with what is
// on screen — and the confirm row below needs it to name its target.
const here = useFsListing(dir).data?.path ?? ''
const here = useFsListing(dir, undefined, listing).data?.path ?? ''
const confirm = () => {
onChange(newFolder.trim() ? `${here}/${newFolder.trim()}` : here)
@@ -40,6 +42,7 @@ export function FolderPicker({ value, onChange, onClose }: Props) {
<FileBrowser
mode="directory"
listing={listing}
path={dir}
onNavigate={setDir}
footer={
+16 -4
View File
@@ -5,6 +5,7 @@ import { api, type ImportPreview, type JobStatus } from '../api'
import { useCaps } from '../lib/capabilities'
import { placedAudioSummary } from '../lib/platformCopy'
import { FolderPicker } from './FolderPicker'
import { useServerImportFolder } from './AddFilesDialog'
/**
* Import a browsed device into the loaded collection.
@@ -45,6 +46,9 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
// One that places its own audio — a stick — needs no destination.
const caps = useCaps()
const places = caps.tracks.places_audio
// A library held by a server: the audio is uploaded into one of ITS folders.
const uploads = !places && caps.tracks.audio_destination === 'library'
const remote = useServerImportFolder(uploads)
const [baseFolder, setBaseFolder] = useState('')
const [useSubfolder, setUseSubfolder] = useState(true)
const [browsing, setBrowsing] = useState(false)
@@ -59,9 +63,13 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
useEffect(() => {
if (!prefsLoaded || baseFolder) return
const p = prefs.data as { importFolder?: string; importSubfolder?: boolean }
setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports')
if (uploads) {
if (remote.folder) setBaseFolder(remote.folder)
} else {
setBaseFolder(p?.importFolder || '~/Music/Konduktor Imports')
}
if (typeof p?.importSubfolder === 'boolean') setUseSubfolder(p.importSubfolder)
}, [prefsLoaded, prefs.data, baseFolder])
}, [prefsLoaded, prefs.data, baseFolder, uploads, remote.folder])
const remember = (patch: Record<string, unknown>) => {
api.patchPrefs(patch).catch(() => {
@@ -153,9 +161,11 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
{browsing && (
<FolderPicker
value={baseFolder}
listing={uploads ? 'library' : 'host'}
onChange={(path) => {
setBaseFolder(path)
remember({ importFolder: path })
if (uploads) remote.remember(path)
else remember({ importFolder: path })
}}
onClose={() => setBrowsing(false)}
/>
@@ -179,7 +189,9 @@ export function ImportDialog({ playlistId, deviceLabel, onClose, onDone, onError
)}
{!places && (
<div>
<span className="mb-1 block text-xs text-muted">Copy audio into</span>
<span className="mb-1 block text-xs text-muted">
{uploads ? `Upload audio to ${remote.serverName}, into` : 'Copy audio into'}
</span>
<div className="flex items-center gap-2">
<span
title={baseFolder}
+47
View File
@@ -0,0 +1,47 @@
import type { ReactNode } from 'react'
import { Icon } from '../lib/icons'
/** One choice in the library picker: an icon tile, a title, one line of facts. */
export function OptionCard({
icon,
lit,
title,
subtitle,
disabled,
busy,
onClick,
}: {
icon: ReactNode
/** A small lit dot on the icon tile: "something is here". */
lit?: boolean
title: string
subtitle: string
disabled?: boolean
busy?: boolean
onClick: () => void
}) {
return (
<button
disabled={disabled || busy}
onClick={onClick}
className="btn-glass group flex w-full items-center gap-3.5 rounded-2xl px-3 py-3 text-left disabled:cursor-not-allowed disabled:opacity-40"
>
<span className="well relative flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-text">
{icon}
{lit && (
<span className="absolute -right-0.5 -top-0.5 h-2.5 w-2.5 rounded-full bg-mint shadow-[0_0_8px_var(--color-mint)] ring-2 ring-[rgb(12_14_24)]" />
)}
</span>
<div className="min-w-0 flex-1">
<div className="text-sm font-semibold text-text">{title}</div>
<div className="truncate text-xs text-faint">{subtitle}</div>
</div>
<Icon
name="chevronRight"
size={14}
strokeWidth={2.2}
className="text-faint transition-colors group-hover:text-text"
/>
</button>
)
}
@@ -0,0 +1,113 @@
import { createPortal } from 'react-dom'
import { useEffect, useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { size } from './ConvertStemsDialog'
/**
* Settings → Remote audio: this computer's copies of a remote library's audio.
*
* Everything that needs a track as a FILE — the deck, analysis, stem
* separation, an export's copy onto a stick — runs here on a downloaded copy,
* kept in one cache so a track is fetched once. Least recently used goes first
* once the cap is reached; clearing it only costs a download the next time.
*/
const CAPS_GB = [2, 5, 10, 20, 50, 100]
export function RemoteCacheSettings({ onClose }: { onClose: () => void }) {
const qc = useQueryClient()
const usage = useQuery({ queryKey: ['remote-cache'], queryFn: api.remoteCache })
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose])
const u = usage.data
const capGb = u ? Math.round(u.cap / 1024 ** 3) : null
const setCap = async (gb: number) => {
setError(null)
try {
const p = await api.patchPrefs({ remoteCacheBytes: gb * 1024 ** 3 })
qc.setQueryData(['prefs'], p)
qc.invalidateQueries({ queryKey: ['remote-cache'] })
} catch (e) {
setError((e as Error).message)
}
}
const clear = async () => {
setBusy(true)
setError(null)
try {
await api.clearRemoteCache()
qc.invalidateQueries({ queryKey: ['remote-cache'] })
} catch (e) {
setError((e as Error).message)
} finally {
setBusy(false)
}
}
return createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onClick={onClose}
>
<div className="flex w-full max-w-md flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Remote audio</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
<div className="space-y-4 px-5 py-4 text-sm">
<p className="text-muted">
Tracks from a remote library are downloaded to this computer to be played, analysed,
converted or exported, and kept so each is fetched only once.
</p>
<div className="text-text">
{u ? `${size(u.bytes)} in ${u.files} file${u.files === 1 ? '' : 's'}` : 'Loading…'}
{u && <span className="text-faint"> · {size(u.free)} free on this disk</span>}
</div>
<label className="flex items-center gap-3">
<span className="text-muted">Keep up to</span>
<select
value={capGb ?? ''}
onChange={(e) => void setCap(Number(e.target.value))}
className="rounded-lg well px-2 py-1 text-sm text-text outline-none"
>
{capGb !== null && !CAPS_GB.includes(capGb) && <option value={capGb}>{capGb} GB</option>}
{CAPS_GB.map((gb) => (
<option key={gb} value={gb}>
{gb} GB
</option>
))}
</select>
<span className="text-faint">— the least recently used go first</span>
</label>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
<button
disabled={busy || !u || u.files === 0}
onClick={() => void clear()}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text disabled:opacity-40"
>
{busy ? 'Clearing…' : 'Clear'}
</button>
<button onClick={onClose} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
Done
</button>
</div>
</div>
</div>,
document.body,
)
}
+375
View File
@@ -0,0 +1,375 @@
import { useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
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 { 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<RemoteSettings | 'new' | null>(null)
const [connecting, setConnecting] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [pending, setPending] = useState<{ status: CollectionStatus; edits: PendingEdits } | null>(null)
const connect = async (r: RemoteSettings, takeover = false): Promise<void> => {
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: (
<>
<p>{remoteHolder(inUse.machine, inUse.since, inUse.batch)}</p>
<p>
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.
</p>
</>
),
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 (
<RemoteFormView
initial={editing === 'new' ? null : editing}
onCancel={() => setEditing(null)}
onSaved={() => {
setEditing(null)
qc.invalidateQueries({ queryKey: ['remotes'] })
qc.invalidateQueries({ queryKey: ['platforms'] })
}}
/>
)
}
const list = remotes.data ?? []
return (
<div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-5">
{remotes.isLoading && <div className="text-sm text-faint">Loading…</div>}
{list.map((r) => (
<div key={r.id} className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<OptionCard
icon={<Icon name="server" size={20} />}
title={r.name}
subtitle={connecting === r.id ? 'Connecting…' : addressLine(r)}
busy={connecting !== null}
onClick={() => void connect(r)}
/>
</div>
<button
title="Edit"
onClick={() => setEditing(r)}
className="btn-glass flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted hover:text-text"
>
<Icon name="pencil" size={14} />
</button>
<button
title="Forget"
onClick={() => void remove(r)}
className="btn-glass flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted hover:text-pink"
>
<Icon name="trash" size={14} />
</button>
</div>
))}
<OptionCard
icon={<Icon name="plus" size={20} />}
title="Add a remote library"
subtitle="The address of a Konduktor server, and the account it was set up with"
onClick={() => setEditing('new')}
/>
{error && (
<div className="rounded-xl bg-pink/10 px-3 py-2 text-xs text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
{error}
</div>
)}
{pending && (
<PendingEditsDialog
edits={pending.edits}
onChoose={async (choice) => {
if (choice === 'save') await api.save()
if (choice === 'discard') await api.discard()
onOpened(pending.status)
}}
onError={(msg) => setError(msg)}
/>
)}
</div>
)
}
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<string | null>(null)
const [results, setResults] = useState<HandshakeResult[] | null>(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) => (
<label className="block space-y-1">
<span className="text-xs font-medium text-muted">{label}</span>
{el}
{hint && <span className="block text-[11px] text-faint">{hint}</span>}
</label>
)
return (
<div className="flex min-h-0 flex-1 flex-col">
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-5">
{field('Name', <input className={input} value={name} onChange={(e) => setName(e.target.value)} placeholder="NAS" autoFocus />)}
{field(
'Address',
<input className={`${input} font-mono`} value={host} onChange={(e) => 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.',
)}
{field(
'Fallback address',
<input className={`${input} font-mono`} value={fallback} onChange={(e) => setFallback(e.target.value)} placeholder="Optional — e.g. its Tailscale address" />,
'Tried when the first one does not answer — away from home, for instance.',
)}
{field('Username', <input className={input} value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="username" />)}
{field(
'Password',
<input
type="password"
className={input}
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={initial?.has_password ? 'Unchanged' : ''}
autoComplete="current-password"
/>,
'Kept in this computer’s keychain.',
)}
{results && (
<div className="space-y-1 rounded-xl well px-3 py-2 text-xs">
{results.map((r) => (
<div key={r.address} className="flex items-start gap-2">
<span className={r.ok ? 'text-mint' : r.kind === 'unreachable' ? 'text-gold' : 'text-pink'}>
<Icon name={r.ok ? 'check' : r.kind === 'unreachable' ? 'warning' : 'close'} size={13} />
</span>
<span className="min-w-0 flex-1">
<span className="text-muted">{r.address === 'primary' ? 'Address' : 'Fallback'}</span>{' '}
<span className="font-mono text-faint">{r.url}</span>
{!r.ok && <span className="block text-faint">{r.error}</span>}
</span>
</div>
))}
</div>
)}
{error && (
<div className="rounded-xl bg-pink/10 px-3 py-2 text-xs text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
{error}
</div>
)}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-5 py-3">
{saved ? (
<button onClick={onSaved} className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold">
Done
</button>
) : (
<>
<button onClick={onCancel} className="btn-glass rounded-full px-4 py-1.5 text-sm text-muted hover:text-text">
Cancel
</button>
<button
disabled={!ready || busy}
onClick={() => void save()}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:cursor-not-allowed disabled:opacity-40"
>
{busy ? 'Checking…' : initial ? 'Save' : 'Add'}
</button>
</>
)}
</div>
</div>
)
}
/** 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<void>
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 createPortal(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onKeyDown={(e) => e.key === 'Escape' && !busy && void choose('later')}
>
<div className="w-full max-w-sm overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-4 text-[15px] font-semibold tracking-tight">
Unsaved edits from {edits.machine || 'another computer'}
</div>
<div className="space-y-2 px-5 py-4 text-sm text-muted">
<p>This library has edits that were never saved: {edits.summary}.</p>
<p>Save them, or discard them to start from the library as it was last saved.</p>
</div>
<div className="flex items-center gap-2 border-t border-line px-5 py-3">
<button
disabled={busy}
onClick={() => void choose('later')}
className="rounded-full px-3 py-1.5 text-sm text-faint hover:text-text disabled:opacity-40"
>
Decide later
</button>
<span className="flex-1" />
<button
disabled={busy}
onClick={() => void choose('discard')}
className="rounded-full bg-pink/15 px-4 py-1.5 text-sm font-semibold text-[#ffd0da] shadow-[inset_0_0_0_1px_rgb(255_122_154/0.55)] hover:bg-pink/25 disabled:opacity-50"
>
Discard
</button>
<button
autoFocus
disabled={busy}
onClick={() => void choose('save')}
className="rounded-full btn-primary px-4 py-1.5 text-sm font-semibold disabled:opacity-50"
>
Save
</button>
</div>
</div>
</div>,
document.body,
)
}
+25
View File
@@ -1,4 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../api'
import { useCaps } from '../lib/capabilities'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog'
import { StemsSettings } from './StemsSettings'
@@ -15,7 +19,13 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [open, setOpen] = useState(false)
const [showShortcuts, setShowShortcuts] = useState(false)
const [showStems, setShowStems] = useState(false)
const [showCache, setShowCache] = useState(false)
const ref = useRef<HTMLDivElement>(null)
// Path remapping is a library on THIS computer's business; a remote's
// mapping is its server's configuration.
const remappable = useCaps().paths.remappable
const collection = useQuery({ queryKey: ['collection'], queryFn: api.collection })
const remote = !!collection.data?.library?.remote
useEffect(() => {
if (!open) return
@@ -56,6 +66,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
up ? 'bottom-full mb-1' : 'mt-1'
}`}
>
{remappable && (
<button
onClick={() => {
onOpenPathMapping()
@@ -68,6 +79,19 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
Point the collection at moved or relocated files
</span>
</button>
)}
{remote && (
<button
onClick={() => {
setShowCache(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">Remote audio…</span>
<span className="text-[11px] text-faint">This computer's copies of the server's tracks</span>
</button>
)}
<button
onClick={() => {
setShowStems(true)
@@ -92,6 +116,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
)}
{showShortcuts && <ShortcutsDialog onClose={() => setShowShortcuts(false)} />}
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
{showCache && <RemoteCacheSettings onClose={() => setShowCache(false)} />}
</div>
)
}
+31 -1
View File
@@ -1,4 +1,5 @@
import { Icon } from '../lib/icons'
import type { RemoteConnection } from '../api'
/** A background job's progress, shown at the right of the bar. */
export interface StatusJob {
label: string
@@ -29,6 +30,8 @@ interface Props {
loading?: boolean
collectionName?: string | null
onChangeCollection?: () => void
/** A remote library's connection; null for a library on this computer. */
connection?: RemoteConnection | null
}
export function StatusBar({
@@ -40,6 +43,7 @@ export function StatusBar({
loading,
collectionName,
onChangeCollection,
connection,
}: Props) {
return (
<div className="glass flex h-7 shrink-0 items-center gap-3 !rounded-full px-4 text-[11px] text-muted">
@@ -145,10 +149,11 @@ export function StatusBar({
</button>
</div>
)}
{connection && <ConnectionDot connection={connection} pushRight={!job} />}
{collectionName && (
<button
onClick={onChangeCollection}
className={`${job ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`}
className={`${job || connection ? '' : 'ml-auto '}flex items-center gap-1.5 rounded px-2 py-0.5 text-faint hover:bg-ink-800 hover:text-text`}
title="Change collection"
>
<Icon name="link" size={12} />
@@ -158,3 +163,28 @@ export function StatusBar({
</div>
)
}
/** How this computer stands with a remote library's server, in a word. */
function ConnectionDot({ connection, pushRight }: { connection: RemoteConnection; pushRight: boolean }) {
const { state, via, machine } = connection
const look = {
connected: { dot: 'bg-mint shadow-[0_0_6px_var(--color-mint)]', text: via === 'fallback' ? 'Connected · fallback' : 'Connected' },
reconnecting: { dot: 'bg-gold animate-pulse', text: 'Reconnecting…' },
offline: { dot: 'bg-pink', text: 'Offline' },
taken_over: { dot: 'bg-pink', text: `Taken over${machine ? ` by ${machine}` : ''}` },
}[state]
const title =
state === 'connected'
? `Connected to the server through its ${via === 'fallback' ? 'fallback' : 'main'} address`
: state === 'taken_over'
? 'Another computer holds this library; it is read-only here'
: state === 'offline'
? 'The server cannot be reached; the library is read-only until it is back'
: 'Trying to reach the server again'
return (
<span className={`${pushRight ? 'ml-auto ' : ''}flex shrink-0 items-center gap-1.5 text-faint`} title={title}>
<span className={`h-1.5 w-1.5 rounded-full ${look.dot}`} />
<span>{look.text}</span>
</span>
)
}
+7
View File
@@ -43,6 +43,13 @@ const PATHS = {
</>
),
export: <path d="M12 3v12M7 8l5-5 5 5M5 15v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4" />,
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.01M11 7.5h6M11 16.5h6" />
</>
),
download: <path d="M12 3v12M7 10l5 5 5-5M5 19h14" />,
settings: (
<>
+28
View File
@@ -57,6 +57,10 @@ export function readOnlyNotice(caps: Capabilities): string | null {
return 'This file is not in your collection yet — add it to edit its tags, cues or beatgrid.'
case 'browsing':
return `This ${caps.save.app_name} drive is open for browsing. Open it for editing to change it.`
case 'taken_over':
return 'Another computer has taken over this remote library, so it is read-only here. Open it again to take it back.'
case 'offline':
return 'The server holding this library cannot be reached. It is read-only until the connection comes back.'
case 'platform_incomplete':
default:
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
@@ -67,6 +71,8 @@ export function readOnlyNotice(caps: Capabilities): string | null {
export function readOnlyShort(caps: Capabilities): string | null {
if (caps.writable) return null
if (caps.readonly_cause === 'not_in_library') return 'Not in collection'
if (caps.readonly_cause === 'taken_over') return 'Read-only · taken over'
if (caps.readonly_cause === 'offline') return 'Read-only · offline'
return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only'
}
@@ -85,6 +91,11 @@ export function readOnlyShort(caps: Capabilities): string | null {
* Someone told "not found" about OneLibrary would go hunting for a missing app.
*/
export function platformAvailability(p: PlatformOption): string {
// A remote is reached, not found: `found` counts the saved ones.
if (p.selects === 'remote') {
if (p.found > 1) return `${p.found} saved servers`
return p.found === 1 ? '1 saved server' : 'A library on a Konduktor server'
}
if (p.found > 1) return p.removable ? `${p.found} drives connected` : `${p.found} found`
if (p.found === 1) return p.removable ? '1 drive connected' : `${p.library_label} found`
return p.removable ? 'No drive connected' : `No ${p.library_label} in the usual place`
@@ -127,3 +138,20 @@ export function removalNote(caps: Capabilities, count: number): string {
? ', and a save can be rolled back from version history.'
: ', and that save cannot be undone.'}`
}
// ---- a remote library -----------------------------------------------------------
/** "Studio iMac (since 14:02) — a stem conversion is running there". */
export function remoteHolder(machine: string | null, since: string | null, batch: string | null): string {
const who = machine || 'another computer'
const when = since ? new Date(since).toLocaleString(undefined, { timeStyle: 'short', dateStyle: 'medium' }) : null
const what: Record<string, string> = {
'grid-analysis': 'a beatgrid analysis',
'auto-hotcues': 'an Auto Hotcues run',
'stem-conversion': 'a stem conversion',
import: 'an import',
export: 'an export',
}
const running = batch ? ` — ${what[batch] ?? 'a batch'} is running there, and taking over cancels it` : ''
return `${who}${when ? ` has had it open since ${when}` : ' has it open'}${running}.`
}
+2
View File
@@ -70,6 +70,8 @@ export function PlatformIcon({
// Masks are addressed by id, and one page can show the same mark twice.
const mask = `pm-${useId().replace(/:/g, '')}`
const Mark = MARKS[platform] ?? MARKS[ALIASES[platform]]
// A remote is a way to reach a library, not a platform with a mark of its own.
if (platform === 'remote') return <Icon name="server" size={size} className={className} />
if (!Mark) return <Icon name="music" size={size} className={className} />
return (
<svg