Implemented midi support`

This commit is contained in:
patben8 committed 2026-11-03 22:56:19 +01:00
1 parent f55b8f06e4
commit 8d0817b39e
41 files changed
+2827 -26

No files matched your search

+7 -5
View File
@@ -26,10 +26,10 @@ 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, listing: Listing = 'host') {
export function useFsListing(path: string | undefined, platform?: string, listing: Listing = 'host', suffix?: string) {
return useQuery({
queryKey: ['fs', listing, path ?? '~', platform ?? null],
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform)),
queryKey: ['fs', listing, path ?? '~', platform ?? null, suffix ?? null],
queryFn: () => (listing === 'library' ? api.libraryListDir(path) : api.listDir(path, platform, suffix)),
})
}
@@ -65,10 +65,12 @@ interface Props {
footer?: ReactNode
/** Whose folders are browsed (see `Listing`). Default: this computer's. */
listing?: Listing
/** Instead of a platform's files, those whose name ends with this. */
suffix?: string
}
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host' }: Props) {
const listing = useFsListing(path, platform, whose)
export function FileBrowser({ mode, platform, path, onNavigate, onPickFile, footer, listing: whose = 'host', suffix }: Props) {
const listing = useFsListing(path, platform, whose, suffix)
const places = useQuery({
queryKey: ['fs-places', platform ?? null],
queryFn: () => api.places(platform),
+4
View File
@@ -5,6 +5,8 @@ import { Icon } from '../lib/icons'
import { RenameField } from './RenameField'
interface Props {
/** The deck's MIDI action prefix (`deck.A`), for on-screen learning. */
midi?: string
cues: CuePoint[]
/** Bank size, from capabilities — not every platform has eight. */
slotCount: number
@@ -42,6 +44,7 @@ const READONLY_LABELS: Record<string, string> = {
* than surfacing the refusal as an error.
*/
export function HotcueBar({
midi,
cues,
slotCount,
slotLabel,
@@ -74,6 +77,7 @@ export function HotcueBar({
return (
<button
key={slot}
data-midi-action={midi && `${midi}.hotcue.${slot + 1}`}
onContextMenu={(e) => {
e.preventDefault()
onSlotMenu(slot, e.clientX, e.clientY)
+13
View File
@@ -12,6 +12,9 @@ export function sizeLabel(size: number): string {
export type LoopMode = 'beat' | 'manual'
interface Props {
/** The deck's MIDI action prefix (`deck.A`): its controls carry
* `data-midi-action` for on-screen learning (lib/midi). */
midi?: string
mode: LoopMode
onMode: (mode: LoopMode) => void
hasGrid: boolean // beat loops and jumps are sized in beats; inert without a grid
@@ -67,6 +70,7 @@ const CLUSTER = 'well flex h-10 w-[8.5rem] shrink-0 items-center gap-0.5 rounded
* Presentational: PrepStrip owns every piece of state and does the seeking.
*/
export function LoopControls({
midi,
mode,
onMode,
hasGrid,
@@ -85,6 +89,7 @@ export function LoopControls({
onToggleLoop,
onMove,
}: Props) {
const m = (op: string) => (midi ? `${midi}.${op}` : undefined)
const atMin = size <= LOOP_SIZES[0]
const atMax = size >= LOOP_SIZES[LOOP_SIZES.length - 1]
const what = loopActive ? 'Move the loop' : `Jump ${sizeLabel(size)} beat${size === 1 ? '' : 's'}`
@@ -107,6 +112,7 @@ export function LoopControls({
<div role="group" aria-label="Loop size" className={`${CLUSTER} font-mono`}>
<button
onClick={onSmaller}
data-midi-action={m('sizeDown')}
disabled={atMin}
title="Halve the size (Cmd/Ctrl+↓)"
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
@@ -115,6 +121,7 @@ export function LoopControls({
</button>
<button
onClick={onToggleSize}
data-midi-action={m('sizeLoop')}
disabled={!hasGrid || !ready}
title={hasGrid ? `${sizeLabel(size)}-beat loop — click to switch on or off` : 'No beatgrid'}
className={`${KEY} h-[34px] min-w-0 flex-1 px-2 text-sm font-semibold ${
@@ -125,6 +132,7 @@ export function LoopControls({
</button>
<button
onClick={onBigger}
data-midi-action={m('sizeUp')}
disabled={atMax}
title="Double the size (Cmd/Ctrl+↑)"
className={`${KEY} h-[34px] w-7 text-[15px] text-muted hover:bg-ink-800 hover:text-text`}
@@ -136,6 +144,7 @@ export function LoopControls({
<div role="group" aria-label="Manual loop" className={`${CLUSTER} text-xs font-semibold`}>
<button
onClick={onLoopIn}
data-midi-action={m('loopIn')}
disabled={!ready}
aria-pressed={inArmed || manualSet}
title={inArmed ? 'Loop in is set — now press OUT (or IN again to move it)' : 'Loop in at the playhead'}
@@ -145,6 +154,7 @@ export function LoopControls({
</button>
<button
onClick={onLoopOut}
data-midi-action={m('loopOut')}
disabled={!ready || (!inArmed && !manualSet)}
aria-pressed={manualSet && !inArmed}
title={
@@ -160,6 +170,7 @@ export function LoopControls({
</button>
<button
onClick={onToggleLoop}
data-midi-action={m('loopToggle')}
disabled={!canToggle}
title={loopActive ? 'Switch the loop off' : 'Switch the loop on'}
aria-pressed={loopActive}
@@ -173,6 +184,7 @@ export function LoopControls({
<div role="group" aria-label="Jump or move loop" className="glass-group flex h-10 items-center rounded-xl">
<button
onClick={() => onMove(-1)}
data-midi-action={m('jumpBack')}
disabled={!canMove}
title={`${what} back (←)`}
className={`${HALF} rounded-l-xl`}
@@ -181,6 +193,7 @@ export function LoopControls({
</button>
<button
onClick={() => onMove(1)}
data-midi-action={m('jumpFwd')}
disabled={!canMove}
title={`${what} forward (→)`}
className={`${HALF} rounded-r-xl`}
@@ -0,0 +1,107 @@
import { useEffect } from 'react'
import { createPortal } from 'react-dom'
import { actionDef } from '../lib/midi/actions'
import { armLearn, getMidiState, setOnScreenLearn, useMidiState } from '../lib/midi/store'
/**
* On-screen MIDI learning (Settings ▸ MIDI Controllers… ▸ Learn on screen):
* every control that has a MIDI action (`data-midi-action`) is ringed;
* clicking one ARMS it instead of using it, and the next control moved on a
* controller is bound to it — into the Shift layer if the controller's Shift
* is held. Mapped controls show solid, the armed one glows, and Done or Esc
* leaves. Mounted once (main.tsx); renders nothing until switched on.
*/
export function MidiLearnOverlay() {
const onScreen = useMidiState((s) => s.onScreen)
const armed = useMidiState((s) => s.armed)
const mappings = useMidiState((s) => s.mappings)
const ports = useMidiState((s) => s.ports)
const learned = useMidiState((s) => s.learned)
// Clicks on a learnable control arm it; nothing else changes. Pointer and
// mouse events are stopped in the capture phase so the control never acts
// (knobs and faders start their drags on pointerdown).
useEffect(() => {
if (!onScreen) return
const target = (e: Event) => (e.target as Element | null)?.closest?.('[data-midi-action]') as HTMLElement | null
const stop = (e: Event) => {
const el = target(e)
if (!el) return
e.preventDefault()
e.stopPropagation()
if (e.type !== 'pointerdown') return
const action = el.dataset.midiAction!
const a = getMidiState().armed
armLearn(a && 'layer' in a && a.action === action ? null : { action, layer: 'normal' })
}
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return
e.preventDefault()
e.stopPropagation()
if (getMidiState().armed) armLearn(null)
else setOnScreenLearn(false)
}
const kinds = ['pointerdown', 'pointerup', 'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu']
for (const k of kinds) window.addEventListener(k, stop, true)
window.addEventListener('keydown', onKey, true)
document.body.classList.add('midi-learn')
return () => {
for (const k of kinds) window.removeEventListener(k, stop, true)
window.removeEventListener('keydown', onKey, true)
document.body.classList.remove('midi-learn')
}
}, [onScreen])
// Mark the controls: mapped (on a connected controller), armed, just learned.
useEffect(() => {
if (!onScreen) return
const mapped = new Set<string>()
for (const p of ports) {
for (const b of Object.values(mappings[p]?.bindings ?? {})) {
if (b.normal) mapped.add(b.normal)
if (b.shift) mapped.add(b.shift)
}
}
const armedId = armed && 'layer' in armed ? armed.action : null
const flash = learned && performance.now() - learned.at < 1500 ? learned.action : null
for (const el of document.querySelectorAll<HTMLElement>('[data-midi-action]')) {
const id = el.dataset.midiAction!
el.toggleAttribute('data-midi-mapped', mapped.has(id))
el.toggleAttribute('data-midi-armed', id === armedId)
el.toggleAttribute('data-midi-learned', id === flash)
}
// The "just learned" flash fades on its own.
const fade = flash ? setTimeout(() => document.querySelector('[data-midi-learned]')?.removeAttribute('data-midi-learned'), 1500) : 0
return () => {
clearTimeout(fade)
for (const el of document.querySelectorAll('[data-midi-action]')) {
el.removeAttribute('data-midi-mapped')
el.removeAttribute('data-midi-armed')
el.removeAttribute('data-midi-learned')
}
}
}, [onScreen, armed, mappings, ports, learned])
if (!onScreen) return null
const armedLabel = armed && 'layer' in armed ? actionDef(armed.action)?.label : null
return createPortal(
<div className="pointer-events-none fixed inset-x-0 top-3 z-[80] flex justify-center">
<div className="pointer-events-auto flex items-center gap-3 glass-overlay rounded-full px-4 py-2 text-sm text-text">
<span className="h-2 w-2 animate-pulse rounded-full bg-accent" />
{ports.length === 0 ? (
<span>MIDI learn — plug in a controller</span>
) : armedLabel ? (
<span>
<span className="font-semibold">{armedLabel}</span>: move a control on your controller (hold its Shift for the Shift layer)
</span>
) : (
<span>MIDI learn — click a control, then move it on your controller</span>
)}
<button onClick={() => setOnScreenLearn(false)} className="rounded-full btn-primary px-3 py-1 text-xs font-semibold">
Done
</button>
</div>
</div>,
document.body,
)
}
+368
View File
@@ -0,0 +1,368 @@
import { useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import { ACTION_GROUPS, ACTIONS, type ActionDef } from '../lib/midi/actions'
import { ENCODING_LABELS, ENCODINGS } from '../lib/midi/encoding'
import {
DEFAULT_JOG_SENSITIVITY,
DEFAULT_SCRUB_SPEED,
emptyMapping,
sanitizeMapping,
setBinding,
sourcesFor,
unbind,
type Layer,
type Mapping,
} from '../lib/midi/mapping'
import { describeSource, type SourceKey } from '../lib/midi/messages'
import { armLearn, replaceMappings, setOnScreenLearn, updateMapping, useMidiState, type LearnTarget } from '../lib/midi/store'
import { askConfirm } from '../lib/confirm'
import { ContextMenu, type MenuItem } from './ContextMenu'
import { FileBrowser } from './FileBrowser'
import { FolderPicker } from './FolderPicker'
import { Modal } from './Modal'
const section = 'text-[11px] font-semibold uppercase tracking-wider text-faint'
const MAPPING_SUFFIX = '.konduktor-midi.json'
const sameTarget = (a: LearnTarget | null, b: LearnTarget) =>
a != null && a.action === b.action && ('layer' in a ? a.layer : null) === ('layer' in b ? b.layer : null)
/**
* Settings ▸ MIDI Controllers… (decided 2026-11-03): every controller is
* mapped by LEARNING — press Learn beside an action (or "Learn on screen" and
* click the control), then move the control. Each control has a normal and a
* free Shift binding; Shift itself is a learned control. Mappings are per
* controller, kept in userprefs, and shareable as files.
*/
export function MidiSettings({ onClose }: { onClose: () => void }) {
const available = useMidiState((s) => s.available)
const blocked = useMidiState((s) => s.blocked)
const ports = useMidiState((s) => s.ports)
const mappings = useMidiState((s) => s.mappings)
const armed = useMidiState((s) => s.armed)
const activity = useMidiState((s) => s.activity)
const learned = useMidiState((s) => s.learned)
const known = useMemo(() => [...new Set([...ports, ...Object.keys(mappings)])], [ports, mappings])
const [selected, setSelected] = useState<string | null>(null)
const port = selected && known.includes(selected) ? selected : (known[0] ?? null)
const mapping: Mapping = (port && mappings[port]) || emptyMapping()
const [filter, setFilter] = useState('')
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
const [exporting, setExporting] = useState(false)
const [importing, setImporting] = useState(false)
const [note, setNote] = useState<{ error: boolean; text: string } | null>(null)
// What was just learned shows under its own controller.
useEffect(() => {
if (learned) setSelected(learned.port)
}, [learned])
// Closing the dialog stops waiting for a control.
useEffect(() => () => armLearn(null), [])
const learn = (t: LearnTarget) => armLearn(sameTarget(armed, t) ? null : t)
const edit = (fn: (m: Mapping) => Mapping) => port && updateMapping(port, fn)
const bindingMenu = (e: React.MouseEvent, src: SourceKey, action: ActionDef, layer: Layer) => {
const b = mapping.bindings[src]
if (!b) return
const r = e.currentTarget.getBoundingClientRect()
const items: MenuItem[] = [{ heading: describeSource(src) }]
if (action.kind !== 'button' && action.kind !== 'hold') {
items.push(
{
label: 'Encoding',
submenu: ENCODINGS.filter((x) => x !== 'button').map((x) => ({
label: ENCODING_LABELS[x],
hint: x === b.encoding ? '✓' : undefined,
onClick: () => edit((m) => setBinding(m, src, { encoding: x })),
})),
},
{ label: 'Reversed', checked: !!b.invert, onToggle: () => edit((m) => setBinding(m, src, { invert: !b.invert || undefined })) },
{ separator: true },
)
}
items.push(
{ label: 'Learn again', onClick: () => learn({ action: action.id, layer }) },
{ label: 'Clear', danger: true, onClick: () => edit((m) => unbind(m, action.id, layer)) },
)
setMenu({ x: r.left, y: r.bottom + 4, items })
}
const cell = (action: ActionDef, layer: Layer) => {
const t: LearnTarget = { action: action.id, layer }
if (sameTarget(armed, t)) {
return (
<button onClick={() => armLearn(null)} className="w-full animate-pulse rounded-md bg-accent/25 px-2 py-1 text-left text-[11px] text-text ring-1 ring-accent">
Move a control…
</button>
)
}
const sources = sourcesFor(mapping, action.id, layer)
if (sources.length === 0) {
return (
<button onClick={() => learn(t)} className="w-full rounded-md px-2 py-1 text-left text-[11px] text-faint hover:bg-ink-800 hover:text-text">
Learn
</button>
)
}
return (
<div className="flex flex-wrap gap-1">
{sources.map((src) => {
const enc = mapping.bindings[src]?.encoding
return (
<button
key={src}
onClick={(e) => bindingMenu(e, src, action, layer)}
title={enc && enc !== 'button' ? ENCODING_LABELS[enc] : undefined}
className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text hover:bg-ink-700"
>
{describeSource(src)}
{mapping.bindings[src]?.invert ? ' ⇄' : ''}
</button>
)
})}
</div>
)
}
const needle = filter.trim().toLowerCase()
const shown = ACTIONS.filter((a) => !needle || a.label.toLowerCase().includes(needle) || a.group.toLowerCase().includes(needle))
const forget = async () => {
if (!port) return
const ok = await askConfirm({
title: `Forget ${port}'s mapping?`,
body: 'Every learned control on this controller is cleared.',
confirmLabel: 'Forget',
})
if (!ok) return
const next = { ...mappings }
delete next[port]
replaceMappings(next)
}
const doExport = async (dir: string) => {
if (!port) return
try {
const { path } = await api.midiExport(dir, port, mapping)
setNote({ error: false, text: `Saved ${path}` })
} catch (e) {
setNote({ error: true, text: (e as Error).message })
}
}
const doImport = async (path: string) => {
setImporting(false)
if (!port) return
try {
const m = sanitizeMapping((await api.midiImport(path)).mapping)
if (!m) throw new Error('That file is not a MIDI mapping')
if (Object.keys(mapping.bindings).length > 0 || mapping.shift) {
const ok = await askConfirm({
title: `Replace ${port}'s mapping?`,
body: 'The imported mapping replaces every control learned on this controller.',
confirmLabel: 'Replace',
})
if (!ok) return
}
updateMapping(port, () => m)
setNote({ error: false, text: `Imported ${Object.keys(m.bindings).length} controls` })
} catch (e) {
setNote({ error: true, text: (e as Error).message })
}
}
return (
<Modal onDismiss={armed ? () => armLearn(null) : onClose}>
<div className="flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden glass-overlay">
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">MIDI Controllers</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
{!available ? (
<div className="px-5 py-6 text-sm text-muted">
MIDI is not available here. The desktop app reads controllers itself; in a browser, use Chrome.
</div>
) : blocked && known.length === 0 ? (
<div className="space-y-1 px-5 py-6 text-sm text-muted">
<p>The browser refused access to MIDI devices.</p>
<p className="text-xs text-faint">
Allow it from the site settings (the icon left of the address: MIDI devices → Allow). Konduktor asks again on
its own. ({blocked})
</p>
</div>
) : known.length === 0 ? (
<div className="px-5 py-6 text-sm text-muted">Plug in a MIDI controller — it shows up here within a couple of seconds.</div>
) : (
<>
<div className="space-y-3 border-b border-line px-5 py-3 text-sm">
<div className="flex flex-wrap items-center gap-2">
<select
value={port ?? ''}
onChange={(e) => setSelected(e.target.value)}
className="min-w-0 max-w-[16rem] rounded-lg well px-2 py-1 text-sm text-text outline-none"
>
{known.map((p) => (
<option key={p} value={p}>
{p}
{ports.includes(p) ? '' : ' (not connected)'}
</option>
))}
</select>
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-faint">
{activity
? `${activity.port}: ${describeSource(activity.source)} → ${activity.value}`
: 'Move a control to see it here'}
</span>
<button
onClick={() => {
setOnScreenLearn(true)
onClose()
}}
className="btn-glass rounded-full px-3 py-1 text-xs text-text"
title="Click a control on screen, then move it on your controller"
>
Learn on screen
</button>
<button onClick={() => setImporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
Import…
</button>
<button onClick={() => setExporting(true)} className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text">
Export…
</button>
{mappings[port ?? ''] && (
<button onClick={() => void forget()} className="rounded-full px-2 py-1 text-xs text-faint hover:text-pink">
Forget
</button>
)}
</div>
{note && <div className={`text-xs ${note.error ? 'text-pink' : 'text-faint'}`}>{note.text}</div>}
<div className="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2">
<span className="text-text">Shift button</span>
<div className="flex items-center gap-2">
{sameTarget(armed, { action: 'shift' }) ? (
<button onClick={() => armLearn(null)} className="animate-pulse rounded-md bg-accent/25 px-2 py-1 text-[11px] text-text ring-1 ring-accent">
Press the controller's Shift…
</button>
) : mapping.shift ? (
<>
<span className="rounded-md bg-ink-800 px-2 py-1 font-mono text-[10.5px] text-text">{describeSource(mapping.shift)}</span>
<button onClick={() => learn({ action: 'shift' })} className="text-[11px] text-faint hover:text-text">
Learn again
</button>
<button onClick={() => edit((m) => ({ ...m, shift: null }))} className="text-[11px] text-faint hover:text-pink">
Clear
</button>
</>
) : (
<button onClick={() => learn({ action: 'shift' })} className="rounded-md px-2 py-1 text-[11px] text-faint hover:bg-ink-800 hover:text-text">
Learn
</button>
)}
<span className="text-[11px] text-faint">Hold it while moving a control to learn its Shift action.</span>
</div>
<span className="text-text">Jog sensitivity</span>
<Slider
value={mapping.jogSensitivity}
min={0.25}
max={4}
step={0.05}
reset={DEFAULT_JOG_SENSITIVITY}
format={(v) => `×${v.toFixed(2)}`}
onChange={(v) => edit((m) => ({ ...m, jogSensitivity: v }))}
/>
<span className="text-text">Fast scrub</span>
<Slider
value={mapping.scrubSpeed}
min={2}
max={32}
step={1}
reset={DEFAULT_SCRUB_SPEED}
format={(v) => `×${v} a jog`}
onChange={(v) => edit((m) => ({ ...m, scrubSpeed: v }))}
/>
</div>
</div>
<div className="flex items-center gap-3 border-b border-line px-5 py-2">
<input
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder="Find an action…"
className="w-56 rounded-md well px-2 py-1 text-xs text-text outline-none focus:ring-1 focus:ring-accent"
/>
<span className="ml-auto w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">Control</span>
<span className="w-36 text-[11px] font-semibold uppercase tracking-wider text-faint">With Shift</span>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-5 pb-4">
{ACTION_GROUPS.map((g) => {
const rows = shown.filter((a) => a.group === g)
if (rows.length === 0) return null
return (
<section key={g} className="pt-3">
<h3 className={`${section} pb-1`}>
{g}
{g === 'Deck B' || g === 'Mixer' ? <span className="ml-2 normal-case tracking-normal">— performance mode only</span> : null}
</h3>
{rows.map((a) => (
<div key={a.id} className="flex items-center gap-3 border-b border-line/40 py-1">
<span className="min-w-0 flex-1 truncate text-sm text-text">{a.label}</span>
<div className="w-36 shrink-0">{cell(a, 'normal')}</div>
<div className="w-36 shrink-0">{cell(a, 'shift')}</div>
</div>
))}
</section>
)
})}
</div>
</>
)}
</div>
{menu && <ContextMenu {...menu} onClose={() => setMenu(null)} />}
{exporting && <FolderPicker value="" onChange={(dir) => void doExport(dir)} onClose={() => setExporting(false)} />}
{importing && <ImportPicker onPick={(p) => void doImport(p)} onClose={() => setImporting(false)} />}
</Modal>
)
}
function Slider({ value, min, max, step, reset, format, onChange }: {
value: number; min: number; max: number; step: number; reset: number; format: (v: number) => string; onChange: (v: number) => void
}) {
return (
<div className="flex items-center gap-3">
<input
type="range"
min={min}
max={max}
step={step}
value={value}
onChange={(e) => onChange(Number(e.target.value))}
onDoubleClick={() => onChange(reset)}
className="w-48"
/>
<span className="font-mono text-[11px] text-muted">{format(value)}</span>
</div>
)
}
/** Pick a `.konduktor-midi.json` file. */
function ImportPicker({ onPick, onClose }: { onPick: (path: string) => void; onClose: () => void }) {
const [dir, setDir] = useState<string | undefined>(undefined)
return (
<Modal onDismiss={onClose} layer="nested" padding="p-4">
<div className="flex h-[70vh] w-full max-w-2xl flex-col overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Import a MIDI mapping</h2>
</div>
<FileBrowser mode="file" suffix={MAPPING_SUFFIX} path={dir} onNavigate={setDir} onPickFile={onPick} />
<div className="flex justify-end border-t border-line px-5 py-3">
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
Cancel
</button>
</div>
</div>
</Modal>
)
}
+39
View File
@@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api, type Capabilities, type Track, type TrackOrigin } from '../api'
import { useDeckKeys, type DeckKeyTargets } from '../lib/deckKeys'
import { useMidiTargets } from '../lib/midi/targets'
import type { DeckMidi } from '../lib/midi/router'
import { useDropTarget, type DragPayload } from '../lib/drag'
import { usePrefsWriter } from '../lib/prefs'
import { mixer } from '../lib/audio/mixer'
@@ -283,6 +285,43 @@ export function PrepStrip({
return phaseOffset(theirs, mine, octaveFor(eo, em))
}
// A controller (lib/midi): the same deck handles the keys get, plus pitch
// and jog. Moving the pitch fader or nudging with the jog releases SYNC, as
// the on-screen fader and the phase meter's bend do (decided 2026-11-03).
const releaseSync = (id: DeckId) => live.current.synced[id] && setSynced((s) => ({ ...s, [id]: false }))
const midiDeck = (id: DeckId): DeckMidi => {
const d = deckOf(id)
return {
...d.shortcuts,
toggleSizeLoop: d.toggleSizeLoop,
loopIn: d.loopIn,
loopOut: d.loopOut,
toggleLoop: d.toggleLoop,
toggleSync: () => {
if (!performance) return
if (synced[id] || !syncBlocked(id)) toggleSync(id)
else onError?.(syncBlocked(id)!)
},
toggleKeylock: () => d.setKeylock(!d.keylock),
pitch: d.pitch,
setPitch: (v) => {
releaseSync(id)
d.setPitch(v)
},
jogTouch: (on) => d.jogTouch(on),
jogTurn: (ticks, sensitivity) => {
if (d.jogTurn(ticks, sensitivity) === 'nudge') releaseSync(id)
},
scrub: (ticks, sensitivity) => d.scrub(ticks, sensitivity),
}
}
useMidiTargets({
performance,
focused: lead,
decks: { A: midiDeck('A'), B: performance ? midiDeck('B') : null },
togglePerformance: onTogglePerformance,
})
const keys = useRef<DeckKeyTargets>({ focused: null, other: null })
keys.current = {
focused: deckOf(lead).shortcuts,
+13
View File
@@ -4,6 +4,7 @@ import { api } from '../api'
import { AppSettings } from './AppSettings'
import { useCaps } from '../lib/capabilities'
import { LocalLibrariesSettings } from './LocalLibrariesSettings'
import { MidiSettings } from './MidiSettings'
import { PerformanceSettings } from './PerformanceSettings'
import { RemoteCacheSettings } from './RemoteCacheSettings'
import { ShortcutsDialog } from './ShortcutsDialog'
@@ -26,6 +27,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [showApp, setShowApp] = useState(false)
const [showLocal, setShowLocal] = useState(false)
const [showPerformance, setShowPerformance] = useState(false)
const [showMidi, setShowMidi] = 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.
@@ -157,6 +159,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
<span className="text-sm text-text">Performance mode…</span>
<span className="text-[11px] text-faint">The second deck, the mixer and its effects</span>
</button>
<button
onClick={() => {
setShowMidi(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">MIDI Controllers…</span>
<span className="text-[11px] text-faint">Map a controller by moving its controls</span>
</button>
<button
onClick={() => {
setShowShortcuts(true)
@@ -175,6 +187,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
{showApp && <AppSettings onClose={() => setShowApp(false)} />}
{showLocal && <LocalLibrariesSettings onClose={() => setShowLocal(false)} />}
{showPerformance && <PerformanceSettings onClose={() => setShowPerformance(false)} />}
{showMidi && <MidiSettings onClose={() => setShowMidi(false)} />}
</div>
)
}
+52 -2
View File
@@ -16,6 +16,10 @@ import { PlatformIcon } from '../lib/platformIcons'
import { addTracksToPlaylist } from '../lib/addTracks'
import { useDragPayload, usePressToDrag, useDropTarget, type DragPayload, type TracksOrFiles } from '../lib/drag'
import { findNode, idsAfter, nodeIdsUnder, playlistIdsUnder } from '../lib/playlistTree'
import { useMidiTargets } from '../lib/midi/targets'
/** All Tracks' place in a controller's walk of the tree (no node has this id). */
const ALL_ROW = 'konduktor:all-tracks'
/**
* Which view the main table is showing.
@@ -104,6 +108,8 @@ interface RowActions {
/** Whether a folder is open, and opening / closing it. */
isOpen: (node: PlaylistNode) => boolean
setOpen: (node: PlaylistNode, open: boolean) => void
/** Where a controller's playlist browsing stands (lib/midi), when not on the open playlist. */
isCursor: (node: PlaylistNode) => boolean
onContextMenu: (e: React.MouseEvent, node: PlaylistNode) => void
onRename: (node: PlaylistNode, name: string, parentId: string | null) => void
onDelete: (node: PlaylistNode) => void
@@ -300,6 +306,7 @@ function NodeRow({
<div
ref={dropRef}
data-node-row
data-node-id={node.id}
onPointerDown={startDrag}
onContextMenu={(e) => actions.onContextMenu(e, node)}
className={`group relative flex items-center gap-1 rounded-[10px] pr-1 text-sm transition-colors ${
@@ -307,7 +314,9 @@ function NodeRow({
? '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'
: actions.isCursor(node)
? 'bg-ink-800 text-text ring-1 ring-accent/60'
: 'text-muted hover:bg-ink-800 hover:text-text'
}`}
>
{line && (
@@ -485,6 +494,45 @@ export function Sidebar({
useEffect(() => setOpenOverrides({}), [library?.path, expandByDefault])
const setFolderOpen = (id: string, open: boolean) =>
setOpenOverrides((o) => ({ ...o, [id]: open }))
const isOpen = (node: PlaylistNode) => openOverrides[node.id] ?? expandByDefault
// A controller's Shift + browse walks All Tracks and the visible playlist
// tree (decided 2026-11-03): a playlist opens as it is reached, a folder is
// only highlighted (the cursor) and opens / closes on the encoder's press.
const [treeCursor, setTreeCursor] = useState<string | null>(null)
useEffect(() => setTreeCursor(null), [source])
const visibleRows = (): { id: string; node: PlaylistNode | null }[] => {
const out: { id: string; node: PlaylistNode | null }[] = [{ id: ALL_ROW, node: null }]
const walk = (nodes: PlaylistNode[]) => {
for (const n of nodes) {
out.push({ id: n.id, node: n })
if (n.kind === 'folder' && isOpen(n)) walk(n.children)
}
}
walk(playlists ?? [])
return out
}
useMidiTargets({
tree: {
step: (ticks) => {
const rows = visibleRows()
const at = treeCursor ?? (source.kind === 'all' ? ALL_ROW : source.kind === 'playlist' ? source.id : null)
const i = rows.findIndex((r) => r.id === at)
const next = rows[Math.max(0, Math.min(rows.length - 1, i < 0 ? 0 : i + ticks))]
if (!next) return
if (!next.node) onSelect({ kind: 'all' })
else if (next.node.kind !== 'folder' && next.node.selectable) {
onSelect({ kind: 'playlist', id: next.node.id, name: next.node.name })
}
setTreeCursor(next.id)
document.querySelector(`[data-node-id="${CSS.escape(next.id)}"]`)?.scrollIntoView({ block: 'nearest' })
},
press: () => {
const node = treeCursor ? findNode(playlists ?? [], treeCursor) : null
if (node?.kind === 'folder') setFolderOpen(node.id, !isOpen(node))
},
},
})
// A folder's id — and so every id under it — may change when it is renamed
// or moved (a platform addressing folders by path), so open state follows
// the subtree to its new ids. Reads the tree as refetched after the edit.
@@ -631,8 +679,9 @@ export function Sidebar({
}
const actions: RowActions = {
isOpen: (node) => openOverrides[node.id] ?? expandByDefault,
isOpen,
setOpen: (node, open) => setFolderOpen(node.id, open),
isCursor: (node) => treeCursor === node.id,
onContextMenu: (e, node) => openMenu(e, nodeItems(node)),
onRename: (node, name, parentId) => rename.mutate({ node, name, parentId }),
onDelete: confirmDelete,
@@ -760,6 +809,7 @@ export function Sidebar({
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
<div className="shrink-0 px-2 pt-3">
<button
data-node-id={ALL_ROW}
onClick={() => onSelect({ kind: 'all' })}
className={`flex w-full items-center gap-2 rounded-[10px] px-2 py-1.5 text-left text-sm transition-colors ${
source.kind === 'all'
+17 -2
View File
@@ -13,6 +13,7 @@ import {
import { useVirtualizer } from '@tanstack/react-virtual'
import { Icon } from '../lib/icons'
import { useCaps } from '../lib/capabilities'
import { useMidiTargets } from '../lib/midi/targets'
import {
DndContext,
PointerSensor,
@@ -542,11 +543,16 @@ export function TrackTable({
}
if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return
e.preventDefault()
moveLead(e.key === 'ArrowDown' ? 1 : -1, e.shiftKey)
}
/** Move the highlight `step` rows (Shift: extend the selection) — ↑/↓, and
* a controller's browse encoder. */
const moveLead = (step: number, extend: boolean) => {
if (!selection || rows.length === 0) return
const lead = indexOf(leadRef.current)
const step = e.key === 'ArrowDown' ? 1 : -1
const next = lead < 0 ? 0 : Math.max(0, Math.min(rows.length - 1, lead + step))
const anchor = indexOf(anchorRef.current)
if (e.shiftKey && anchor >= 0) {
if (extend && anchor >= 0) {
leadRef.current = rows[next].original.id
selection.onChange(new Set(rangeIds(anchor, next)))
} else {
@@ -554,6 +560,15 @@ export function TrackTable({
}
virtualizer.scrollToIndex(next)
}
// A controller's browse encoder moves the highlight as ↑/↓ do, and its load
// buttons take the highlighted row (lib/midi).
useMidiTargets({
browse: selection && onPlay ? (ticks) => moveLead(ticks, false) : null,
lead: () => {
const i = indexOf(leadRef.current)
return i >= 0 && selection?.selected.has(rows[i].original.id) ? rows[i].original : null
},
})
useEffect(() => {
const onKey = (e: KeyboardEvent) => keysRef.current(e)
window.addEventListener('keydown', onKey)
@@ -88,11 +88,15 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
renamingSlot,
renameSlot,
tempoProps,
channel,
} = deck
// On-screen MIDI learning (lib/midi): controls carry their action.
const midi = `deck.${channel}`
const transport = (
<>
<button
onClick={toggle}
data-midi-action={`${midi}.play`}
disabled={!ready}
className={
'flex h-10 w-10 shrink-0 items-center justify-center rounded-full transition-all active:scale-95 disabled:cursor-not-allowed disabled:opacity-40 ' +
@@ -107,6 +111,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
<Icon name={playing ? 'pause' : 'play'} size={16} />
</button>
<button
data-midi-action={`${midi}.cue`}
onPointerDown={(e) => {
e.preventDefault()
e.currentTarget.setPointerCapture(e.pointerId)
@@ -131,6 +136,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
)
const loopControls = (
<LoopControls
midi={midi}
mode={loopMode}
onMode={setLoopMode}
hasGrid={grid != null}
@@ -198,6 +204,7 @@ export function DeckControls({ deck, stacked = false }: { deck: Deck; stacked?:
/>
) : (
<HotcueBar
midi={midi}
cues={cueData?.cues ?? []}
slotCount={slotCount}
slotLabel={slotLabel}
@@ -36,6 +36,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
return (
<div className="flex h-9 shrink-0 items-center gap-2">
<button
data-midi-action={`deck.${deck.channel}.keylock`}
onClick={() => setKeylock(!keylock)}
disabled={!keylockAvailable}
aria-pressed={keylock}
@@ -51,6 +52,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
KEY
</button>
<button
data-midi-action={`deck.${deck.channel}.sync`}
onClick={onSync}
disabled={!track || (!synced && syncBlocked != null)}
aria-pressed={synced}
@@ -79,6 +81,7 @@ export function DeckTempo({ deck, master, synced, syncBlocked, onSync, onMaster,
}}
/>
<Fader
midi={`deck.${deck.channel}.pitch`}
orientation="horizontal"
value={pitch}
min={-1}
@@ -5,6 +5,7 @@ import { Icon } from '../../lib/icons'
export function PerformanceButton({ on, onToggle }: { on: boolean; onToggle: () => void }) {
return (
<button
data-midi-action="app.performance"
onClick={onToggle}
aria-pressed={on}
aria-label="Performance mode"
+90 -1
View File
@@ -48,6 +48,15 @@ import { LOOP_SIZES, type LoopMode } from '../LoopControls'
import type { StemLane } from '../MainWaveform'
import { usePrefsWriter } from '../../lib/prefs'
/** A controller's jog (lib/midi), at sensitivity 1: seconds of track per
* tick — scratch and scrub (vinyl at 33⅓ is 1.8 s a turn, over a typical
* ~500 ticks) — and the nudge's bend per tick in a frame, its limit, and the
* frames without a tick before it springs back. */
const JOG_SEC_PER_TICK = 1.8 / 500
const JOG_NUDGE_PER_TICK = 0.004
const JOG_NUDGE_MAX = 0.1
const JOG_NUDGE_IDLE_FRAMES = 4
export interface DeckOptions {
/** The track loaded into this deck, if any. */
track: Track | null
@@ -634,6 +643,81 @@ export function useDeck({
}
}
// ---- jog (MIDI controllers) ---------------------------------------------
// Touching the top SCRATCHES — the same engine path as dragging the
// waveform, the target sent straight to the worklet. A turn without touch
// NUDGES while playing (a momentary bend, as the phase meter's drag) and
// SCRUBS while paused; `scrub` (Shift + jog) moves fast, playing or not.
// Nudge and scrub are gathered per frame so a jog's flood of messages costs
// one render a frame. How many ticks a turn sends differs per controller,
// so the scale is a starting point times the mapping's sensitivity.
const jogRef = useRef({ touching: false, target: 0, nudge: 0, scrub: 0, raf: 0, idle: 0, bending: false })
const jogLatest = useRef({ seekManual, duration })
jogLatest.current = { seekManual, duration }
const flushJog = () => {
const j = jogRef.current
j.raf = 0
const eng = playbackRef.current
if (!eng) return
const { seekManual: seekTo, duration: dur } = jogLatest.current
if (j.scrub !== 0) {
seekTo(Math.max(0, Math.min(dur, eng.getPosition() + j.scrub)))
j.scrub = 0
}
if (j.nudge !== 0) {
setBend(1 + Math.max(-JOG_NUDGE_MAX, Math.min(JOG_NUDGE_MAX, j.nudge * JOG_NUDGE_PER_TICK)))
j.nudge = 0
j.idle = 0
j.bending = true
} else if (j.bending && ++j.idle >= JOG_NUDGE_IDLE_FRAMES) {
setBend(1)
j.bending = false
}
if (j.bending) j.raf = requestAnimationFrame(flushJog)
}
const scheduleJog = () => {
if (!jogRef.current.raf) jogRef.current.raf = requestAnimationFrame(flushJog)
}
useEffect(() => () => cancelAnimationFrame(jogRef.current.raf), [])
const jogTouch = (on: boolean) => {
const j = jogRef.current
const eng = playbackRef.current
if (on) {
if (!eng || !eng.ready || j.touching) return
j.touching = true
onScratchStart()
j.target = eng.getPosition()
} else if (j.touching) {
j.touching = false
onScratchEnd(j.target)
}
}
/** A jog turn. Returns 'nudge' when it bent a playing deck (SYNC lets go). */
const jogTurn = (ticks: number, sensitivity: number): 'nudge' | null => {
const j = jogRef.current
const eng = playbackRef.current
if (!eng || !eng.ready) return null
if (j.touching && engagedRef.current) {
j.target = Math.max(0, Math.min(duration, j.target + ticks * JOG_SEC_PER_TICK * sensitivity))
eng.scratchTarget(j.target)
return null
}
if (eng.playing) {
j.nudge += ticks * sensitivity
scheduleJog()
return 'nudge'
}
j.scrub += ticks * JOG_SEC_PER_TICK * sensitivity
scheduleJog()
return null
}
const scrub = (ticks: number, sensitivity: number) => {
if (!playbackRef.current?.ready) return
jogRef.current.scrub += ticks * JOG_SEC_PER_TICK * sensitivity
scheduleJog()
}
// ---- loops ------------------------------------------------------------
// Snap a time to the nearest beat when Snap is on (needs a beatgrid).
const snapTime = (t: number) => (snap && grid ? grid.snapToBeat(t) : Math.max(0, t))
@@ -1216,7 +1300,8 @@ export function useDeck({
// A pitch BEND: a momentary push or drag on top of the fader (the phase
// meter's drag), 1 = none. Part of `rate`, so the readout and a follower see it.
const [bend, setBend] = useState(1)
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : 1
// A jog nudge bends the prep deck too (its pitch fader does not apply there).
const rate = tempoActive ? (1 + pitch * pitchRange) * bend : bend
useEffect(() => {
playbackRef.current?.setRate(rate)
}, [rate, ready])
@@ -1376,6 +1461,7 @@ export function useDeck({
}
return {
channel,
caps,
track,
origin,
@@ -1493,6 +1579,9 @@ export function useDeck({
keylock,
setKeylock,
keylockAvailable,
jogTouch,
jogTurn,
scrub,
}
}
+8 -2
View File
@@ -23,6 +23,8 @@ interface KnobProps {
describe: (v: number) => string
color?: string
size?: number
/** Its MIDI action, for on-screen learning (lib/midi). */
midi?: string
}
/** A point on the knob's circle at angle `deg` (0 = straight up). */
@@ -40,6 +42,7 @@ function arc(r: number, from: number, to: number, c: number): string {
}
export function Knob({
midi,
value,
min,
max,
@@ -76,7 +79,7 @@ export function Knob({
onChange(clamp(value - (e.deltaY / (e.shiftKey ? 2000 : 400)) * range, min, max))
}
return (
<div className="flex flex-col items-center gap-0.5" title={describe(value)}>
<div className="flex flex-col items-center gap-0.5" title={describe(value)} data-midi-action={midi}>
<div
role="slider"
aria-label={label}
@@ -125,10 +128,12 @@ interface FaderProps {
label: string
describe: (v: number) => string
className?: string
/** Its MIDI action, for on-screen learning (lib/midi). */
midi?: string
}
/** A fader: grab anywhere on it and the cap follows the pointer. */
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '' }: FaderProps) {
export function Fader({ value, min, max, defaultValue, onChange, orientation, label, describe, className = '', midi }: FaderProps) {
const vertical = orientation === 'vertical'
const t = (clamp(value, min, max) - min) / (max - min)
const set = (e: PointerEvent<HTMLDivElement>) => {
@@ -139,6 +144,7 @@ export function Fader({ value, min, max, defaultValue, onChange, orientation, la
return (
<div
role="slider"
data-midi-action={midi}
aria-label={label}
aria-orientation={orientation}
aria-valuemin={min}
@@ -133,6 +133,7 @@ export function MixerPanel({
<div className="flex h-6 shrink-0 items-center justify-center gap-2 px-1">
<span className="font-mono text-[11px] font-semibold text-muted">A</span>
<Fader
midi="mixer.crossfader"
orientation="horizontal"
value={crossfader}
min={-1}
@@ -187,6 +188,7 @@ function Strip({
}
const eq = (band: 'high' | 'mid' | 'low', label: string, name: string) => (
<Knob
midi={`mixer.${ch}.${band}`}
value={s[band]}
min={-1}
max={1}
@@ -205,6 +207,7 @@ function Strip({
<div className={`flex items-center gap-2 self-center ${mirrored ? 'flex-row-reverse' : ''}`}>
<div className="grid grid-cols-2 gap-x-1.5 gap-y-1.5">
<Knob
midi={`mixer.${ch}.gain`}
value={s.trim}
min={-TRIM_RANGE_DB}
max={TRIM_RANGE_DB}
@@ -230,6 +233,7 @@ function Strip({
</div>
<div className="flex flex-col items-center gap-2" style={{ width: FILTER_KNOB }}>
<button
data-midi-action={`mixer.${ch}.fxNext`}
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect()
setFxMenu({ x: r.left, y: r.bottom + 4 })
@@ -241,6 +245,7 @@ function Strip({
<Icon name="chevronDown" size={9} />
</button>
<Knob
midi={`mixer.${ch}.filter`}
value={s.color}
min={-1}
max={1}
@@ -258,6 +263,7 @@ function Strip({
const fader = (
<div className="flex flex-col items-center gap-0.5">
<Fader
midi={`mixer.${ch}.fader`}
orientation="vertical"
value={s.fader}
min={0}