mirror of
https://github.com/MrPatben8/konduktor.git
synced 2026-11-27 10:22:51 +01:00
Implemented drag to import
This commit is contained in:
1 parent
87cbd3720e
commit
a65ef959b2
14 files changed
+807
-114
No files matched your search
+136
-11
@@ -1,11 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table'
|
||||
import { CapabilitiesContext, slotLabeller } from './lib/capabilities'
|
||||
import { removalNote, writeHint } from './lib/platformCopy'
|
||||
import { readOnlyNotice, removalNote, writeHint } from './lib/platformCopy'
|
||||
import { invalidateTrackLists } from './lib/trackQueries'
|
||||
import { addTracksToPlaylist } from './lib/addTracks'
|
||||
import { useDropTarget } from './lib/drag'
|
||||
import { useDragPayload, useDropTarget } from './lib/drag'
|
||||
import { useNativeFileDrop } from './lib/fileDrop'
|
||||
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 { askConfirm } from './lib/confirm'
|
||||
@@ -30,7 +32,7 @@ import { RelocateDialog } from './components/RelocateDialog'
|
||||
import { HistoryPanel } from './components/HistoryPanel'
|
||||
import { PrepStrip } from './components/PrepStrip'
|
||||
import { ImportDialog } from './components/ImportDialog'
|
||||
import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog'
|
||||
import { AddFilesDialog, type AddTarget, type ForeignOrigin } from './components/AddFilesDialog'
|
||||
import { ConvertStemsDialog } from './components/ConvertStemsDialog'
|
||||
import { StemReportDialog } from './components/StemReportDialog'
|
||||
import { SetPositionDialog } from './components/SetPositionDialog'
|
||||
@@ -84,8 +86,12 @@ export default function App() {
|
||||
// The browsed folder's rows that ARE collection tracks: collection id → the
|
||||
// file's folder id. A ref, for the callbacks below that outlive a render.
|
||||
const folderFilesRef = useRef<Record<string, string>>({})
|
||||
// Browsed files being added to the collection (and maybe a playlist/export).
|
||||
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null)
|
||||
// Browsed (or dropped) files being added to the collection (and maybe a
|
||||
// playlist/export). `note` says what a drop left out.
|
||||
const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null; note?: string | null } | null>(null)
|
||||
// How many dropped items are being read (a dropped folder is searched all
|
||||
// the way down, which can take a while): shown until the dialog opens.
|
||||
const [readingDrop, setReadingDrop] = useState(0)
|
||||
const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays
|
||||
const [importing, setImporting] = useState(false)
|
||||
// Device tracks dropped on a collection playlist / export: Import, with
|
||||
@@ -377,9 +383,78 @@ export default function App() {
|
||||
// export: they are not in the collection yet, so the drop opens the dialog
|
||||
// that adds them — with that target filled in, and copy-vs-reference still
|
||||
// asked (decided 2026-10-06).
|
||||
// Files dragged in from Finder / Explorer (lib/fileDrop.ts). What is in them
|
||||
// is read first — folders all the way down — and then they go where a
|
||||
// browsed folder's files go: the add dialog, copy-vs-reference asked.
|
||||
const readDrop = useCallback(
|
||||
async (paths: string[]) => {
|
||||
setReadingDrop(paths.length)
|
||||
try {
|
||||
return await api.folderDropped(paths)
|
||||
} catch (e) {
|
||||
onError((e as Error).message)
|
||||
return null
|
||||
} finally {
|
||||
setReadingDrop(0)
|
||||
}
|
||||
},
|
||||
[onError],
|
||||
)
|
||||
const dropFiles = useCallback(
|
||||
async (paths: string[], target: AddTarget | null) => {
|
||||
const r = await readDrop(paths)
|
||||
if (!r) return
|
||||
if (!r.tracks.length) {
|
||||
onError(
|
||||
paths.length === 1 && r.skipped
|
||||
? 'That is not an audio file this library can hold.'
|
||||
: 'No audio files this library can hold were found there.',
|
||||
)
|
||||
return
|
||||
}
|
||||
const notes: string[] = []
|
||||
if (r.skipped)
|
||||
notes.push(
|
||||
r.skipped === 1
|
||||
? '1 dropped item is not audio this library can hold and was left out.'
|
||||
: `${r.skipped} dropped items are not audio this library can hold and were left out.`,
|
||||
)
|
||||
if (r.truncated) notes.push(`Only the first ${r.tracks.length.toLocaleString()} files are included.`)
|
||||
// Files the collection holds are its tracks already: as with a folder's
|
||||
// rows, nothing to add first — straight into the target, if there is one.
|
||||
const held = r.tracks.filter((t) => r.files[t.id]).map((t) => t.id)
|
||||
if (held.length === r.tracks.length) {
|
||||
if (target?.kind === 'playlist') void addToPlaylist(target.id, held)
|
||||
else if (target) void addToExport(target.id, held)
|
||||
else
|
||||
notify(
|
||||
'success',
|
||||
held.length === 1 ? 'Already in your collection' : `All ${held.length} are already in your collection`,
|
||||
)
|
||||
return
|
||||
}
|
||||
setAdding({ ids: r.tracks.map((t) => r.files[t.id] ?? t.id), target, note: notes.join(' ') || null })
|
||||
},
|
||||
[readDrop, addToPlaylist, addToExport, notify, onError],
|
||||
)
|
||||
// One dropped audio file on the deck: loaded to listen to, added to nothing.
|
||||
const loadDropped = useCallback(
|
||||
async (path: string) => {
|
||||
const r = await readDrop([path])
|
||||
if (!r) return
|
||||
const t = r.tracks[0]
|
||||
if (!t) {
|
||||
onError('That is not an audio file this library can hold.')
|
||||
return
|
||||
}
|
||||
loadTrack(t, r.files[t.id] ? 'collection' : 'folder')
|
||||
},
|
||||
[readDrop, loadTrack, onError],
|
||||
)
|
||||
const addForeign = useCallback(
|
||||
(origin: TrackOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'folder') {
|
||||
(origin: ForeignOrigin, ids: string[], target: AddTarget) => {
|
||||
if (origin === 'dropped') void dropFiles(ids, target)
|
||||
else if (origin === 'folder') {
|
||||
const files = folderFilesRef.current
|
||||
// Rows that are all collection tracks already: nothing to add first.
|
||||
if (ids.every((id) => files[id])) {
|
||||
@@ -388,13 +463,44 @@ export default function App() {
|
||||
} else setAdding({ ids: ids.map((id) => files[id] ?? id), target })
|
||||
} else if (origin === 'device') setImportDrop({ ids, target })
|
||||
},
|
||||
[addToPlaylist, addToExport],
|
||||
[addToPlaylist, addToExport, dropFiles],
|
||||
)
|
||||
const audioFormats = capabilities.data?.tracks.audio_formats
|
||||
const isAudioPath = (path: string) =>
|
||||
path.lastIndexOf('.') > 0 && !!audioFormats?.includes(path.slice(path.lastIndexOf('.')).toLowerCase())
|
||||
const [deckDropRef, deckOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'tracks' ? true : null),
|
||||
hint: (p) =>
|
||||
p.kind === 'tracks' || (p.kind === 'files' && p.paths.length === 1 && isAudioPath(p.paths[0])) ? true : null,
|
||||
label: (p) => (p.kind === 'tracks' && p.ids.length > 1 ? `Load “${p.lead.title || 'Untitled'}” into the deck` : 'Load into the deck'),
|
||||
onDrop: (p) => p.kind === 'tracks' && loadTrack(p.lead, p.origin),
|
||||
onDrop: (p) => {
|
||||
if (p.kind === 'tracks') loadTrack(p.lead, p.origin)
|
||||
else if (p.kind === 'files') void loadDropped(p.paths[0])
|
||||
},
|
||||
})
|
||||
// Files dropped anywhere no other target takes them: the collection. A
|
||||
// library that cannot add tracks still takes the drop, to say why not —
|
||||
// silently ignoring it would read as the feature being broken.
|
||||
const canAddFiles = (capabilities.data?.writable ?? false) && !!capabilities.data?.tracks.addable
|
||||
const cannotAddFiles =
|
||||
capabilities.data && !capabilities.data.writable
|
||||
? (readOnlyNotice(capabilities.data) ?? 'This library is read-only.')
|
||||
: 'Tracks cannot be added to this library.'
|
||||
const [rootDropRef, rootOver] = useDropTarget<true>({
|
||||
hint: (p) => (p.kind === 'files' ? true : null),
|
||||
label: () => (canAddFiles ? 'Add to your collection…' : null),
|
||||
onDrop: (p) => {
|
||||
if (p.kind !== 'files') return
|
||||
if (canAddFiles) void dropFiles(p.paths, null)
|
||||
else notify('error', cannotAddFiles)
|
||||
},
|
||||
})
|
||||
const draggingFiles = useDragPayload()?.kind === 'files'
|
||||
useNativeFileDrop(loaded && !forcePicker, () =>
|
||||
notify(
|
||||
'warning',
|
||||
'Dropping files works in the Konduktor app, not in a browser (it cannot tell the page where a file is). Browse to it under Files in the sidebar instead.',
|
||||
),
|
||||
)
|
||||
const removeFromExport = useCallback(
|
||||
async (id: string, ids: string[]) => {
|
||||
try {
|
||||
@@ -1066,8 +1172,26 @@ export default function App() {
|
||||
<CapabilitiesContext.Provider value={capabilities.data!}>
|
||||
{/* Floating glass panels with gaps between them: the ambient backdrop
|
||||
(main.tsx) shows through the gutters as well as through the glass. */}
|
||||
<div className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
|
||||
<div ref={rootDropRef} className="flex h-screen w-screen flex-col gap-3 overflow-hidden p-3">
|
||||
<Toast toast={toast} onClose={() => setToast(null)} />
|
||||
{draggingFiles && rootOver &&
|
||||
createPortal(
|
||||
<div aria-hidden className="pointer-events-none fixed inset-0 z-[85] flex items-center justify-center">
|
||||
<div className="absolute inset-1.5 rounded-[26px] ring-2 ring-accent" />
|
||||
<div className="glass-overlay flex items-center gap-2.5 overflow-hidden rounded-2xl px-5 py-3 text-sm text-text shadow-lg">
|
||||
<Icon name="music" size={15} className={canAddFiles ? 'text-accent' : 'text-pink'} />
|
||||
{canAddFiles ? 'Drop to add to your collection' : cannotAddFiles}
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
{readingDrop > 0 &&
|
||||
createPortal(
|
||||
<div className="glass-overlay pointer-events-none fixed bottom-14 left-1/2 z-[80] -translate-x-1/2 overflow-hidden rounded-full px-4 py-2 text-xs text-muted shadow-lg">
|
||||
Looking for audio in {readingDrop === 1 ? 'the dropped item' : `${readingDrop} dropped items`}…
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
{menu && (
|
||||
<ContextMenu
|
||||
// Remount per opening: a right-click on another row while a menu is
|
||||
@@ -1280,6 +1404,7 @@ export default function App() {
|
||||
<AddFilesDialog
|
||||
trackIds={adding.ids}
|
||||
target={adding.target}
|
||||
note={adding.note}
|
||||
onClose={() => setAdding(null)}
|
||||
onDone={(msg) => {
|
||||
setAdding(null)
|
||||
|
||||
@@ -514,7 +514,27 @@ export interface FolderAddRequest {
|
||||
}
|
||||
|
||||
export interface FolderAddPreview extends ImportPreview {
|
||||
/** Some of the files to add are on an external drive. */
|
||||
removable: boolean
|
||||
/** How many, and on which drives — per FILE, since a drop can mix drives. */
|
||||
removable_count?: number
|
||||
removable_drives?: string[]
|
||||
/** Copy mode: files already inside the import folder (copying makes a
|
||||
* second copy beside them). */
|
||||
in_destination?: number
|
||||
}
|
||||
|
||||
/** What files dropped onto the window from the OS resolved to: the audio in
|
||||
* them (folders searched all the way down), listed as a folder lists its
|
||||
* files — a file the collection holds is its collection track. */
|
||||
export interface DroppedFiles {
|
||||
tracks: Track[]
|
||||
/** Collection id → the file's folder id (= its path), for held rows. */
|
||||
files: Record<string, string>
|
||||
/** Dropped files that are not audio this library can hold, or are gone. */
|
||||
skipped: number
|
||||
/** Too many files: only the first 20,000 are included. */
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export type JobState = 'running' | 'done' | 'failed' | 'cancelled'
|
||||
@@ -1177,6 +1197,7 @@ export const api = {
|
||||
folderAddPreview: (body: FolderAddRequest) =>
|
||||
send<FolderAddPreview>('POST', '/api/folder/add/preview', body),
|
||||
folderAdd: (body: FolderAddRequest) => send<JobStatus>('POST', '/api/folder/add', body),
|
||||
folderDropped: (paths: string[]) => send<DroppedFiles>('POST', '/api/folder/dropped', { paths }),
|
||||
// ---- import ----
|
||||
importPreview: (body: ImportRequest) => send<ImportPreview>('POST', '/api/import/preview', body),
|
||||
/** Starts the job and returns immediately — poll `job()` for progress. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus } from '../api'
|
||||
import { api, isServerPath, type FolderAddPreview, type FolderAddRequest, type JobStatus, type TrackOrigin } from '../api'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { placedAudioSummary } from '../lib/platformCopy'
|
||||
import { FolderPicker } from './FolderPicker'
|
||||
@@ -25,6 +25,10 @@ import { FolderPicker } from './FolderPicker'
|
||||
* library can reach them, so they are added in place, uploaded nowhere and
|
||||
* nothing asked (decided 2026-10-10).
|
||||
*
|
||||
* Files dropped onto the window from the OS (`lib/fileDrop.ts`) arrive here
|
||||
* too, so a drop asks exactly what the sidebar's Add to Collection asks. A
|
||||
* drop can mix drives, so the external-drive warning counts files per drive.
|
||||
*
|
||||
* 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
|
||||
@@ -45,15 +49,32 @@ export interface AddTarget {
|
||||
name: string
|
||||
}
|
||||
|
||||
/** Where tracks headed for the collection come from: another library's or a
|
||||
* folder's track ids, or — `dropped` — paths dragged in from the OS. */
|
||||
export type ForeignOrigin = TrackOrigin | 'dropped'
|
||||
|
||||
interface Props {
|
||||
trackIds: string[]
|
||||
target: AddTarget | null
|
||||
/** A line about what was left out before the dialog (a drop's non-audio files). */
|
||||
note?: string | null
|
||||
onClose: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
}
|
||||
|
||||
export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: Props) {
|
||||
/** The leave-in-place warning, per drive: a drop can mix the computer's own
|
||||
* disk with a stick, and only the stick's files go missing on unplug. */
|
||||
function removableWarning(p: FolderAddPreview, newCount: number): string {
|
||||
const count = p.removable_count ?? newCount
|
||||
const drives = p.removable_drives ?? []
|
||||
const where = drives.length === 1 ? `${drives[0]}, an external drive` : 'external drives'
|
||||
const what = count >= newCount ? 'These files are' : `${count} of these files are`
|
||||
const unplugged = drives.length === 1 ? 'it is' : 'they are'
|
||||
return `${what} on ${where}. They will go missing from your collection whenever ${unplugged} unplugged.`
|
||||
}
|
||||
|
||||
export function AddFilesDialog({ trackIds, target, note, onClose, onDone, onError }: Props) {
|
||||
const qc = useQueryClient()
|
||||
// The LIBRARY's capabilities (this dialog is mounted outside the browsed
|
||||
// view's swapped context). A library that places its own audio — a stick —
|
||||
@@ -177,9 +198,12 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
const newCount = p?.importable ?? 0
|
||||
const shown = places ? 'placed' : mode
|
||||
const libraryName = places ? caps.save.app_name : 'your collection'
|
||||
// Every file is held already: nothing is copied or referenced, so there is
|
||||
// nothing to ask — only the target to fill.
|
||||
const nothingNew = !!p && newCount === 0 && p.existing.length > 0
|
||||
const canAdd =
|
||||
!starting && shown !== null && !!p && (newCount > 0 || (!!target && p.existing.length > 0)) &&
|
||||
p.enough_space !== false
|
||||
!starting && (shown !== null || nothingNew) && !!p &&
|
||||
(newCount > 0 || (!!target && p.existing.length > 0)) && p.enough_space !== false
|
||||
|
||||
const title = target
|
||||
? `Add ${n} track${n === 1 ? '' : 's'} to ${target.name}`
|
||||
@@ -265,7 +289,9 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!places && !uploads && !onServer && (
|
||||
{note && <div className="text-xs text-muted">{note}</div>}
|
||||
|
||||
{!places && !uploads && !onServer && !nothingNew && (
|
||||
<div className="space-y-1">
|
||||
{option(
|
||||
'copy',
|
||||
@@ -296,9 +322,14 @@ export function AddFilesDialog({ trackIds, target, onClose, onDone, onError }: P
|
||||
)}
|
||||
|
||||
{mode === 'reference' && p?.removable && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-gold">{removableWarning(p, newCount)}</div>
|
||||
)}
|
||||
|
||||
{mode === 'copy' && !!p?.in_destination && (
|
||||
<div className="rounded well px-3 py-2 text-xs text-gold">
|
||||
These files are on an external drive. They will go missing from your
|
||||
collection whenever the drive is unplugged.
|
||||
{p.in_destination === newCount ? 'These files are' : `${p.in_destination} of these files are`}{' '}
|
||||
already in your import folder. Copying makes a second copy beside{' '}
|
||||
{p.in_destination === 1 ? 'it' : 'them'}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type ExportSet, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { api, type ExportSet } from '../api'
|
||||
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { ExportDialog } from './ExportDialog'
|
||||
import { ExportRunDialog } from './ExportRunDialog'
|
||||
@@ -31,7 +31,7 @@ interface Props {
|
||||
onSelect: (s: Source) => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
}
|
||||
|
||||
export function ExportsSection({ source, onSelect, onDone, onError, onAddForeign }: Props) {
|
||||
@@ -151,7 +151,7 @@ function ExportRow({
|
||||
onDelete: () => void
|
||||
onDone: (msg: string) => void
|
||||
onError: (msg: string) => void
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
}) {
|
||||
const qc = useQueryClient()
|
||||
// The COLLECTION's capabilities (the sidebar sits outside the browsed view's
|
||||
@@ -196,14 +196,20 @@ function ExportRow({
|
||||
const accepts = (p: DragPayload) =>
|
||||
p.kind === 'tracks'
|
||||
? p.origin === 'collection' || (caps.writable && caps.tracks.addable)
|
||||
: playlistIdsUnder(p.node).length > 0
|
||||
: p.kind === 'files'
|
||||
? caps.writable && caps.tracks.addable
|
||||
: playlistIdsUnder(p.node).length > 0
|
||||
const [dropRef, over] = useDropTarget<true>({
|
||||
hint: (p) => (accepts(p) ? true : null),
|
||||
label: (p) =>
|
||||
p.kind === 'tracks' && p.origin === 'device'
|
||||
? `Import into export ${set.name}…`
|
||||
: `Add to export ${set.name}${p.kind === 'tracks' && p.origin === 'folder' ? '…' : ''}`,
|
||||
: `Add to export ${set.name}${(p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files' ? '…' : ''}`,
|
||||
onDrop: async (p) => {
|
||||
if (p.kind === 'files') {
|
||||
onAddForeign('dropped', p.paths, { kind: 'export', id: set.id, name: set.name })
|
||||
return
|
||||
}
|
||||
if (p.kind === 'tracks' && p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'export', id: set.id, name: set.name })
|
||||
return
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api, type PlaylistKind, type PlaylistNode, type TrackOrigin } from '../api'
|
||||
import type { AddTarget } from './AddFilesDialog'
|
||||
import { api, type PlaylistKind, type PlaylistNode } from '../api'
|
||||
import type { AddTarget, ForeignOrigin } from './AddFilesDialog'
|
||||
import { useCaps } from '../lib/capabilities'
|
||||
import { SaveBar } from './SaveBar'
|
||||
import { confirmDiscardUnsaved } from '../lib/unsaved'
|
||||
@@ -14,7 +14,7 @@ import { ContextMenu, type MenuItem } from './ContextMenu'
|
||||
import { Icon, type IconName } from '../lib/icons'
|
||||
import { PlatformIcon } from '../lib/platformIcons'
|
||||
import { addTracksToPlaylist } from '../lib/addTracks'
|
||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload } from '../lib/drag'
|
||||
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
|
||||
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
|
||||
|
||||
/**
|
||||
@@ -55,9 +55,10 @@ interface Props {
|
||||
/** Open a drive's library as THE library (Devices' "Open for editing…"). */
|
||||
onOpenLibrary: (path: string) => void
|
||||
onDone: (msg: string) => void
|
||||
/** Tracks not in the collection yet (a device's, a folder's) dropped on a
|
||||
* playlist or export: open the dialog that adds them, target filled in. */
|
||||
onAddForeign: (origin: TrackOrigin, ids: string[], target: AddTarget) => void
|
||||
/** Tracks not in the collection yet (a device's, a folder's — or files
|
||||
* dropped from the OS, as paths) dropped on a playlist or export: open the
|
||||
* dialog that adds them, target filled in. */
|
||||
onAddForeign: (origin: ForeignOrigin, ids: string[], target: AddTarget) => void
|
||||
onOpenPathMapping: () => void
|
||||
/** After unsaved edits were discarded (SaveBar). */
|
||||
onDiscarded?: () => void
|
||||
@@ -111,11 +112,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
|
||||
/** Whether a drag of tracks (or of files from the OS) may drop on this playlist. */
|
||||
acceptsTracks: (node: PlaylistNode, p: TracksOrFiles) => 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
|
||||
onDropTracks: (node: PlaylistNode, p: TracksOrFiles, alt: boolean) => void
|
||||
/** Whether a node may be dragged elsewhere in the tree. */
|
||||
canMove: (node: PlaylistNode) => boolean
|
||||
/** A node dropped in the tree: `index` among `parentId`'s children,
|
||||
@@ -265,14 +266,14 @@ function NodeRow({
|
||||
label: (p, h, at) => {
|
||||
if (h.zone === 'tracks') {
|
||||
if (p.kind === 'tracks' && p.origin === 'device') return `Import into ${node.name}…`
|
||||
if (p.kind === 'tracks' && p.origin === 'folder') return `Add to ${node.name}…`
|
||||
if ((p.kind === 'tracks' && p.origin === 'folder') || p.kind === 'files') return `Add to ${node.name}…`
|
||||
return `${moves(p, at.alt) ? 'Move' : 'Add'} to ${node.name}`
|
||||
}
|
||||
if (h.zone === 'peek') return null
|
||||
return h.zone === 'into' || h.zone === 'first' ? `Move into ${node.name}` : `Move ${h.zone} ${node.name}`
|
||||
},
|
||||
onDrop: (p, h, at) => {
|
||||
if (p.kind === 'tracks') {
|
||||
if (p.kind !== 'node') {
|
||||
if (h.zone === 'tracks') actions.onDropTracks(node, p, at.alt)
|
||||
} else if ('parentId' in h) {
|
||||
actions.onMoveNode(p.node, h.parentId, h.index, h.zone === 'into' && !expanded ? node : null)
|
||||
@@ -664,7 +665,7 @@ export function Sidebar({
|
||||
acceptsTracks: (node, p) =>
|
||||
caps.writable &&
|
||||
node.can_add_tracks &&
|
||||
(p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
|
||||
(p.kind === 'tracks' && p.origin === 'collection' ? p.fromPlaylist !== node.id : caps.tracks.addable),
|
||||
canMove: (node) => caps.writable && node.can_move,
|
||||
onMoveNode: async (node, parentId, index, into) => {
|
||||
try {
|
||||
@@ -678,6 +679,10 @@ export function Sidebar({
|
||||
}
|
||||
},
|
||||
onDropTracks: async (node, p, alt) => {
|
||||
if (p.kind === 'files') {
|
||||
onAddForeign('dropped', p.paths, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
}
|
||||
if (p.origin !== 'collection') {
|
||||
onAddForeign(p.origin, p.ids, { kind: 'playlist', id: node.id, name: node.name })
|
||||
return
|
||||
|
||||
+85
-36
@@ -18,6 +18,11 @@ import { Icon } from './icons'
|
||||
* events for its own file drop on Windows, so HTML5 DnD silently dies in the
|
||||
* packaged app.
|
||||
*
|
||||
* Files dragged in from Finder / Explorer ride the same store as a `files`
|
||||
* payload: Tauri reports that drag (with real paths) instead of the webview,
|
||||
* and `lib/fileDrop.ts` feeds it in through `nativeDragStart` / `Move` / `End`,
|
||||
* so the same targets light up and the same ghost names what a drop would do.
|
||||
*
|
||||
* The state lives in a module-level store read through useSyncExternalStore
|
||||
* with narrow selectors, so a pointer move re-renders only the target under it
|
||||
* (and the ghost) — never the table.
|
||||
@@ -39,6 +44,12 @@ export type DragPayload =
|
||||
source: object
|
||||
}
|
||||
| { kind: 'node'; node: PlaylistNode; parentId: string | null }
|
||||
/** Files and folders from the OS, as absolute paths. Not yet tracks: a
|
||||
* target hands them to the drop resolver, which reads what is in them. */
|
||||
| { kind: 'files'; paths: string[] }
|
||||
|
||||
/** What a playlist or export row takes: track rows, or files from the OS. */
|
||||
export type TracksOrFiles = Exclude<DragPayload, { kind: 'node' }>
|
||||
|
||||
export interface DropPoint {
|
||||
x: number
|
||||
@@ -117,44 +128,26 @@ function evaluate() {
|
||||
|
||||
let detach: (() => void) | null = null
|
||||
|
||||
/** Start a drag. Call it once the press has moved past the source's threshold. */
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
|
||||
/** End the drag in progress, dropping on the target under the pointer if `drop`. */
|
||||
function finish(drop: boolean) {
|
||||
const { payload: p, target, hint, x, y, alt } = state
|
||||
detach?.()
|
||||
if (!drop || !p || !target) return
|
||||
const spec = targets.get(target)
|
||||
try {
|
||||
spec?.current.onDrop(p, hint, { x, y, alt })
|
||||
} catch (err) {
|
||||
console.error('drop failed', err)
|
||||
}
|
||||
}
|
||||
|
||||
/** Publish a new drag and start edge auto-scroll. Returns what undoes both. */
|
||||
function open(payload: DragPayload, at: { x: number; y: number; alt: boolean }): () => void {
|
||||
detach?.()
|
||||
set({ ...IDLE, payload, ...at })
|
||||
document.documentElement.classList.add('is-dragging')
|
||||
window.getSelection()?.removeAllRanges()
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
// One notification per move: evaluate() publishes the position with the hint.
|
||||
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
|
||||
evaluate()
|
||||
}
|
||||
const finish = (drop: boolean) => {
|
||||
const { payload: p, target, hint, x, y, alt } = state
|
||||
detach?.()
|
||||
if (!drop || !p || !target) return
|
||||
const spec = targets.get(target)
|
||||
try {
|
||||
spec?.current.onDrop(p, hint, { x, y, alt })
|
||||
} catch (err) {
|
||||
console.error('drop failed', err)
|
||||
}
|
||||
}
|
||||
const onUp = () => finish(true)
|
||||
const onCancel = () => finish(false)
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && e.type === 'keydown') {
|
||||
// Before every other Esc handler: cancelling the drag is all Esc does.
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
|
||||
set({ alt: e.type === 'keydown' })
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
// Hold near the edge of a `data-drag-scroll` element to scroll it. Its
|
||||
// value is the height covered at the top (a sticky header). The edge is
|
||||
// thinner than a row and must be HELD for a moment first: otherwise the
|
||||
@@ -187,6 +180,37 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
}
|
||||
raf = requestAnimationFrame(autoScroll)
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(raf)
|
||||
document.documentElement.classList.remove('is-dragging')
|
||||
set(IDLE)
|
||||
}
|
||||
}
|
||||
|
||||
/** Start a drag. Call it once the press has moved past the source's threshold. */
|
||||
export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt: boolean }) {
|
||||
const close = open(payload, at)
|
||||
|
||||
const onMove = (e: PointerEvent) => {
|
||||
// One notification per move: evaluate() publishes the position with the hint.
|
||||
state = { ...state, x: e.clientX, y: e.clientY, alt: e.altKey }
|
||||
evaluate()
|
||||
}
|
||||
const onUp = () => finish(true)
|
||||
const onCancel = () => finish(false)
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && e.type === 'keydown') {
|
||||
// Before every other Esc handler: cancelling the drag is all Esc does.
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
finish(false)
|
||||
return
|
||||
}
|
||||
if (e.key === 'Alt' && state.alt !== (e.type === 'keydown')) {
|
||||
set({ alt: e.type === 'keydown' })
|
||||
evaluate()
|
||||
}
|
||||
}
|
||||
window.addEventListener('pointermove', onMove)
|
||||
window.addEventListener('pointerup', onUp)
|
||||
window.addEventListener('pointercancel', onCancel)
|
||||
@@ -195,14 +219,12 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
window.addEventListener('blur', onCancel)
|
||||
detach = () => {
|
||||
detach = null
|
||||
cancelAnimationFrame(raf)
|
||||
window.removeEventListener('pointermove', onMove)
|
||||
window.removeEventListener('pointerup', onUp)
|
||||
window.removeEventListener('pointercancel', onCancel)
|
||||
window.removeEventListener('keydown', onKey, true)
|
||||
window.removeEventListener('keyup', onKey, true)
|
||||
window.removeEventListener('blur', onCancel)
|
||||
document.documentElement.classList.remove('is-dragging')
|
||||
// The pointerup that ended the drag is followed by a click on whatever
|
||||
// is under it; that click is part of the drop, not a click of its own.
|
||||
const swallow = (e: MouseEvent) => {
|
||||
@@ -211,11 +233,34 @@ export function beginDrag(payload: DragPayload, at: { x: number; y: number; alt:
|
||||
}
|
||||
window.addEventListener('click', swallow, true)
|
||||
setTimeout(() => window.removeEventListener('click', swallow, true), 0)
|
||||
set(IDLE)
|
||||
close()
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** A drag the OS owns (files from Finder / Explorer): it enters the window… */
|
||||
export function nativeDragStart(payload: DragPayload, at: { x: number; y: number }) {
|
||||
const close = open(payload, { ...at, alt: false })
|
||||
detach = () => {
|
||||
detach = null
|
||||
close()
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** …moves over it (window coordinates, CSS pixels)… */
|
||||
export function nativeDragMove(at: { x: number; y: number }) {
|
||||
if (!state.payload) return
|
||||
state = { ...state, ...at }
|
||||
evaluate()
|
||||
}
|
||||
|
||||
/** …and is dropped (or leaves the window: `drop` false). */
|
||||
export function nativeDragEnd(drop: boolean, at?: { x: number; y: number }) {
|
||||
if (drop && at) nativeDragMove(at)
|
||||
finish(drop)
|
||||
}
|
||||
|
||||
/** 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
|
||||
@@ -273,6 +318,10 @@ export function useDropTarget<H>(spec: DropSpec<H>): [(el: HTMLElement | null) =
|
||||
function describe(p: DragPayload): { icon: 'music' | 'playlist' | 'folder' | 'smart'; text: string } {
|
||||
if (p.kind === 'node')
|
||||
return { icon: p.node.kind === 'folder' ? 'folder' : p.node.kind === 'smart' ? 'smart' : 'playlist', text: p.node.name }
|
||||
if (p.kind === 'files')
|
||||
return p.paths.length === 1
|
||||
? { icon: 'music', text: p.paths[0].split(/[\\/]/).filter(Boolean).pop() ?? p.paths[0] }
|
||||
: { icon: 'music', text: `${p.paths.length} items` }
|
||||
if (p.ids.length === 1) {
|
||||
const t = p.tracks[0]
|
||||
return { icon: 'music', text: t ? [t.artist, t.title].filter(Boolean).join(' – ') || 'Untitled' : '1 track' }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { nativeDragEnd, nativeDragMove, nativeDragStart } from './drag'
|
||||
|
||||
/**
|
||||
* Files dragged in from Finder / Explorer, fed into the window's ONE drag
|
||||
* store (`lib/drag.tsx`) as a `files` payload, so the targets that take track
|
||||
* rows — playlists, exports, the deck — take files too, and anywhere else is
|
||||
* "add to the collection" (App's own target).
|
||||
*
|
||||
* Tauri only: the shell's webview hands the OS drag to Tauri, which reports it
|
||||
* with real paths — what adding a file IN PLACE needs. A plain browser gives a
|
||||
* page `File` objects without paths, so in a browser a file drop is only
|
||||
* CAUGHT — left alone, the browser navigates to the dropped file and the app
|
||||
* is gone — and `onBrowserDrop` says why nothing happened.
|
||||
*
|
||||
* `enabled` false (no library open yet) and an open dialog both refuse the
|
||||
* drag at its start, before anything is highlighted.
|
||||
*/
|
||||
export function useNativeFileDrop(enabled: boolean, onBrowserDrop: () => void) {
|
||||
const enabledRef = useRef(enabled)
|
||||
enabledRef.current = enabled
|
||||
const onBrowserDropRef = useRef(onBrowserDrop)
|
||||
onBrowserDropRef.current = onBrowserDrop
|
||||
|
||||
useEffect(() => {
|
||||
if (!('__TAURI_INTERNALS__' in window)) {
|
||||
// Only drags carrying files: the app's own drags are pointer events,
|
||||
// and a text drag into a field must keep working.
|
||||
const hasFiles = (e: DragEvent) => !!e.dataTransfer?.types.includes('Files')
|
||||
const over = (e: DragEvent) => {
|
||||
if (hasFiles(e)) e.preventDefault()
|
||||
}
|
||||
const drop = (e: DragEvent) => {
|
||||
if (!hasFiles(e)) return
|
||||
e.preventDefault()
|
||||
onBrowserDropRef.current()
|
||||
}
|
||||
window.addEventListener('dragover', over)
|
||||
window.addEventListener('drop', drop)
|
||||
return () => {
|
||||
window.removeEventListener('dragover', over)
|
||||
window.removeEventListener('drop', drop)
|
||||
}
|
||||
}
|
||||
let unlisten: (() => void) | undefined
|
||||
let cancelled = false
|
||||
let active = false
|
||||
void (async () => {
|
||||
const { getCurrentWebview } = await import('@tauri-apps/api/webview')
|
||||
const off = await getCurrentWebview().onDragDropEvent(({ payload }) => {
|
||||
// Tauri reports PHYSICAL pixels; the page works in CSS pixels.
|
||||
const scale = window.devicePixelRatio || 1
|
||||
const at = 'position' in payload ? { x: payload.position.x / scale, y: payload.position.y / scale } : null
|
||||
switch (payload.type) {
|
||||
case 'enter':
|
||||
active =
|
||||
enabledRef.current &&
|
||||
payload.paths.length > 0 &&
|
||||
!document.querySelector('[aria-modal="true"]')
|
||||
if (active && at) nativeDragStart({ kind: 'files', paths: payload.paths }, at)
|
||||
break
|
||||
case 'over':
|
||||
if (active && at) nativeDragMove(at)
|
||||
break
|
||||
case 'drop':
|
||||
if (active) nativeDragEnd(true, at ?? undefined)
|
||||
active = false
|
||||
break
|
||||
case 'leave':
|
||||
if (active) nativeDragEnd(false)
|
||||
active = false
|
||||
break
|
||||
}
|
||||
})
|
||||
if (cancelled) off()
|
||||
else unlisten = off
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
unlisten?.()
|
||||
if (active) nativeDragEnd(false)
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
Reference in new issue
Block a user