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

+130 -3
View File
@@ -43,6 +43,38 @@ dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "alsa"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3f93573e7ddb15145d27c58c0fa0a452faad9f5452ac17ed4554ea035ea9b71"
dependencies = [
"alsa-sys",
"bitflags 2.13.0",
"cfg-if",
"libc",
]
[[package]]
name = "alsa-sys"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0320138053ef93099f168102c37b46ac0b9c53affc56ef7696633ad5477e2be"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "android-build"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "android_log-sys"
version = "0.3.2"
@@ -80,6 +112,7 @@ name = "app"
version = "0.1.1"
dependencies = [
"log",
"midir",
"serde",
"serde_json",
"tauri",
@@ -516,6 +549,27 @@ dependencies = [
"libc",
]
[[package]]
name = "coremidi"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a57ede822fdaf19280cf1320a5a5d3a522c75c910d01750af1e8122b6ad2595b"
dependencies = [
"block2",
"core-foundation 0.10.1",
"core-foundation-sys",
"coremidi-sys",
]
[[package]]
name = "coremidi-sys"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a2b8c2cefa9a8f712213c5a1383ffe428efc8f1a1fd1e2f757be94daf7e256a"
dependencies = [
"core-foundation-sys",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -739,6 +793,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "dlopen2"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60768c353d76ba6dd1b6332a5dbbdd3bc2dddadc2935f4cc6a9d0f17ca8ecb6a"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "dlopen2_derive"
version = "0.4.3"
@@ -1706,6 +1770,15 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "java-locator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09c46c1fe465c59b1474e665e85e1256c3893dd00927b8d55f63b09044c1e64f"
dependencies = [
"glob",
]
[[package]]
name = "javascriptcore-rs"
version = "1.1.2"
@@ -1738,7 +1811,9 @@ dependencies = [
"cesu8",
"cfg-if",
"combine",
"java-locator",
"jni-sys 0.3.1",
"libloading",
"log",
"thiserror 1.0.69",
"walkdir",
@@ -1775,6 +1850,21 @@ dependencies = [
"syn 2.0.118",
]
[[package]]
name = "jni-min-helper"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "913370a00ba1851b0f3369b49d0f3e745da2d20d3f15ecc296a64234ccda45f7"
dependencies = [
"android-build",
"dlopen2 0.9.0",
"jni 0.21.1",
"libc",
"log",
"ndk-context",
"process_path",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
@@ -1873,9 +1963,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.186"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libdbus-sys"
@@ -1961,6 +2051,27 @@ dependencies = [
"autocfg",
]
[[package]]
name = "midir"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea58b9250a667b032ff61fb1bf77aed74873152563f5cd613016dce4c821832"
dependencies = [
"alsa",
"cc",
"coremidi",
"jni 0.21.1",
"jni-min-helper",
"js-sys",
"libc",
"log",
"ndk-context",
"parking_lot",
"wasm-bindgen",
"web-sys",
"windows",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -2030,6 +2141,12 @@ dependencies = [
"thiserror 1.0.69",
]
[[package]]
name = "ndk-context"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
[[package]]
name = "ndk-sys"
version = "0.6.0+11769913"
@@ -2602,6 +2719,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "process_path"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f676f11eb0b3e2ea0fbaee218fa6b806689e2297b8c8adc5bf73df465c4f6171"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "ptr_meta"
version = "0.1.4"
@@ -3568,7 +3695,7 @@ dependencies = [
"crossbeam-channel",
"dbus",
"dispatch2",
"dlopen2",
"dlopen2 0.8.2",
"dpi",
"gdkwayland-sys",
"gdkx11-sys",
+2
View File
@@ -31,4 +31,6 @@ tokio = { version = "1", features = ["time"] } # timeout on the port handshake
# One-click update (UpdateDialog.tsx). No `zip` feature: it only unpacks
# v1-style zipped Windows installers (we ship the bare NSIS setup.exe), and
# every zip 4.x it would need is yanked.
# MIDI controller input (src/midi.rs): CoreMIDI on macOS, WinMM on Windows.
midir = "0.11"
tauri-plugin-updater = { version = "2.12", default-features = false, features = ["rustls-tls", "system-proxy"] }
+44
View File
@@ -0,0 +1,44 @@
// MIDI transport spike (macOS): a virtual CoreMIDI source named
// "Konduktor Flood" that sends a jog-like CC stream at a fixed rate, so the
// shell's MIDI path can be measured without hardware.
//
// cargo run --example midi_flood -- <rate Hz> <count> <start delay s>
//
// Each message is CC 33 on channel 1 with a 7-bit counter as its value, so
// the receiver can check for drops and reordering.
#[cfg(target_os = "macos")]
fn main() {
use midir::os::unix::VirtualOutput;
use midir::MidiOutput;
use std::time::{Duration, Instant};
let args: Vec<String> = std::env::args().collect();
let rate: f64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(1000.0);
let count: u32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(5000);
let delay: f64 = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(3.0);
let out = MidiOutput::new("Konduktor Flood").expect("MIDI client");
let mut conn = out.create_virtual("Konduktor Flood").expect("virtual source");
std::thread::sleep(Duration::from_secs_f64(delay));
let start = Instant::now();
let step = Duration::from_secs_f64(1.0 / rate);
for i in 0..count {
let due = start + step * i;
while Instant::now() < due {
let left = due - Instant::now();
if left > Duration::from_micros(300) {
std::thread::sleep(left - Duration::from_micros(200));
}
}
conn.send(&[0xB0, 33, (i % 128) as u8]).expect("send");
}
eprintln!("sent {count} at {rate} Hz in {:.3} s", start.elapsed().as_secs_f64());
std::thread::sleep(Duration::from_secs(1));
}
#[cfg(not(target_os = "macos"))]
fn main() {
eprintln!("midi_flood needs CoreMIDI virtual ports (macOS).");
}
+11 -1
View File
@@ -37,6 +37,12 @@
// runs. Cancel in the Save / Discard prompt keeps the update staged, so the
// next ordinary quit installs it (without relaunching). A failed install is
// written to `failed.json` for the next launch's dialog to report.
//
// MIDI controllers (midi.rs): WKWebView has no Web MIDI, so the shell lists
// and opens the input ports itself and streams their messages to the page
// (`midi_ports` / `midi_open` / `midi_close`); everything else is the page's.
mod midi;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
@@ -459,6 +465,7 @@ pub fn run() {
.manage(Staged(Mutex::new(None)))
.manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) })
.manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) })
.manage(midi::MidiInputs::default())
.invoke_handler(tauri::generate_handler![
backend_status,
backend_restart,
@@ -467,7 +474,10 @@ pub fn run() {
quit_now,
update_download,
update_restart,
update_take_failure
update_take_failure,
midi::midi_ports,
midi::midi_open,
midi::midi_close
])
.on_window_event(|window, event| {
if let WindowEvent::CloseRequested { api, .. } = event {
+124
View File
@@ -0,0 +1,124 @@
// MIDI INPUT for controller mapping (decided 2026-11-03,
// .claude/discussions/discuss-midi-controllers-2026-11-03.md).
//
// WKWebView has no Web MIDI, so the shell reads the ports itself with midir
// (CoreMIDI on macOS, WinMM on Windows) and streams each port's messages to the
// page over a `Channel` — the frontend does all parsing, mapping and learning
// (lib/midi/). Input only: nothing is ever sent to a controller.
//
// Batching without a timer: the driver's callback queues each message on an
// mpsc; one sender thread per port blocks on it, then drains whatever else has
// queued and sends that as ONE batch. Idle, a message goes out the moment it
// arrives; under a jog wheel's flood, messages coalesce instead of queueing up
// one IPC call each. System messages (SysEx, MIDI clock, active sensing) are
// ignored at the driver: a 24-ppqn clock from a mixer would flood the page.
//
// `wall_us` is the wall clock (µs since the Unix epoch) when the driver handed
// the message over, so the page can measure transport latency against its own
// `Date.now()`.
use std::collections::HashMap;
use std::sync::mpsc;
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use midir::{Ignore, MidiInput, MidiInputConnection, MidiInputPort};
use serde::Serialize;
use tauri::ipc::Channel;
use tauri::State;
#[derive(Clone, Serialize)]
pub struct MidiPacket {
pub wall_us: u64,
pub bytes: Vec<u8>,
}
/// Open connections by port name. Dropping one closes the port and ends its
/// sender thread (the callback's mpsc sender goes with it).
#[derive(Default)]
pub struct MidiInputs(Mutex<HashMap<String, MidiInputConnection<()>>>);
fn client() -> Result<MidiInput, String> {
let mut input = MidiInput::new("Konduktor").map_err(|e| e.to_string())?;
input.ignore(Ignore::All);
Ok(input)
}
/// Every input port with a unique name: two identical controllers are
/// "X" and "X #2", in the order the OS lists them.
fn named_ports(input: &MidiInput) -> Vec<(String, MidiInputPort)> {
let mut seen: HashMap<String, usize> = HashMap::new();
input
.ports()
.into_iter()
.filter_map(|p| {
let base = input.port_name(&p).ok()?;
let n = seen.entry(base.clone()).or_insert(0);
*n += 1;
let name = if *n == 1 { base } else { format!("{base} #{n}") };
Some((name, p))
})
.collect()
}
fn now_us() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_micros() as u64).unwrap_or(0)
}
#[tauri::command]
pub fn midi_ports() -> Result<Vec<String>, String> {
Ok(named_ports(&client()?).into_iter().map(|(name, _)| name).collect())
}
/// Open `port` and stream its messages to `on_message`. Opening a port that is
/// already open replaces the old connection (a page reload re-opens).
#[tauri::command]
pub fn midi_open(
inputs: State<'_, MidiInputs>,
port: String,
on_message: Channel<Vec<MidiPacket>>,
) -> Result<(), String> {
let input = client()?;
let found = named_ports(&input)
.into_iter()
.find(|(name, _)| *name == port)
.map(|(_, p)| p)
.ok_or_else(|| format!("MIDI port not found: {port}"))?;
let (tx, rx) = mpsc::channel::<MidiPacket>();
std::thread::Builder::new()
.name(format!("midi:{port}"))
.spawn(move || {
while let Ok(first) = rx.recv() {
let mut batch = vec![first];
while let Ok(more) = rx.try_recv() {
batch.push(more);
}
if on_message.send(batch).is_err() {
break; // the page went away
}
}
})
.map_err(|e| e.to_string())?;
let conn = input
.connect(
&found,
"Konduktor input",
move |_stamp, bytes, _| {
let _ = tx.send(MidiPacket { wall_us: now_us(), bytes: bytes.to_vec() });
},
(),
)
.map_err(|e| e.to_string())?;
inputs.0.lock().unwrap().insert(port, conn);
Ok(())
}
#[tauri::command]
pub fn midi_close(inputs: State<'_, MidiInputs>, port: String) {
if let Some(conn) = inputs.0.lock().unwrap().remove(&port) {
conn.close();
}
}
+12
View File
@@ -41,6 +41,8 @@ import { StemReportDialog } from './components/StemReportDialog'
import { SetPositionDialog } from './components/SetPositionDialog'
import { Icon } from './lib/icons'
import { usePrefsWriter } from './lib/prefs'
import { useMidi } from './lib/midi/useMidi'
import { midiTargets, useMidiTargets } from './lib/midi/targets'
function applyFilters(tracks: Track[], f: Filters): Track[] {
const q = f.search.trim().toLowerCase()
@@ -261,6 +263,16 @@ export default function App() {
}, [])
const onError = useCallback((msg: string) => notify('error', msg), [notify])
// MIDI controllers (lib/midi): found as they are plugged in; a controller's
// load buttons take the track list's highlighted row, loaded paused.
useMidi(notify)
useMidiTargets({
load: (deck) => {
const t = midiTargets.lead?.()
if (t) loadTrack(t, undefined, deck)
},
})
// Inline single-field edit from a double-clicked table cell. Only offered when
// the library can take an edit: passing `undefined` makes those cells inert
// rather than firing a request the adapter will refuse. Defaults to false, so
+6 -2
View File
@@ -1140,8 +1140,12 @@ export const api = {
// shortcuts and the browsable files are only meaningful inside that answer.
collectionOptions: (platform?: string) =>
getJSON<CollectionOptions>(`/api/library/options${qs({ platform })}`),
listDir: (path?: string, platform?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform })}`),
listDir: (path?: string, platform?: string, suffix?: string) =>
getJSON<FsListing>(`/api/fs/list${qs({ path, platform, suffix })}`),
/** A MIDI controller mapping to / from a file (lib/midi/mapping.ts). */
midiExport: (dir: string, name: string, mapping: unknown) =>
send<{ path: string }>('POST', '/api/midi/export', { dir, name, mapping }),
midiImport: (path: string) => getJSON<{ mapping: unknown }>(`/api/midi/import${qs({ path })}`),
/** Folders on the machine that HOLDS the library (a remote's server),
* confined to its content folder — `home` is that folder. */
libraryListDir: (path?: string) => getJSON<FsListing>(`/api/library/fs/list${qs({ path })}`),
+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}
+28
View File
@@ -324,3 +324,31 @@ option {
@media (prefers-reduced-motion: reduce) {
.ambient-wash { animation: none !important; }
}
/* ---- On-screen MIDI learning (MidiLearnOverlay.tsx) --------------------- */
/* Outlines, not borders or shadows: they sit outside the control and change
no layout, and the controls' own shadows (lit buttons) stay as they are. */
body.midi-learn [data-midi-action] {
outline: 1px dashed color-mix(in oklab, var(--color-accent) 70%, transparent);
outline-offset: 2px;
cursor: crosshair;
}
body.midi-learn [data-midi-action][data-midi-mapped] {
outline-style: solid;
}
body.midi-learn [data-midi-action][data-midi-armed] {
outline: 2px solid var(--color-accent);
outline-offset: 3px;
animation: midi-armed 0.9s ease-in-out infinite alternate;
}
body.midi-learn [data-midi-action][data-midi-learned] {
outline: 2px solid var(--color-mint);
outline-offset: 3px;
}
@keyframes midi-armed {
from { outline-color: var(--color-accent); }
to { outline-color: color-mix(in oklab, var(--color-accent) 30%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
body.midi-learn [data-midi-action][data-midi-armed] { animation: none; }
}
+128
View File
@@ -0,0 +1,128 @@
// Everything a controller can be mapped to. Buttons do what the deck keys do
// (lib/deckKeys.ts), so a key and a pad mean the same thing; the rest are the
// controls a keyboard has no equivalent for — pitch, jog, the mixer, browsing.
//
// Kinds: `button` acts on press; `hold` also on release (CUE and hotcue
// previews, jog touch); `continuous` takes a position (or relative ticks from
// an endless knob); `jog` takes ticks.
export type DeckId = 'A' | 'B'
export type ActionKind = 'button' | 'hold' | 'continuous' | 'jog'
export type ActionGroup = 'Deck A' | 'Deck B' | 'Mixer' | 'Library' | 'App'
export interface ActionDef {
id: string
label: string
group: ActionGroup
kind: ActionKind
}
/** Hotcue pads offered per deck (a platform's bank may be smaller: the deck ignores the rest). */
export const HOTCUE_ACTIONS = 8
export const STEM_ACTIONS = 4
function deckActions(d: DeckId): ActionDef[] {
const group: ActionGroup = `Deck ${d}`
const a = (id: string, label: string, kind: ActionKind = 'button'): ActionDef => ({
id: `deck.${d}.${id}`,
label,
group,
kind,
})
const range = (n: number) => Array.from({ length: n }, (_, i) => i + 1)
return [
a('play', 'Play / pause'),
a('cue', 'CUE', 'hold'),
a('sync', 'SYNC'),
a('keylock', 'Keylock'),
a('pitch', 'Pitch fader', 'continuous'),
a('jog', 'Jog wheel', 'jog'),
a('jogTouch', 'Jog touch (scratch)', 'hold'),
a('scrub', 'Fast scrub', 'jog'),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcue.${n}`, `Hotcue ${n}`, 'hold')),
...range(HOTCUE_ACTIONS).map((n) => a(`hotcueErase.${n}`, `Erase hotcue ${n}`)),
a('jumpBack', 'Beat jump / move loop back'),
a('jumpFwd', 'Beat jump / move loop forward'),
a('markerPrev', 'Previous grid marker'),
a('markerNext', 'Next grid marker'),
a('sizeDown', 'Loop / jump size −'),
a('sizeUp', 'Loop / jump size +'),
a('sizeLoop', 'Loop (at size)'),
a('loopIn', 'Loop in'),
a('loopOut', 'Loop out'),
a('loopToggle', 'Loop on / off'),
...range(STEM_ACTIONS).map((n) => a(`stem.${n}`, `Mute stem ${n}`)),
...range(STEM_ACTIONS).map((n) => a(`stemSolo.${n}`, `Solo stem ${n}`)),
a('load', 'Load selected track'),
]
}
function channelActions(c: DeckId): ActionDef[] {
const a = (id: string, label: string, kind: ActionKind = 'continuous'): ActionDef => ({
id: `mixer.${c}.${id}`,
label: `${c}: ${label}`,
group: 'Mixer',
kind,
})
return [
a('gain', 'Gain'),
a('high', 'EQ high'),
a('mid', 'EQ mid'),
a('low', 'EQ low'),
a('filter', 'Filter'),
a('fxNext', 'Next effect', 'button'),
a('fxPrev', 'Previous effect', 'button'),
a('fader', 'Channel fader'),
]
}
export const ACTIONS: ActionDef[] = [
...deckActions('A'),
...deckActions('B'),
...channelActions('A'),
...channelActions('B'),
{ id: 'mixer.crossfader', label: 'Crossfader', group: 'Mixer', kind: 'continuous' },
{ id: 'library.browse', label: 'Browse tracks', group: 'Library', kind: 'jog' },
{ id: 'library.browsePress', label: 'Load to focused deck', group: 'Library', kind: 'button' },
{ id: 'library.tree', label: 'Browse playlists', group: 'Library', kind: 'jog' },
{ id: 'library.treePress', label: 'Open / close folder', group: 'Library', kind: 'button' },
{ id: 'app.performance', label: 'Performance mode on / off', group: 'App', kind: 'button' },
]
export const ACTION_GROUPS: ActionGroup[] = ['Deck A', 'Deck B', 'Mixer', 'Library', 'App']
const BY_ID = new Map(ACTIONS.map((a) => [a.id, a]))
export const actionDef = (id: string): ActionDef | undefined => BY_ID.get(id)
/**
* What a control does under Shift when nothing else is chosen: the keyboard's
* Shift meaning (hotcue -> erase it, stem -> solo it, beat jump -> step
* markers), plus Shift+jog = fast scrub and Shift+browse = the playlist tree
* (decided 2026-11-03). Filled in when the control is learned; overridable.
*/
export function shiftDefault(id: string): string | null {
const m = id.match(/^deck\.([AB])\.(.+)$/)
if (m) {
const [, d, rest] = m
const swap: Record<string, string> = { jumpBack: 'markerPrev', jumpFwd: 'markerNext', jog: 'scrub' }
if (swap[rest]) return `deck.${d}.${swap[rest]}`
const n = rest.match(/^(hotcue|stem)\.(\d+)$/)
if (n) return `deck.${d}.${n[1] === 'hotcue' ? 'hotcueErase' : 'stemSolo'}.${n[2]}`
return null
}
if (id === 'library.browse') return 'library.tree'
if (id === 'library.browsePress') return 'library.treePress'
return null
}
/** The deck an action belongs to, if any (mixer channels count as their deck). */
export function actionDeck(id: string): DeckId | null {
const m = id.match(/^(?:deck|mixer)\.([AB])\./)
return m ? (m[1] as DeckId) : null
}
/** Acts only in performance mode: deck B and the whole mixer (prep mode has
* one deck and plays past the mixer). */
export function performanceOnly(id: string): boolean {
return id.startsWith('mixer.') || actionDeck(id) === 'B'
}
+103
View File
@@ -0,0 +1,103 @@
import { describe, expect, it } from 'vitest'
import { absValue, Decoder, detectEncoding, relativeTicks, wrapDelta } from './encoding'
import { describeSource, parseMessage, parseSource, sourceKey, type MidiMessage } from './messages'
const cc = (number: number, value: number, channel = 1): MidiMessage => ({ kind: 'cc', channel, number, value })
const note = (number: number, value: number, channel = 1): MidiMessage => ({ kind: 'note', channel, number, value })
describe('messages', () => {
it('parses notes, CCs and pitch bend, and ignores the rest', () => {
expect(parseMessage([0x91, 11, 127])).toEqual({ kind: 'note', channel: 2, number: 11, value: 127 })
expect(parseMessage([0x81, 11, 64])).toEqual({ kind: 'note', channel: 2, number: 11, value: 0 })
expect(parseMessage([0x90, 11, 0])?.value).toBe(0)
expect(parseMessage([0xb0, 33, 65])).toEqual({ kind: 'cc', channel: 1, number: 33, value: 65 })
expect(parseMessage([0xe3, 0x7f, 0x7f])).toEqual({ kind: 'pb', channel: 4, number: 0, value: 16383 })
expect(parseMessage([0xc0, 5])).toBeNull()
expect(parseMessage([0xf8])).toBeNull()
})
it('names sources and reads them back', () => {
expect(sourceKey(cc(33, 1, 2))).toBe('cc:2:33')
expect(sourceKey({ kind: 'pb', channel: 1, number: 0 })).toBe('pb:1')
expect(parseSource('note:16:127')).toEqual({ kind: 'note', channel: 16, number: 127 })
expect(parseSource('cc:17:1')).toBeNull()
expect(describeSource('cc:2:33')).toBe('CC 33 · Ch 2')
})
})
describe('decoding', () => {
it('reads the three relative schemes', () => {
expect([1, 3, 127, 125].map((v) => relativeTicks('relTwos', v))).toEqual([1, 3, -1, -3])
expect([65, 67, 63, 61].map((v) => relativeTicks('rel64', v))).toEqual([1, 3, -1, -3])
expect([1, 3, 65, 67].map((v) => relativeTicks('relSignMag', v))).toEqual([1, 3, -1, -3])
})
it('maps a knob centre to exactly 0 and its ends to ±1', () => {
expect(absValue(64, 127).bipolar).toBe(0)
expect(absValue(0, 127).bipolar).toBe(-1)
expect(absValue(127, 127).bipolar).toBe(1)
expect(absValue(8192, 16383).bipolar).toBe(0)
expect(absValue(127, 127).unit).toBe(1)
})
it('steps the short way round a wheel', () => {
expect(wrapDelta(120, 3, 128)).toBe(11)
expect(wrapDelta(3, 120, 128)).toBe(-11)
expect(wrapDelta(16380, 4, 16384)).toBe(8)
})
it('turns an absolute jog position into ticks across the wrap, both ways', () => {
const d = new Decoder('jogAbs7')
expect(d.feed(cc(16, 125))).toBeNull() // the first position only sets where we are
expect(d.feed(cc(16, 127))).toEqual({ type: 'delta', ticks: 2 })
expect(d.feed(cc(16, 2))).toEqual({ type: 'delta', ticks: 3 })
expect(d.feed(cc(16, 126))).toEqual({ type: 'delta', ticks: -4 })
})
it('combines a 14-bit MSB/LSB pair, and pitch bend', () => {
const d = new Decoder('abs14')
d.feed(cc(0, 64))
const v = d.feed(cc(32, 0), true)
expect(v).toEqual({ type: 'abs', unit: 8192 / 16383, bipolar: 0 })
const j = new Decoder('jogAbs14')
expect(j.feed({ kind: 'pb', channel: 1, number: 0, value: 16380 })).toBeNull()
expect(j.feed({ kind: 'pb', channel: 1, number: 0, value: 5 })).toEqual({ type: 'delta', ticks: 9 })
})
it('inverts positions and ticks', () => {
expect(new Decoder('abs7', true).feed(cc(1, 0))).toEqual({ type: 'abs', unit: 1, bipolar: 1 })
expect(new Decoder('rel64', true).feed(cc(1, 66))).toEqual({ type: 'delta', ticks: -2 })
})
it('treats any value above 0 as a press', () => {
const b = new Decoder('button')
expect(b.feed(note(1, 1))).toEqual({ type: 'press', down: true })
expect(b.feed(cc(1, 0))).toEqual({ type: 'press', down: false })
})
})
describe('detecting an encoding while learning', () => {
const seq = (vals: number[], n = 20) => vals.map((v) => cc(n, v))
it('a fader swept up and back is absolute', () => {
expect(detectEncoding(seq([10, 14, 19, 25, 33, 40, 48, 41, 30, 22, 15, 9]), 'continuous')).toBe('abs7')
})
it('a knob moved a little near its centre, changing every message, is absolute', () => {
expect(detectEncoding(seq([60, 61, 62, 63, 64, 65, 66, 67, 68, 67, 66, 65]), 'continuous')).toBe('abs7')
})
it('a jog reporting its position (wrapping) is an absolute jog', () => {
expect(detectEncoding(seq([100, 108, 116, 124, 4, 12, 20, 28, 36, 44, 52, 60]), 'jog')).toBe('jogAbs7')
})
it('centred-on-64 relative, both ways and one way', () => {
expect(detectEncoding(seq([65, 65, 66, 65, 63, 62, 63, 63]), 'jog')).toBe('rel64')
expect(detectEncoding(seq([65, 65, 65, 66, 65]), 'jog')).toBe('rel64')
})
it('a fast centred jog jittering with speed is still relative', () => {
expect(detectEncoding(seq([66, 70, 68, 73, 69, 72, 67, 71, 75, 70, 66, 69]), 'jog')).toBe('rel64')
})
it("two's complement and sign-magnitude", () => {
expect(detectEncoding(seq([1, 1, 2, 1, 127, 127, 126]), 'jog')).toBe('relTwos')
expect(detectEncoding(seq([1, 1, 2, 1, 65, 65, 66]), 'jog')).toBe('relSignMag')
})
it('a 14-bit pair, whichever half came first', () => {
const pair = [cc(39, 3), cc(7, 40), cc(39, 90), cc(7, 41), cc(39, 12), cc(7, 42)]
expect(detectEncoding([cc(7, 40), ...pair], 'continuous')).toBe('abs14')
expect(detectEncoding([{ kind: 'pb', channel: 1, number: 0, value: 9000 }], 'continuous')).toBe('abs14')
expect(detectEncoding([{ kind: 'pb', channel: 1, number: 0, value: 9000 }], 'jog')).toBe('jogAbs14')
})
it('a button is a button', () => {
expect(detectEncoding([note(1, 127)], 'button')).toBe('button')
})
})
+175
View File
@@ -0,0 +1,175 @@
// How a control encodes what it does, and turning its raw values into
// something an action can use: a press, a position, or a number of ticks.
//
// Controllers disagree on everything here, so a binding stores its encoding
// (detected while learning — `detectEncoding` — and overridable in the editor):
// button a note or CC: any value > 0 = down, 0 = up
// abs7 a knob / fader, 0-127
// abs14 a 14-bit knob / fader: CC n (MSB) + CC n+32 (LSB), or pitch bend
// relTwos relative, two's complement: 1.. = +1.., 127.. = -1..
// rel64 relative, centred on 64: 65.. = +1.., 63.. = -1..
// relSignMag relative, sign + magnitude: 1.. = +1.., 65.. = -1..
// jogAbs7 a jog reporting its ABSOLUTE position, 7 bits, wrapping
// jogAbs14 the same at 14 bits (MSB/LSB pair, or pitch bend)
import type { MidiMessage } from './messages'
export const ENCODINGS = ['button', 'abs7', 'abs14', 'relTwos', 'rel64', 'relSignMag', 'jogAbs7', 'jogAbs14'] as const
export type Encoding = (typeof ENCODINGS)[number]
export const ENCODING_LABELS: Record<Encoding, string> = {
button: 'Button',
abs7: 'Absolute',
abs14: 'Absolute 14-bit',
relTwos: 'Relative (01 / 7F)',
rel64: 'Relative (41 / 3F)',
relSignMag: 'Relative (01 / 41)',
jogAbs7: 'Jog position',
jogAbs14: 'Jog position 14-bit',
}
/** Whether a 14-bit encoding pairs this CC with CC number + 32. */
export const isFourteenBit = (e: Encoding) => e === 'abs14' || e === 'jogAbs14'
/** What one message means once decoded. */
export type Decoded =
| { type: 'press'; down: boolean }
/** `unit` 0..1; `bipolar` -1..1 with the control's centre detent exactly 0. */
| { type: 'abs'; unit: number; bipolar: number }
| { type: 'delta'; ticks: number }
/** Two's-complement / centred / sign-magnitude value -> signed ticks. */
export function relativeTicks(encoding: Encoding, v: number): number {
switch (encoding) {
case 'relTwos':
return v < 64 ? v : v - 128
case 'rel64':
return v - 64
case 'relSignMag':
return v < 64 ? v : -(v - 64)
default:
return 0
}
}
/** The shortest signed step from position `prev` to `next` on a wheel of
* `size` positions: 120 -> 3 on a 7-bit jog is +11, not -117. */
export function wrapDelta(prev: number, next: number, size: number): number {
let d = (next - prev) % size
if (d > size / 2) d -= size
if (d < -size / 2) d += size
return d
}
/** A position on 0..max -> unit and bipolar, the centre value (max+1)/2
* mapping to exactly 0 (64 of 0-127: a knob's detent reads flat). */
export function absValue(raw: number, max: number): { unit: number; bipolar: number } {
const c = (max + 1) / 2
return { unit: raw / max, bipolar: raw < c ? (raw - c) / c : (raw - c) / (max - c) }
}
/**
* Decodes one control's messages. Keeps the state an encoding needs between
* them: the other half of a 14-bit pair, and an absolute jog's last position.
* One per bound source (the router keys them by port + source).
*/
export class Decoder {
private msb = 0
private lsb = 0
private lastPos: number | null = null
readonly encoding: Encoding
readonly invert: boolean
constructor(encoding: Encoding, invert = false) {
this.encoding = encoding
this.invert = invert
}
/** `isLsb`: the message is the CC n+32 half of a 14-bit pair. */
feed(m: MidiMessage, isLsb = false): Decoded | null {
const e = this.encoding
const flip = this.invert ? -1 : 1
if (e === 'button') return { type: 'press', down: m.value > 0 }
if (e === 'abs7') {
const v = absValue(m.value, 127)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
if (e === 'abs14' || e === 'jogAbs14') {
let pos: number
if (m.kind === 'pb') pos = m.value
else {
if (isLsb) this.lsb = m.value
else this.msb = m.value
pos = (this.msb << 7) | this.lsb
}
if (e === 'abs14') {
const v = absValue(pos, 16383)
return this.invert ? { unit: 1 - v.unit, bipolar: -v.bipolar, type: 'abs' } : { type: 'abs', ...v }
}
return this.jog(pos, 16384, flip)
}
if (e === 'jogAbs7') return this.jog(m.value, 128, flip)
const ticks = relativeTicks(e, m.value) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
private jog(pos: number, size: number, flip: number): Decoded | null {
const prev = this.lastPos
this.lastPos = pos
if (prev == null) return null // the first position only sets where we are
const ticks = wrapDelta(prev, pos, size) * flip
return ticks === 0 ? null : { type: 'delta', ticks }
}
}
/** What the action being learned expects, which narrows the guess. */
export type LearnKind = 'button' | 'continuous' | 'jog'
/**
* Guess a control's encoding from the messages it sent while being learned
* (the user was asked to move it both ways). The tells:
* - Pitch bend, or CC n with CC n+32 interleaved, is 14-bit.
* - A relative control REPEATS values (65 65 65 while turning steadily) and
* stays in its zones (near 0 / 127, or near 64); an absolute one changes on
* every message and wanders across its range.
* - Which relative scheme: 63s mean centred on 64; 127s mean two's
* complement; 1s with 65s mean sign-magnitude; one direction only is
* ambiguous between schemes and falls back to the common one.
* Wrong guesses are rare and fixable in the editor.
*/
export function detectEncoding(samples: MidiMessage[], kind: LearnKind): Encoding {
if (kind === 'button' || samples.length === 0) return 'button'
const absolute = kind === 'jog' ? 'jogAbs' : 'abs'
const first = samples[0]
if (first.kind === 'pb') return `${absolute}14` as Encoding
if (first.kind === 'cc' && first.number < 32 && samples.some((m) => m.kind === 'cc' && m.number === first.number + 32)) {
return `${absolute}14` as Encoding
}
const vals = samples.filter((m) => m.kind === first.kind && m.number === first.number).map((m) => m.value)
let repeats = 0
for (let i = 1; i < vals.length; i++) if (vals[i] === vals[i - 1]) repeats++
const inZones = vals.every((v) => v <= 16 || v >= 112 || (v >= 48 && v <= 80))
const distinct = new Set(vals).size
// An absolute control moved both ways turns back once or twice; a relative
// one at varying speed jitters up and down all the time.
let reversals = 0
let lastSign = 0
for (let i = 1; i < vals.length; i++) {
const d = Math.sign(wrapDelta(vals[i - 1], vals[i], 128))
if (d === 0) continue
if (lastSign !== 0 && d !== lastSign) reversals++
lastSign = d
}
const relative = repeats >= 2 || (inZones && (distinct <= 6 || reversals > 2))
if (!relative) return `${absolute}7` as Encoding
const has = (lo: number, hi: number) => vals.some((v) => v >= lo && v <= hi)
if (has(48, 63)) return 'rel64'
if (has(112, 127)) return 'relTwos'
if (has(1, 16) && has(65, 80)) return 'relSignMag'
if (has(65, 80)) return 'rel64'
return 'relTwos'
}
+73
View File
@@ -0,0 +1,73 @@
import { describe, expect, it } from 'vitest'
import { ACTIONS, shiftDefault } from './actions'
import { bind, bindShift, emptyMapping, resolveBinding, sanitizeMapping, sourcesFor, unbind } from './mapping'
describe('actions', () => {
it('have unique ids', () => {
expect(new Set(ACTIONS.map((a) => a.id)).size).toBe(ACTIONS.length)
})
it("default Shift layer = the keyboard's Shift meaning", () => {
expect(shiftDefault('deck.A.hotcue.3')).toBe('deck.A.hotcueErase.3')
expect(shiftDefault('deck.B.stem.2')).toBe('deck.B.stemSolo.2')
expect(shiftDefault('deck.A.jumpFwd')).toBe('deck.A.markerNext')
expect(shiftDefault('deck.B.jog')).toBe('deck.B.scrub')
expect(shiftDefault('library.browse')).toBe('library.tree')
expect(shiftDefault('deck.A.play')).toBeNull()
for (const a of ACTIONS) {
const d = shiftDefault(a.id)
if (d) expect(ACTIONS.some((x) => x.id === d)).toBe(true)
}
})
})
describe('mapping', () => {
it('learning fills the Shift layer with the default, and replaces the old control', () => {
let m = bind(emptyMapping(), 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1')
expect(m.bindings['note:1:0']).toEqual({ encoding: 'button', normal: 'deck.A.hotcue.1', shift: 'deck.A.hotcueErase.1' })
m = bind(m, 'note:1:8', 'button', 'normal', 'deck.A.hotcue.1')
expect(sourcesFor(m, 'deck.A.hotcue.1', 'normal')).toEqual(['note:1:8'])
// The old pad keeps its Shift action, and the new one does not duplicate it.
expect(m.bindings['note:1:0']).toEqual({ encoding: 'button', shift: 'deck.A.hotcueErase.1' })
expect(m.bindings['note:1:8'].shift).toBeUndefined()
})
it('a free Shift layer: any action under Shift', () => {
let m = bind(emptyMapping(), 'note:1:11', 'button', 'normal', 'deck.A.play')
m = bind(m, 'note:1:11', 'button', 'shift', 'deck.A.sync')
expect(m.bindings['note:1:11']).toEqual({ encoding: 'button', normal: 'deck.A.play', shift: 'deck.A.sync' })
m = unbind(m, 'deck.A.play', 'normal')
expect(m.bindings['note:1:11']).toEqual({ encoding: 'button', shift: 'deck.A.sync' })
m = unbind(m, 'deck.A.sync', 'shift')
expect(m.bindings['note:1:11']).toBeUndefined()
})
it('the Shift control does nothing else', () => {
let m = bind(emptyMapping(), 'note:1:63', 'button', 'normal', 'deck.A.play')
m = bindShift(m, 'note:1:63')
expect(m.shift).toBe('note:1:63')
expect(m.bindings['note:1:63']).toBeUndefined()
m = bind(m, 'note:1:63', 'button', 'normal', 'deck.A.cue')
expect(m.shift).toBeNull()
})
it('the LSB half of a 14-bit pair reaches its MSB', () => {
const m = bind(emptyMapping(), 'cc:1:0', 'abs14', 'normal', 'deck.A.pitch')
expect(resolveBinding(m, 'cc:1:32')).toMatchObject({ key: 'cc:1:0', isLsb: true })
const seven = bind(emptyMapping(), 'cc:1:0', 'abs7', 'normal', 'deck.A.pitch')
expect(resolveBinding(seven, 'cc:1:32')).toBeNull()
})
it('sanitises what prefs or a file hold', () => {
const m = sanitizeMapping({
version: 1,
shift: 'note:1:63',
jogSensitivity: 99,
bindings: {
'note:1:0': { encoding: 'button', normal: 'deck.A.play' },
'note:1:1': { encoding: 'bogus', normal: 'deck.A.play' },
'note:1:2': { encoding: 'button', normal: 'no.such.action' },
'nonsense': { encoding: 'button', normal: 'deck.A.play' },
},
})
expect(m?.shift).toBe('note:1:63')
expect(m?.jogSensitivity).toBe(10)
expect(Object.keys(m!.bindings)).toEqual(['note:1:0'])
expect(sanitizeMapping({ version: 2 })).toBeNull()
})
})
+143
View File
@@ -0,0 +1,143 @@
// A controller's mapping: which physical control does what, in the normal
// and the Shift layer. Keyed by SOURCE (the control), so two buttons may share
// an action; the editor looks the other way, action -> sources. One mapping
// per controller, keyed by its port name, kept in userprefs (`midiMappings`)
// and exported / imported as a file.
import { actionDef, shiftDefault } from './actions'
import { ENCODINGS, isFourteenBit, type Encoding } from './encoding'
import { parseSource, type SourceKey } from './messages'
export type Layer = 'normal' | 'shift'
export interface Binding {
encoding: Encoding
invert?: boolean
normal?: string
shift?: string
}
export interface Mapping {
version: 1
/** The control acting as Shift (itself a learned control). */
shift: SourceKey | null
bindings: Record<SourceKey, Binding>
/** Jog: scratch / nudge / scrub sensitivity (1 = the default feel). */
jogSensitivity: number
/** Fast scrub (Shift + jog) relative to an ordinary scrub. */
scrubSpeed: number
}
export type Mappings = Record<string, Mapping>
export const DEFAULT_JOG_SENSITIVITY = 1
export const DEFAULT_SCRUB_SPEED = 8
export function emptyMapping(): Mapping {
return { version: 1, shift: null, bindings: {}, jogSensitivity: DEFAULT_JOG_SENSITIVITY, scrubSpeed: DEFAULT_SCRUB_SPEED }
}
const num = (v: unknown, lo: number, hi: number, fallback: number) =>
typeof v === 'number' && isFinite(v) ? Math.min(hi, Math.max(lo, v)) : fallback
/** A mapping from prefs or a file, keeping only what is valid. */
export function sanitizeMapping(raw: unknown): Mapping | null {
if (!raw || typeof raw !== 'object') return null
const r = raw as Record<string, unknown>
if (r.version !== 1) return null
const out = emptyMapping()
if (typeof r.shift === 'string' && parseSource(r.shift)) out.shift = r.shift
out.jogSensitivity = num(r.jogSensitivity, 0.1, 10, DEFAULT_JOG_SENSITIVITY)
out.scrubSpeed = num(r.scrubSpeed, 1, 64, DEFAULT_SCRUB_SPEED)
const bindings = r.bindings && typeof r.bindings === 'object' ? (r.bindings as Record<string, unknown>) : {}
for (const [key, b] of Object.entries(bindings)) {
if (!parseSource(key) || !b || typeof b !== 'object') continue
const x = b as Record<string, unknown>
if (!ENCODINGS.includes(x.encoding as Encoding)) continue
const binding: Binding = { encoding: x.encoding as Encoding }
if (x.invert === true) binding.invert = true
if (typeof x.normal === 'string' && actionDef(x.normal)) binding.normal = x.normal
if (typeof x.shift === 'string' && actionDef(x.shift)) binding.shift = x.shift
if (binding.normal || binding.shift) out.bindings[key] = binding
}
return out
}
export function sanitizeMappings(raw: unknown): Mappings {
const out: Mappings = {}
if (!raw || typeof raw !== 'object') return out
for (const [port, m] of Object.entries(raw as Record<string, unknown>)) {
const clean = sanitizeMapping(m)
if (clean) out[port] = clean
}
return out
}
/** The sources bound to `action` in `layer`. */
export function sourcesFor(m: Mapping, action: string, layer: Layer): SourceKey[] {
return Object.entries(m.bindings)
.filter(([, b]) => b[layer] === action)
.map(([k]) => k)
}
/** Drop `action` from `layer` everywhere (and bindings left empty). */
export function unbind(m: Mapping, action: string, layer: Layer): Mapping {
const bindings: Record<SourceKey, Binding> = {}
for (const [k, b] of Object.entries(m.bindings)) {
const next = b[layer] === action ? { ...b, [layer]: undefined } : b
if (next.normal || next.shift) bindings[k] = next
}
return { ...m, bindings }
}
/**
* Learn: `source` now does `action` in `layer`. It REPLACES the action's
* previous control in that layer (learning means "this is the control for
* X"). Learning a control's normal action fills its Shift layer with the
* keyboard's Shift meaning when the Shift layer is empty. A control that was
* Shift stops being Shift.
*/
export function bind(m: Mapping, source: SourceKey, encoding: Encoding, layer: Layer, action: string): Mapping {
const cleared = unbind(m, action, layer)
const prev = cleared.bindings[source]
// A new encoding (another kind of control) leaves the other layer's action
// only if it still makes sense: same kind of encoding.
const sameKind = prev && (prev.encoding === 'button') === (encoding === 'button')
const next: Binding = { encoding, invert: prev?.invert, normal: sameKind ? prev?.normal : undefined, shift: sameKind ? prev?.shift : undefined }
next[layer] = action
if (layer === 'normal' && !next.shift) {
const d = shiftDefault(action)
if (d && sourcesFor(cleared, d, 'shift').length === 0) next.shift = d
}
if (!next.invert) delete next.invert
return { ...cleared, shift: cleared.shift === source ? null : cleared.shift, bindings: { ...cleared.bindings, [source]: next } }
}
/** Make `source` the Shift control (it then does nothing else). */
export function bindShift(m: Mapping, source: SourceKey): Mapping {
const bindings = { ...m.bindings }
delete bindings[source]
return { ...m, shift: source, bindings }
}
export function setBinding(m: Mapping, source: SourceKey, patch: Partial<Binding>): Mapping {
const b = m.bindings[source]
if (!b) return m
return { ...m, bindings: { ...m.bindings, [source]: { ...b, ...patch } } }
}
/**
* The binding a message's source reaches: its own, or — for the LSB half of
* a 14-bit pair (CC n+32) — its MSB's. `isLsb` says which half it is.
*/
export function resolveBinding(m: Mapping, source: SourceKey): { key: SourceKey; binding: Binding; isLsb: boolean } | null {
const own = m.bindings[source]
if (own) return { key: source, binding: own, isLsb: false }
const s = parseSource(source)
if (s?.kind === 'cc' && s.number >= 32 && s.number < 64) {
const key = `cc:${s.channel}:${s.number - 32}`
const msb = m.bindings[key]
if (msb && isFourteenBit(msb.encoding)) return { key, binding: msb, isLsb: true }
}
return null
}
+61
View File
@@ -0,0 +1,61 @@
// MIDI messages as the mapping layer sees them: notes, control changes and
// pitch bend, each from a SOURCE — what one physical control sends on.
// Everything else a controller may send (aftertouch, program change) is
// ignored; system messages never leave the shell (src-tauri/src/midi.rs).
export type MidiKind = 'note' | 'cc' | 'pb'
export interface MidiMessage {
kind: MidiKind
/** 1-16, as controllers' manuals number them. */
channel: number
/** Note or controller number; 0 for pitch bend. */
number: number
/** 0-127; pitch bend 0-16383. A note-off (or note-on at velocity 0) is 0. */
value: number
}
/** One physical control: `note:1:11`, `cc:2:33`, `pb:1`. */
export type SourceKey = string
export function parseMessage(bytes: ArrayLike<number>): MidiMessage | null {
if (bytes.length < 2) return null
const type = bytes[0] & 0xf0
const channel = (bytes[0] & 0x0f) + 1
const d1 = bytes[1] & 0x7f
const d2 = bytes.length > 2 ? bytes[2] & 0x7f : 0
switch (type) {
case 0x80:
return { kind: 'note', channel, number: d1, value: 0 }
case 0x90:
return { kind: 'note', channel, number: d1, value: d2 }
case 0xb0:
return { kind: 'cc', channel, number: d1, value: d2 }
case 0xe0:
return { kind: 'pb', channel, number: 0, value: d1 | (d2 << 7) }
default:
return null
}
}
export function sourceKey(m: Pick<MidiMessage, 'kind' | 'channel' | 'number'>): SourceKey {
return m.kind === 'pb' ? `pb:${m.channel}` : `${m.kind}:${m.channel}:${m.number}`
}
export function parseSource(key: SourceKey): Pick<MidiMessage, 'kind' | 'channel' | 'number'> | null {
const [kind, ch, num] = key.split(':')
const channel = Number(ch)
if (!(channel >= 1 && channel <= 16)) return null
if (kind === 'pb') return { kind, channel, number: 0 }
const number = Number(num)
if ((kind !== 'note' && kind !== 'cc') || !(number >= 0 && number <= 127)) return null
return { kind, channel, number }
}
/** "Note 11 · Ch 1", "CC 33 · Ch 2", "Pitch bend · Ch 1". */
export function describeSource(key: SourceKey): string {
const s = parseSource(key)
if (!s) return key
const what = s.kind === 'pb' ? 'Pitch bend' : s.kind === 'note' ? `Note ${s.number}` : `CC ${s.number}`
return `${what} · Ch ${s.channel}`
}
+192
View File
@@ -0,0 +1,192 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { bind, bindShift, emptyMapping, type Mapping } from './mapping'
import { EMPTY_TARGETS, MidiRouter, type DeckMidi, type MidiTargets } from './router'
import { armLearn, getMidiState, replaceMappings } from './store'
import { getMixerState, setChannel, setMixer } from '../audio/mixerState'
const PORT = 'DDJ'
function fakeDeck(): DeckMidi & { calls: string[] } {
const calls: string[] = []
const log = (name: string) => (...args: unknown[]) => void calls.push([name, ...args].join(' '))
return {
calls,
slotCount: 8,
pitch: 0,
toggle: log('toggle'),
onCuePress: log('cuePress'),
onCueRelease: log('cueRelease'),
onSlotPress: log('slotPress'),
onSlotRelease: log('slotRelease'),
deleteHotcueSlot: log('deleteSlot'),
toggleStem: log('stem'),
moveOrJump: log('move'),
prevMarker: log('prevMarker'),
nextMarker: log('nextMarker'),
stepSize: log('stepSize'),
toggleSizeLoop: log('sizeLoop'),
loopIn: log('loopIn'),
loopOut: log('loopOut'),
toggleLoop: log('toggleLoop'),
toggleSync: log('sync'),
toggleKeylock: log('keylock'),
setPitch: log('pitch'),
jogTouch: log('jogTouch'),
jogTurn: log('jogTurn'),
scrub: log('scrub'),
}
}
let A: ReturnType<typeof fakeDeck>
let B: ReturnType<typeof fakeDeck>
let targets: MidiTargets
let router: MidiRouter
const note = (n: number, v: number) => router.receive(PORT, [0x90, n, v])
const cc = (n: number, v: number) => router.receive(PORT, [0xb0, n, v])
function map(fn: (m: Mapping) => Mapping) {
replaceMappings({ [PORT]: fn(emptyMapping()) }, false)
}
beforeEach(() => {
A = fakeDeck()
B = fakeDeck()
targets = { ...EMPTY_TARGETS, decks: { A, B }, load: vi.fn(), browse: vi.fn() }
router = new MidiRouter(() => targets)
armLearn(null)
setMixer({ crossfader: 0 })
setChannel('A', { fader: 1, trim: 0, color: 0, fx: 'filter' })
map((m) => {
m = bindShift(m, 'note:1:63')
m = bind(m, 'note:1:11', 'button', 'normal', 'deck.A.play')
m = bind(m, 'note:1:0', 'button', 'normal', 'deck.A.hotcue.1')
m = bind(m, 'note:2:11', 'button', 'normal', 'deck.B.play')
m = bind(m, 'cc:1:33', 'rel64', 'normal', 'deck.A.jog')
m = bind(m, 'note:1:54', 'button', 'normal', 'deck.A.jogTouch')
m = bind(m, 'cc:1:0', 'abs14', 'normal', 'deck.A.pitch')
m = bind(m, 'cc:7:19', 'abs7', 'normal', 'mixer.A.fader')
m = bind(m, 'cc:7:31', 'abs7', 'normal', 'mixer.crossfader')
m = bind(m, 'cc:7:64', 'rel64', 'normal', 'library.browse')
return m
})
})
describe('router', () => {
it('runs a button on press only', () => {
note(11, 127)
note(11, 0)
expect(A.calls).toEqual(['toggle'])
})
it('Shift + pad erases the hotcue; the pad alone presses and releases it', () => {
note(0, 127)
note(0, 0)
note(63, 127)
note(0, 127)
note(63, 0)
expect(A.calls).toEqual(['slotPress 0', 'slotRelease 0', 'deleteSlot 0'])
})
it('a held pad releases where it was pressed, even if Shift changes between', () => {
note(0, 127)
note(63, 127)
note(0, 0)
expect(A.calls).toEqual(['slotPress 0', 'slotRelease 0'])
})
it('an unbound Shift layer falls back to the normal action', () => {
note(63, 127)
note(11, 127)
expect(A.calls).toEqual(['toggle'])
})
it('prep mode: deck B and the mixer do nothing', () => {
router.receive(PORT, [0x91, 11, 127]) // deck B's play, channel 2
router.receive(PORT, [0xb6, 19, 0]) // channel A's fader, channel 7
expect(B.calls).toEqual([])
expect(getMixerState().A.fader).toBe(1)
targets.performance = true
router.receive(PORT, [0x91, 11, 127])
router.receive(PORT, [0xb6, 19, 0])
expect(B.calls).toEqual(['toggle'])
expect(getMixerState().A.fader).toBe(0)
})
it('positions jump straight to the control (no takeover)', () => {
targets.performance = true
router.receive(PORT, [0xb6, 31, 127])
expect(getMixerState().crossfader).toBe(1)
router.receive(PORT, [0xb6, 31, 64])
expect(getMixerState().crossfader).toBe(0)
})
it('a 14-bit pitch fader: MSB then LSB', () => {
cc(0, 0)
cc(32, 0)
expect(A.calls.at(-1)).toBe('pitch -1')
cc(0, 64)
expect(A.calls.at(-1)).toBe('pitch 0')
})
it('jog ticks carry the mapping sensitivity; Shift + jog = fast scrub', () => {
cc(33, 66)
note(63, 127)
cc(33, 62)
expect(A.calls).toEqual(['jogTurn 2 1', 'scrub -2 8'])
})
it('jog touch is a hold', () => {
note(54, 127)
note(54, 0)
expect(A.calls).toEqual(['jogTouch true 1', 'jogTouch false 1'])
})
it('browse moves the track list; Shift + browse would move the tree', () => {
router.receive(PORT, [0xb6, 64, 63])
expect(targets.browse).toHaveBeenCalledWith(-1)
})
})
describe('learning', () => {
it('a button learns from its first press, into the Shift layer if Shift is held', () => {
armLearn({ action: 'deck.A.cue', layer: 'normal' })
note(12, 127)
expect(getMidiState().mappings[PORT].bindings['note:1:12']?.normal).toBe('deck.A.cue')
expect(getMidiState().armed).toBeNull()
armLearn({ action: 'deck.A.sync', layer: 'normal' })
note(63, 127)
note(12, 127)
expect(getMidiState().mappings[PORT].bindings['note:1:12']?.shift).toBe('deck.A.sync')
expect(A.calls).toEqual([]) // learning never acts
})
it('a continuous control learns its encoding from what it sent', () => {
armLearn({ action: 'mixer.B.fader', layer: 'normal' })
for (const v of [10, 20, 30, 40, 50, 60, 70, 80, 90, 80, 70, 60]) router.receive(PORT, [0xb1, 19, v])
expect(getMidiState().mappings[PORT].bindings['cc:2:19']).toEqual({ encoding: 'abs7', normal: 'mixer.B.fader' })
})
it('a jog ignores its touch note while learning, and finds it is relative', () => {
armLearn({ action: 'deck.B.jog', layer: 'normal' })
router.receive(PORT, [0x91, 54, 127])
for (const v of [65, 65, 66, 65, 65, 63, 63, 62, 63, 63, 65, 65]) router.receive(PORT, [0xb1, 34, v])
expect(getMidiState().mappings[PORT].bindings['cc:2:34']).toMatchObject({ encoding: 'rel64', normal: 'deck.B.jog', shift: 'deck.B.scrub' })
})
it('a 14-bit pitch fader learns on its MSB, whichever half arrives first', () => {
armLearn({ action: 'deck.B.pitch', layer: 'normal' })
for (let i = 0; i < 6; i++) {
router.receive(PORT, [0xb1, 32 + 5, (i * 37) % 128]) // LSB (CC 37)
router.receive(PORT, [0xb1, 5, 60 + i]) // MSB (CC 5)
}
const b = getMidiState().mappings[PORT].bindings
expect(b['cc:2:5']).toEqual({ encoding: 'abs14', normal: 'deck.B.pitch' })
expect(b['cc:2:37']).toBeUndefined()
// …and then drives the deck from both halves.
targets.performance = true
router.receive(PORT, [0xb1, 5, 127])
router.receive(PORT, [0xb1, 37, 127])
expect(B.calls.at(-1)).toBe('pitch 1')
})
it('a jog reporting its absolute position learns as one, and turns across the wrap', () => {
armLearn({ action: 'deck.A.jog', layer: 'normal' })
for (const v of [100, 108, 116, 124, 4, 12, 20, 28, 36, 44, 52, 60]) cc(40, v)
expect(getMidiState().mappings[PORT].bindings['cc:1:40']?.encoding).toBe('jogAbs7')
cc(40, 126)
cc(40, 3)
expect(A.calls).toEqual(['jogTurn 5 1'])
})
it('the Shift control itself', () => {
armLearn({ action: 'shift' })
note(70, 127)
expect(getMidiState().mappings[PORT].shift).toBe('note:1:70')
})
})
+343
View File
@@ -0,0 +1,343 @@
// Every MIDI message from every controller comes through here: Shift is
// tracked, Learn gets first look, then the message is decoded through its
// binding and the action is run on whatever is mounted to take it (`targets`).
//
// Rules from the discussion (2026-11-03):
// - Shift is a learned control; each control has a free Shift binding, and
// an unbound one falls back to the control's normal action.
// - Prep mode has one deck: deck B and the mixer act only in performance mode.
// - The controller always wins: a position is applied as it arrives (no soft
// takeover), and moving pitch or nudging with the jog releases SYNC (the
// deck target does that, as the on-screen fader and phase meter do).
// - A held control's release reaches the action its press ran, even if
// Shift was let go in between (as useDeckKeys' `held`).
import { actionDef, actionDeck, performanceOnly, type ActionKind, type DeckId } from './actions'
import { Decoder, detectEncoding, type Decoded, type Encoding, type LearnKind } from './encoding'
import { bind, bindShift, resolveBinding, type Layer } from './mapping'
import { parseMessage, sourceKey, type MidiMessage, type SourceKey } from './messages'
import { armLearn, getMidiState, patchMidi, updateMapping, type LearnTarget } from './store'
import type { Track } from '../../api'
import type { DeckShortcuts } from '../deckKeys'
import { FX_TYPES, getMixerState, setChannel, setMixer, type ChannelState } from '../audio/mixerState'
import { TRIM_RANGE_DB } from '../audio/mixerMath'
/** What a deck offers a controller: its keys, plus what keys cannot do. */
export interface DeckMidi extends DeckShortcuts {
toggleSizeLoop(): void
loopIn(): void
loopOut(): void
toggleLoop(): void
toggleSync(): void
toggleKeylock(): void
/** The pitch fader, -1..1. */
pitch: number
/** A hand move of the pitch fader (releases SYNC). */
setPitch(v: number): void
jogTouch(on: boolean, sensitivity: number): void
jogTurn(ticks: number, sensitivity: number): void
scrub(ticks: number, sensitivity: number): void
}
export interface MidiTargets {
performance: boolean
/** The deck loads go to. */
focused: DeckId
decks: Record<DeckId, DeckMidi | null>
togglePerformance: (() => void) | null
/** Load the track list's highlighted row into `deck`. */
load: ((deck: DeckId) => void) | null
/** Move the track list's highlight by `ticks` rows. */
browse: ((ticks: number) => void) | null
/** The track list's highlighted row (what `load` loads). */
lead: (() => Track | null) | null
/** The sidebar's playlist tree. */
tree: { step(ticks: number): void; press(): void } | null
}
export const EMPTY_TARGETS: MidiTargets = {
performance: false,
focused: 'A',
decks: { A: null, B: null },
togglePerformance: null,
load: null,
browse: null,
lead: null,
tree: null,
}
/** Messages a learn capture waits for before guessing an encoding. */
const LEARN_SAMPLES = 12
/** …or this long after the first one. */
const LEARN_WINDOW_MS = 800
/** A CC button waits this long for a note-on (a touch-sensitive jog sends both). */
const LEARN_CC_BUTTON_MS = 250
const learnKind = (k: ActionKind | 'shift'): LearnKind =>
k === 'continuous' ? 'continuous' : k === 'jog' ? 'jog' : 'button'
interface Capture {
target: LearnTarget
kind: LearnKind
port: string | null
source: SourceKey | null
samples: MidiMessage[]
layer: Layer
timer: ReturnType<typeof setTimeout> | null
}
export class MidiRouter {
private shiftHeld = new Map<string, boolean>()
private decoders = new Map<string, Decoder>()
private held = new Map<string, string>()
private capture: Capture | null = null
private lastActivity = 0
private targets: () => MidiTargets
constructor(targets: () => MidiTargets) {
this.targets = targets
}
/** Raw bytes from `port`. */
receive(port: string, bytes: ArrayLike<number>): void {
const m = parseMessage(bytes)
if (m) this.handle(port, m)
}
handle(port: string, m: MidiMessage): void {
const key = sourceKey(m)
const st = getMidiState()
// The settings dialog's activity line: a jog sends hundreds a second.
const now = performance.now()
if (now - this.lastActivity > 50) {
this.lastActivity = now
patchMidi({ activity: { port, source: key, value: m.value, at: now } })
}
const mapping = st.mappings[port]
// Shift: tracked always, and never an action of its own.
if (mapping?.shift === key && !(st.armed?.action === 'shift')) {
this.shiftHeld.set(port, m.value > 0)
return
}
if (st.armed) {
this.learn(port, m, key, st.armed)
return
}
if (!mapping) return
const hit = resolveBinding(mapping, key)
if (!hit) return
const { binding, isLsb } = hit
const decKey = `${port}|${hit.key}`
let dec = this.decoders.get(decKey)
if (!dec || dec.encoding !== binding.encoding || dec.invert !== !!binding.invert) {
dec = new Decoder(binding.encoding, !!binding.invert)
this.decoders.set(decKey, dec)
}
const d = dec.feed(m, isLsb)
if (!d) return
const heldKey = `${port}|${hit.key}`
// A release goes where its press went.
if (d.type === 'press' && !d.down) {
const action = this.held.get(heldKey)
if (action) {
this.held.delete(heldKey)
this.run(action, d, mapping.jogSensitivity, mapping.scrubSpeed)
}
return
}
const action = this.shiftHeld.get(port) ? (binding.shift ?? binding.normal) : binding.normal
if (!action) return
if (d.type === 'press' && actionDef(action)?.kind === 'hold') this.held.set(heldKey, action)
this.run(action, d, mapping.jogSensitivity, mapping.scrubSpeed)
}
/** Forget held controls and decoder state (a controller unplugged). */
forget(port: string): void {
this.shiftHeld.delete(port)
for (const k of [...this.decoders.keys()]) if (k.startsWith(`${port}|`)) this.decoders.delete(k)
for (const k of [...this.held.keys()]) if (k.startsWith(`${port}|`)) this.held.delete(k)
}
// ---- actions -----------------------------------------------------------------
private run(action: string, d: Decoded, sensitivity: number, scrubSpeed: number): void {
const t = this.targets()
if (performanceOnly(action) && !t.performance) return
const def = actionDef(action)
if (!def) return
// A press as the action's kind wants it; a position on a button = pressed past halfway.
const down = d.type === 'press' ? d.down : d.type === 'abs' ? d.unit > 0.5 : null
if (action.startsWith('mixer.')) return this.mixer(action, d, down)
if (action === 'app.performance') return void (down && t.togglePerformance?.())
if (action === 'library.browse') return void (d.type === 'delta' && t.browse?.(d.ticks))
if (action === 'library.tree') return void (d.type === 'delta' && t.tree?.step(d.ticks))
if (action === 'library.browsePress') return void (down && t.load?.(t.focused))
if (action === 'library.treePress') return void (down && t.tree?.press())
const deckId = actionDeck(action)
const deck = deckId && t.decks[deckId]
if (!deck || !deckId) return
const op = action.slice('deck.A.'.length)
if (def.kind === 'continuous') {
if (op !== 'pitch') return
if (d.type === 'abs') deck.setPitch(d.bipolar)
else if (d.type === 'delta') deck.setPitch(Math.max(-1, Math.min(1, deck.pitch + d.ticks / 512)))
return
}
if (def.kind === 'jog') {
if (d.type !== 'delta') return
if (op === 'jog') deck.jogTurn(d.ticks, sensitivity)
else if (op === 'scrub') deck.scrub(d.ticks, sensitivity * scrubSpeed)
return
}
if (down == null) return
if (def.kind === 'hold') {
const slot = op.match(/^hotcue\.(\d+)$/)
if (slot) {
const s = Number(slot[1]) - 1
if (s >= deck.slotCount) return
return void (down ? deck.onSlotPress(s) : deck.onSlotRelease(s))
}
if (op === 'cue') return down ? deck.onCuePress() : deck.onCueRelease()
if (op === 'jogTouch') return deck.jogTouch(down, sensitivity)
return
}
if (!down) return
const n = op.match(/^(hotcueErase|stem|stemSolo)\.(\d+)$/)
if (n) {
const i = Number(n[2]) - 1
if (n[1] === 'hotcueErase') return void (i < deck.slotCount && deck.deleteHotcueSlot(i))
return deck.toggleStem(i, n[1] === 'stemSolo')
}
switch (op) {
case 'play':
return deck.toggle()
case 'sync':
return deck.toggleSync()
case 'keylock':
return deck.toggleKeylock()
case 'jumpBack':
return deck.moveOrJump(-1)
case 'jumpFwd':
return deck.moveOrJump(1)
case 'markerPrev':
return deck.prevMarker()
case 'markerNext':
return deck.nextMarker()
case 'sizeDown':
return deck.stepSize(-1)
case 'sizeUp':
return deck.stepSize(1)
case 'sizeLoop':
return deck.toggleSizeLoop()
case 'loopIn':
return deck.loopIn()
case 'loopOut':
return deck.loopOut()
case 'loopToggle':
return deck.toggleLoop()
case 'load':
return void t.load?.(deckId)
}
}
private mixer(action: string, d: Decoded, down: boolean | null): void {
const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v))
if (action === 'mixer.crossfader') {
const x = getMixerState().crossfader
if (d.type === 'abs') setMixer({ crossfader: d.bipolar })
else if (d.type === 'delta') setMixer({ crossfader: clamp(x + d.ticks / 64, -1, 1) })
return
}
const m = action.match(/^mixer\.([AB])\.(\w+)$/)
if (!m) return
const ch = m[1] as DeckId
const op = m[2]
const s = getMixerState()[ch]
if (op === 'fxNext' || op === 'fxPrev') {
if (!down) return
const i = FX_TYPES.indexOf(s.fx)
const n = FX_TYPES.length
return setChannel(ch, { fx: FX_TYPES[(i + (op === 'fxNext' ? 1 : n - 1)) % n] })
}
const field: Record<string, keyof ChannelState> = { gain: 'trim', high: 'high', mid: 'mid', low: 'low', filter: 'color', fader: 'fader' }
const f = field[op]
if (!f) return
// Gain is ±TRIM_RANGE_DB, the fader 0..1, the rest -1..1 (centre flat).
const [lo, hi] = f === 'trim' ? [-TRIM_RANGE_DB, TRIM_RANGE_DB] : f === 'fader' ? [0, 1] : [-1, 1]
let v: number
if (d.type === 'abs') v = f === 'fader' ? d.unit : d.bipolar * hi
else if (d.type === 'delta') v = clamp((s[f] as number) + (d.ticks * (hi - lo)) / 128, lo, hi)
else return
setChannel(ch, { [f]: v })
}
// ---- learn ---------------------------------------------------------------------
private learn(port: string, m: MidiMessage, key: SourceKey, target: LearnTarget): void {
const kind = learnKind(target.action === 'shift' ? 'shift' : (actionDef(target.action)?.kind ?? 'button'))
let c = this.capture
if (!c || c.target !== target) {
if (c?.timer) clearTimeout(c.timer)
const layer: Layer = 'layer' in target ? (this.shiftHeld.get(port) ? 'shift' : target.layer) : 'normal'
c = this.capture = { target, kind, port: null, source: null, samples: [], layer, timer: null }
}
if (c.port && c.port !== port) return // one controller at a time
if (kind === 'button') {
if (m.value === 0) return
if (m.kind === 'note') return this.commit(c, port, key, 'button')
if (m.kind === 'cc' && !c.source) {
// Wait briefly in case a note-on follows (a touch jog sends both).
c.port = port
c.source = key
c.timer = setTimeout(() => this.commit(c!, port, key, 'button'), LEARN_CC_BUTTON_MS)
}
return
}
// A position or ticks: notes (a jog's touch sensor, a stray pad) do not count.
if (m.kind === 'note') return
if (!c.source) {
c.port = port
c.source = key
c.timer = setTimeout(() => this.finish(), LEARN_WINDOW_MS)
} else if (m.kind === 'cc' && c.source.startsWith('cc:')) {
// The MSB of a 14-bit pair is the lower number, whichever came first.
const first = Number(c.source.split(':')[2])
if (m.channel === Number(c.source.split(':')[1]) && m.number === first - 32) c.source = key
}
c.samples.push(m)
if (c.samples.length >= LEARN_SAMPLES) this.finish()
}
/** Commit a continuous / jog capture now (its window ran out). */
finish(): void {
const c = this.capture
if (!c || !c.port || !c.source) return
const src = c.source
// The bound control's own message first: the guess reads its kind and number.
const lead = c.samples.find((s) => sourceKey(s) === src)
const ordered = lead ? [lead, ...c.samples.filter((s) => s !== lead)] : c.samples
// A 14-bit pair binds on its MSB; anything else on the control that moved.
this.commit(c, c.port, src, detectEncoding(ordered, c.kind))
}
private commit(c: Capture, port: string, source: SourceKey, encoding: Encoding): void {
if (c.timer) clearTimeout(c.timer)
if (this.capture !== c) return
this.capture = null
const t = c.target
if (t.action === 'shift') updateMapping(port, (m) => bindShift(m, source))
else {
updateMapping(port, (m) => bind(m, source, encoding, c.layer, t.action))
patchMidi({ learned: { port, action: t.action, layer: c.layer, at: performance.now() } })
}
this.decoders.delete(`${port}|${source}`)
armLearn(null)
}
}
+88
View File
@@ -0,0 +1,88 @@
// MIDI state the UI shows and the router reads, in one small external store
// read through useSyncExternalStore (as lib/audio/mixerState.ts is): the
// connected controllers, every controller's mapping, what is being learned and
// the last message seen (the settings dialog's activity line).
//
// Mappings are persisted by whoever installs `setPersist` (useMidi, through
// the shared prefs writer); everything else lives for the session.
import { useSyncExternalStore } from 'react'
import type { Layer, Mapping, Mappings } from './mapping'
import { emptyMapping } from './mapping'
import type { SourceKey } from './messages'
/** What Learn is waiting for: an action in a layer, or the Shift control itself. */
export type LearnTarget = { action: string; layer: Layer } | { action: 'shift' }
export interface MidiState {
/** Whether this build can read MIDI at all (desktop app, or a Web MIDI browser). */
available: boolean
/** Why MIDI could not be read (a browser refused access), else null. */
blocked: string | null
/** Connected controllers, by port name. */
ports: string[]
mappings: Mappings
/** Armed: the next control moved is bound to this. */
armed: LearnTarget | null
/** On-screen learn mode: clicking a control arms it. */
onScreen: boolean
/** The last binding learned (the on-screen mode flashes it). */
learned: { port: string; action: string; layer: Layer; at: number } | null
activity: { port: string; source: SourceKey; value: number; at: number } | null
}
let state: MidiState = {
available: false,
blocked: null,
ports: [],
mappings: {},
armed: null,
onScreen: false,
learned: null,
activity: null,
}
const listeners = new Set<() => void>()
let persist: ((m: Mappings) => void) | null = null
export function getMidiState(): MidiState {
return state
}
export function subscribeMidi(fn: () => void): () => void {
listeners.add(fn)
return () => listeners.delete(fn)
}
export function patchMidi(patch: Partial<MidiState>): void {
state = { ...state, ...patch }
for (const fn of listeners) fn()
}
export function setPersist(fn: ((m: Mappings) => void) | null): void {
persist = fn
}
/** Change one controller's mapping (created empty on first use) and save. */
export function updateMapping(port: string, fn: (m: Mapping) => Mapping): void {
const mappings = { ...state.mappings, [port]: fn(state.mappings[port] ?? emptyMapping()) }
patchMidi({ mappings })
persist?.(mappings)
}
export function replaceMappings(mappings: Mappings, save = true): void {
patchMidi({ mappings })
if (save) persist?.(mappings)
}
export function armLearn(target: LearnTarget | null): void {
patchMidi({ armed: target })
}
export function setOnScreenLearn(on: boolean): void {
patchMidi({ onScreen: on, armed: null })
}
/** A slice of the MIDI state, re-rendering only when it changes. */
export function useMidiState<T>(select: (s: MidiState) => T): T {
return useSyncExternalStore(subscribeMidi, () => select(state))
}
+29
View File
@@ -0,0 +1,29 @@
// What the router acts on, filled in by whoever is mounted to take it:
// PrepStrip (the decks, performance mode), App (loading), TrackTable (browse)
// and Sidebar (the playlist tree). Assigned on every render — as PrepStrip's
// `keys` ref is — so the router always sees the latest handlers.
//
// Unmounting clears only what THIS component last set: switching views
// renders the new table (which registers) before the old one's cleanup runs,
// and a blanket reset would wipe the newcomer's handlers.
import { useEffect, useRef } from 'react'
import { EMPTY_TARGETS, type MidiTargets } from './router'
export const midiTargets: MidiTargets = { ...EMPTY_TARGETS, decks: { A: null, B: null } }
export function useMidiTargets(patch: Partial<MidiTargets>): void {
Object.assign(midiTargets, patch)
const mine = useRef(patch)
mine.current = patch
useEffect(
() => () => {
const t = midiTargets as unknown as Record<string, unknown>
for (const [k, v] of Object.entries(mine.current)) {
if (t[k] !== v) continue
t[k] = k === 'decks' ? { A: null, B: null } : EMPTY_TARGETS[k as keyof MidiTargets]
}
},
[],
)
}
+89
View File
@@ -0,0 +1,89 @@
// Where MIDI comes from. The desktop app reads ports in the shell
// (src-tauri/src/midi.rs: WKWebView has no Web MIDI); a browser under
// `./dev.sh` uses Web MIDI (Chrome) — same interface, so nothing above here
// knows which. Neither (Safari, Firefox without the permission) = no MIDI.
export type OnBytes = (batch: ArrayLike<number>[]) => void
export interface MidiTransport {
ports(): Promise<string[]>
/** Start receiving; resolves to the function that stops it. */
open(port: string, onBytes: OnBytes): Promise<() => void>
}
/** "X", "X #2" for two identical controllers — the shell names them the same way. */
export function uniqueNames(names: string[]): string[] {
const seen = new Map<string, number>()
return names.map((n) => {
const k = (seen.get(n) ?? 0) + 1
seen.set(n, k)
return k === 1 ? n : `${n} #${k}`
})
}
function tauriTransport(): MidiTransport {
const core = () => import('@tauri-apps/api/core')
return {
ports: async () => (await core()).invoke<string[]>('midi_ports'),
open: async (port, onBytes) => {
const { invoke, Channel } = await core()
// A fresh Channel per open: Tauri ends one whose Rust side was dropped.
const ch = new Channel<{ wall_us: number; bytes: number[] }[]>()
ch.onmessage = (batch) => onBytes(batch.map((p) => p.bytes))
await invoke('midi_open', { port, onMessage: ch })
return () => void invoke('midi_close', { port }).catch(() => {})
},
}
}
function webMidiTransport(): MidiTransport {
// Chrome asks the user first. A refusal is not kept for good: after
// REASK_MS the poll asks again, so allowing MIDI in the site settings takes
// effect without a reload — but a dismissed prompt is not shown again at
// once (every 1.5 s would nag, and Chrome blocks a site after repeats).
const REASK_MS = 20_000
let access: Promise<MIDIAccess> | null = null
let refused: { at: number; error: unknown } | null = null
const get = () => {
if (refused && performance.now() - refused.at < REASK_MS) return Promise.reject(refused.error)
return (access ??= navigator.requestMIDIAccess({ sysex: false }).then(
(a) => ((refused = null), a),
(e: unknown) => {
access = null
refused = { at: performance.now(), error: e }
throw e
},
))
}
const inputs = async () => {
const list = [...(await get()).inputs.values()].filter((i) => i.state === 'connected')
const names = uniqueNames(list.map((i) => i.name ?? 'MIDI input'))
return list.map((input, k) => ({ input, name: names[k] }))
}
return {
ports: async () => (await inputs()).map((i) => i.name),
open: async (port, onBytes) => {
const hit = (await inputs()).find((i) => i.name === port)
if (!hit) throw new Error(`MIDI port not found: ${port}`)
const handler = (e: MIDIMessageEvent) => {
// System messages stay out, as the shell ignores them.
if (e.data && e.data[0] < 0xf0) onBytes([e.data])
}
hit.input.addEventListener('midimessage', handler)
// Only SETTING `onmidimessage` opens a port implicitly; a listener added
// with addEventListener does not, so open it ourselves.
await hit.input.open()
return () => {
hit.input.removeEventListener('midimessage', handler)
void hit.input.close().catch(() => {})
}
},
}
}
export function midiTransport(): MidiTransport | null {
if (typeof window === 'undefined') return null
if ('__TAURI_INTERNALS__' in window) return tauriTransport()
if (typeof navigator.requestMIDIAccess === 'function') return webMidiTransport()
return null
}
+101
View File
@@ -0,0 +1,101 @@
// MIDI for the whole app, mounted once (App): finds controllers as they come
// and go, feeds their messages to the router, and keeps the mappings in
// userprefs (`midiMappings`, through the shared debounced prefs writer).
//
// midir has no connect notifications (nor does every Web MIDI), so the port
// list is polled — cheap, and a newly plugged controller works within ~1.5 s.
import { useEffect, useRef } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '../../api'
import { usePrefsWriter } from '../prefs'
import { sanitizeMappings } from './mapping'
import { MidiRouter } from './router'
import { getMidiState, patchMidi, replaceMappings, setPersist } from './store'
import { midiTargets } from './targets'
import { midiTransport } from './transport'
const POLL_MS = 1500
/** The router every message goes through (one per app). */
export const midiRouter = new MidiRouter(() => midiTargets)
export function useMidi(onNotify: (kind: 'success' | 'warning', msg: string) => void): void {
const writePrefs = usePrefsWriter()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }).data
const hydrated = useRef(false)
const notify = useRef(onNotify)
notify.current = onNotify
// Mappings: hydrated once from prefs, then saved on every change.
useEffect(() => {
if (hydrated.current || !prefs) return
hydrated.current = true
replaceMappings(sanitizeMappings((prefs as { midiMappings?: unknown }).midiMappings), false)
setPersist((m) => writePrefs({ midiMappings: m }))
}, [prefs, writePrefs])
useEffect(() => () => setPersist(null), [])
useEffect(() => {
const transport = midiTransport()
if (!transport) return
patchMidi({ available: true })
const open = new Map<string, () => void>()
const opening = new Set<string>()
let first = true
let stopped = false
const poll = async () => {
let ports: string[]
try {
ports = await transport.ports()
if (getMidiState().blocked) patchMidi({ blocked: null })
} catch (e) {
// A browser refusing MIDI access (Chrome asks first): say so in the
// MIDI dialog rather than looking like no controller is plugged in.
const why = e instanceof Error ? e.message : String(e)
if (getMidiState().blocked !== why) patchMidi({ blocked: why })
return
}
if (stopped) return
for (const [port, close] of open) {
if (ports.includes(port)) continue
close()
open.delete(port)
midiRouter.forget(port)
}
for (const port of ports) {
if (open.has(port) || opening.has(port)) continue
opening.add(port)
// Ports present at launch connect quietly; later ones are news.
const announce = !first
transport
.open(port, (batch) => {
for (const bytes of batch) midiRouter.receive(port, bytes)
})
.then((close) => {
if (stopped) return close()
open.set(port, close)
if (!announce) return
const mapped = !!getMidiState().mappings[port]
notify.current(
mapped ? 'success' : 'warning',
mapped ? `${port} connected` : `${port} connected — not mapped yet (Settings ▸ MIDI Controllers…)`,
)
})
.catch(() => {})
.finally(() => opening.delete(port))
}
patchMidi({ ports })
first = false
}
void poll()
const t = setInterval(() => void poll(), POLL_MS)
return () => {
stopped = true
clearInterval(t)
for (const close of open.values()) close()
patchMidi({ ports: [] })
}
}, [])
}
+3
View File
@@ -12,6 +12,7 @@ import { DragLayer } from './lib/drag.tsx'
import { QuitGuard } from './components/QuitGuard.tsx'
import { preventHistoryNavigation } from './lib/noNavigation.ts'
import { StartupGate } from './components/StartupScreen.tsx'
import { MidiLearnOverlay } from './components/MidiLearnOverlay.tsx'
preventHistoryNavigation()
@@ -38,6 +39,8 @@ createRoot(document.getElementById('root')!).render(
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* MIDI learning by clicking controls (Settings ▸ MIDI Controllers…). */}
<MidiLearnOverlay />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
</StartupGate>