import { createPortal } from 'react-dom' import { useEffect, useRef, useState } from 'react' import { maxPosition, moveToPosition } from '../lib/playlistOrder' interface Props { /** The playlist's full entry order — never the sorted or filtered view, so * the move is safe whatever the table is showing. */ order: string[] /** The tracks to move; they keep their playlist order as one block. */ ids: string[] onMove: (order: string[]) => void onClose: () => void } /** "Set Position…": type where the first selected track should end up. */ export function SetPositionDialog({ order, ids, onMove, onClose }: Props) { const moving = new Set(ids) const count = order.filter((id) => moving.has(id)).length const max = maxPosition(order, moving) const current = order.findIndex((id) => moving.has(id)) + 1 const [value, setValue] = useState(String(current)) const input = useRef(null) useEffect(() => input.current?.select(), []) const typed = Number.parseInt(value, 10) const position = Number.isFinite(typed) ? Math.min(Math.max(typed, 1), max) : null const submit = () => { if (position === null) return const next = moveToPosition(order, moving, position) if (next.some((id, i) => id !== order[i])) onMove(next) onClose() } useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, [onClose]) const span = (p: number) => (count > 1 ? `#${p}–${p + count - 1}` : `#${p}`) return createPortal(
e.stopPropagation()} onSubmit={(e) => { e.preventDefault() submit() }} >
Set position
{position === null ? 'Type a position.' : count > 1 ? `Will occupy ${span(position)}` : `Now ${span(current)} · will be ${span(position)}`}
, document.body, ) }