Tracks can be added to playlists via drag

This commit is contained in:
patben8 committed 2026-10-06 22:41:29 +02:00
1 parent b154df430a
commit 89c7dade25
8 files changed
+246 -23

No files matched your search

+7 -6
View File
@@ -4,6 +4,7 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
import { removalNote, writeHint } from './lib/platformCopy'
import { invalidateTrackLists } from './lib/trackQueries'
import { addTracksToPlaylist } from './lib/addTracks'
import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api'
import { confirmDiscardUnsaved } from './lib/unsaved'
import {
@@ -342,20 +343,20 @@ export default function App() {
},
[refreshExport, exportSets.data, notify, onError],
)
// The same path as a drop on a sidebar playlist (lib/addTracks.ts), so the
// menu and the drag ask about duplicates alike.
const duplicatesAllowed = !!capabilities.data?.playlists.duplicates
const addToPlaylist = useCallback(
async (uuid: string, ids: string[]) => {
try {
const res = await api.addEntries(uuid, ids)
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', uuid] })
const name = addablePlaylists.find((p) => p.id === uuid)?.name ?? 'playlist'
notify('success', `Added ${res.added} track${res.added === 1 ? '' : 's'} to ${name}`)
const msg = await addTracksToPlaylist({ qc, playlist: { id: uuid, name }, ids, duplicatesAllowed })
if (msg) notify('success', msg)
} catch (e) {
onError((e as Error).message)
}
},
[qc, addablePlaylists, notify, onError],
[qc, addablePlaylists, duplicatesAllowed, notify, onError],
)
const removeFromExport = useCallback(
async (id: string, ids: string[]) => {
+17 -1
View File
@@ -10,6 +10,10 @@ export interface ConfirmRequest {
/** `danger` (default) for destructive actions — a pink button; `primary`
* for a caution that is not destruction, e.g. switching library. */
tone?: 'danger' | 'primary'
/** A second way to go ahead, as a plain button beside the confirm one
* (e.g. "Add them again" next to "Add 6 new"). Enter still means confirm. */
altLabel?: string
onAlt?: () => void
onConfirm: () => Promise<void> | void
}
@@ -19,7 +23,7 @@ interface Props extends ConfirmRequest {
/** A yes/no confirmation for destructive actions. Enter confirms and Esc
* cancels, so a confirmed Delete key stays a two-keystroke action. */
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onConfirm, onClose }: Props) {
export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', altLabel, onAlt, onConfirm, onClose }: Props) {
const [busy, setBusy] = useState(false)
const confirm = async () => {
@@ -69,6 +73,18 @@ export function ConfirmDialog({ title, body, confirmLabel, tone = 'danger', onCo
>
Cancel
</button>
{altLabel && onAlt && (
<button
onClick={() => {
onAlt()
onClose()
}}
disabled={busy}
className="btn-glass rounded-full px-4 py-1.5 text-sm text-text disabled:opacity-40"
>
{altLabel}
</button>
)}
<button
onClick={() => void confirm()}
disabled={busy}
+46 -1
View File
@@ -6,6 +6,8 @@ import { ExportRunDialog } from './ExportRunDialog'
import type { Source } from './Sidebar'
import { askConfirm } from '../lib/confirm'
import { Icon } from '../lib/icons'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { playlistIdsUnder } from '../lib/playlistTree'
/**
* Exports in the sidebar: each one a named, persisted slice of the library
@@ -105,6 +107,7 @@ export function ExportsSection({ source, onSelect, onDone, onError }: Props) {
onSelect={onSelect}
onEdit={() => setDialog({ editing: set })}
onRun={() => setRunning(set)}
onDone={onDone}
onDelete={async () => {
// Deleting a set never touches its destination folder — the files
// already exported are the user's, not Konduktor's to clean up.
@@ -132,6 +135,7 @@ function ExportRow({
onEdit,
onRun,
onDelete,
onDone,
onError,
}: {
set: ExportSet
@@ -140,6 +144,7 @@ function ExportRow({
onEdit: () => void
onRun: () => void
onDelete: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}) {
const qc = useQueryClient()
@@ -170,11 +175,51 @@ function ExportRow({
const data = contents.data
const expanded = open || inside
// A drop target for the collection's tracks (they become loose tracks) and
// for playlists or folders dragged from the tree (referenced, live, as
// "Add to export" does). Not gated on the library being writable: an export
// set is Konduktor's own data.
const refresh = () => {
qc.invalidateQueries({ queryKey: ['export-contents', set.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', set.id] })
qc.invalidateQueries({ queryKey: ['export-loose', set.id] })
}
const accepts = (p: DragPayload) =>
p.kind === 'tracks' ? p.origin === 'collection' : playlistIdsUnder(p.node).length > 0
const [dropRef, over] = useDropTarget<true>({
hint: (p) => (accepts(p) ? true : null),
label: () => `Add to export ${set.name}`,
onDrop: async (p) => {
try {
if (p.kind === 'tracks') {
await api.addToExport(set.id, { track_ids: p.ids })
onDone(`Added ${p.ids.length} track${p.ids.length === 1 ? '' : 's'} to ${set.name}`)
} else {
const ids = playlistIdsUnder(p.node)
await api.addToExport(set.id, { playlist_ids: ids })
onDone(
p.node.kind === 'folder'
? `Added ${ids.length} playlist${ids.length === 1 ? '' : 's'} from “${p.node.name}” to ${set.name}`
: `Added “${p.node.name}” to ${set.name}`,
)
}
refresh()
} catch (e) {
onError((e as Error).message)
}
},
})
return (
<div>
<div
ref={dropRef}
className={`group flex w-full items-center gap-1 rounded-md pr-1 transition-colors ${
selected ? 'is-selected text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
over
? 'bg-gold/10 text-text ring-1 ring-gold'
: selected
? 'is-selected text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<button
+54 -8
View File
@@ -11,6 +11,9 @@ import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { Icon, type IconName } from '../lib/icons'
import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
import { playlistIdsUnder } from '../lib/playlistTree'
/**
* Which view the main table is showing.
@@ -57,11 +60,6 @@ interface Props {
// Kind picks the icon; every behavioural question is answered by the node's own
// flags, so nothing here infers what a node can do from what it is called.
/** Every selectable playlist at or under a node, in tree order. */
function playlistIdsUnder(node: PlaylistNode): string[] {
const here = node.kind === 'folder' ? [] : [node.id]
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
}
/** The confirm wording for deleting a node. A folder says what goes with it,
* since the whole subtree is deleted and the row only shows the folder. */
@@ -105,6 +103,11 @@ interface RowActions {
onPickExport: (e: React.MouseEvent<HTMLElement>, node: PlaylistNode) => void
onCommitDraft: (name: string) => void
onCancelDraft: () => void
/** Whether a drag of tracks may drop on this playlist. */
acceptsTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>) => boolean
/** Tracks dropped on a playlist; `alt` (Option) moves them out of the
* playlist they came from. */
onDropTracks: (node: PlaylistNode, p: Extract<DragPayload, { kind: 'tracks' }>, alt: boolean) => void
}
/** The inline name field for a node being created. Enter or clicking away
@@ -156,6 +159,7 @@ function DraftRow({
function NodeRow({
node,
parentId,
depth,
source,
onSelect,
@@ -166,6 +170,8 @@ function NodeRow({
actions,
}: {
node: PlaylistNode
/** The folder this node sits in; null = the top level. */
parentId: string | null
depth: number
source: Source
onSelect: (s: Source) => void
@@ -191,12 +197,30 @@ function NodeRow({
setRenamingId(node.id)
}
// A row is a drag SOURCE (onto an export, or elsewhere in the tree) and a
// drop TARGET for tracks. Whether it takes them is the node's own
// `can_add_tracks` plus the library being writable, decided by the sidebar.
const startDrag = usePressToDrag(() => (renaming ? null : { kind: 'node', node, parentId }))
const moves = (p: DragPayload, alt: boolean) =>
p.kind === 'tracks' && alt && !!p.fromPlaylist && p.fromPlaylist !== node.id
const [dropRef, over] = useDropTarget<true>({
hint: (p) => (p.kind === 'tracks' && actions.acceptsTracks(node, p) ? true : null),
label: (p, _h, at) => `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`,
onDrop: (p, _h, at) => p.kind === 'tracks' && actions.onDropTracks(node, p, at.alt),
})
return (
<div>
<div
ref={dropRef}
onPointerDown={startDrag}
onContextMenu={(e) => actions.onContextMenu(e, node)}
className={`group flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
selected ? 'is-selected font-medium text-text' : 'text-muted hover:bg-ink-800 hover:text-text'
over
? 'bg-accent-soft/40 text-text ring-1 ring-accent'
: selected
? 'is-selected font-medium text-text'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
<button
@@ -298,6 +322,7 @@ function NodeRow({
<NodeRow
key={c.id}
node={c}
parentId={node.id}
depth={depth + 1}
source={source}
onSelect={onSelect}
@@ -339,8 +364,9 @@ export function Sidebar({
}
// There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate.
const canCreate = useCaps().writable
const foldersSupported = useCaps().playlists.folders
const caps = useCaps()
const canCreate = caps.writable
const foldersSupported = caps.playlists.folders
const { data: playlists, isLoading } = useQuery({
queryKey: ['playlists'],
queryFn: api.playlists,
@@ -496,6 +522,24 @@ export function Sidebar({
setDraft(null)
},
onCancelDraft: () => setDraft(null),
// Only the collection's own tracks: a device's or a folder's ids mean
// nothing to the collection's playlists.
acceptsTracks: (node, p) =>
caps.writable && node.can_add_tracks && p.origin === 'collection' && p.fromPlaylist !== node.id,
onDropTracks: async (node, p, alt) => {
try {
const msg = await addTracksToPlaylist({
qc,
playlist: node,
ids: p.ids,
duplicatesAllowed: caps.playlists.duplicates,
moveFrom: alt ? p.fromPlaylist : undefined,
})
if (msg) onDone(msg)
} catch (e) {
onError((e as Error).message)
}
},
}
return (
@@ -563,6 +607,7 @@ export function Sidebar({
{/* Right-click here (below the rows) creates at the top level; rows
stop the event so they get their own menu. */}
<div
data-drag-scroll=""
className="mt-1 min-h-24 flex-1 overflow-y-auto px-2 pb-4"
onContextMenu={(e) => openMenu(e, createItems(null))}
>
@@ -572,6 +617,7 @@ export function Sidebar({
<NodeRow
key={n.id}
node={n}
parentId={null}
depth={0}
source={source}
onSelect={onSelect}
+69
View File
@@ -0,0 +1,69 @@
import type { QueryClient } from '@tanstack/react-query'
import { api } from '../api'
import { askChoice } from './confirm'
const plural = (n: number) => `${n} track${n === 1 ? '' : 's'}`
/**
* Add tracks to a playlist — the context menu's "Add to" and a drop on a
* sidebar playlist alike, so the two cannot drift.
*
* Tracks the playlist already holds are ASKED about (decided 2026-10-06), but
* only where the platform can hold a track twice (`playlists.duplicates`);
* elsewhere they are skipped and the message says so. Nothing is asked when
* there are none.
*
* `moveFrom` is an Option-drag out of another (editable) playlist: once the
* tracks are in the target they leave the source. Cancelling the duplicates
* question cancels the move too.
*
* Resolves the message to show, or null when the user cancelled.
*/
export async function addTracksToPlaylist(opts: {
qc: QueryClient
playlist: { id: string; name: string }
ids: string[]
duplicatesAllowed: boolean
moveFrom?: string
}): Promise<string | null> {
const { qc, playlist, ids, duplicatesAllowed, moveFrom } = opts
let res = await api.addEntries(playlist.id, ids, duplicatesAllowed ? 'ask' : 'skip')
if (res.status === 'duplicates') {
const fresh = ids.length - res.duplicates
const all = fresh === 0
const choice = await askChoice({
title: all
? `${ids.length === 1 ? 'This track is' : `All ${ids.length} tracks are`} already in “${playlist.name}”`
: `${plural(res.duplicates)} ${res.duplicates === 1 ? 'is' : 'are'} already in “${playlist.name}”`,
body: all
? ids.length === 1
? 'Add it again, so the playlist holds it twice?'
: 'Add them again, so the playlist holds them twice?'
: `Add only the ${plural(fresh)} not there yet, or add every track — the ${res.duplicates === 1 ? 'one already there' : `${res.duplicates} already there`} a second time?`,
// All of them there: "skip" would add nothing, which is just Cancel —
// so the question is only whether to add them again.
confirmLabel: all ? 'Add again' : `Add ${plural(fresh)}`,
altLabel: all ? undefined : `Add all ${ids.length}`,
tone: 'primary',
})
if (choice === null) return null
res = await api.addEntries(playlist.id, ids, choice === 'alt' || all ? 'add' : 'skip')
}
let moved = false
if (moveFrom && moveFrom !== playlist.id) {
const gone = new Set(ids)
const current = await api.playlistTracks(moveFrom)
await api.setEntries(moveFrom, current.map((t) => t.id).filter((id) => !gone.has(id)))
qc.invalidateQueries({ queryKey: ['playlist', moveFrom] })
moved = true
}
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', playlist.id] })
const skipped = ids.length - res.added
if (moved) return `Moved ${plural(ids.length)} to ${playlist.name}`
if (res.added === 0) return `Nothing added — ${ids.length === 1 ? 'it is' : 'they are all'} already in ${playlist.name}`
return `Added ${plural(res.added)} to ${playlist.name}${skipped > 0 ? ` · ${skipped} already there` : ''}`
}
+15 -7
View File
@@ -12,19 +12,26 @@
import { useEffect, useState } from 'react'
import { ConfirmDialog, type ConfirmRequest } from '../components/ConfirmDialog'
type Ask = Omit<ConfirmRequest, 'onConfirm'>
type Pending = { req: Ask; resolve: (ok: boolean) => void }
type Ask = Omit<ConfirmRequest, 'onConfirm' | 'onAlt' | 'altLabel'>
type Choice = 'confirm' | 'alt' | null
type Pending = { req: Ask & { altLabel?: string }; resolve: (choice: Choice) => void }
let open: ((p: Pending) => void) | null = null
/** Show a confirmation and resolve true (confirmed) or false (cancelled). */
export function askConfirm(req: Ask): Promise<boolean> {
return askChoice(req).then((c) => c === 'confirm')
}
/** A confirmation with a SECOND way to go ahead (`altLabel`): resolves
* 'confirm', 'alt', or null when cancelled. */
export function askChoice(req: Ask & { altLabel?: string }): Promise<Choice> {
return new Promise((resolve) => {
if (open) open({ req, resolve })
// No host mounted (should not happen outside tests): refuse rather than
// fall back to a native dialog, since a destructive action must not go
// ahead unconfirmed.
else resolve(false)
else resolve(null)
})
}
@@ -34,7 +41,7 @@ export function ConfirmHost() {
useEffect(() => {
open = (p) =>
setPending((prev) => {
prev?.resolve(false) // a second ask supersedes an unanswered one
prev?.resolve(null) // a second ask supersedes an unanswered one
return p
})
return () => {
@@ -45,10 +52,11 @@ export function ConfirmHost() {
return (
<ConfirmDialog
{...pending.req}
// A promise settles once, so confirm-then-close resolves `true`.
onConfirm={() => pending.resolve(true)}
// A promise settles once, so confirm-then-close resolves 'confirm'.
onConfirm={() => pending.resolve('confirm')}
onAlt={() => pending.resolve('alt')}
onClose={() => {
pending.resolve(false)
pending.resolve(null)
setPending(null)
}}
/>
+28
View File
@@ -204,6 +204,34 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
evaluate()
}
/** A pointerdown handler that starts a drag once the press moves 6 px. A plain
* click never moves that far, so the element keeps its click; a press on a
* field inside it (a rename input) never drags. `make` is asked at the moment
* the drag starts and may return null to refuse. */
export function usePressToDrag(make: () => DragPayload | null): (e: React.PointerEvent) => void {
const makeRef = useRef(make)
makeRef.current = make
return useCallback((e: React.PointerEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey) return
if ((e.target as HTMLElement).closest('input, textarea, select')) return
const start = { x: e.clientX, y: e.clientY }
const onMove = (m: PointerEvent) => {
if (Math.hypot(m.clientX - start.x, m.clientY - start.y) < 6) return
stop()
const payload = makeRef.current()
if (payload) beginDrag(payload, { x: m.clientX, y: m.clientY, alt: m.altKey })
}
const stop = () => {
window.removeEventListener('pointermove', onMove)
window.removeEventListener('pointerup', stop)
window.removeEventListener('pointercancel', stop)
}
window.addEventListener('pointermove', onMove)
window.addEventListener('pointerup', stop)
window.addEventListener('pointercancel', stop)
}, [])
}
/** The drag in progress, or null. Changes only when a drag starts or ends. */
export function useDragPayload(): DragPayload | null {
return useSyncExternalStore(subscribe, () => state.payload)
+10
View File
@@ -0,0 +1,10 @@
import type { PlaylistNode } from '../api'
/** Every selectable playlist at or under a node, in tree order. A folder
* contributes its nested playlists, a playlist itself — which is what adding a
* node to an export means: the export stores playlist ids, and a folder is a
* shape in the tree, not a thing with tracks. */
export function playlistIdsUnder(node: PlaylistNode): string[] {
const here = node.kind === 'folder' ? [] : [node.id]
return [...here, ...(node.children ?? []).flatMap(playlistIdsUnder)]
}