Added extensive add to in context menu

This commit is contained in:
patben8 committed 2026-09-25 10:32:01 +02:00
1 parent 07e85cfdc9
commit 5909c704f4
6 files changed
+181 -181

No files matched your search

+111 -30
View File
@@ -1,10 +1,10 @@
import { useEffect, useRef } from 'react'
import { useEffect, useRef, useState } from 'react'
export interface MenuItem {
label: string
onClick: () => void
danger?: boolean
}
/** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */
export type MenuItem =
| { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: string }
| { label: string; submenu: MenuItem[] }
| { heading: string; empty?: string }
interface Props {
x: number
@@ -13,8 +13,12 @@ interface Props {
onClose: () => void
}
const SUBMENU_WIDTH = 240
const SUBMENU_MAX_HEIGHT = 288
// Lightweight fixed-position menu. Closes on outside click, scroll, or Escape.
export function ContextMenu({ x, y, items, onClose }: Props) {
const rootRef = useRef<HTMLDivElement>(null)
// Read through a ref so the listeners are attached ONCE. Callers pass an
// inline `onClose`; if the effect depended on it, a click that re-renders the
// parent (e.g. selecting a row) would detach the listeners before the
@@ -23,47 +27,124 @@ export function ContextMenu({ x, y, items, onClose }: Props) {
onCloseRef.current = onClose
useEffect(() => {
const close = () => onCloseRef.current()
// Scrolling a long submenu must not dismiss the menu it belongs to.
const onScroll = (e: Event) => {
if (e.target instanceof Node && rootRef.current?.contains(e.target)) return
close()
}
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onCloseRef.current()
// Defer attaching outside-dismiss listeners by a tick so the very
// right-click/click that opened the menu can't immediately close it.
const id = setTimeout(() => {
window.addEventListener('click', close)
window.addEventListener('contextmenu', close)
window.addEventListener('scroll', close, true)
window.addEventListener('scroll', onScroll, true)
window.addEventListener('keydown', onKey)
}, 0)
return () => {
clearTimeout(id)
window.removeEventListener('click', close)
window.removeEventListener('contextmenu', close)
window.removeEventListener('scroll', close, true)
window.removeEventListener('scroll', onScroll, true)
window.removeEventListener('keydown', onKey)
}
}, [])
return (
<div
role="menu"
className="fixed z-50 min-w-[160px] overflow-hidden rounded-lg border border-line bg-ink-850 py-1 shadow-2xl"
style={{ top: Math.min(y, window.innerHeight - 100), left: Math.min(x, window.innerWidth - 180) }}
onClick={(e) => e.stopPropagation()}
>
{items.map((item, i) => (
<button
key={i}
onClick={() => {
item.onClick()
onClose()
}}
className={`block w-full px-3 py-1.5 text-left text-sm ${
item.danger
? 'text-pink hover:bg-ink-800'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{item.label}
</button>
))}
<div ref={rootRef} role="menu" onClick={(e) => e.stopPropagation()}>
<MenuPanel
items={items}
onClose={onClose}
className="min-w-[160px]"
style={{ top: Math.min(y, window.innerHeight - 100), left: Math.min(x, window.innerWidth - 180) }}
/>
</div>
)
}
function MenuPanel({
items,
onClose,
className = '',
style,
}: {
items: MenuItem[]
onClose: () => void
className?: string
style: React.CSSProperties
}) {
// The open submenu: which row, and where to draw it. Fixed-positioned from
// the row's rect, flipping left / up when it would run off the window.
const [open, setOpen] = useState<{ index: number; style: React.CSSProperties } | null>(null)
const openSubmenu = (index: number, row: HTMLElement) => {
const r = row.getBoundingClientRect()
const left =
r.right + SUBMENU_WIDTH > window.innerWidth ? Math.max(0, r.left - SUBMENU_WIDTH) : r.right
const top = Math.max(8, Math.min(r.top - 4, window.innerHeight - SUBMENU_MAX_HEIGHT - 8))
setOpen({ index, style: { left, top, width: SUBMENU_WIDTH, maxHeight: SUBMENU_MAX_HEIGHT } })
}
const openItem = open ? items[open.index] : null
return (
<>
<div
className={`fixed z-50 overflow-y-auto rounded-lg border border-line bg-ink-850 py-1 shadow-2xl ${className}`}
style={style}
>
{items.map((item, i) => {
if ('heading' in item) {
return (
<div key={i}>
<div className="px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-wider text-faint">
{item.heading}
</div>
{item.empty && <div className="px-3 py-1.5 text-sm text-faint">{item.empty}</div>}
</div>
)
}
if ('submenu' in item) {
return (
<button
key={i}
onMouseEnter={(e) => openSubmenu(i, e.currentTarget)}
onClick={(e) => openSubmenu(i, e.currentTarget)}
className={`flex w-full items-center justify-between gap-4 px-3 py-1.5 text-left text-sm hover:bg-ink-800 hover:text-text ${
open?.index === i ? 'bg-ink-800 text-text' : 'text-muted'
}`}
>
<span>{item.label}</span>
<span className="text-[10px] text-faint">▸</span>
</button>
)
}
return (
<button
key={i}
onMouseEnter={() => setOpen(null)}
onClick={() => {
item.onClick()
onClose()
}}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${
item.danger
? 'text-pink hover:bg-ink-800'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{item.icon && <span className="shrink-0 text-[11px] text-gold">{item.icon}</span>}
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.hint && (
<span className="shrink-0 text-[10px] tabular-nums text-faint">{item.hint}</span>
)}
</button>
)
})}
</div>
{open && openItem && 'submenu' in openItem && (
<MenuPanel items={openItem.submenu} onClose={onClose} style={open.style} />
)}
</>
)
}
+1 -1
View File
@@ -279,7 +279,7 @@ function ExportRow({
{expanded && data && data.tracks === 0 && (
<div style={{ paddingLeft: 24 }} className="py-1 pr-2 text-[11px] text-faint">
Empty — select tracks and use “Add to…”.
Empty — right-click tracks and choose Add to.
</div>
)}
-123
View File
@@ -1,123 +0,0 @@
import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistNode } from '../api'
interface Props {
count: number
trackIds: string[]
onClear: () => void
onDone: (msg: string) => void
onError: (msg: string) => void
}
function flattenPlaylists(nodes: PlaylistNode[]): PlaylistNode[] {
return nodes.flatMap((n) => [
...(n.can_add_tracks ? [n] : []),
...flattenPlaylists(n.children),
])
}
// Floating action bar shown when tracks are selected in the explorer.
export function SelectionBar({ count, trackIds, onClear, onDone, onError }: Props) {
const qc = useQueryClient()
const [menuOpen, setMenuOpen] = useState(false)
const { data: playlists } = useQuery({ queryKey: ['playlists'], queryFn: api.playlists })
const { data: exportSets } = useQuery({ queryKey: ['exports'], queryFn: api.exports })
const flat = playlists ? flattenPlaylists(playlists) : []
const sets = exportSets ?? []
// Adding to an EXPORT does not touch the library — an export set is
// Konduktor's own curation — so unlike the playlist mutation this dirties
// nothing and invalidates only the export's own live counts.
const addToExport = useMutation({
mutationFn: ({ id, ids }: { id: string; ids: string[] }) =>
api.addToExport(id, { track_ids: ids }),
onSuccess: (_res, vars) => {
qc.invalidateQueries({ queryKey: ['export-contents', vars.id] })
qc.invalidateQueries({ queryKey: ['export-tracks', vars.id] })
qc.invalidateQueries({ queryKey: ['export-loose', vars.id] })
const set = sets.find((s) => s.id === vars.id)
onDone(`Added ${vars.ids.length} track${vars.ids.length === 1 ? '' : 's'} to ${set?.name ?? 'export'}`)
setMenuOpen(false)
onClear()
},
onError: (e: Error) => onError(e.message),
})
const add = useMutation({
mutationFn: ({ uuid, ids }: { uuid: string; ids: string[] }) => api.addEntries(uuid, ids),
onSuccess: (res, vars) => {
qc.invalidateQueries({ queryKey: ['state'] })
qc.invalidateQueries({ queryKey: ['playlists'] })
qc.invalidateQueries({ queryKey: ['playlist', vars.uuid] })
const pl = flat.find((p) => p.id === vars.uuid)
onDone(`Added ${res.added} track${res.added === 1 ? '' : 's'} to ${pl?.name ?? 'playlist'}`)
setMenuOpen(false)
onClear()
},
onError: (e: Error) => onError(e.message),
})
if (count === 0) return null
return (
<div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 flex justify-center">
<div className="pointer-events-auto flex items-center gap-3 rounded-full border border-line bg-ink-800 py-2 pl-4 pr-2 shadow-xl">
<span className="text-sm text-text">
<span className="font-semibold tabular-nums">{count}</span> selected
</span>
<div className="relative">
<button
onClick={() => setMenuOpen((o) => !o)}
className="rounded-full bg-accent px-3 py-1.5 text-sm font-medium text-ink-950 hover:brightness-110"
>
Add to… ▾
</button>
{menuOpen && (
<div className="absolute bottom-full right-0 mb-2 max-h-72 w-60 overflow-y-auto rounded-lg border border-line bg-ink-850 p-1 shadow-2xl">
<div className="px-3 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-wider text-faint">
Playlists
</div>
{flat.length === 0 && (
<div className="px-3 py-1.5 text-sm text-faint">No playlists yet</div>
)}
{flat.map((p) => (
<button
key={p.id}
onClick={() => add.mutate({ uuid: p.id, ids: trackIds })}
className="flex w-full items-center justify-between gap-2 rounded-md px-3 py-1.5 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
>
<span className="truncate">{p.name}</span>
<span className="shrink-0 text-[10px] tabular-nums text-faint">{p.count}</span>
</button>
))}
<div className="px-3 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-wider text-faint">
Exports
</div>
{sets.length === 0 && (
<div className="px-3 py-1.5 text-sm text-faint">No exports yet</div>
)}
{sets.map((set) => (
<button
key={set.id}
onClick={() => addToExport.mutate({ id: set.id, ids: trackIds })}
className="flex w-full items-center gap-2 rounded-md px-3 py-1.5 text-left text-sm text-muted hover:bg-ink-800 hover:text-text"
>
<span className="shrink-0 text-[11px] text-gold">◈</span>
<span className="truncate">{set.name}</span>
</button>
))}
</div>
)}
</div>
<button
onClick={onClear}
className="rounded-full px-2 py-1.5 text-sm text-muted hover:bg-ink-700 hover:text-text"
>
Clear
</button>
</div>
</div>
)
}
+9
View File
@@ -2,6 +2,8 @@ interface Props {
showing: number
total: number
sourceName: string
/** Rows currently selected; shown only when non-zero. */
selected?: number
loading?: boolean
collectionName?: string | null
onChangeCollection?: () => void
@@ -11,6 +13,7 @@ export function StatusBar({
showing,
total,
sourceName,
selected = 0,
loading,
collectionName,
onChangeCollection,
@@ -32,6 +35,12 @@ export function StatusBar({
)}
</span>
)}
{selected > 0 && (
<>
<span className="text-faint">·</span>
<span className="tabular-nums text-accent">{selected.toLocaleString()} selected</span>
</>
)}
{collectionName && (
<button
onClick={onChangeCollection}