Files
beat-hound/src/components/CircularTimeline.tsx
T

235 lines
8.0 KiB
TypeScript

import { useRef } from 'react';
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react';
import type { BeatPoint } from '../domain/sequencer';
import {
PLAYBACK_SUBSTEPS_PER_STEP,
STEPS_PER_BEAT,
} from '../domain/sequencer';
import {
getPointForStep,
getLoopPositionPercent,
getSoundOrbitRadius,
getStepFromPosition,
ORBIT_RADIUS,
SVG_CENTER,
SVG_SIZE,
getStackedPosition,
wrapStepPosition,
} from '../domain/timeline';
import { INSTRUMENT_BY_ID } from '../domain/instruments';
import type { InstrumentId } from '../domain/instruments';
interface CircularTimelineProps {
beats: BeatPoint[];
soundIds: readonly InstrumentId[];
colorBySoundId: Partial<Record<InstrumentId, string>>;
currentStep: number;
totalSteps: number;
focusedSoundId: InstrumentId | null;
selectedBeatId: string | null;
onMoveBeat: (beatId: string, step: number) => void;
onSelectBeat: (beatId: string) => void;
onSelectSound: (soundId: InstrumentId) => void;
}
function getPointerCoordinates(event: ReactPointerEvent<SVGSVGElement>) {
const bounds = event.currentTarget.getBoundingClientRect();
return {
x: ((event.clientX - bounds.left) / bounds.width) * SVG_SIZE,
y: ((event.clientY - bounds.top) / bounds.height) * SVG_SIZE,
};
}
export function CircularTimeline({
beats,
soundIds,
colorBySoundId,
currentStep,
totalSteps,
focusedSoundId,
selectedBeatId,
onMoveBeat,
onSelectBeat,
onSelectSound,
}: CircularTimelineProps) {
const draggingBeatIdRef = useRef<string | null>(null);
const selectedBeatSoundId = beats.find((beat) => beat.id === selectedBeatId)?.soundId;
const activeSoundId = selectedBeatSoundId ?? focusedSoundId;
const orderedSoundIds = activeSoundId
? [
...soundIds.filter((soundId) => soundId === activeSoundId),
...soundIds.filter((soundId) => soundId !== activeSoundId),
]
: soundIds;
function handlePointerDown(event: ReactPointerEvent<SVGGElement>, beatId: string): void {
event.preventDefault();
event.stopPropagation();
draggingBeatIdRef.current = beatId;
onSelectBeat(beatId);
event.currentTarget.setPointerCapture(event.pointerId);
}
function handlePointerMove(event: ReactPointerEvent<SVGSVGElement>): void {
const beatId = draggingBeatIdRef.current;
if (!beatId) return;
const { x, y } = getPointerCoordinates(event);
onMoveBeat(beatId, getStepFromPosition(x, y, SVG_CENTER, totalSteps));
}
function handleMarkerKeyDown(event: ReactKeyboardEvent<SVGGElement>, beat: BeatPoint): void {
let nextStep: number | null = null;
const stepSize = event.shiftKey ? 1 : 1 / PLAYBACK_SUBSTEPS_PER_STEP;
if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
nextStep = wrapStepPosition(beat.step + stepSize, totalSteps);
}
if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
nextStep = wrapStepPosition(beat.step - stepSize, totalSteps);
}
if (nextStep === null) return;
event.preventDefault();
onSelectBeat(beat.id);
onMoveBeat(beat.id, nextStep);
}
function handleOrbitKeyDown(
event: ReactKeyboardEvent<SVGCircleElement>,
soundId: InstrumentId,
): void {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
onSelectSound(soundId);
}
return (
<svg
className="circular-timeline"
viewBox={`0 0 ${SVG_SIZE} ${SVG_SIZE}`}
role="group"
aria-label={`${totalSteps}-step circular beat timeline with one orbit per sound. Drag beat points to move them.`}
onPointerMove={handlePointerMove}
onPointerUp={() => { draggingBeatIdRef.current = null; }}
onPointerCancel={() => { draggingBeatIdRef.current = null; }}
>
{orderedSoundIds.map((soundId, soundIndex) => {
const focused = soundId === activeSoundId;
return (
<circle
key={soundId}
cx={SVG_CENTER}
cy={SVG_CENTER}
r={getSoundOrbitRadius(soundIndex, orderedSoundIds.length)}
className={`timeline-orbit${focused ? ' is-focused' : ''}`}
style={{
stroke: colorBySoundId[soundId] ?? '#b8b4e0',
opacity: focused ? 0.55 : 0.32,
strokeWidth: focused ? 2.2 : 1.5,
}}
/>
);
})}
{Array.from({ length: totalSteps * PLAYBACK_SUBSTEPS_PER_STEP }, (_, tick) => {
const step = tick / PLAYBACK_SUBSTEPS_PER_STEP;
const major = tick % (STEPS_PER_BEAT * PLAYBACK_SUBSTEPS_PER_STEP) === 0;
const fullStep = tick % PLAYBACK_SUBSTEPS_PER_STEP === 0;
const inner = getPointForStep(step, ORBIT_RADIUS + 11, SVG_CENTER, totalSteps);
const outer = getPointForStep(
step,
ORBIT_RADIUS + (major ? 24 : fullStep ? 18 : 14),
SVG_CENTER,
totalSteps,
);
const label = getPointForStep(step, ORBIT_RADIUS + 53, SVG_CENTER, totalSteps);
return (
<g
className={`timeline-tick${major ? ' is-major' : fullStep ? '' : ' is-substep'}`}
key={tick}
>
<line x1={inner.x} y1={inner.y} x2={outer.x} y2={outer.y} />
{major && (
<text x={label.x} y={label.y} textAnchor="middle" dominantBaseline="middle">
{String(Math.floor(step + 1)).padStart(2, '0')}
</text>
)}
</g>
);
})}
{orderedSoundIds.map((soundId, soundIndex) => (
<circle
key={soundId}
cx={SVG_CENTER}
cy={SVG_CENTER}
r={getSoundOrbitRadius(soundIndex, orderedSoundIds.length)}
className="timeline-orbit-hit-area"
fill="none"
stroke="transparent"
strokeWidth="24"
pointerEvents="stroke"
role="button"
tabIndex={0}
aria-label={`Select ${INSTRUMENT_BY_ID[soundId].label} ring`}
aria-pressed={soundId === activeSoundId}
onClick={() => onSelectSound(soundId)}
onKeyDown={(event) => handleOrbitKeyDown(event, soundId)}
onFocus={() => onSelectSound(soundId)}
/>
))}
{currentStep >= 0 && (() => {
const cursor = getPointForStep(currentStep, ORBIT_RADIUS + 1, SVG_CENTER, totalSteps);
return (
<g className="timeline-playhead" aria-hidden="true">
<line x1={SVG_CENTER} y1={SVG_CENTER} x2={cursor.x} y2={cursor.y} />
<circle cx={cursor.x} cy={cursor.y} r="4" />
</g>
);
})()}
{beats.map((beat) => {
const instrument = INSTRUMENT_BY_ID[beat.soundId];
const soundIndex = orderedSoundIds.indexOf(beat.soundId);
const point = getStackedPosition(
beat,
beats,
totalSteps,
getSoundOrbitRadius(soundIndex, orderedSoundIds.length),
);
const selected = selectedBeatId === beat.id;
return (
<g
key={beat.id}
className={`sound-point${selected ? ' is-selected' : ''}`}
style={{ color: colorBySoundId[beat.soundId] ?? '#f4f1ed' }}
role="button"
tabIndex={0}
aria-label={`${instrument.label}, beat ${beat.letter}, ${getLoopPositionPercent(beat.step, totalSteps)}% around the loop. Drag to move freely, or use arrow keys for small steps.`}
aria-pressed={selected}
onPointerDown={(event) => handlePointerDown(event, beat.id)}
onClick={() => onSelectBeat(beat.id)}
onKeyDown={(event) => handleMarkerKeyDown(event, beat)}
onFocus={() => onSelectBeat(beat.id)}
>
<circle cx={point.x} cy={point.y} r="19" className="sound-point-hit-area" />
<circle cx={point.x} cy={point.y} r="10" className="sound-point-face" />
<text
x={point.x}
y={point.y}
className="sound-point-letter"
textAnchor="middle"
dominantBaseline="middle"
aria-hidden="true"
>
{beat.letter}
</text>
</g>
);
})}
</svg>
);
}