Build BeatHound sequencer app

This commit is contained in:
Ninosaurier committed 2026-11-15 10:47:01 +01:00
1 parent 226ababcf1
commit e23825cdb1
49 files changed
+6455 -2

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import { IonApp, IonContent, IonPage } from '@ionic/react';
import { BeatLoopPanel } from './components/BeatLoopPanel';
import { BeatTemplateSelector } from './components/BeatTemplateSelector';
import { TransportBar } from './components/TransportBar';
import { useBeatStudio } from './hooks/useBeatStudio';
function App() {
const studio = useBeatStudio();
return (
<IonApp>
<IonPage>
<IonContent fullscreen className="app-content">
<div className="app-shell">
<header className="app-header">
<a className="brand" href="#studio" aria-label="BeatHound home">
<img
className="brand-logo"
src="/logo/logo-horizontal-dark-notagline.svg"
alt=""
/>
</a>
<span className="header-tag">Sharpen your sense of rhythm</span>
</header>
<main id="studio" className="studio">
<div className="studio-heading">
<h1>Build a beat.</h1>
<p className="template-prompt">Choose a dance template</p>
<BeatTemplateSelector onSelectTemplate={studio.applyTemplate} />
<p
className={`intro-copy${studio.sequencer.beats.length > 0 ? ' is-hidden' : ''}`}
aria-hidden={studio.sequencer.beats.length > 0}
>
Add a sound, then move it around the loop.
</p>
</div>
<BeatLoopPanel sequencer={studio.sequencer} soundPalette={studio.soundPalette} />
{studio.sequencer.audioError && (
<p className="audio-error" role="alert">{studio.sequencer.audioError}</p>
)}
</main>
</div>
</IonContent>
<TransportBar
isPlaying={studio.sequencer.isPlaying}
isStarting={studio.sequencer.isStarting}
hasBeats={studio.sequencer.beats.length > 0}
onTogglePlayback={studio.sequencer.togglePlayback}
onAddSound={studio.addSound}
/>
</IonPage>
</IonApp>
);
}
export default App;
+43
View File
@@ -0,0 +1,43 @@
import type { SoundId } from '../domain/sounds';
import { SOUND_VOICES } from './soundVoices';
type AudioWindow = Window & typeof globalThis & {
webkitAudioContext?: typeof AudioContext;
};
export class AudioEngine {
private context: AudioContext | null = null;
async start(): Promise<void> {
if (typeof window === 'undefined') {
throw new Error('Web Audio is not available in this browser.');
}
const audioWindow = window as AudioWindow;
const AudioContextConstructor = audioWindow.AudioContext ?? audioWindow.webkitAudioContext;
if (!AudioContextConstructor) {
throw new Error('Web Audio is not available in this browser.');
}
if (!this.context || this.context.state === 'closed') {
this.context = new AudioContextConstructor();
}
const context = this.context;
await context.resume();
if (context.state !== 'running') {
throw new Error('The browser did not enable audio playback.');
}
}
play(soundId: SoundId): void {
if (this.context?.state !== 'running') return;
SOUND_VOICES[soundId](this.context);
}
async dispose(): Promise<void> {
const context = this.context;
this.context = null;
if (context && context.state !== 'closed') await context.close();
}
}
+53
View File
@@ -0,0 +1,53 @@
export function playKick(context: AudioContext): void {
const now = context.currentTime;
const oscillator = context.createOscillator();
const transient = context.createOscillator();
const gain = context.createGain();
const transientGain = context.createGain();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(175, now);
oscillator.frequency.exponentialRampToValueAtTime(62, now + 0.16);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(0.95, now + 0.008);
gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.32);
oscillator.connect(gain);
gain.connect(context.destination);
oscillator.start(now);
oscillator.stop(now + 0.33);
transient.type = 'triangle';
transient.frequency.setValueAtTime(850, now);
transient.frequency.exponentialRampToValueAtTime(180, now + 0.025);
transientGain.gain.setValueAtTime(0.18, now);
transientGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.03);
transient.connect(transientGain);
transientGain.connect(context.destination);
transient.start(now);
transient.stop(now + 0.035);
}
export function playHiHat(context: AudioContext): void {
const now = context.currentTime;
const duration = 0.075;
const buffer = context.createBuffer(1, Math.ceil(context.sampleRate * duration), context.sampleRate);
const channel = buffer.getChannelData(0);
for (let index = 0; index < channel.length; index += 1) {
channel[index] = Math.random() * 2 - 1;
}
const source = context.createBufferSource();
const filter = context.createBiquadFilter();
const gain = context.createGain();
source.buffer = buffer;
filter.type = 'highpass';
filter.frequency.setValueAtTime(5500, now);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(0.38, now + 0.004);
gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);
source.connect(filter);
filter.connect(gain);
gain.connect(context.destination);
source.start(now);
source.stop(now + duration);
}
+9
View File
@@ -0,0 +1,9 @@
import type { SoundId } from '../domain/sounds';
import { playHiHat, playKick } from './instruments';
export type SoundVoice = (context: AudioContext) => void;
export const SOUND_VOICES: Record<SoundId, SoundVoice> = {
'hi-hat': playHiHat,
kick: playKick,
};
+117
View File
@@ -0,0 +1,117 @@
import { useMemo } from 'react';
import { IonButton, IonIcon } from '@ionic/react';
import { trash } from 'ionicons/icons';
import { BeatSelectionHint } from './BeatSelectionHint';
import { CircularTimeline } from './CircularTimeline';
import { SoundRingSelector } from './SoundRingSelector';
import { TempoControl } from './TempoControl';
import { TimeSignatureSelector } from './TimeSignatureSelector';
import { SOUND_BY_ID, SOUND_CATALOG } from '../domain/sounds';
import type { BeatSequencer } from '../hooks/useBeatSequencer';
import type { SoundPalette } from '../hooks/useSoundPalette';
interface BeatLoopPanelProps {
sequencer: BeatSequencer;
soundPalette: SoundPalette;
}
export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
const soundIdsInLoop = useMemo(() => {
const soundsInLoop = new Set(sequencer.beats.map((beat) => beat.soundId));
return SOUND_CATALOG
.filter((sound) => soundsInLoop.has(sound.id))
.map((sound) => sound.id);
}, [sequencer.beats]);
const legendSounds = useMemo(() => {
const soundsInLoop = new Set(soundIdsInLoop);
return soundPalette.activeSounds.filter((sound) => soundsInLoop.has(sound.id));
}, [soundPalette.activeSounds, soundIdsInLoop]);
const focusedRingSoundId = sequencer.focusedSoundId
&& soundIdsInLoop.includes(sequencer.focusedSoundId)
? sequencer.focusedSoundId
: null;
const hasDeleteTarget = Boolean(sequencer.selectedBeat || focusedRingSoundId);
const deleteLabel = sequencer.selectedBeat
? `Remove ${SOUND_BY_ID[sequencer.selectedBeat.soundId].label}`
: focusedRingSoundId
? `Remove ${SOUND_BY_ID[focusedRingSoundId].label} ring`
: 'Remove sound';
return (
<>
<section className="orbit-card" aria-label="Beat loop">
<div className="orbit-card-heading">
<TimeSignatureSelector
beatsPerBar={sequencer.beatsPerBar}
onChange={sequencer.setBeatsPerBar}
/>
<SoundRingSelector
soundIds={soundIdsInLoop}
focusedSoundId={sequencer.focusedSoundId}
colorBySoundId={soundPalette.colorBySoundId}
onSelectSound={sequencer.selectSound}
/>
</div>
<div className="timeline-wrap">
<CircularTimeline
beats={sequencer.beats}
soundIds={soundIdsInLoop}
colorBySoundId={soundPalette.colorBySoundId}
currentStep={sequencer.currentStep}
totalSteps={sequencer.totalSteps}
focusedSoundId={sequencer.focusedSoundId}
selectedBeatId={sequencer.selectedBeat?.id ?? null}
onMoveBeat={sequencer.moveBeat}
onSelectBeat={sequencer.selectBeat}
onSelectSound={sequencer.selectSound}
/>
</div>
<div className="timeline-hint-row">
<div className="timeline-hint-tempo">
<TempoControl
tempoBpm={sequencer.tempoBpm}
onTempoChange={sequencer.setTempoBpm}
/>
</div>
<BeatSelectionHint
selectedBeat={sequencer.selectedBeat}
focusedSoundId={focusedRingSoundId}
colorBySoundId={soundPalette.colorBySoundId}
totalSteps={sequencer.totalSteps}
/>
<div className="timeline-hint-actions">
{hasDeleteTarget ? (
<IonButton
className="timeline-delete-button"
fill="clear"
aria-label={deleteLabel}
onClick={sequencer.selectedBeat
? sequencer.removeSelectedBeat
: sequencer.removeFocusedSound}
>
<IonIcon icon={trash} />
</IonButton>
) : (
<span className="timeline-delete-placeholder" aria-hidden="true" />
)}
</div>
</div>
</section>
<div className="sound-legend" aria-label="Sounds in this loop" aria-live="polite">
{legendSounds.length > 0 ? (
legendSounds.map((activeSound) => (
<span className="legend-sound" key={activeSound.id}>
<span className="legend-swatch" style={{ backgroundColor: activeSound.color }} />
{SOUND_BY_ID[activeSound.id].label}
</span>
))
) : (
<span className="legend-empty">Your added sounds will appear here.</span>
)}
</div>
</>
);
}
+39
View File
@@ -0,0 +1,39 @@
import { memo } from 'react';
import { getLoopPositionPercent } from '../domain/timeline';
import { SOUND_BY_ID } from '../domain/sounds';
import type { BeatPoint } from '../domain/sequencer';
import type { SoundId } from '../domain/sounds';
interface BeatSelectionHintProps {
selectedBeat: BeatPoint | undefined;
focusedSoundId: SoundId | null;
colorBySoundId: Partial<Record<SoundId, string>>;
totalSteps: number;
}
export const BeatSelectionHint = memo(function BeatSelectionHint({
selectedBeat,
focusedSoundId,
colorBySoundId,
totalSteps,
}: BeatSelectionHintProps) {
const soundId = selectedBeat?.soundId ?? focusedSoundId;
if (!soundId) return <p className="timeline-hint" aria-live="polite" />;
return (
<p className="timeline-hint" aria-live="polite">
<span
className="hint-swatch"
style={{ backgroundColor: colorBySoundId[soundId] }}
/>
{SOUND_BY_ID[soundId].label}
{selectedBeat && (
<>
<span className="hint-separator">·</span>
Step {getLoopPositionPercent(selectedBeat.step, totalSteps)}% selected
</>
)}
{!selectedBeat && ' ring selected'}
</p>
);
});
+74
View File
@@ -0,0 +1,74 @@
import { memo, useState } from 'react';
import { IonButton, IonIcon, IonPopover } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { BEAT_TEMPLATES } from '../domain/beatTemplates';
import type { BeatTemplate, BeatTemplateId } from '../domain/beatTemplates';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface BeatTemplateSelectorProps {
onSelectTemplate: (template: BeatTemplate) => void;
}
export const BeatTemplateSelector = memo(function BeatTemplateSelector({
onSelectTemplate,
}: BeatTemplateSelectorProps) {
const popover = usePopoverDisclosure();
const [selectedTemplateId, setSelectedTemplateId] = useState<BeatTemplateId>(BEAT_TEMPLATES[0].id);
const selectedTemplate = BEAT_TEMPLATES.find((template) => template.id === selectedTemplateId);
function selectTemplate(template: BeatTemplate): void {
setSelectedTemplateId(template.id);
onSelectTemplate(template);
}
return (
<div className="beat-template-selector">
<IonButton
id="beat-template-trigger"
className="beat-template-trigger"
fill="solid"
aria-label={`Dance template: ${selectedTemplate?.label ?? 'Select a template'}`}
aria-haspopup="dialog"
aria-expanded={popover.isOpen}
>
<span className="beat-template-trigger-content">
<span>{selectedTemplate?.label ?? 'Dance templates'}</span>
<IonIcon icon={chevronDown} />
</span>
</IonButton>
<IonPopover
className="beat-template-popover"
trigger="beat-template-trigger"
triggerAction="click"
side="bottom"
alignment="center"
dismissOnSelect
onDidPresent={popover.onDidPresent}
onDidDismiss={popover.onDidDismiss}
>
<div className="beat-template-options" role="group" aria-label="Dance templates">
{BEAT_TEMPLATES.map((template) => (
<IonButton
key={template.id}
className="beat-template-option"
fill={template.id === selectedTemplateId ? 'solid' : 'clear'}
aria-pressed={template.id === selectedTemplateId}
onClick={() => selectTemplate(template)}
>
<span className="beat-template-option-content">
<span className="beat-template-option-copy">
<span className="beat-template-option-label">{template.label}</span>
<span className="beat-template-option-description">{template.description}</span>
</span>
<span className="beat-template-option-meta">
{template.beatsPerBar}/4 · {template.tempoBpm} BPM
</span>
</span>
</IonButton>
))}
</div>
</IonPopover>
</div>
);
});
+218
View File
@@ -0,0 +1,218 @@
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 { SOUND_BY_ID } from '../domain/sounds';
import type { SoundId } from '../domain/sounds';
interface CircularTimelineProps {
beats: BeatPoint[];
soundIds: readonly SoundId[];
colorBySoundId: Partial<Record<SoundId, string>>;
currentStep: number;
totalSteps: number;
focusedSoundId: SoundId | null;
selectedBeatId: string | null;
onMoveBeat: (beatId: string, step: number) => void;
onSelectBeat: (beatId: string) => void;
onSelectSound: (soundId: SoundId) => 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: SoundId): 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 a separate orbit per sound. Drag sound points to move them.`}
onPointerMove={handlePointerMove}
onPointerUp={() => { draggingBeatIdRef.current = null; }}
onPointerCancel={() => { draggingBeatIdRef.current = null; }}
>
{orderedSoundIds.map((soundId, soundIndex) => (
<circle
key={soundId}
cx={SVG_CENTER}
cy={SVG_CENTER}
r={getSoundOrbitRadius(soundIndex, orderedSoundIds.length)}
className={`timeline-orbit${soundId === activeSoundId ? ' is-focused' : ''}`}
style={{
stroke: colorBySoundId[soundId] ?? '#b8b4e0',
opacity: soundId === activeSoundId ? 0.55 : 0.32,
strokeWidth: soundId === activeSoundId ? 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 ${SOUND_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 sound = SOUND_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={`${sound.label}, ${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" />
</g>
);
})}
</svg>
);
}
+82
View File
@@ -0,0 +1,82 @@
import { memo } from 'react';
import { IonButton, IonIcon, IonPopover } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { SOUND_BY_ID } from '../domain/sounds';
import type { SoundId } from '../domain/sounds';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface SoundRingSelectorProps {
soundIds: SoundId[];
focusedSoundId: SoundId | null;
colorBySoundId: Partial<Record<SoundId, string>>;
onSelectSound: (soundId: SoundId) => void;
}
export const SoundRingSelector = memo(function SoundRingSelector({
soundIds,
focusedSoundId,
colorBySoundId,
onSelectSound,
}: SoundRingSelectorProps) {
const popover = usePopoverDisclosure();
const focusedSound = focusedSoundId ? SOUND_BY_ID[focusedSoundId] : undefined;
return (
<>
<IonButton
id="sound-ring-selector-trigger"
className="sound-ring-selector-trigger"
fill="clear"
disabled={soundIds.length === 0}
aria-label={focusedSound ? `Selected ring: ${focusedSound.label}` : 'Select a sound ring'}
aria-haspopup="dialog"
aria-expanded={popover.isOpen}
>
<span className="sound-ring-trigger-content">
{focusedSoundId && (
<span
className="ring-selector-swatch"
style={{ backgroundColor: colorBySoundId[focusedSoundId] ?? '#b8b4e0' }}
/>
)}
<span>{focusedSound ? `${focusedSound.label} ring` : 'Sound rings'}</span>
<IonIcon icon={chevronDown} />
</span>
</IonButton>
<IonPopover
className="sound-ring-popover"
trigger="sound-ring-selector-trigger"
triggerAction="click"
side="bottom"
alignment="end"
dismissOnSelect
onDidPresent={popover.onDidPresent}
onDidDismiss={popover.onDidDismiss}
>
<div className="sound-ring-options" role="group" aria-label="Sound rings">
{soundIds.map((soundId) => {
const selected = soundId === focusedSoundId;
return (
<IonButton
key={soundId}
className="sound-ring-option"
fill={selected ? 'solid' : 'clear'}
aria-pressed={selected}
onClick={() => onSelectSound(soundId)}
>
<span className="sound-ring-option-content">
<span
className="ring-selector-swatch"
style={{ backgroundColor: colorBySoundId[soundId] ?? '#b8b4e0' }}
/>
<span>{SOUND_BY_ID[soundId].label} ring</span>
</span>
</IonButton>
);
})}
</div>
</IonPopover>
</>
);
});
+59
View File
@@ -0,0 +1,59 @@
import { memo } from 'react';
import { IonButton, IonIcon, IonPopover, IonRange } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { MAX_TEMPO_BPM, MIN_TEMPO_BPM } from '../domain/sequencer';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface TempoControlProps {
tempoBpm: number;
onTempoChange: (tempoBpm: number) => void;
}
export const TempoControl = memo(function TempoControl({ tempoBpm, onTempoChange }: TempoControlProps) {
const popover = usePopoverDisclosure();
return (
<>
<IonButton
id="main-tempo-control-trigger"
className="tempo-trigger"
fill="solid"
aria-label={`Change tempo, currently ${tempoBpm} BPM`}
aria-haspopup="dialog"
aria-expanded={popover.isOpen}
>
<span className="tempo-trigger-content">
<span>{tempoBpm} BPM</span>
<IonIcon icon={chevronDown} />
</span>
</IonButton>
<IonPopover
className="tempo-popover"
trigger="main-tempo-control-trigger"
triggerAction="click"
side="top"
alignment="start"
onDidPresent={popover.onDidPresent}
onDidDismiss={popover.onDidDismiss}
>
<div className="tempo-popover-content">
<output className="tempo-value" aria-live="polite">{tempoBpm} BPM</output>
<div className="tempo-range-track">
<IonRange
className="tempo-range"
aria-label="Tempo in beats per minute"
min={MIN_TEMPO_BPM}
max={MAX_TEMPO_BPM}
step={1}
value={tempoBpm}
onIonInput={(event) => {
if (typeof event.detail.value === 'number') onTempoChange(event.detail.value);
}}
/>
</div>
</div>
</IonPopover>
</>
);
});
+61
View File
@@ -0,0 +1,61 @@
import { memo } from 'react';
import { IonButton, IonIcon, IonPopover } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { BEATS_PER_BAR_OPTIONS } from '../domain/sequencer';
import type { BeatsPerBar } from '../domain/sequencer';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface TimeSignatureSelectorProps {
beatsPerBar: BeatsPerBar;
onChange: (beatsPerBar: BeatsPerBar) => void;
}
export const TimeSignatureSelector = memo(function TimeSignatureSelector({
beatsPerBar,
onChange,
}: TimeSignatureSelectorProps) {
const popover = usePopoverDisclosure();
return (
<>
<IonButton
id="time-signature-trigger"
className="meter-trigger"
fill="solid"
aria-label={`Change time signature, currently ${beatsPerBar}/4`}
aria-haspopup="dialog"
aria-expanded={popover.isOpen}
>
<span className="meter-trigger-content">
<span>Time signature {beatsPerBar}/4</span>
<IonIcon icon={chevronDown} />
</span>
</IonButton>
<IonPopover
className="meter-popover"
trigger="time-signature-trigger"
triggerAction="click"
side="bottom"
alignment="start"
dismissOnSelect
onDidPresent={popover.onDidPresent}
onDidDismiss={popover.onDidDismiss}
>
<div className="meter-popover-content" role="group" aria-label="Time signature">
{BEATS_PER_BAR_OPTIONS.map((option) => (
<IonButton
key={option}
className="meter-option"
fill={option === beatsPerBar ? 'solid' : 'clear'}
aria-pressed={option === beatsPerBar}
onClick={() => onChange(option)}
>
<span className="meter-option-content">{option}/4</span>
</IonButton>
))}
</div>
</IonPopover>
</>
);
});
+67
View File
@@ -0,0 +1,67 @@
import { memo } from 'react';
import {
IonFab,
IonButton,
IonFabButton,
IonFabList,
IonFooter,
IonIcon,
IonToolbar,
} from '@ionic/react';
import { add, musicalNotes, pause, play } from 'ionicons/icons';
import type { SoundId } from '../domain/sounds';
import { SOUND_CATALOG } from '../domain/sounds';
interface TransportBarProps {
isPlaying: boolean;
isStarting: boolean;
hasBeats: boolean;
onTogglePlayback: () => Promise<void>;
onAddSound: (soundId: SoundId) => void;
}
export const TransportBar = memo(function TransportBar({
isPlaying,
isStarting,
hasBeats,
onTogglePlayback,
onAddSound,
}: TransportBarProps) {
return (
<IonFooter className="transport-footer">
<IonToolbar className="transport-toolbar">
<div className="transport-inner">
<IonButton
className="transport-play-button"
onClick={() => void onTogglePlayback()}
disabled={isStarting || !hasBeats}
>
<IonIcon slot="start" icon={isPlaying ? pause : play} />
{isStarting ? 'Starting' : isPlaying ? 'Pause' : 'Play'}
</IonButton>
</div>
</IonToolbar>
<IonFab className="transport-fab">
<IonFabButton className="add-sound-fab" aria-label="Add a sound">
<IonIcon icon={add} />
</IonFabButton>
<IonFabList className="sound-fab-list" side="top">
{SOUND_CATALOG.map((sound) => (
<IonFabButton
className="sound-fab-option"
key={sound.id}
aria-label={`Add ${sound.label}`}
onClick={() => onAddSound(sound.id)}
>
<span className="sound-fab-option-content">
<IonIcon icon={musicalNotes} />
<span>{sound.label}</span>
</span>
</IonFabButton>
))}
</IonFabList>
</IonFab>
</IonFooter>
);
});
+54
View File
@@ -0,0 +1,54 @@
import { DEFAULT_BEATS_PER_BAR, TEMPO_BPM } from './sequencer';
import type { BeatsPerBar } from './sequencer';
import type { SoundId } from './sounds';
export interface TemplateBeat {
soundId: SoundId;
step: number;
}
export type BeatTemplateId = 'empty' | 'bachata' | 'salsa' | 'lindy-hop';
export interface BeatTemplate {
id: BeatTemplateId;
label: string;
description: string;
beatsPerBar: BeatsPerBar;
tempoBpm: number;
beats: readonly TemplateBeat[];
}
export const BEAT_TEMPLATES = [
{
id: 'empty',
label: 'Empty',
description: 'Clear the current loop.',
beatsPerBar: DEFAULT_BEATS_PER_BAR,
tempoBpm: TEMPO_BPM,
beats: [],
},
{
id: 'bachata',
label: 'Bachata',
description: 'Kick on beats 1, 2, 3, and 4.',
beatsPerBar: DEFAULT_BEATS_PER_BAR,
tempoBpm: 120,
beats: [0, 4, 8, 12].map((step) => ({ soundId: 'kick', step })),
},
{
id: 'salsa',
label: 'Salsa',
description: 'Kick on beats 1, 2, and 3.',
beatsPerBar: DEFAULT_BEATS_PER_BAR,
tempoBpm: 180,
beats: [0, 4, 8].map((step) => ({ soundId: 'kick', step })),
},
{
id: 'lindy-hop',
label: 'Lindy Hop',
description: 'Kick on beats 1–8.',
beatsPerBar: 8,
tempoBpm: 120,
beats: [0, 4, 8, 12, 16, 20, 24, 28].map((step) => ({ soundId: 'kick', step })),
},
] as const satisfies readonly BeatTemplate[];
+40
View File
@@ -0,0 +1,40 @@
import type { SoundId } from './sounds';
export const STEPS_PER_BEAT = 4;
export const PLAYBACK_SUBSTEPS_PER_STEP = 4;
export const DEFAULT_BEATS_PER_BAR = 4;
export const BEATS_PER_BAR_OPTIONS = [2, 3, 4, 5, 6, 7, 8] as const;
export type BeatsPerBar = (typeof BEATS_PER_BAR_OPTIONS)[number];
export const TOTAL_STEPS = DEFAULT_BEATS_PER_BAR * STEPS_PER_BEAT;
export const TEMPO_BPM = 112;
export const MIN_TEMPO_BPM = 60;
export const MAX_TEMPO_BPM = 180;
export function getTotalSteps(beatsPerBar: BeatsPerBar): number {
return beatsPerBar * STEPS_PER_BEAT;
}
export function clampTempoBpm(tempoBpm: number): number {
return Math.min(MAX_TEMPO_BPM, Math.max(MIN_TEMPO_BPM, Math.round(tempoBpm)));
}
export function getPlaybackTickDurationMs(tempoBpm: number): number {
return 60_000 / tempoBpm / STEPS_PER_BEAT / PLAYBACK_SUBSTEPS_PER_STEP;
}
export interface BeatPoint {
id: string;
soundId: SoundId;
/** Position in sixteenth-note steps; fractional values represent microtiming. */
step: number;
}
export function getNextAvailableStep(
beats: readonly BeatPoint[],
totalSteps = TOTAL_STEPS,
): number {
const occupiedSteps = new Set(beats.map((beat) => beat.step));
const nextStep = Array.from({ length: totalSteps }, (_, step) => step)
.find((step) => !occupiedSteps.has(step));
return nextStep ?? 0;
}
+117
View File
@@ -0,0 +1,117 @@
import { clampTempoBpm, DEFAULT_BEATS_PER_BAR, getTotalSteps, TEMPO_BPM } from './sequencer';
import type { BeatsPerBar, BeatPoint } from './sequencer';
import type { SoundId } from './sounds';
export interface SequencerState {
beats: BeatPoint[];
selectedBeatId: string | null;
focusedSoundId: SoundId | null;
tempoBpm: number;
beatsPerBar: BeatsPerBar;
}
export type SequencerAction =
| { type: 'beat-added'; beat: BeatPoint }
| { type: 'beat-moved'; beatId: string; step: number }
| { type: 'beat-selected'; beatId: string }
| { type: 'sound-selected'; soundId: SoundId }
| { type: 'selected-beat-removed' }
| { type: 'focused-sound-removed' }
| { type: 'tempo-changed'; tempoBpm: number }
| { type: 'time-signature-changed'; beatsPerBar: BeatsPerBar }
| { type: 'template-loaded'; beats: BeatPoint[]; tempoBpm: number; beatsPerBar: BeatsPerBar };
export function createInitialSequencerState(): SequencerState {
return {
beats: [],
selectedBeatId: null,
focusedSoundId: null,
tempoBpm: TEMPO_BPM,
beatsPerBar: DEFAULT_BEATS_PER_BAR,
};
}
function assertNever(action: never): never {
throw new Error(`Unhandled sequencer action: ${action}`);
}
export function sequencerReducer(state: SequencerState, action: SequencerAction): SequencerState {
switch (action.type) {
case 'beat-added':
return {
...state,
beats: [...state.beats, action.beat],
selectedBeatId: action.beat.id,
focusedSoundId: action.beat.soundId,
};
case 'beat-moved':
return {
...state,
beats: state.beats.map((beat) => (
beat.id === action.beatId ? { ...beat, step: action.step } : beat
)),
};
case 'beat-selected': {
const beat = state.beats.find((candidate) => candidate.id === action.beatId);
if (!beat) return state;
return { ...state, selectedBeatId: beat.id, focusedSoundId: beat.soundId };
}
case 'sound-selected':
return { ...state, focusedSoundId: action.soundId, selectedBeatId: null };
case 'selected-beat-removed': {
if (!state.selectedBeatId) return state;
const removedBeat = state.beats.find((beat) => beat.id === state.selectedBeatId);
if (!removedBeat) return { ...state, selectedBeatId: null };
const beats = state.beats.filter((beat) => beat.id !== removedBeat.id);
const soundRemains = beats.some((beat) => beat.soundId === removedBeat.soundId);
return {
...state,
beats,
selectedBeatId: null,
focusedSoundId: state.focusedSoundId === removedBeat.soundId && !soundRemains
? beats[0]?.soundId ?? null
: state.focusedSoundId,
};
}
case 'focused-sound-removed': {
if (!state.focusedSoundId) return state;
const beats = state.beats.filter((beat) => beat.soundId !== state.focusedSoundId);
return {
...state,
beats,
selectedBeatId: null,
focusedSoundId: beats[0]?.soundId ?? null,
};
}
case 'tempo-changed':
return { ...state, tempoBpm: clampTempoBpm(action.tempoBpm) };
case 'time-signature-changed': {
const totalSteps = getTotalSteps(action.beatsPerBar);
const visibleBeats = state.beats.filter((beat) => beat.step < totalSteps);
const selectedBeat = visibleBeats.find((beat) => beat.id === state.selectedBeatId);
const focusedSoundRemains = visibleBeats.some((beat) => beat.soundId === state.focusedSoundId);
return {
...state,
beatsPerBar: action.beatsPerBar,
selectedBeatId: selectedBeat?.id ?? null,
focusedSoundId: focusedSoundRemains
? state.focusedSoundId
: visibleBeats[0]?.soundId ?? null,
};
}
case 'template-loaded': {
const firstBeat = action.beats[0];
return {
...state,
beats: action.beats,
selectedBeatId: firstBeat?.id ?? null,
focusedSoundId: firstBeat?.soundId ?? null,
tempoBpm: clampTempoBpm(action.tempoBpm),
beatsPerBar: action.beatsPerBar,
};
}
default:
return assertNever(action);
}
}
+15
View File
@@ -0,0 +1,15 @@
const FIRST_HUE = 18;
const GOLDEN_ANGLE = 137.508;
const HUE_CYCLE = 360;
export function generateUniqueSoundColor(existingColors: readonly string[]): string {
const existing = new Set(existingColors);
for (let index = existingColors.length; index < existingColors.length + HUE_CYCLE; index += 1) {
const hue = ((FIRST_HUE + index * GOLDEN_ANGLE) % HUE_CYCLE).toFixed(2);
const color = `hsl(${hue} 76% 65%)`;
if (!existing.has(color)) return color;
}
throw new Error('Unable to generate a unique sound color.');
}
+10
View File
@@ -0,0 +1,10 @@
const SOUND_DEFINITIONS = {
'hi-hat': { id: 'hi-hat', label: 'Hi-hat', description: 'Bright tick' },
kick: { id: 'kick', label: 'Kick', description: 'Low pulse' },
} as const;
export type SoundId = keyof typeof SOUND_DEFINITIONS;
export type SoundDefinition = (typeof SOUND_DEFINITIONS)[SoundId];
export const SOUND_BY_ID: Record<SoundId, SoundDefinition> = SOUND_DEFINITIONS;
export const SOUND_CATALOG: readonly SoundDefinition[] = Object.values(SOUND_DEFINITIONS);
+74
View File
@@ -0,0 +1,74 @@
import type { BeatPoint } from './sequencer';
import {
PLAYBACK_SUBSTEPS_PER_STEP,
TOTAL_STEPS,
} from './sequencer';
export const SVG_SIZE = 600;
export const SVG_CENTER = SVG_SIZE / 2;
export const ORBIT_RADIUS = 216;
const MARKER_STEP_OFFSET = 0.3;
export interface CirclePoint {
x: number;
y: number;
}
export function getStepFromPosition(
x: number,
y: number,
center = SVG_CENTER,
totalSteps = TOTAL_STEPS,
): number {
const angle = Math.atan2(y - center, x - center) + Math.PI / 2;
const normalizedAngle = (angle + Math.PI * 2) % (Math.PI * 2);
return (normalizedAngle / (Math.PI * 2)) * totalSteps;
}
export function getPointForStep(
step: number,
radius: number,
center = SVG_CENTER,
totalSteps = TOTAL_STEPS,
): CirclePoint {
const angle = (step / totalSteps) * Math.PI * 2 - Math.PI / 2;
return {
x: center + Math.cos(angle) * radius,
y: center + Math.sin(angle) * radius,
};
}
export function getLoopPositionPercent(step: number, totalSteps: number): number {
return Math.round((step / totalSteps) * 100);
}
export function wrapStepPosition(step: number, totalSteps: number): number {
return ((step % totalSteps) + totalSteps) % totalSteps;
}
export function getSoundOrbitRadius(soundIndex: number, soundCount: number): number {
return ORBIT_RADIUS * (soundCount + 1 - soundIndex) / (soundCount + 1);
}
export function getPlaybackTick(step: number, totalSteps: number): number {
const totalPlaybackTicks = totalSteps * PLAYBACK_SUBSTEPS_PER_STEP;
return Math.round(step * PLAYBACK_SUBSTEPS_PER_STEP) % totalPlaybackTicks;
}
export function getStackedPosition(
beat: BeatPoint,
beats: readonly BeatPoint[],
totalSteps: number,
orbitRadius: number,
): CirclePoint {
const siblings = beats
.filter((candidate) => (
candidate.soundId === beat.soundId
&& getPlaybackTick(candidate.step, totalSteps) === getPlaybackTick(beat.step, totalSteps)
))
.sort((first, second) => first.id.localeCompare(second.id));
const index = siblings.findIndex((candidate) => candidate.id === beat.id);
const offset = (index - (siblings.length - 1) / 2) * MARKER_STEP_OFFSET;
return getPointForStep(beat.step + offset, orbitRadius, SVG_CENTER, totalSteps);
}
+124
View File
@@ -0,0 +1,124 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { AudioEngine } from '../audio/AudioEngine';
import {
getPlaybackTickDurationMs,
PLAYBACK_SUBSTEPS_PER_STEP,
} from '../domain/sequencer';
import type { BeatPoint } from '../domain/sequencer';
interface UseBeatPlaybackOptions {
beats: readonly BeatPoint[];
tempoBpm: number;
totalSteps: number;
}
export interface BeatPlayback {
currentStep: number;
isPlaying: boolean;
isStarting: boolean;
audioError: string | null;
togglePlayback: () => Promise<void>;
resetPlayback: () => void;
}
export function useBeatPlayback({
beats,
tempoBpm,
totalSteps,
}: UseBeatPlaybackOptions): BeatPlayback {
const [currentStep, setCurrentStep] = useState(-1);
const [isPlaying, setIsPlaying] = useState(false);
const [isStarting, setIsStarting] = useState(false);
const [audioError, setAudioError] = useState<string | null>(null);
const audioEngineRef = useRef<AudioEngine | null>(null);
const beatsRef = useRef(beats);
const totalStepsRef = useRef(totalSteps);
const nextPlaybackTickRef = useRef(0);
if (audioEngineRef.current === null) audioEngineRef.current = new AudioEngine();
beatsRef.current = beats;
totalStepsRef.current = totalSteps;
const advanceStep = useCallback(() => {
const totalPlaybackTicks = totalStepsRef.current * PLAYBACK_SUBSTEPS_PER_STEP;
const playbackTick = nextPlaybackTickRef.current % totalPlaybackTicks;
const step = playbackTick / PLAYBACK_SUBSTEPS_PER_STEP;
setCurrentStep(step);
beatsRef.current.forEach((beat) => {
if (beat.step >= totalStepsRef.current) return;
const beatTick = Math.round(beat.step * PLAYBACK_SUBSTEPS_PER_STEP) % totalPlaybackTicks;
if (beatTick === playbackTick) audioEngineRef.current?.play(beat.soundId);
});
nextPlaybackTickRef.current = (playbackTick + 1) % totalPlaybackTicks;
}, []);
useEffect(() => {
if (!isPlaying) {
setCurrentStep(-1);
nextPlaybackTickRef.current = 0;
return;
}
advanceStep();
}, [isPlaying, advanceStep]);
useEffect(() => {
if (!isPlaying) return undefined;
const interval = window.setInterval(
advanceStep,
getPlaybackTickDurationMs(tempoBpm),
);
return () => window.clearInterval(interval);
}, [isPlaying, tempoBpm, advanceStep]);
useEffect(() => {
if (beats.length === 0 && isPlaying) setIsPlaying(false);
}, [beats.length, isPlaying]);
useEffect(() => {
nextPlaybackTickRef.current %= totalSteps * PLAYBACK_SUBSTEPS_PER_STEP;
setCurrentStep((step) => (step >= totalSteps ? step % totalSteps : step));
}, [totalSteps]);
useEffect(() => () => {
void audioEngineRef.current?.dispose();
}, []);
const togglePlayback = useCallback(async () => {
if (isPlaying) {
setIsPlaying(false);
return;
}
if (beats.length === 0 || isStarting) return;
setIsStarting(true);
setAudioError(null);
try {
await audioEngineRef.current?.start();
setIsPlaying(true);
} catch {
setAudioError('Audio could not start. Check your browser audio settings and try again.');
} finally {
setIsStarting(false);
}
}, [beats.length, isPlaying, isStarting]);
const resetPlayback = useCallback(() => {
nextPlaybackTickRef.current = 0;
setCurrentStep(-1);
setAudioError(null);
}, []);
return {
currentStep,
isPlaying,
isStarting,
audioError,
togglePlayback,
resetPlayback,
};
}
+137
View File
@@ -0,0 +1,137 @@
import { useCallback, useMemo, useReducer, useRef } from 'react';
import type { BeatTemplate } from '../domain/beatTemplates';
import {
getNextAvailableStep,
getTotalSteps,
} from '../domain/sequencer';
import type { BeatsPerBar } from '../domain/sequencer';
import type { BeatPoint } from '../domain/sequencer';
import type { SoundId } from '../domain/sounds';
import { createInitialSequencerState, sequencerReducer } from '../domain/sequencerReducer';
import { useBeatPlayback } from './useBeatPlayback';
export interface BeatSequencer {
beats: BeatPoint[];
currentStep: number;
isPlaying: boolean;
isStarting: boolean;
audioError: string | null;
tempoBpm: number;
beatsPerBar: BeatsPerBar;
totalSteps: number;
focusedSoundId: SoundId | null;
selectedBeat: BeatPoint | undefined;
addBeat: (soundId: SoundId) => void;
moveBeat: (beatId: string, step: number) => void;
selectBeat: (beatId: string) => void;
selectSound: (soundId: SoundId) => void;
removeSelectedBeat: () => void;
removeFocusedSound: () => void;
setTempoBpm: (tempoBpm: number) => void;
setBeatsPerBar: (beatsPerBar: BeatsPerBar) => void;
loadTemplate: (template: BeatTemplate) => void;
togglePlayback: () => Promise<void>;
}
export function useBeatSequencer(): BeatSequencer {
const [state, dispatch] = useReducer(
sequencerReducer,
undefined,
createInitialSequencerState,
);
const { beats, beatsPerBar, focusedSoundId, selectedBeatId, tempoBpm } = state;
const totalSteps = getTotalSteps(beatsPerBar);
const nextBeatIdRef = useRef(1);
const visibleBeats = useMemo(
() => beats.filter((beat) => beat.step < totalSteps),
[beats, totalSteps],
);
const selectedBeat = useMemo(
() => visibleBeats.find((beat) => beat.id === selectedBeatId),
[selectedBeatId, visibleBeats],
);
const playback = useBeatPlayback({ beats: visibleBeats, tempoBpm, totalSteps });
const resetPlayback = playback.resetPlayback;
const addBeat = useCallback((soundId: SoundId): void => {
const beat: BeatPoint = {
id: `beat-${nextBeatIdRef.current}`,
soundId,
step: getNextAvailableStep(beats, totalSteps),
};
nextBeatIdRef.current += 1;
dispatch({ type: 'beat-added', beat });
}, [beats, totalSteps]);
const moveBeat = useCallback((beatId: string, step: number): void => {
dispatch({ type: 'beat-moved', beatId, step });
}, []);
const selectBeat = useCallback((beatId: string): void => {
dispatch({ type: 'beat-selected', beatId });
}, []);
const selectSound = useCallback((soundId: SoundId): void => {
dispatch({ type: 'sound-selected', soundId });
}, []);
const removeSelectedBeat = useCallback((): void => {
dispatch({ type: 'selected-beat-removed' });
}, []);
const removeFocusedSound = useCallback((): void => {
dispatch({ type: 'focused-sound-removed' });
}, []);
const setTempoBpm = useCallback((tempo: number): void => {
dispatch({ type: 'tempo-changed', tempoBpm: tempo });
}, []);
const setBeatsPerBar = useCallback((nextBeatsPerBar: BeatsPerBar): void => {
dispatch({ type: 'time-signature-changed', beatsPerBar: nextBeatsPerBar });
}, []);
const loadTemplate = useCallback((template: BeatTemplate): void => {
const templateBeats: BeatPoint[] = template.beats.map((templateBeat) => {
const beat: BeatPoint = {
id: `beat-${nextBeatIdRef.current}`,
...templateBeat,
};
nextBeatIdRef.current += 1;
return beat;
});
dispatch({
type: 'template-loaded',
beats: templateBeats,
tempoBpm: template.tempoBpm,
beatsPerBar: template.beatsPerBar,
});
resetPlayback();
}, [resetPlayback]);
return {
beats: visibleBeats,
currentStep: playback.currentStep,
isPlaying: playback.isPlaying,
isStarting: playback.isStarting,
audioError: playback.audioError,
tempoBpm,
beatsPerBar,
totalSteps,
focusedSoundId,
selectedBeat,
addBeat,
moveBeat,
selectBeat,
selectSound,
removeSelectedBeat,
removeFocusedSound,
setTempoBpm,
setBeatsPerBar,
loadTemplate,
togglePlayback: playback.togglePlayback,
};
}
+33
View File
@@ -0,0 +1,33 @@
import { useCallback } from 'react';
import type { BeatTemplate } from '../domain/beatTemplates';
import type { SoundId } from '../domain/sounds';
import type { BeatSequencer } from './useBeatSequencer';
import { useBeatSequencer } from './useBeatSequencer';
import type { SoundPalette } from './useSoundPalette';
import { useSoundPalette } from './useSoundPalette';
export interface BeatStudio {
sequencer: BeatSequencer;
soundPalette: SoundPalette;
addSound: (soundId: SoundId) => void;
applyTemplate: (template: BeatTemplate) => void;
}
export function useBeatStudio(): BeatStudio {
const sequencer = useBeatSequencer();
const soundPalette = useSoundPalette();
const { addBeat, loadTemplate } = sequencer;
const { activateSounds } = soundPalette;
const addSound = useCallback((soundId: SoundId): void => {
activateSounds([soundId]);
addBeat(soundId);
}, [activateSounds, addBeat]);
const applyTemplate = useCallback((template: BeatTemplate): void => {
loadTemplate(template);
activateSounds(template.beats.map((beat) => beat.soundId));
}, [activateSounds, loadTemplate]);
return { sequencer, soundPalette, addSound, applyTemplate };
}
+16
View File
@@ -0,0 +1,16 @@
import { useCallback, useState } from 'react';
export interface PopoverDisclosure {
isOpen: boolean;
onDidPresent: () => void;
onDidDismiss: () => void;
}
export function usePopoverDisclosure(): PopoverDisclosure {
const [isOpen, setIsOpen] = useState(false);
const onDidPresent = useCallback(() => setIsOpen(true), []);
const onDidDismiss = useCallback(() => setIsOpen(false), []);
return { isOpen, onDidPresent, onDidDismiss };
}
+44
View File
@@ -0,0 +1,44 @@
import { useCallback, useMemo, useState } from 'react';
import type { SoundId } from '../domain/sounds';
import { generateUniqueSoundColor } from '../domain/soundColors';
export interface PaletteSound {
id: SoundId;
color: string;
}
export interface SoundPalette {
activeSounds: PaletteSound[];
colorBySoundId: Partial<Record<SoundId, string>>;
activateSounds: (soundIds: readonly SoundId[]) => void;
}
export function useSoundPalette(): SoundPalette {
const [activeSounds, setActiveSounds] = useState<PaletteSound[]>([]);
const activateSounds = useCallback((soundIds: readonly SoundId[]): void => {
setActiveSounds((currentSounds) => {
const nextSounds = [...currentSounds];
const currentCount = nextSounds.length;
soundIds.forEach((soundId) => {
if (nextSounds.some((sound) => sound.id === soundId)) return;
nextSounds.push({
id: soundId,
color: generateUniqueSoundColor(nextSounds.map((sound) => sound.color)),
});
});
return nextSounds.length === currentCount ? currentSounds : nextSounds;
});
}, []);
const colorBySoundId = useMemo(() => {
const colors: Partial<Record<SoundId, string>> = {};
activeSounds.forEach((sound) => {
colors[sound.id] = sound.color;
});
return colors;
}, [activeSounds]);
return { activeSounds, colorBySoundId, activateSounds };
}
+8
View File
@@ -0,0 +1,8 @@
declare module 'ionicons/icons' {
export const add: string;
export const chevronDown: string;
export const musicalNotes: string;
export const pause: string;
export const play: string;
export const trash: string;
}
+24
View File
@@ -0,0 +1,24 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { setupIonicReact } from '@ionic/react';
import App from './App';
import '@ionic/react/css/core.css';
import '@ionic/react/css/normalize.css';
import '@ionic/react/css/structure.css';
import '@ionic/react/css/typography.css';
import '@ionic/react/css/padding.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';
import './styles.css';
setupIonicReact();
const rootElement = document.getElementById('root');
if (!rootElement) throw new Error('The app root element was not found.');
createRoot(rootElement).render(
<StrictMode>
<App />
</StrictMode>,
);
+197
View File
@@ -0,0 +1,197 @@
import { describe, expect, it } from 'vitest';
import { BEAT_TEMPLATES } from './sequencer';
import {
createInitialSequencerState,
sequencerReducer,
} from './domain/sequencerReducer';
import { generateUniqueSoundColor } from './domain/soundColors';
import {
getNextAvailableStep,
getPlaybackTickDurationMs,
getLoopPositionPercent,
getPointForStep,
getStepFromPosition,
getTotalSteps,
MAX_TEMPO_BPM,
MIN_TEMPO_BPM,
SVG_CENTER,
wrapStepPosition,
TOTAL_STEPS,
TEMPO_BPM,
} from './sequencer';
import type { BeatPoint } from './sequencer';
describe('circular step positions', () => {
it('derives playback timing from tempo and fine-grained subdivisions', () => {
expect(getPlaybackTickDurationMs(120)).toBeCloseTo(60_000 / 120 / 16, 8);
});
it('maps each of the 16 points back to its step', () => {
for (let step = 0; step < TOTAL_STEPS; step += 1) {
const point = getPointForStep(step, 180);
expect(getStepFromPosition(point.x, point.y)).toBeCloseTo(step, 8);
}
});
it('wraps points just before the first step to the end of the loop', () => {
const point = getPointForStep(TOTAL_STEPS - 1, 180);
expect(getStepFromPosition(point.x, point.y)).toBeCloseTo(TOTAL_STEPS - 1, 8);
});
it('maps all steps around a three-beat bar', () => {
const totalSteps = getTotalSteps(3);
for (let step = 0; step < totalSteps; step += 1) {
const point = getPointForStep(step, 180, SVG_CENTER, totalSteps);
expect(getStepFromPosition(point.x, point.y, SVG_CENTER, totalSteps)).toBeCloseTo(step, 8);
}
});
it('maps all steps around an eight-beat bar', () => {
const totalSteps = getTotalSteps(8);
for (let step = 0; step < totalSteps; step += 1) {
const point = getPointForStep(step, 180, SVG_CENTER, totalSteps);
expect(getStepFromPosition(point.x, point.y, SVG_CENTER, totalSteps)).toBeCloseTo(step, 8);
}
});
it('preserves fractional positions between the regular steps', () => {
const fractionalStep = 3.375;
const point = getPointForStep(fractionalStep, 180);
expect(getStepFromPosition(point.x, point.y)).toBeCloseTo(fractionalStep, 8);
});
it('wraps fractional positions and reports loop percentages', () => {
expect(wrapStepPosition(16.25, 16)).toBeCloseTo(0.25);
expect(wrapStepPosition(-0.25, 16)).toBeCloseTo(15.75);
expect(getLoopPositionPercent(4, 16)).toBe(25);
});
it('adds a sound at the next empty step', () => {
const beats: BeatPoint[] = [
{ id: 'first', soundId: 'kick', step: 0 },
{ id: 'second', soundId: 'hi-hat', step: 1 },
];
expect(getNextAvailableStep(beats)).toBe(2);
});
it('reuses the first step when every step is occupied', () => {
const beats: BeatPoint[] = Array.from({ length: TOTAL_STEPS }, (_, step) => ({
id: `beat-${step}`,
soundId: 'kick',
step,
}));
expect(getNextAvailableStep(beats)).toBe(0);
});
it('reuses the first step when a three-beat bar is full', () => {
const totalSteps = getTotalSteps(3);
const beats: BeatPoint[] = Array.from({ length: totalSteps }, (_, step) => ({
id: `beat-${step}`,
soundId: 'kick',
step,
}));
expect(getNextAvailableStep(beats, totalSteps)).toBe(0);
});
});
describe('sound colors', () => {
it('generates a distinct color for each added sound', () => {
const colors: string[] = [];
for (let soundIndex = 0; soundIndex < 8; soundIndex += 1) {
const color = generateUniqueSoundColor(colors);
expect(colors).not.toContain(color);
colors.push(color);
}
});
});
describe('sequencer state transitions', () => {
it('loads a template with a focused first beat and removes a focused sound ring', () => {
const templateBeats: BeatPoint[] = [
{ id: 'kick-1', soundId: 'kick', step: 0 },
{ id: 'kick-2', soundId: 'kick', step: 4 },
{ id: 'hat-1', soundId: 'hi-hat', step: 8 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
beats: templateBeats,
tempoBpm: 120,
beatsPerBar: 4,
});
expect(loaded.selectedBeatId).toBe('kick-1');
expect(loaded.focusedSoundId).toBe('kick');
const afterRingRemoval = sequencerReducer(loaded, { type: 'focused-sound-removed' });
expect(afterRingRemoval.beats).toEqual([templateBeats[2]]);
expect(afterRingRemoval.selectedBeatId).toBeNull();
expect(afterRingRemoval.focusedSoundId).toBe('hi-hat');
});
it('clears out-of-range selections when the time signature gets shorter', () => {
const beats: BeatPoint[] = [
{ id: 'hat-1', soundId: 'hi-hat', step: 0 },
{ id: 'kick-1', soundId: 'kick', step: 12 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
beats,
tempoBpm: 120,
beatsPerBar: 4,
});
const selected = sequencerReducer(loaded, { type: 'beat-selected', beatId: 'kick-1' });
const shortened = sequencerReducer(selected, {
type: 'time-signature-changed',
beatsPerBar: 2,
});
expect(shortened.beats).toEqual(beats);
expect(shortened.selectedBeatId).toBeNull();
expect(shortened.focusedSoundId).toBe('hi-hat');
});
it('removes a focused sound and keeps the remaining ring selected', () => {
const beats: BeatPoint[] = [
{ id: 'kick-1', soundId: 'kick', step: 0 },
{ id: 'hat-1', soundId: 'hi-hat', step: 4 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
beats,
tempoBpm: TEMPO_BPM,
beatsPerBar: 4,
});
const hatSelected = sequencerReducer(loaded, { type: 'sound-selected', soundId: 'hi-hat' });
const removed = sequencerReducer(hatSelected, { type: 'focused-sound-removed' });
expect(removed.beats).toEqual([beats[0]]);
expect(removed.focusedSoundId).toBe('kick');
expect(removed.selectedBeatId).toBeNull();
});
it('clamps tempo changes to the supported range', () => {
const initial = createInitialSequencerState();
const tooSlow = sequencerReducer(initial, { type: 'tempo-changed', tempoBpm: 10 });
const tooFast = sequencerReducer(initial, { type: 'tempo-changed', tempoBpm: 300 });
expect(tooSlow.tempoBpm).toBe(MIN_TEMPO_BPM);
expect(tooFast.tempoBpm).toBe(MAX_TEMPO_BPM);
});
});
describe('dance templates', () => {
it('keeps each beat inside its template time signature', () => {
BEAT_TEMPLATES.forEach((template) => {
const totalSteps = getTotalSteps(template.beatsPerBar);
expect(template.tempoBpm).toBeGreaterThanOrEqual(MIN_TEMPO_BPM);
expect(template.tempoBpm).toBeLessThanOrEqual(MAX_TEMPO_BPM);
template.beats.forEach((beat) => {
expect(beat.step).toBeGreaterThanOrEqual(0);
expect(beat.step).toBeLessThan(totalSteps);
});
});
});
});
+3
View File
@@ -0,0 +1,3 @@
export * from './domain/beatTemplates';
export * from './domain/sequencer';
export * from './domain/timeline';
+968
View File
@@ -0,0 +1,968 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');
/* Theme tokens and document defaults */
:root {
font-family: 'DM Sans', sans-serif;
color: var(--ink);
background: var(--base);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
color-scheme: dark;
--ion-color-primary: #edebff;
--ion-color-primary-rgb: 237, 235, 255;
--ion-color-primary-contrast: #111116;
--ion-color-primary-contrast-rgb: 17, 17, 22;
--ion-color-primary-shade: #d1cfe0;
--ion-color-primary-tint: #efedff;
--ion-color-secondary: #ff8a3d;
--ion-color-secondary-rgb: 255, 138, 61;
--ion-color-secondary-contrast: #111116;
--ion-color-secondary-contrast-rgb: 17, 17, 22;
--ion-color-secondary-shade: #e07936;
--ion-color-secondary-tint: #ff9650;
--ion-color-medium: #b8b4e0;
--ion-color-medium-rgb: 184, 180, 224;
--ion-color-medium-contrast: #111116;
--ion-color-medium-contrast-rgb: 17, 17, 22;
--ion-color-medium-shade: #a29ec5;
--ion-color-medium-tint: #c2bfe4;
--ion-background-color: #111116;
--ion-background-color-rgb: 17, 17, 22;
--ion-text-color: #edebff;
--ion-text-color-rgb: 237, 235, 255;
--base: #111116;
--surface: #1a1a21;
--surface-raised: #23232b;
--border: #302f38;
--ink: #f4f1ed;
--muted: #b8b4e0;
--soft: #9e9acb;
--accent: #ff8a3d;
--accent-hover: #ff9b5c;
--accent-pressed: #e07936;
--primary-rgb: 244, 241, 237;
--accent-rgb: 255, 138, 61;
--mono: 'DM Mono', monospace;
--display: 'Space Grotesk', sans-serif;
}
* {
box-sizing: border-box;
}
html,
body,
ion-app,
ion-page {
min-width: 320px;
min-height: 100%;
margin: 0;
background: var(--base);
}
body {
font-family: 'DM Sans', sans-serif;
}
ion-content.app-content {
--background: var(--base);
color: var(--ink);
}
/* Application shell and studio heading */
.app-shell {
min-height: 100%;
padding: 0 24px 32px;
background: var(--base);
}
.app-header {
display: flex;
width: min(100%, 900px);
height: 76px;
align-items: center;
justify-content: space-between;
margin: 0 auto;
border-bottom: 1px solid rgba(var(--primary-rgb), 0.1);
}
.brand {
display: inline-flex;
align-items: center;
text-decoration: none;
}
.brand-logo {
display: block;
width: 156px;
max-height: 42px;
object-fit: contain;
}
.orbit-card-heading {
font-family: var(--mono);
font-size: 9px;
font-weight: 500;
letter-spacing: 1px;
}
.header-tag {
color: var(--soft);
font-family: 'DM Sans', sans-serif;
font-size: 12px;
font-weight: 500;
letter-spacing: 0.1px;
}
.studio {
width: min(100%, 660px);
margin: 0 auto;
padding-bottom: 24px;
}
.studio-heading {
padding: 37px 0 10px;
text-align: center;
}
.studio-heading h1 {
margin: 0;
color: var(--ink);
font: 500 clamp(34px, 7vw, 44px)/1.1 var(--display);
letter-spacing: -1.8px;
}
.template-prompt {
margin: 18px 0 0;
color: var(--muted);
font-size: 10px;
}
.beat-template-selector {
display: flex;
justify-content: center;
margin-top: 6px;
}
.beat-template-trigger {
--color: var(--ink);
--background: var(--surface-raised);
--background-hover: #33323b;
--background-activated: #3b3944;
--border-radius: 9px;
--border-width: 0;
height: 40px;
margin: 0;
font-size: 11px;
font-weight: 600;
text-transform: none;
}
.beat-template-trigger::part(native) {
padding-inline: 14px;
}
.beat-template-trigger-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
justify-content: center;
gap: 8px;
}
.beat-template-trigger ion-icon {
font-size: 13px;
}
.beat-template-popover {
--width: 230px;
--background: var(--surface);
--backdrop-opacity: 0;
--box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
}
.beat-template-options {
display: flex;
flex-direction: column;
gap: 3px;
padding: 7px;
}
.beat-template-option {
--color: var(--ink);
--background: var(--surface-raised);
--background-hover: #33323b;
--background-activated: #3b3944;
--border-radius: 8px;
width: 100%;
height: 56px;
flex: 0 0 56px;
margin: 0;
font-size: 11px;
text-transform: none;
}
.beat-template-option::part(native) {
padding-inline: 11px;
}
.beat-template-option-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
flex-direction: column;
justify-content: center;
gap: 2px;
text-align: center;
}
.beat-template-option-copy {
display: flex;
min-width: 0;
flex-direction: column;
align-items: center;
gap: 2px;
text-align: center;
}
.beat-template-option-label {
color: var(--ink);
font-weight: 600;
}
.beat-template-option-description {
color: var(--muted);
font-size: 9px;
font-weight: 400;
}
.beat-template-option-meta {
color: var(--soft);
font-size: 9px;
text-align: center;
white-space: nowrap;
}
.intro-copy {
margin: 7px 0 0;
color: var(--muted);
font-size: 13px;
}
.intro-copy.is-hidden {
visibility: hidden;
}
/* Preset and instrument selectors */
.orbit-card {
overflow: hidden;
padding: 21px 27px 17px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--base);
}
.orbit-card-heading {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--ink);
}
.sound-ring-selector-trigger {
--color: var(--muted);
--border-radius: 7px;
height: 30px;
margin: 0;
font-family: var(--mono);
font-size: 8px;
font-weight: 500;
letter-spacing: 0.65px;
text-transform: uppercase;
}
.sound-ring-selector-trigger::part(native) {
padding: 0 4px;
}
.sound-ring-trigger-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
justify-content: center;
gap: 8px;
white-space: nowrap;
}
.sound-ring-selector-trigger ion-icon {
font-size: 12px;
}
.ring-selector-swatch {
display: inline-block;
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
}
.sound-ring-popover {
--width: 160px;
--background: var(--surface);
--backdrop-opacity: 0;
--box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
}
.sound-ring-options {
display: flex;
flex-direction: column;
gap: 3px;
padding: 7px;
}
.sound-ring-option {
--color: var(--ink);
--background: var(--surface-raised);
--background-hover: #33323b;
--background-activated: #3b3944;
--border-radius: 7px;
width: 100%;
height: 36px;
flex: 0 0 36px;
margin: 0;
font-size: 11px;
text-align: left;
text-transform: none;
}
.sound-ring-option::part(native) {
padding-inline: 10px;
}
.sound-ring-option-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
justify-content: center;
gap: 8px;
}
.timeline-wrap {
width: min(100%, 570px);
margin: 0 auto;
}
/* Circular timeline, markers, and playback cursor */
.circular-timeline {
display: block;
width: 100%;
overflow: visible;
touch-action: none;
user-select: none;
}
.timeline-orbit {
fill: none;
stroke: rgba(var(--primary-rgb), 0.22);
stroke-width: 1.5;
transform-box: fill-box;
transform-origin: center;
transition: r 720ms cubic-bezier(0.22, 1.15, 0.36, 1), opacity 360ms ease, stroke-width 360ms ease;
}
.timeline-orbit.is-focused {
animation: orbit-focus-wave 900ms ease-out both;
}
@keyframes orbit-focus-wave {
0% { transform: scale(1); }
24% { transform: scale(1.045); }
46% { transform: scale(0.985); }
68% { transform: scale(1.022); }
86% { transform: scale(0.995); }
100% { transform: scale(1); }
}
.timeline-orbit-hit-area {
cursor: pointer;
transition: r 720ms cubic-bezier(0.22, 1.15, 0.36, 1);
}
.timeline-tick line {
stroke: rgba(var(--primary-rgb), 0.34);
stroke-width: 1;
}
.timeline-tick.is-substep line {
stroke: rgba(var(--primary-rgb), 0.18);
stroke-width: 0.75;
}
.timeline-tick.is-major line {
stroke: #b8b4e0;
stroke-width: 1.5;
}
.timeline-tick text {
fill: var(--muted);
font: 9px var(--mono);
}
.timeline-playhead line {
stroke: #fff;
stroke-width: 1;
}
.timeline-playhead circle {
fill: #fff;
filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.75));
}
.sound-point {
cursor: grab;
outline: none;
}
.sound-point:active {
cursor: grabbing;
}
.sound-point-hit-area {
fill: transparent;
pointer-events: all;
transition: cx 720ms cubic-bezier(0.22, 1.15, 0.36, 1), cy 720ms cubic-bezier(0.22, 1.15, 0.36, 1);
}
.sound-point-face {
fill: currentColor;
stroke: var(--base);
stroke-width: 3;
transition:
cx 720ms cubic-bezier(0.22, 1.15, 0.36, 1),
cy 720ms cubic-bezier(0.22, 1.15, 0.36, 1),
stroke-width 120ms ease,
filter 120ms ease;
}
.sound-point:hover .sound-point-face,
.sound-point.is-selected .sound-point-face,
.sound-point:focus-visible .sound-point-face {
stroke: #fff;
stroke-width: 2.5;
filter: drop-shadow(0 0 5px currentColor);
}
.timeline-hint-row {
display: grid;
height: 44px;
min-height: 44px;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
}
/* Beat selection status and actions */
.timeline-hint-tempo {
display: flex;
justify-content: flex-start;
}
.timeline-hint {
display: block;
width: 100%;
min-width: 0;
height: 20px;
min-height: 20px;
margin: 0;
padding: 0;
color: var(--muted);
font-size: 11px;
line-height: 20px;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.timeline-hint-tempo .tempo-trigger::part(native) {
padding-inline: 8px;
}
.timeline-hint-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
}
.timeline-delete-button {
width: 44px;
height: 44px;
margin: 0;
--color: #ff5964;
--color-activated: #ff303f;
--background-hover: rgba(255, 89, 100, 0.12);
--border-radius: 9px;
}
.timeline-delete-placeholder {
display: block;
width: 44px;
height: 44px;
flex: 0 0 44px;
}
.timeline-delete-button ion-icon {
font-size: 28px;
}
.hint-swatch,
.legend-swatch {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
}
.hint-swatch {
display: inline-block;
margin-right: 7px;
vertical-align: middle;
}
.hint-separator {
display: inline-block;
margin: 0 7px;
color: #7671a7;
}
.sound-legend {
display: flex;
justify-content: center;
gap: 22px;
padding-top: 17px;
}
.legend-sound {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 11px;
}
.legend-empty {
color: var(--soft);
font-size: 11px;
}
.legend-swatch {
width: 7px;
height: 7px;
}
.audio-error {
margin: 13px auto 0;
color: #ffad8b;
font-size: 12px;
text-align: center;
}
/* Transport and sound-add controls */
.transport-footer {
--background: rgba(17, 17, 22, 0.97);
position: relative;
overflow: visible;
border-top: 1px solid rgba(var(--primary-rgb), 0.12);
backdrop-filter: blur(18px);
}
.transport-toolbar {
--background: transparent;
--border-color: transparent;
--min-height: 84px;
}
.transport-inner {
display: flex;
width: min(100%, 660px);
min-height: 84px;
align-items: center;
justify-content: flex-start;
gap: 17px;
margin: 0 auto;
padding: 12px 86px max(12px, env(safe-area-inset-bottom)) 20px;
}
.transport-play-button {
--background: var(--accent);
--background-hover: var(--accent-hover);
--background-activated: var(--accent-pressed);
--color: var(--ion-color-secondary-contrast);
--border-radius: 11px;
--box-shadow: none;
min-width: 112px;
height: 49px;
margin: 0;
font-size: 13px;
font-weight: 700;
text-transform: none;
}
.transport-play-button ion-icon {
font-size: 17px;
}
.tempo-trigger {
--color: var(--ink);
--background: var(--surface-raised);
--background-hover: #33323b;
--background-activated: #3b3944;
--border-radius: 8px;
--border-width: 0;
--padding-top: 8px;
--padding-bottom: 8px;
height: 42px;
margin: 0;
font-size: 11px;
font-variant-numeric: tabular-nums;
font-weight: 600;
text-transform: none;
}
.meter-trigger {
--color: var(--ink);
--background: var(--surface-raised);
--background-hover: #33323b;
--background-activated: #3b3944;
--border-radius: 8px;
--border-width: 0;
--padding-top: 8px;
--padding-bottom: 8px;
height: 42px;
margin: 0;
font-size: 11px;
font-variant-numeric: tabular-nums;
font-weight: 600;
text-transform: none;
}
.tempo-trigger ion-icon,
.meter-trigger ion-icon {
margin-left: 4px;
font-size: 13px;
}
.tempo-trigger::part(native),
.meter-trigger::part(native) {
padding-inline: 14px;
}
.tempo-trigger-content,
.meter-trigger-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
justify-content: center;
gap: 8px;
white-space: nowrap;
}
.tempo-value {
color: var(--ink);
font-size: 12px;
font-weight: 600;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
/* Popover contents */
.tempo-popover {
--width: 94px;
--height: 226px;
--background: var(--surface);
--backdrop-opacity: 0;
--box-shadow: 0 10px 28px rgba(var(--primary-rgb), 0.2);
}
.tempo-popover-content {
display: flex;
width: 100%;
height: 100%;
box-sizing: border-box;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
padding: 10px;
}
.tempo-range-track {
position: relative;
width: 28px;
height: 164px;
flex: 0 0 164px;
}
.tempo-range {
position: absolute;
top: 50%;
left: 50%;
width: 164px;
height: 28px;
margin: 0;
transform: translate(-50%, -50%) rotate(-90deg);
--bar-background: #58537d;
--bar-background-active: var(--accent);
--bar-height: 3px;
--height: 28px;
--knob-background: var(--accent);
--knob-size: 12px;
--padding-top: 2px;
--padding-bottom: 2px;
--padding-start: 2px;
--padding-end: 2px;
}
.meter-popover {
--width: 96px;
--height: 224px;
--background: var(--surface);
--backdrop-opacity: 0;
--box-shadow: 0 10px 28px rgba(var(--primary-rgb), 0.2);
}
.meter-popover-content {
display: flex;
width: 100%;
height: 100%;
box-sizing: border-box;
flex-direction: column;
gap: 2px;
padding: 8px;
}
.meter-option {
--color: var(--ink);
--background: var(--surface-raised);
--background-activated: #3b3944;
--background-hover: #33323b;
--border-radius: 7px;
width: 100%;
height: 31px;
flex: 0 0 31px;
margin: 0;
font-size: 11px;
font-weight: 600;
text-transform: none;
}
.meter-option-content {
display: flex;
width: 100%;
justify-content: center;
text-align: center;
}
.meter-option::part(native) {
text-align: center;
}
.transport-fab {
position: absolute;
top: 15px;
right: max(14px, calc((100vw - 660px) / 2 + 20px));
bottom: auto;
left: auto;
z-index: 1001;
display: block;
width: 54px;
height: 54px;
flex: 0 0 54px;
}
.add-sound-fab {
--background: var(--surface-raised);
--background-activated: #33323b;
--color: var(--ink);
--box-shadow: none;
width: 54px;
height: 54px;
margin: 0;
border: 1px solid var(--border);
border-radius: 50%;
font-size: 22px;
}
.sound-fab-list {
right: 0;
left: auto;
z-index: 3;
}
.sound-fab-option {
--background: var(--surface);
--background-activated: var(--surface-raised);
--color: var(--ink);
--box-shadow: 0 5px 16px rgba(var(--primary-rgb), 0.16);
--border-radius: 12px;
width: 112px;
height: 42px;
margin: 5px 0;
font-size: 11px;
font-weight: 600;
white-space: nowrap;
}
.sound-fab-option::part(native) {
padding: 0 10px;
}
.sound-fab-option-content {
display: flex;
width: 100%;
min-width: 0;
align-items: center;
justify-content: center;
gap: 7px;
}
.sound-fab-option-content > span {
text-align: center;
}
.sound-fab-option ion-icon {
font-size: 15px;
}
@media (max-width: 600px) {
/* Compact layout */
.app-shell {
padding: 0 14px 26px;
}
.app-header {
height: 65px;
}
.brand-logo {
width: min(142px, 42vw);
max-height: 38px;
}
.header-tag {
font-size: 9px;
letter-spacing: 0;
}
.studio-heading {
padding: 28px 0 8px;
}
.studio-heading h1 {
font-size: 36px;
}
.template-prompt {
margin-top: 13px;
}
.intro-copy {
font-size: 12px;
}
.orbit-card {
padding: 17px 11px 14px;
border-radius: 14px;
}
.timeline-wrap {
width: min(100%, 490px);
}
.timeline-hint {
font-size: 10px;
}
.timeline-hint-tempo .tempo-trigger::part(native) {
padding-inline: 6px;
}
.transport-inner {
gap: 4px;
padding-right: 80px;
padding-left: 14px;
}
.transport-play-button {
min-width: 98px;
}
.tempo-trigger,
.meter-trigger {
font-size: 10px;
}
.tempo-trigger::part(native),
.meter-trigger::part(native) {
padding-inline: 10px;
}
}
@media (max-width: 360px) {
.header-tag {
max-width: 145px;
font-size: 8px;
text-align: right;
}
.transport-inner {
gap: 3px;
padding-right: 80px;
padding-left: 10px;
}
.transport-play-button {
min-width: 82px;
--padding-start: 10px;
--padding-end: 10px;
font-size: 12px;
}
.tempo-trigger,
.meter-trigger {
font-size: 9px;
}
.tempo-trigger::part(native),
.meter-trigger::part(native) {
padding-inline: 8px;
}
.timeline-hint-tempo .tempo-trigger::part(native) {
padding-inline: 4px;
}
.tempo-trigger ion-icon,
.meter-trigger ion-icon {
margin-left: 1px;
font-size: 11px;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
scroll-behavior: auto !important;
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}