import { useEffect, useMemo, useRef, useState } from 'react'; import { InputChannel, OutputChannel } from '../../features/dsp408/types'; import { DSP408 } from '../../types'; import { INPUT_ORDER, OUTPUT_ORDER, MATRIX_GAIN_MIN, MATRIX_GAIN_MAX, MATRIX_GAIN_STEP, } from '../../features/dsp408/constants'; import { SidebarId } from '../../features/dsp408/constants'; import './SignalFlowMatrix.css'; const INPUT_SIDEBAR: Record = { InA: 'ina', InB: 'inb', InC: 'inc', InD: 'ind', }; const OUTPUT_SIDEBAR: Record = { Out1: 'out1', Out2: 'out2', Out3: 'out3', Out4: 'out4', Out5: 'out5', Out6: 'out6', Out7: 'out7', Out8: 'out8', }; const INPUT_STAGES: { key: string; label: string; sidebar: SidebarId | 'input'; }[] = [ { key: 'gain', label: 'GAIN', sidebar: 'gain' }, { key: 'gate', label: 'GATE', sidebar: 'gate' }, { key: 'geq', label: 'GEQ', sidebar: 'geq' }, { key: 'peq', label: 'PEQ', sidebar: 'input' }, { key: 'hplp', label: 'HP/LP', sidebar: 'input' }, { key: 'delay', label: 'DELAY', sidebar: 'delay' }, ]; const OUTPUT_STAGES: { key: string; label: string; sidebar: SidebarId | 'output'; }[] = [ { key: 'xover', label: 'XOVER', sidebar: 'output' }, { key: 'peq', label: 'PEQ', sidebar: 'output' }, { key: 'gain', label: 'GAIN', sidebar: 'gain' }, { key: 'compressor', label: 'COMP', sidebar: 'compressor' }, { key: 'limiter', label: 'LIMIT', sidebar: 'limiter' }, { key: 'delay', label: 'DELAY', sidebar: 'delay' }, { key: 'mute', label: 'MUTE', sidebar: 'output' }, ]; const INPUT_COLORS = [ 'var(--accent-a, #60a5fa)', 'var(--accent-b, #34d399)', 'var(--accent-c, #f59e0b)', 'var(--accent-d, #f472b6)', ]; const W = 1800; const H = 520; const MARGIN = 36; const LEFT_CHAIN_W = 560; const RIGHT_CHAIN_W = 620; // Width of the invisible "hitbox" stroke drawn under each visible line, in SVG // user units. Much wider than the visible 1–2.5px line so it's easy to click // or catch with a scroll wheel without needing pixel-perfect aim. const LINE_HITBOX_WIDTH = 14; // How long the gain tooltip stays visible after the last wheel tick, in ms. const GAIN_TOOLTIP_HOLD_MS = 700; function getRoutes(dsp: DSP408, output: OutputChannel) { return dsp.state.current_config.output_states[output].matrix_routes; } function isRouted(dsp: DSP408, output: OutputChannel, input: InputChannel) { return getRoutes(dsp, output).connected.includes(input); } function getGain(dsp: DSP408, output: OutputChannel, input: InputChannel) { return getRoutes(dsp, output).gains[input]; } function formatGainDb(value: number) { const sign = value > 0 ? '+' : ''; return `${sign}${value.toFixed(1)} dB`; } export function useNonPassiveWheel( ref: React.RefObject, handler: (e: WheelEvent) => void ) { const handlerRef = useRef(handler); handlerRef.current = handler; useEffect(() => { const el = ref.current; if (!el) return; const listener = (e: Event) => handlerRef.current(e as WheelEvent); el.addEventListener('wheel', listener, { passive: false }); return () => el.removeEventListener('wheel', listener); }, [ref]); } type GainTooltipState = { visible: boolean; x: number; y: number; label: string; }; function SignalFlowMatrix({ dsp, setMatrixRouting, setMatrixGain, setActiveSidebar, onGainPreview, }: { dsp: DSP408; setMatrixRouting: (output: OutputChannel, inputs: InputChannel[]) => Promise; setMatrixGain: (input: InputChannel, output: OutputChannel, gain: number) => Promise; setActiveSidebar: React.Dispatch>; onGainPreview: (input: InputChannel, output: OutputChannel, value: number | null) => void; }) { const nInputs = INPUT_ORDER.length; const nOutputs = OUTPUT_ORDER.length; const usableH = H - MARGIN * 2; const inputRowH = usableH / nInputs; const outputRowH = usableH / nOutputs; const inputStageW = LEFT_CHAIN_W / (INPUT_STAGES.length + 1); const outputStageW = RIGHT_CHAIN_W / (OUTPUT_STAGES.length + 1); const leftStart = MARGIN; const rightStart = W - MARGIN - RIGHT_CHAIN_W; const inputCenterY = (i: number) => MARGIN + inputRowH * (i + 0.5); const outputCenterY = (j: number) => MARGIN + outputRowH * (j + 0.5); const inputNodeX = leftStart + LEFT_CHAIN_W; const outputNodeX = rightStart; const [gainTooltip, setGainTooltip] = useState({ visible: false, x: 0, y: 0, label: '', }); const hideTooltipTimer = useRef | null>(null); const WHEEL_COMMIT_DELAY = 250; // key = `${input}-${output}` const pendingGains = useRef>(new Map()); const commitTimers = useRef>>(new Map()); useEffect(() => { const timers = commitTimers.current; const tooltipTimer = hideTooltipTimer.current; return () => { if (tooltipTimer) { clearTimeout(tooltipTimer); } timers.forEach((timer) => clearTimeout(timer)); timers.clear(); }; }, []); const handleToggle = (output: OutputChannel, input: InputChannel) => { const routes = getRoutes(dsp, output); const next = routes.connected.includes(input) ? routes.connected.filter((c) => c !== input) : [...routes.connected, input]; void setMatrixRouting(output, next); }; const svgRef = useRef(null); const handleWheelGain = (e: WheelEvent, output: OutputChannel, input: InputChannel) => { e.preventDefault(); const key = `${input}-${output}`; // Base on the pending value if we're mid-wheel, otherwise the real state const current = pendingGains.current.get(key) ?? getGain(dsp, output, input); const delta = e.deltaY < 0 ? MATRIX_GAIN_STEP : -MATRIX_GAIN_STEP; const next = Math.round(Math.min(MATRIX_GAIN_MAX, Math.max(MATRIX_GAIN_MIN, current + delta)) * 10) / 10; pendingGains.current.set(key, next); onGainPreview(input, output, next); // Debounced send: only the final value goes out once the wheel pauses const existing = commitTimers.current.get(key); if (existing) clearTimeout(existing); commitTimers.current.set( key, setTimeout(async () => { commitTimers.current.delete(key); const value = pendingGains.current.get(key); if (value === undefined) return; await setMatrixGain(input, output, value); // Only release if the user hasn't wheeled again while we were awaiting if (pendingGains.current.get(key) === value) { pendingGains.current.delete(key); onGainPreview(input, output, null); } }, WHEEL_COMMIT_DELAY) ); // Tooltip (unchanged, shows the pending value) if (hideTooltipTimer.current) clearTimeout(hideTooltipTimer.current); setGainTooltip({ visible: true, x: e.clientX, y: e.clientY, label: formatGainDb(next) }); hideTooltipTimer.current = setTimeout(() => { setGainTooltip((t) => ({ ...t, visible: false })); }, GAIN_TOOLTIP_HOLD_MS); }; useNonPassiveWheel(svgRef, (e) => { const hit = (e.target as Element).closest('[data-wheel-route]'); if (!hit) return; // not over a connected line: let the page scroll normally const { input, output } = hit.dataset; if (!input || !output) return; handleWheelGain(e, output as OutputChannel, input as InputChannel); }); const routePairs = useMemo(() => { const pairs: { input: InputChannel; output: OutputChannel; i: number; j: number }[] = []; OUTPUT_ORDER.forEach((output, j) => { INPUT_ORDER.forEach((input, i) => pairs.push({ input, output, i, j })); }); return pairs; }, []); // Draw dashed (unconnected) links first so connected (solid) links always // paint on top of them, regardless of input/output index order. This has // to be recomputed whenever routing changes, since isRouted reads live // dsp state — unlike routePairs above, which is just static index pairs. const orderedRoutePairs = useMemo(() => { return [...routePairs].sort((a, b) => { const aConnected = isRouted(dsp, a.output, a.input) ? 1 : 0; const bConnected = isRouted(dsp, b.output, b.input) ? 1 : 0; return aConnected - bConnected; }); }, [routePairs, dsp]); return (
{orderedRoutePairs.map(({ input, output, i, j }) => { const connected = isRouted(dsp, output, input); const y1 = inputCenterY(i); const y2 = outputCenterY(j); const cx1 = inputNodeX + (outputNodeX - inputNodeX) * 0.4; const cx2 = inputNodeX + (outputNodeX - inputNodeX) * 0.6; const path = `M ${inputNodeX} ${y1} C ${cx1} ${y1}, ${cx2} ${y2}, ${outputNodeX} ${y2}`; const color = INPUT_COLORS[i % INPUT_COLORS.length]; return ( {/* Invisible wide-stroke hitbox: carries the click/wheel handlers so the line is easy to grab without needing to hit the thin visible stroke exactly. Sits directly under the visible path. */} handleToggle(output, input)} data-wheel-route={connected ? '' : undefined} data-input={input} data-output={output} /> {/* Visible line, purely decorative — no pointer events, so it never competes with the hitbox above for hover/click/wheel. */} ); })} {INPUT_ORDER.map((input, i) => { const y = inputCenterY(i); const boxH = Math.min(inputRowH * 0.55, 40); const name = dsp.state.current_config.input_states[input].name; const boxes = [{ key: 'name', label: name, sidebar: 'input' as const }, ...INPUT_STAGES]; return ( {boxes.map((stage, si) => { const x = leftStart + si * inputStageW; const sidebarId = stage.sidebar === 'input' ? INPUT_SIDEBAR[input] : stage.sidebar; return ( setActiveSidebar(sidebarId as SidebarId)} > {si === 0 ? name : stage.label} ); })} ); })} {OUTPUT_ORDER.map((output, j) => { const y = outputCenterY(j); const boxH = Math.min(outputRowH * 0.55, 32); const name = dsp.state.current_config.output_states[output].name; const boxes = [ ...OUTPUT_STAGES, { key: 'name', label: name, sidebar: 'output' as const }, ]; return ( {boxes.map((stage, si) => { const x = rightStart + si * outputStageW; const sidebarId = stage.sidebar === 'output' ? OUTPUT_SIDEBAR[output] : stage.sidebar; const isLast = si === boxes.length - 1; return ( setActiveSidebar(sidebarId as SidebarId)} > {isLast ? name : stage.label} ); })} ); })} {gainTooltip.visible && (
{gainTooltip.label}
)}
); } export default SignalFlowMatrix;