Add category rings and beat labels

This commit is contained in:
Ninosaurier committed 2026-11-15 14:35:36 +01:00
1 parent 9d8f277971
commit 4f221ea122
21 files changed
+752 -339

No files matched your search

-1
View File
@@ -37,7 +37,6 @@ export function AppHeader({ activeView, onNavigate }: AppHeaderProps) {
</a>
<div className="app-header-actions">
<span className="header-tag">Sharpen your sense of rhythm</span>
<IonButton
id="app-menu-trigger"
className="app-menu-trigger"
+46 -42
View File
@@ -2,39 +2,45 @@ import { useMemo } from 'react';
import { IonButton, IonIcon } from '@ionic/react';
import { trash } from 'ionicons/icons';
import { BeatSelectionHint } from './BeatSelectionHint';
import { CategoryLegend } from './CategoryLegend';
import { CategoryRingSelector } from './CategoryRingSelector';
import { CircularTimeline } from './CircularTimeline';
import { SoundRingSelector } from './SoundRingSelector';
import { TempoControl } from './TempoControl';
import { TimeSignatureSelector } from './TimeSignatureSelector';
import { INSTRUMENT_BY_ID, INSTRUMENT_CATALOG } from '../domain/instruments';
import {
INSTRUMENT_BY_ID,
INSTRUMENT_CATEGORIES,
INSTRUMENT_CATEGORY_BY_ID,
} from '../domain/instruments';
import type { InstrumentCategoryId } from '../domain/instruments';
import type { BeatSequencer } from '../hooks/useBeatSequencer';
import type { SoundPalette } from '../hooks/useSoundPalette';
import type { CategoryLabels } from '../hooks/useCategoryLabels';
interface BeatLoopPanelProps {
sequencer: BeatSequencer;
soundPalette: SoundPalette;
categoryLabels: CategoryLabels;
}
export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
const soundIdsInLoop = useMemo(() => {
const soundsInLoop = new Set(sequencer.beats.map((beat) => beat.soundId));
return INSTRUMENT_CATALOG
.filter((sound) => soundsInLoop.has(sound.id))
.map((sound) => sound.id);
export function BeatLoopPanel({ sequencer, soundPalette, categoryLabels }: BeatLoopPanelProps) {
const categoryIdsInLoop = useMemo(() => {
const categoryIds = new Set<InstrumentCategoryId>(
sequencer.beats.map((beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId),
);
return INSTRUMENT_CATEGORIES
.filter((category) => categoryIds.has(category.id))
.map((category) => category.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
const focusedRingCategoryId = sequencer.focusedCategoryId
&& categoryIdsInLoop.includes(sequencer.focusedCategoryId)
? sequencer.focusedCategoryId
: null;
const hasDeleteTarget = Boolean(sequencer.selectedBeat || focusedRingSoundId);
const hasDeleteTarget = Boolean(sequencer.selectedBeat || focusedRingCategoryId);
const deleteLabel = sequencer.selectedBeat
? `Remove ${INSTRUMENT_BY_ID[sequencer.selectedBeat.soundId].label}`
: focusedRingSoundId
? `Remove ${INSTRUMENT_BY_ID[focusedRingSoundId].label} ring`
: focusedRingCategoryId
? `Remove ${categoryLabels.labelByCategoryId[focusedRingCategoryId] ?? INSTRUMENT_CATEGORY_BY_ID[focusedRingCategoryId].label} category`
: 'Remove sound';
return (
@@ -45,26 +51,28 @@ export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
beatsPerBar={sequencer.beatsPerBar}
onChange={sequencer.setBeatsPerBar}
/>
<SoundRingSelector
soundIds={soundIdsInLoop}
focusedSoundId={sequencer.focusedSoundId}
colorBySoundId={soundPalette.colorBySoundId}
onSelectSound={sequencer.selectSound}
<CategoryRingSelector
categoryIds={categoryIdsInLoop}
focusedCategoryId={sequencer.focusedCategoryId}
colorByCategoryId={soundPalette.colorByCategoryId}
labelByCategoryId={categoryLabels.labelByCategoryId}
onSelectCategory={sequencer.selectCategory}
/>
</div>
<div className="timeline-wrap">
<CircularTimeline
beats={sequencer.beats}
soundIds={soundIdsInLoop}
colorBySoundId={soundPalette.colorBySoundId}
categoryIds={categoryIdsInLoop}
colorByCategoryId={soundPalette.colorByCategoryId}
labelByCategoryId={categoryLabels.labelByCategoryId}
currentStep={sequencer.currentStep}
totalSteps={sequencer.totalSteps}
focusedSoundId={sequencer.focusedSoundId}
focusedCategoryId={sequencer.focusedCategoryId}
selectedBeatId={sequencer.selectedBeat?.id ?? null}
onMoveBeat={sequencer.moveBeat}
onSelectBeat={sequencer.selectBeat}
onSelectSound={sequencer.selectSound}
onSelectCategory={sequencer.selectCategory}
/>
</div>
@@ -77,8 +85,9 @@ export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
</div>
<BeatSelectionHint
selectedBeat={sequencer.selectedBeat}
focusedSoundId={focusedRingSoundId}
colorBySoundId={soundPalette.colorBySoundId}
focusedCategoryId={focusedRingCategoryId}
categoryLabelById={categoryLabels.labelByCategoryId}
colorByCategoryId={soundPalette.colorByCategoryId}
totalSteps={sequencer.totalSteps}
/>
<div className="timeline-hint-actions">
@@ -89,7 +98,7 @@ export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
aria-label={deleteLabel}
onClick={sequencer.selectedBeat
? sequencer.removeSelectedBeat
: sequencer.removeFocusedSound}
: sequencer.removeFocusedCategory}
>
<IonIcon icon={trash} />
</IonButton>
@@ -100,18 +109,13 @@ export function BeatLoopPanel({ sequencer, soundPalette }: BeatLoopPanelProps) {
</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 }} />
{INSTRUMENT_BY_ID[activeSound.id].label}
</span>
))
) : (
<span className="legend-empty">Your added sounds will appear here.</span>
)}
</div>
<CategoryLegend
beats={sequencer.beats}
categoryIds={categoryIdsInLoop}
colorByCategoryId={soundPalette.colorByCategoryId}
labelByCategoryId={categoryLabels.labelByCategoryId}
onRenameCategory={categoryLabels.renameCategory}
/>
</>
);
}
+19 -10
View File
@@ -1,34 +1,43 @@
import { memo } from 'react';
import { getLoopPositionPercent } from '../domain/timeline';
import { INSTRUMENT_BY_ID } from '../domain/instruments';
import { INSTRUMENT_BY_ID, INSTRUMENT_CATEGORY_BY_ID } from '../domain/instruments';
import type { BeatPoint } from '../domain/sequencer';
import type { InstrumentId } from '../domain/instruments';
import type { InstrumentCategoryId } from '../domain/instruments';
import type { CategoryLabelOverrides } from '../hooks/useCategoryLabels';
interface BeatSelectionHintProps {
selectedBeat: BeatPoint | undefined;
focusedSoundId: InstrumentId | null;
colorBySoundId: Partial<Record<InstrumentId, string>>;
focusedCategoryId: InstrumentCategoryId | null;
categoryLabelById: CategoryLabelOverrides;
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
totalSteps: number;
}
export const BeatSelectionHint = memo(function BeatSelectionHint({
selectedBeat,
focusedSoundId,
colorBySoundId,
focusedCategoryId,
categoryLabelById,
colorByCategoryId,
totalSteps,
}: BeatSelectionHintProps) {
const soundId = selectedBeat?.soundId ?? focusedSoundId;
if (!soundId) return <p className="timeline-hint" aria-live="polite" />;
const selectedInstrument = selectedBeat ? INSTRUMENT_BY_ID[selectedBeat.soundId] : undefined;
const categoryId = selectedInstrument?.categoryId ?? focusedCategoryId;
if (!categoryId) return <p className="timeline-hint" aria-live="polite" />;
const category = INSTRUMENT_CATEGORY_BY_ID[categoryId];
const categoryLabel = categoryLabelById[categoryId] ?? category.label;
return (
<p className="timeline-hint" aria-live="polite">
<span
className="hint-swatch"
style={{ backgroundColor: colorBySoundId[soundId] }}
style={{ backgroundColor: colorByCategoryId[categoryId] }}
/>
{INSTRUMENT_BY_ID[soundId].label}
{category.letter} · {categoryLabel}
{selectedBeat && (
<>
<span className="hint-separator">·</span>
{selectedBeat.letter} · {selectedInstrument?.label}
<span className="hint-separator">·</span>
Step {getLoopPositionPercent(selectedBeat.step, totalSteps)}% selected
</>
+124
View File
@@ -0,0 +1,124 @@
import { useEffect, useRef, useState } from 'react';
import { IonAlert, IonButton } from '@ionic/react';
import { INSTRUMENT_BY_ID, INSTRUMENT_CATEGORY_BY_ID } from '../domain/instruments';
import type { InstrumentCategoryId } from '../domain/instruments';
import type { BeatPoint } from '../domain/sequencer';
import type { CategoryLabelOverrides } from '../hooks/useCategoryLabels';
interface CategoryLegendProps {
beats: readonly BeatPoint[];
categoryIds: readonly InstrumentCategoryId[];
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
labelByCategoryId: CategoryLabelOverrides;
onRenameCategory: (categoryId: InstrumentCategoryId, label: string) => void;
}
export function CategoryLegend({
beats,
categoryIds,
colorByCategoryId,
labelByCategoryId,
onRenameCategory,
}: CategoryLegendProps) {
const [editingCategoryId, setEditingCategoryId] = useState<InstrumentCategoryId | null>(null);
const longPressTimerRef = useRef<number | null>(null);
const editingCategory = editingCategoryId
? INSTRUMENT_CATEGORY_BY_ID[editingCategoryId]
: undefined;
const editingLabel = editingCategory
? labelByCategoryId[editingCategory.id] ?? editingCategory.label
: '';
function clearLongPressTimer(): void {
if (longPressTimerRef.current === null) return;
window.clearTimeout(longPressTimerRef.current);
longPressTimerRef.current = null;
}
function beginRename(categoryId: InstrumentCategoryId): void {
clearLongPressTimer();
setEditingCategoryId(categoryId);
}
function saveRename(value: unknown): void {
if (!editingCategoryId || typeof value !== 'object' || value === null) return;
const label = (value as Record<string, unknown>).categoryName;
if (typeof label === 'string') onRenameCategory(editingCategoryId, label);
}
useEffect(() => () => {
if (longPressTimerRef.current !== null) window.clearTimeout(longPressTimerRef.current);
}, []);
return (
<>
<div className="sound-legend" aria-label="Instrument categories in this loop" aria-live="polite">
{categoryIds.length > 0 ? (
categoryIds.map((categoryId) => {
const category = INSTRUMENT_CATEGORY_BY_ID[categoryId];
const label = labelByCategoryId[categoryId] ?? category.label;
const categoryBeats = beats.filter(
(beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId === categoryId,
);
return (
<div className="legend-category-entry" key={categoryId}>
<IonButton
className="legend-category"
fill="clear"
aria-label={`Press and hold to rename ${label}`}
onPointerDown={() => {
clearLongPressTimer();
longPressTimerRef.current = window.setTimeout(
() => beginRename(categoryId),
550,
);
}}
onPointerUp={clearLongPressTimer}
onPointerLeave={clearLongPressTimer}
onPointerCancel={clearLongPressTimer}
onContextMenu={(event) => {
event.preventDefault();
beginRename(categoryId);
}}
onKeyDown={(event) => {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
beginRename(categoryId);
}}
>
<span
className="legend-swatch"
style={{ backgroundColor: colorByCategoryId[categoryId] }}
/>
<span className="legend-category-letter">{category.letter}</span>
<span>{label}</span>
</IonButton>
<span className="legend-beat-list">
{categoryBeats.map((beat) => (
<span key={beat.id}>
<strong>{beat.letter}</strong> {INSTRUMENT_BY_ID[beat.soundId].label}
</span>
))}
</span>
</div>
);
})
) : (
<span className="legend-empty">Added instrument categories will appear here.</span>
)}
</div>
<IonAlert
isOpen={editingCategory !== undefined}
header={`Rename ${editingLabel || 'category'}`}
message="This name is shown in the loop legend."
inputs={[{ name: 'categoryName', type: 'text', value: editingLabel, placeholder: 'Category name' }]}
buttons={[
{ text: 'Cancel', role: 'cancel' },
{ text: 'Save', handler: (value: unknown) => saveRename(value) },
]}
onDidDismiss={() => setEditingCategoryId(null)}
/>
</>
);
}
+96
View File
@@ -0,0 +1,96 @@
import { memo } from 'react';
import { IonButton, IonIcon, IonPopover } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { INSTRUMENT_CATEGORY_BY_ID } from '../domain/instruments';
import type { InstrumentCategoryId } from '../domain/instruments';
import type { CategoryLabelOverrides } from '../hooks/useCategoryLabels';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface CategoryRingSelectorProps {
categoryIds: readonly InstrumentCategoryId[];
focusedCategoryId: InstrumentCategoryId | null;
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
labelByCategoryId: CategoryLabelOverrides;
onSelectCategory: (categoryId: InstrumentCategoryId) => void;
}
export const CategoryRingSelector = memo(function CategoryRingSelector({
categoryIds,
focusedCategoryId,
colorByCategoryId,
labelByCategoryId,
onSelectCategory,
}: CategoryRingSelectorProps) {
const popover = usePopoverDisclosure();
const focusedCategory = focusedCategoryId
? INSTRUMENT_CATEGORY_BY_ID[focusedCategoryId]
: undefined;
const focusedLabel = focusedCategory
? labelByCategoryId[focusedCategory.id] ?? focusedCategory.label
: undefined;
return (
<>
<IonButton
id="category-ring-selector-trigger"
className="sound-ring-selector-trigger"
fill="clear"
disabled={categoryIds.length === 0}
aria-label={focusedCategory ? `Selected ring: ${focusedLabel}` : 'Select a category ring'}
aria-haspopup="dialog"
aria-expanded={popover.isOpen}
>
<span className="sound-ring-trigger-content">
{focusedCategory && (
<>
<span
className="ring-selector-swatch"
style={{ backgroundColor: colorByCategoryId[focusedCategory.id] ?? '#b8b4e0' }}
/>
<span className="category-letter-badge">{focusedCategory.letter}</span>
</>
)}
<span>{focusedLabel ? `${focusedLabel} ring` : 'Category rings'}</span>
<IonIcon icon={chevronDown} />
</span>
</IonButton>
<IonPopover
className="sound-ring-popover"
trigger="category-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="Category rings">
{categoryIds.map((categoryId) => {
const category = INSTRUMENT_CATEGORY_BY_ID[categoryId];
const label = labelByCategoryId[categoryId] ?? category.label;
const selected = categoryId === focusedCategoryId;
return (
<IonButton
key={categoryId}
className="sound-ring-option"
fill={selected ? 'solid' : 'clear'}
aria-pressed={selected}
onClick={() => onSelectCategory(categoryId)}
>
<span className="sound-ring-option-content">
<span
className="ring-selector-swatch"
style={{ backgroundColor: colorByCategoryId[categoryId] ?? '#b8b4e0' }}
/>
<span className="category-letter-badge">{category.letter}</span>
<span>{label} ring</span>
</span>
</IonButton>
);
})}
</div>
</IonPopover>
</>
);
});
+82 -46
View File
@@ -8,7 +8,7 @@ import {
import {
getPointForStep,
getLoopPositionPercent,
getSoundOrbitRadius,
getCategoryOrbitRadius,
getStepFromPosition,
ORBIT_RADIUS,
SVG_CENTER,
@@ -16,20 +16,22 @@ import {
getStackedPosition,
wrapStepPosition,
} from '../domain/timeline';
import { INSTRUMENT_BY_ID } from '../domain/instruments';
import type { InstrumentId } from '../domain/instruments';
import { INSTRUMENT_BY_ID, INSTRUMENT_CATEGORY_BY_ID } from '../domain/instruments';
import type { InstrumentCategoryId } from '../domain/instruments';
import type { CategoryLabelOverrides } from '../hooks/useCategoryLabels';
interface CircularTimelineProps {
beats: BeatPoint[];
soundIds: readonly InstrumentId[];
colorBySoundId: Partial<Record<InstrumentId, string>>;
categoryIds: readonly InstrumentCategoryId[];
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
labelByCategoryId: CategoryLabelOverrides;
currentStep: number;
totalSteps: number;
focusedSoundId: InstrumentId | null;
focusedCategoryId: InstrumentCategoryId | null;
selectedBeatId: string | null;
onMoveBeat: (beatId: string, step: number) => void;
onSelectBeat: (beatId: string) => void;
onSelectSound: (soundId: InstrumentId) => void;
onSelectCategory: (categoryId: InstrumentCategoryId) => void;
}
function getPointerCoordinates(event: ReactPointerEvent<SVGSVGElement>) {
@@ -42,25 +44,29 @@ function getPointerCoordinates(event: ReactPointerEvent<SVGSVGElement>) {
export function CircularTimeline({
beats,
soundIds,
colorBySoundId,
categoryIds,
colorByCategoryId,
labelByCategoryId,
currentStep,
totalSteps,
focusedSoundId,
focusedCategoryId,
selectedBeatId,
onMoveBeat,
onSelectBeat,
onSelectSound,
onSelectCategory,
}: CircularTimelineProps) {
const draggingBeatIdRef = useRef<string | null>(null);
const selectedBeatSoundId = beats.find((beat) => beat.id === selectedBeatId)?.soundId;
const activeSoundId = selectedBeatSoundId ?? focusedSoundId;
const orderedSoundIds = activeSoundId
const selectedBeatCategoryId = selectedBeatSoundId
? INSTRUMENT_BY_ID[selectedBeatSoundId].categoryId
: null;
const activeCategoryId = selectedBeatCategoryId ?? focusedCategoryId;
const orderedCategoryIds = activeCategoryId
? [
...soundIds.filter((soundId) => soundId === activeSoundId),
...soundIds.filter((soundId) => soundId !== activeSoundId),
...categoryIds.filter((categoryId) => categoryId === activeCategoryId),
...categoryIds.filter((categoryId) => categoryId !== activeCategoryId),
]
: soundIds;
: categoryIds;
function handlePointerDown(event: ReactPointerEvent<SVGGElement>, beatId: string): void {
event.preventDefault();
@@ -96,11 +102,11 @@ export function CircularTimeline({
function handleOrbitKeyDown(
event: ReactKeyboardEvent<SVGCircleElement>,
soundId: InstrumentId,
categoryId: InstrumentCategoryId,
): void {
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
onSelectSound(soundId);
onSelectCategory(categoryId);
}
return (
@@ -108,25 +114,44 @@ export function CircularTimeline({
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.`}
aria-label={`${totalSteps}-step circular beat timeline with one orbit per instrument category. Drag beat 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,
}}
/>
))}
{orderedCategoryIds.map((categoryId, categoryIndex) => {
const category = INSTRUMENT_CATEGORY_BY_ID[categoryId];
const color = colorByCategoryId[categoryId] ?? '#b8b4e0';
const radius = getCategoryOrbitRadius(categoryIndex, orderedCategoryIds.length);
const letterPosition = getPointForStep(totalSteps * 0.12, radius, SVG_CENTER, totalSteps);
const focused = categoryId === activeCategoryId;
return (
<g key={categoryId}>
<circle
cx={SVG_CENTER}
cy={SVG_CENTER}
r={radius}
className={`timeline-orbit${focused ? ' is-focused' : ''}`}
style={{
stroke: color,
opacity: focused ? 0.55 : 0.32,
strokeWidth: focused ? 2.2 : 1.5,
}}
/>
<g className="timeline-category-letter" style={{ color }} aria-hidden="true">
<circle cx={letterPosition.x} cy={letterPosition.y} r="9" />
<text
x={letterPosition.x}
y={letterPosition.y}
textAnchor="middle"
dominantBaseline="middle"
>
{category.letter}
</text>
</g>
</g>
);
})}
{Array.from({ length: totalSteps * PLAYBACK_SUBSTEPS_PER_STEP }, (_, tick) => {
const step = tick / PLAYBACK_SUBSTEPS_PER_STEP;
@@ -155,12 +180,12 @@ export function CircularTimeline({
);
})}
{orderedSoundIds.map((soundId, soundIndex) => (
{orderedCategoryIds.map((categoryId, categoryIndex) => (
<circle
key={soundId}
key={categoryId}
cx={SVG_CENTER}
cy={SVG_CENTER}
r={getSoundOrbitRadius(soundIndex, orderedSoundIds.length)}
r={getCategoryOrbitRadius(categoryIndex, orderedCategoryIds.length)}
className="timeline-orbit-hit-area"
fill="none"
stroke="transparent"
@@ -168,11 +193,11 @@ export function CircularTimeline({
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)}
aria-label={`Select ${INSTRUMENT_CATEGORY_BY_ID[categoryId].letter} ${labelByCategoryId[categoryId] ?? INSTRUMENT_CATEGORY_BY_ID[categoryId].label} ring`}
aria-pressed={categoryId === activeCategoryId}
onClick={() => onSelectCategory(categoryId)}
onKeyDown={(event) => handleOrbitKeyDown(event, categoryId)}
onFocus={() => onSelectCategory(categoryId)}
/>
))}
@@ -187,23 +212,24 @@ export function CircularTimeline({
})()}
{beats.map((beat) => {
const sound = INSTRUMENT_BY_ID[beat.soundId];
const soundIndex = orderedSoundIds.indexOf(beat.soundId);
const instrument = INSTRUMENT_BY_ID[beat.soundId];
const category = INSTRUMENT_CATEGORY_BY_ID[instrument.categoryId];
const categoryIndex = orderedCategoryIds.indexOf(instrument.categoryId);
const point = getStackedPosition(
beat,
beats,
totalSteps,
getSoundOrbitRadius(soundIndex, orderedSoundIds.length),
getCategoryOrbitRadius(categoryIndex, orderedCategoryIds.length),
);
const selected = selectedBeatId === beat.id;
return (
<g
key={beat.id}
className={`sound-point${selected ? ' is-selected' : ''}`}
style={{ color: colorBySoundId[beat.soundId] ?? '#f4f1ed' }}
style={{ color: colorByCategoryId[instrument.categoryId] ?? '#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-label={`${category.letter} ${labelByCategoryId[category.id] ?? category.label}, beat ${beat.letter}, ${instrument.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)}
@@ -212,6 +238,16 @@ export function CircularTimeline({
>
<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>
);
})}
+1 -82
View File
@@ -1,82 +1 @@
import { memo } from 'react';
import { IonButton, IonIcon, IonPopover } from '@ionic/react';
import { chevronDown } from 'ionicons/icons';
import { INSTRUMENT_BY_ID } from '../domain/instruments';
import type { InstrumentId } from '../domain/instruments';
import { usePopoverDisclosure } from '../hooks/usePopoverDisclosure';
interface SoundRingSelectorProps {
soundIds: InstrumentId[];
focusedSoundId: InstrumentId | null;
colorBySoundId: Partial<Record<InstrumentId, string>>;
onSelectSound: (soundId: InstrumentId) => void;
}
export const SoundRingSelector = memo(function SoundRingSelector({
soundIds,
focusedSoundId,
colorBySoundId,
onSelectSound,
}: SoundRingSelectorProps) {
const popover = usePopoverDisclosure();
const focusedSound = focusedSoundId ? INSTRUMENT_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>{INSTRUMENT_BY_ID[soundId].label} ring</span>
</span>
</IonButton>
);
})}
</div>
</IonPopover>
</>
);
});
export { CategoryRingSelector as SoundRingSelector } from './CategoryRingSelector';
+21 -6
View File
@@ -136,6 +136,7 @@ export type InstrumentCategoryId = InstrumentDefinition['categoryId'];
export interface InstrumentCategory {
id: InstrumentCategoryId;
label: string;
letter: string;
instrumentIds: readonly InstrumentId[];
}
@@ -148,19 +149,33 @@ export function isInstrumentId(value: unknown): value is InstrumentId {
}
export const INSTRUMENT_CATEGORIES = [
{ id: 'drums', label: 'Drums', instrumentIds: ['kick', 'snare', 'hi-hat', 'toms', 'cymbals'] },
{
id: 'drums',
label: 'Drums',
letter: 'A',
instrumentIds: ['kick', 'snare', 'hi-hat', 'toms', 'cymbals'],
},
{
id: 'percussion',
label: 'Percussion',
letter: 'B',
instrumentIds: ['clap', 'shaker', 'cowbell', 'woodblock', 'bongos'],
},
{ id: 'bass', label: 'Bass', instrumentIds: ['bass'] },
{ id: 'keys', label: 'Keys', instrumentIds: ['piano', 'organ'] },
{ id: 'strings', label: 'Strings', instrumentIds: ['strings'] },
{ id: 'winds', label: 'Winds', instrumentIds: ['winds'] },
{ id: 'synth', label: 'Synth', instrumentIds: ['synth'] },
{ id: 'bass', label: 'Bass', letter: 'C', instrumentIds: ['bass'] },
{ id: 'keys', label: 'Keys', letter: 'D', instrumentIds: ['piano', 'organ'] },
{ id: 'strings', label: 'Strings', letter: 'E', instrumentIds: ['strings'] },
{ id: 'winds', label: 'Winds', letter: 'F', instrumentIds: ['winds'] },
{ id: 'synth', label: 'Synth', letter: 'G', instrumentIds: ['synth'] },
] as const satisfies readonly InstrumentCategory[];
export const INSTRUMENT_CATEGORY_BY_ID = INSTRUMENT_CATEGORIES.reduce(
(categories, category) => {
categories[category.id] = category;
return categories;
},
{} as Record<InstrumentCategoryId, InstrumentCategory>,
);
export const DEFAULT_PITCH_SEMITONES = 0;
export const MIN_PITCH_SEMITONES = -24;
export const MAX_PITCH_SEMITONES = 24;
+36 -1
View File
@@ -1,4 +1,5 @@
import type { InstrumentId } from './instruments';
import { INSTRUMENT_BY_ID } from './instruments';
import type { InstrumentCategoryId, InstrumentId } from './instruments';
export const STEPS_PER_BEAT = 4;
export const PLAYBACK_SUBSTEPS_PER_STEP = 4;
@@ -25,12 +26,46 @@ export function getPlaybackTickDurationMs(tempoBpm: number): number {
export interface BeatPoint {
id: string;
soundId: InstrumentId;
/** Short unique label within its instrument category, such as a, b, or c. */
letter: string;
/** Position in sixteenth-note steps; fractional values represent microtiming. */
step: number;
/** Pitch offset from the instrument's base note in semitones. */
pitchSemitones?: number;
}
export function getAlphabeticLabel(index: number): string {
let value = Math.floor(index) + 1;
if (!Number.isSafeInteger(value) || value < 1) return '';
let label = '';
while (value > 0) {
value -= 1;
label = String.fromCharCode(65 + (value % 26)) + label;
value = Math.floor(value / 26);
}
return label;
}
export function getNextBeatLetter(
beats: readonly BeatPoint[],
categoryId: InstrumentCategoryId,
): string {
const usedLetters = new Set(
beats
.filter((beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId === categoryId)
.map((beat) => beat.letter),
);
let index = 0;
let letter = getAlphabeticLabel(index).toLowerCase();
while (usedLetters.has(letter)) {
index += 1;
letter = getAlphabeticLabel(index).toLowerCase();
}
return letter;
}
export function getNextAvailableStep(
beats: readonly BeatPoint[],
totalSteps = TOTAL_STEPS,
+34 -23
View File
@@ -5,13 +5,13 @@ import {
TEMPO_BPM,
} from './sequencer';
import type { BeatsPerBar, BeatPoint } from './sequencer';
import { clampPitchSemitones } from './instruments';
import type { InstrumentId } from './instruments';
import { clampPitchSemitones, INSTRUMENT_BY_ID } from './instruments';
import type { InstrumentCategoryId } from './instruments';
export interface SequencerState {
beats: BeatPoint[];
selectedBeatId: string | null;
focusedSoundId: InstrumentId | null;
focusedCategoryId: InstrumentCategoryId | null;
tempoBpm: number;
beatsPerBar: BeatsPerBar;
}
@@ -21,9 +21,9 @@ export type SequencerAction =
| { type: 'beat-moved'; beatId: string; step: number }
| { type: 'beat-pitch-changed'; beatId: string; pitchSemitones: number }
| { type: 'beat-selected'; beatId: string }
| { type: 'sound-selected'; soundId: InstrumentId }
| { type: 'category-selected'; categoryId: InstrumentCategoryId }
| { type: 'selected-beat-removed' }
| { type: 'focused-sound-removed' }
| { type: 'focused-category-removed' }
| { type: 'tempo-changed'; tempoBpm: number }
| { type: 'time-signature-changed'; beatsPerBar: BeatsPerBar }
| { type: 'template-loaded'; beats: BeatPoint[]; tempoBpm: number; beatsPerBar: BeatsPerBar };
@@ -32,7 +32,7 @@ export function createInitialSequencerState(): SequencerState {
return {
beats: [],
selectedBeatId: null,
focusedSoundId: null,
focusedCategoryId: null,
tempoBpm: TEMPO_BPM,
beatsPerBar: DEFAULT_BEATS_PER_BAR,
};
@@ -49,7 +49,7 @@ export function sequencerReducer(state: SequencerState, action: SequencerAction)
...state,
beats: [...state.beats, action.beat],
selectedBeatId: action.beat.id,
focusedSoundId: action.beat.soundId,
focusedCategoryId: INSTRUMENT_BY_ID[action.beat.soundId].categoryId,
};
case 'beat-moved':
return {
@@ -70,34 +70,43 @@ export function sequencerReducer(state: SequencerState, action: SequencerAction)
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 };
return {
...state,
selectedBeatId: beat.id,
focusedCategoryId: INSTRUMENT_BY_ID[beat.soundId].categoryId,
};
}
case 'sound-selected':
return { ...state, focusedSoundId: action.soundId, selectedBeatId: null };
case 'category-selected':
return { ...state, focusedCategoryId: action.categoryId, 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);
const removedCategoryId = INSTRUMENT_BY_ID[removedBeat.soundId].categoryId;
const categoryRemains = beats.some(
(beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId === removedCategoryId,
);
return {
...state,
beats,
selectedBeatId: null,
focusedSoundId: state.focusedSoundId === removedBeat.soundId && !soundRemains
? beats[0]?.soundId ?? null
: state.focusedSoundId,
focusedCategoryId: state.focusedCategoryId === removedCategoryId && !categoryRemains
? beats[0] ? INSTRUMENT_BY_ID[beats[0].soundId].categoryId : null
: state.focusedCategoryId,
};
}
case 'focused-sound-removed': {
if (!state.focusedSoundId) return state;
const beats = state.beats.filter((beat) => beat.soundId !== state.focusedSoundId);
case 'focused-category-removed': {
if (!state.focusedCategoryId) return state;
const beats = state.beats.filter(
(beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId !== state.focusedCategoryId,
);
return {
...state,
beats,
selectedBeatId: null,
focusedSoundId: beats[0]?.soundId ?? null,
focusedCategoryId: beats[0] ? INSTRUMENT_BY_ID[beats[0].soundId].categoryId : null,
};
}
case 'tempo-changed':
@@ -106,14 +115,16 @@ export function sequencerReducer(state: SequencerState, action: SequencerAction)
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);
const focusedCategoryRemains = visibleBeats.some(
(beat) => INSTRUMENT_BY_ID[beat.soundId].categoryId === state.focusedCategoryId,
);
return {
...state,
beatsPerBar: action.beatsPerBar,
selectedBeatId: selectedBeat?.id ?? null,
focusedSoundId: focusedSoundRemains
? state.focusedSoundId
: visibleBeats[0]?.soundId ?? null,
focusedCategoryId: focusedCategoryRemains
? state.focusedCategoryId
: visibleBeats[0] ? INSTRUMENT_BY_ID[visibleBeats[0].soundId].categoryId : null,
};
}
case 'template-loaded': {
@@ -122,7 +133,7 @@ export function sequencerReducer(state: SequencerState, action: SequencerAction)
...state,
beats: action.beats,
selectedBeatId: firstBeat?.id ?? null,
focusedSoundId: firstBeat?.soundId ?? null,
focusedCategoryId: firstBeat ? INSTRUMENT_BY_ID[firstBeat.soundId].categoryId : null,
tempoBpm: clampTempoBpm(action.tempoBpm),
beatsPerBar: action.beatsPerBar,
};
+7 -3
View File
@@ -1,4 +1,5 @@
import type { BeatPoint } from './sequencer';
import { INSTRUMENT_BY_ID } from './instruments';
import {
PLAYBACK_SUBSTEPS_PER_STEP,
TOTAL_STEPS,
@@ -47,10 +48,12 @@ 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 getCategoryOrbitRadius(categoryIndex: number, categoryCount: number): number {
return ORBIT_RADIUS * (categoryCount + 1 - categoryIndex) / (categoryCount + 1);
}
export const getSoundOrbitRadius = getCategoryOrbitRadius;
export function getPlaybackTick(step: number, totalSteps: number): number {
const totalPlaybackTicks = totalSteps * PLAYBACK_SUBSTEPS_PER_STEP;
return Math.round(step * PLAYBACK_SUBSTEPS_PER_STEP) % totalPlaybackTicks;
@@ -64,7 +67,8 @@ export function getStackedPosition(
): CirclePoint {
const siblings = beats
.filter((candidate) => (
candidate.soundId === beat.soundId
INSTRUMENT_BY_ID[candidate.soundId].categoryId
=== INSTRUMENT_BY_ID[beat.soundId].categoryId
&& getPlaybackTick(candidate.step, totalSteps) === getPlaybackTick(beat.step, totalSteps)
))
.sort((first, second) => first.id.localeCompare(second.id));
+21 -13
View File
@@ -1,13 +1,15 @@
import { useCallback, useMemo, useReducer, useRef } from 'react';
import type { BeatTemplate } from '../domain/beatTemplates';
import {
getAlphabeticLabel,
getNextAvailableStep,
getNextBeatLetter,
getTotalSteps,
} from '../domain/sequencer';
import type { BeatsPerBar } from '../domain/sequencer';
import type { BeatPoint } from '../domain/sequencer';
import { DEFAULT_PITCH_SEMITONES } from '../domain/instruments';
import type { InstrumentId } from '../domain/instruments';
import { DEFAULT_PITCH_SEMITONES, INSTRUMENT_BY_ID } from '../domain/instruments';
import type { InstrumentCategoryId, InstrumentId } from '../domain/instruments';
import { createInitialSequencerState, sequencerReducer } from '../domain/sequencerReducer';
import { useBeatPlayback } from './useBeatPlayback';
@@ -20,15 +22,15 @@ export interface BeatSequencer {
tempoBpm: number;
beatsPerBar: BeatsPerBar;
totalSteps: number;
focusedSoundId: InstrumentId | null;
focusedCategoryId: InstrumentCategoryId | null;
selectedBeat: BeatPoint | undefined;
addBeat: (soundId: InstrumentId) => void;
moveBeat: (beatId: string, step: number) => void;
changeBeatPitch: (beatId: string, pitchSemitones: number) => void;
selectBeat: (beatId: string) => void;
selectSound: (soundId: InstrumentId) => void;
selectCategory: (categoryId: InstrumentCategoryId) => void;
removeSelectedBeat: () => void;
removeFocusedSound: () => void;
removeFocusedCategory: () => void;
setTempoBpm: (tempoBpm: number) => void;
setBeatsPerBar: (beatsPerBar: BeatsPerBar) => void;
loadTemplate: (template: BeatTemplate) => void;
@@ -41,7 +43,7 @@ export function useBeatSequencer(): BeatSequencer {
undefined,
createInitialSequencerState,
);
const { beats, beatsPerBar, focusedSoundId, selectedBeatId, tempoBpm } = state;
const { beats, beatsPerBar, focusedCategoryId, selectedBeatId, tempoBpm } = state;
const totalSteps = getTotalSteps(beatsPerBar);
const nextBeatIdRef = useRef(1);
@@ -61,6 +63,7 @@ export function useBeatSequencer(): BeatSequencer {
const beat: BeatPoint = {
id: `beat-${nextBeatIdRef.current}`,
soundId,
letter: getNextBeatLetter(beats, INSTRUMENT_BY_ID[soundId].categoryId),
step: getNextAvailableStep(beats, totalSteps),
pitchSemitones: DEFAULT_PITCH_SEMITONES,
};
@@ -80,16 +83,16 @@ export function useBeatSequencer(): BeatSequencer {
dispatch({ type: 'beat-selected', beatId });
}, []);
const selectSound = useCallback((soundId: InstrumentId): void => {
dispatch({ type: 'sound-selected', soundId });
const selectCategory = useCallback((categoryId: InstrumentCategoryId): void => {
dispatch({ type: 'category-selected', categoryId });
}, []);
const removeSelectedBeat = useCallback((): void => {
dispatch({ type: 'selected-beat-removed' });
}, []);
const removeFocusedSound = useCallback((): void => {
dispatch({ type: 'focused-sound-removed' });
const removeFocusedCategory = useCallback((): void => {
dispatch({ type: 'focused-category-removed' });
}, []);
const setTempoBpm = useCallback((tempo: number): void => {
@@ -101,10 +104,15 @@ export function useBeatSequencer(): BeatSequencer {
}, []);
const loadTemplate = useCallback((template: BeatTemplate): void => {
const nextLetterByCategory = new Map<InstrumentCategoryId, number>();
const templateBeats: BeatPoint[] = template.beats.map((templateBeat) => {
const categoryId = INSTRUMENT_BY_ID[templateBeat.soundId].categoryId;
const letterIndex = nextLetterByCategory.get(categoryId) ?? 0;
nextLetterByCategory.set(categoryId, letterIndex + 1);
const beat: BeatPoint = {
id: `beat-${nextBeatIdRef.current}`,
...templateBeat,
letter: getAlphabeticLabel(letterIndex).toLowerCase(),
pitchSemitones: templateBeat.pitchSemitones ?? DEFAULT_PITCH_SEMITONES,
};
nextBeatIdRef.current += 1;
@@ -129,15 +137,15 @@ export function useBeatSequencer(): BeatSequencer {
tempoBpm,
beatsPerBar,
totalSteps,
focusedSoundId,
focusedCategoryId,
selectedBeat,
addBeat,
moveBeat,
changeBeatPitch,
selectBeat,
selectSound,
selectCategory,
removeSelectedBeat,
removeFocusedSound,
removeFocusedCategory,
setTempoBpm,
setBeatsPerBar,
loadTemplate,
+5 -1
View File
@@ -5,10 +5,13 @@ import type { BeatSequencer } from './useBeatSequencer';
import { useBeatSequencer } from './useBeatSequencer';
import type { SoundPalette } from './useSoundPalette';
import { useSoundPalette } from './useSoundPalette';
import type { CategoryLabels } from './useCategoryLabels';
import { useCategoryLabels } from './useCategoryLabels';
export interface BeatStudio {
sequencer: BeatSequencer;
soundPalette: SoundPalette;
categoryLabels: CategoryLabels;
addSound: (soundId: InstrumentId) => void;
applyTemplate: (template: BeatTemplate) => void;
}
@@ -16,6 +19,7 @@ export interface BeatStudio {
export function useBeatStudio(): BeatStudio {
const sequencer = useBeatSequencer();
const soundPalette = useSoundPalette();
const categoryLabels = useCategoryLabels();
const { addBeat, loadTemplate } = sequencer;
const { activateSounds } = soundPalette;
@@ -29,5 +33,5 @@ export function useBeatStudio(): BeatStudio {
activateSounds(template.beats.map((beat) => beat.soundId));
}, [activateSounds, loadTemplate]);
return { sequencer, soundPalette, addSound, applyTemplate };
return { sequencer, soundPalette, categoryLabels, addSound, applyTemplate };
}
+25
View File
@@ -0,0 +1,25 @@
import { useCallback, useState } from 'react';
import type { InstrumentCategoryId } from '../domain/instruments';
export type CategoryLabelOverrides = Partial<Record<InstrumentCategoryId, string>>;
export interface CategoryLabels {
labelByCategoryId: CategoryLabelOverrides;
renameCategory: (categoryId: InstrumentCategoryId, label: string) => void;
}
export function useCategoryLabels(): CategoryLabels {
const [labelByCategoryId, setLabelByCategoryId] = useState<CategoryLabelOverrides>({});
const renameCategory = useCallback((categoryId: InstrumentCategoryId, label: string): void => {
const trimmedLabel = label.trim();
if (!trimmedLabel) return;
setLabelByCategoryId((currentLabels) => ({
...currentLabels,
[categoryId]: trimmedLabel,
}));
}, []);
return { labelByCategoryId, renameCategory };
}
+30 -24
View File
@@ -1,44 +1,50 @@
import { useCallback, useMemo, useState } from 'react';
import type { InstrumentId } from '../domain/instruments';
import { INSTRUMENT_BY_ID, INSTRUMENT_CATEGORIES } from '../domain/instruments';
import type { InstrumentCategoryId, InstrumentId } from '../domain/instruments';
import { generateUniqueSoundColor } from '../domain/soundColors';
export interface PaletteSound {
id: InstrumentId;
export interface PaletteCategory {
id: InstrumentCategoryId;
color: string;
}
export interface SoundPalette {
activeSounds: PaletteSound[];
colorBySoundId: Partial<Record<InstrumentId, string>>;
activateSounds: (soundIds: readonly InstrumentId[]) => void;
activeCategories: PaletteCategory[];
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
activateSounds: (instrumentIds: readonly InstrumentId[]) => void;
}
export function useSoundPalette(): SoundPalette {
const [activeSounds, setActiveSounds] = useState<PaletteSound[]>([]);
const [activeCategories, setActiveCategories] = useState<PaletteCategory[]>([]);
const activateSounds = useCallback((soundIds: readonly InstrumentId[]): void => {
setActiveSounds((currentSounds) => {
const nextSounds = [...currentSounds];
const currentCount = nextSounds.length;
soundIds.forEach((soundId) => {
if (nextSounds.some((sound) => sound.id === soundId)) return;
const activateSounds = useCallback((instrumentIds: readonly InstrumentId[]): void => {
setActiveCategories((currentCategories) => {
const nextCategories = [...currentCategories];
const currentCount = nextCategories.length;
const categoryIds = instrumentIds.map(
(instrumentId) => INSTRUMENT_BY_ID[instrumentId].categoryId,
);
INSTRUMENT_CATEGORIES
.filter((category) => categoryIds.includes(category.id))
.forEach((category) => {
if (nextCategories.some((active) => active.id === category.id)) return;
nextSounds.push({
id: soundId,
color: generateUniqueSoundColor(nextSounds.map((sound) => sound.color)),
nextCategories.push({
id: category.id,
color: generateUniqueSoundColor(nextCategories.map((active) => active.color)),
});
});
});
return nextSounds.length === currentCount ? currentSounds : nextSounds;
return nextCategories.length === currentCount ? currentCategories : nextCategories;
});
}, []);
const colorBySoundId = useMemo(() => {
const colors: Partial<Record<InstrumentId, string>> = {};
activeSounds.forEach((sound) => {
colors[sound.id] = sound.color;
const colorByCategoryId = useMemo(() => {
const colors: Partial<Record<InstrumentCategoryId, string>> = {};
activeCategories.forEach((category) => {
colors[category.id] = category.color;
});
return colors;
}, [activeSounds]);
}, [activeCategories]);
return { activeSounds, colorBySoundId, activateSounds };
return { activeCategories, colorByCategoryId, activateSounds };
}
+57 -21
View File
@@ -11,11 +11,14 @@ import {
INSTRUMENT_CATEGORIES,
INSTRUMENT_CATALOG,
INSTRUMENT_BY_ID,
INSTRUMENT_CATEGORY_BY_ID,
MAX_PITCH_SEMITONES,
MIN_PITCH_SEMITONES,
} from './domain/instruments';
import { INSTRUMENT_VOICES } from './audio/soundVoices';
import {
getAlphabeticLabel,
getNextBeatLetter,
getNextAvailableStep,
getPlaybackTickDurationMs,
getLoopPositionPercent,
@@ -30,6 +33,7 @@ import {
TEMPO_BPM,
} from './sequencer';
import type { BeatPoint } from './sequencer';
import { getStackedPosition } from './domain/timeline';
describe('circular step positions', () => {
it('derives playback timing from tempo and fine-grained subdivisions', () => {
@@ -72,6 +76,17 @@ describe('circular step positions', () => {
expect(getStepFromPosition(point.x, point.y)).toBeCloseTo(fractionalStep, 8);
});
it('visually separates same-category instruments at the same beat tick', () => {
const beats: BeatPoint[] = [
{ id: 'kick-a', soundId: 'kick', letter: 'a', step: 4 },
{ id: 'snare-b', soundId: 'snare', letter: 'b', step: 4 },
];
const kickPosition = getStackedPosition(beats[0], beats, TOTAL_STEPS, 180);
const snarePosition = getStackedPosition(beats[1], beats, TOTAL_STEPS, 180);
expect(kickPosition).not.toEqual(snarePosition);
});
it('wraps fractional positions and reports loop percentages', () => {
expect(wrapStepPosition(16.25, 16)).toBeCloseTo(0.25);
expect(wrapStepPosition(-0.25, 16)).toBeCloseTo(15.75);
@@ -80,8 +95,8 @@ describe('circular step positions', () => {
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 },
{ id: 'first', soundId: 'kick', letter: 'a', step: 0 },
{ id: 'second', soundId: 'hi-hat', letter: 'b', step: 1 },
];
expect(getNextAvailableStep(beats)).toBe(2);
});
@@ -90,6 +105,7 @@ describe('circular step positions', () => {
const beats: BeatPoint[] = Array.from({ length: TOTAL_STEPS }, (_, step) => ({
id: `beat-${step}`,
soundId: 'kick',
letter: getAlphabeticLabel(step).toLowerCase(),
step,
}));
expect(getNextAvailableStep(beats)).toBe(0);
@@ -100,6 +116,7 @@ describe('circular step positions', () => {
const beats: BeatPoint[] = Array.from({ length: totalSteps }, (_, step) => ({
id: `beat-${step}`,
soundId: 'kick',
letter: getAlphabeticLabel(step).toLowerCase(),
step,
}));
expect(getNextAvailableStep(beats, totalSteps)).toBe(0);
@@ -125,6 +142,8 @@ describe('instrument catalog and pitch', () => {
);
expect(new Set(categorizedInstruments).size).toBe(INSTRUMENT_CATALOG.length);
expect(new Set(INSTRUMENT_CATEGORIES.map((category) => category.letter)).size)
.toBe(INSTRUMENT_CATEGORIES.length);
INSTRUMENT_CATALOG.forEach((instrument) => {
expect(categorizedInstruments).toContain(instrument.id);
expect(typeof INSTRUMENT_VOICES[instrument.id]).toBe('function');
@@ -140,14 +159,27 @@ describe('instrument catalog and pitch', () => {
expect(getPitchLabel(MAX_PITCH_SEMITONES)).toBe('C6');
expect(getPitchLabel(0, INSTRUMENT_BY_ID.kick.pitchBaseMidi)).toBe('F3');
});
it('assigns beat letters within their category and supports labels beyond Z', () => {
const beats: BeatPoint[] = [
{ id: 'kick-1', soundId: 'kick', letter: 'a', step: 0 },
{ id: 'snare-1', soundId: 'snare', letter: 'b', step: 4 },
{ id: 'piano-1', soundId: 'piano', letter: 'a', step: 8 },
];
expect(getNextBeatLetter(beats, 'drums')).toBe('c');
expect(getNextBeatLetter(beats, 'keys')).toBe('b');
expect(getAlphabeticLabel(26)).toBe('AA');
expect(INSTRUMENT_CATEGORY_BY_ID.drums.letter).toBe('A');
});
});
describe('sequencer state transitions', () => {
it('loads a template with a focused first beat and removes a focused sound ring', () => {
it('loads a template and removes every instrument in the focused category 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 },
{ id: 'kick-1', soundId: 'kick', letter: 'a', step: 0 },
{ id: 'snare-1', soundId: 'snare', letter: 'b', step: 4 },
{ id: 'piano-1', soundId: 'piano', letter: 'a', step: 8 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
@@ -157,18 +189,18 @@ describe('sequencer state transitions', () => {
});
expect(loaded.selectedBeatId).toBe('kick-1');
expect(loaded.focusedSoundId).toBe('kick');
expect(loaded.focusedCategoryId).toBe('drums');
const afterRingRemoval = sequencerReducer(loaded, { type: 'focused-sound-removed' });
const afterRingRemoval = sequencerReducer(loaded, { type: 'focused-category-removed' });
expect(afterRingRemoval.beats).toEqual([templateBeats[2]]);
expect(afterRingRemoval.selectedBeatId).toBeNull();
expect(afterRingRemoval.focusedSoundId).toBe('hi-hat');
expect(afterRingRemoval.focusedCategoryId).toBe('keys');
});
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 },
{ id: 'hat-1', soundId: 'hi-hat', letter: 'a', step: 0 },
{ id: 'kick-1', soundId: 'kick', letter: 'b', step: 12 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
@@ -184,13 +216,14 @@ describe('sequencer state transitions', () => {
expect(shortened.beats).toEqual(beats);
expect(shortened.selectedBeatId).toBeNull();
expect(shortened.focusedSoundId).toBe('hi-hat');
expect(shortened.focusedCategoryId).toBe('drums');
});
it('removes a focused sound and keeps the remaining ring selected', () => {
it('removes one category ring and focuses a remaining category', () => {
const beats: BeatPoint[] = [
{ id: 'kick-1', soundId: 'kick', step: 0 },
{ id: 'hat-1', soundId: 'hi-hat', step: 4 },
{ id: 'kick-1', soundId: 'kick', letter: 'a', step: 0 },
{ id: 'hat-1', soundId: 'hi-hat', letter: 'b', step: 4 },
{ id: 'bass-1', soundId: 'bass', letter: 'a', step: 8 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
@@ -198,11 +231,14 @@ describe('sequencer state transitions', () => {
tempoBpm: TEMPO_BPM,
beatsPerBar: 4,
});
const hatSelected = sequencerReducer(loaded, { type: 'sound-selected', soundId: 'hi-hat' });
const removed = sequencerReducer(hatSelected, { type: 'focused-sound-removed' });
const bassSelected = sequencerReducer(loaded, {
type: 'category-selected',
categoryId: 'bass',
});
const removed = sequencerReducer(bassSelected, { type: 'focused-category-removed' });
expect(removed.beats).toEqual([beats[0]]);
expect(removed.focusedSoundId).toBe('kick');
expect(removed.beats).toEqual([beats[0], beats[1]]);
expect(removed.focusedCategoryId).toBe('drums');
expect(removed.selectedBeatId).toBeNull();
});
@@ -217,8 +253,8 @@ describe('sequencer state transitions', () => {
it('changes pitch on one selected beat and clamps it to the supported range', () => {
const beats: BeatPoint[] = [
{ id: 'bass-1', soundId: 'bass', step: 0, pitchSemitones: 0 },
{ id: 'piano-1', soundId: 'piano', step: 4, pitchSemitones: 0 },
{ id: 'bass-1', soundId: 'bass', letter: 'a', step: 0, pitchSemitones: 0 },
{ id: 'piano-1', soundId: 'piano', letter: 'a', step: 4, pitchSemitones: 0 },
];
const loaded = sequencerReducer(createInitialSequencerState(), {
type: 'template-loaded',
+90 -28
View File
@@ -108,14 +108,6 @@ ion-content.app-content {
letter-spacing: 1px;
}
.header-tag {
color: var(--soft);
font-family: 'DM Sans', sans-serif;
font-size: 12px;
font-weight: 500;
letter-spacing: 0.1px;
}
.app-header-actions {
display: flex;
min-width: 0;
@@ -328,8 +320,9 @@ ion-content.app-content {
.studio-heading h1 {
margin: 0;
color: var(--ink);
font: 500 clamp(34px, 7vw, 44px)/1.1 var(--display);
letter-spacing: -1.8px;
font: 500 clamp(24px, 6vw, 40px)/1.1 var(--display);
letter-spacing: -1.1px;
white-space: nowrap;
}
.template-prompt {
@@ -592,6 +585,17 @@ ion-content.app-content {
transition: r 720ms cubic-bezier(0.22, 1.15, 0.36, 1);
}
.timeline-category-letter circle {
fill: var(--base);
stroke: currentColor;
stroke-width: 1.5;
}
.timeline-category-letter text {
fill: currentColor;
font: 700 9px var(--mono);
}
.timeline-tick line {
stroke: rgba(var(--primary-rgb), 0.34);
stroke-width: 1;
@@ -648,6 +652,13 @@ ion-content.app-content {
filter 120ms ease;
}
.sound-point-letter {
fill: var(--base);
font: 700 9px var(--mono);
pointer-events: none;
text-transform: lowercase;
}
.sound-point:hover .sound-point-face,
.sound-point.is-selected .sound-point-face,
.sound-point:focus-visible .sound-point-face {
@@ -742,17 +753,79 @@ ion-content.app-content {
.sound-legend {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 22px;
align-items: flex-start;
gap: 8px 12px;
padding-top: 17px;
}
.legend-sound {
display: inline-flex;
.legend-category-entry {
display: flex;
max-width: 220px;
flex-direction: column;
align-items: center;
gap: 7px;
}
.legend-category {
display: inline-flex;
height: 30px;
align-items: center;
margin: 0;
--color: var(--muted);
--background: transparent;
--background-hover: rgba(var(--primary-rgb), 0.08);
--background-activated: rgba(var(--primary-rgb), 0.12);
--border-radius: 7px;
font-size: 10px;
text-transform: none;
touch-action: manipulation;
user-select: none;
}
.legend-category::part(native) {
gap: 6px;
min-height: 30px;
padding: 0 8px;
}
.legend-category-letter,
.category-letter-badge {
display: inline-flex;
width: 17px;
height: 17px;
flex: 0 0 17px;
align-items: center;
justify-content: center;
border: 1px solid currentColor;
border-radius: 50%;
color: var(--ink);
font: 600 9px var(--mono);
}
.legend-category .legend-category-letter {
color: var(--muted);
font-size: 11px;
}
.legend-beat-list {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 2px 7px;
padding: 0 4px;
color: var(--soft);
font-size: 9px;
line-height: 1.5;
}
.legend-beat-list span {
white-space: nowrap;
}
.legend-beat-list strong {
color: var(--ink);
font-family: var(--mono);
text-transform: lowercase;
}
.legend-empty {
@@ -1150,12 +1223,6 @@ ion-popover.instrument-picker-popover {
flex-basis: 36px;
}
.header-tag {
font-size: 9px;
letter-spacing: 0;
max-width: 115px;
}
.about-view {
padding: 31px 0 24px;
}
@@ -1195,7 +1262,8 @@ ion-popover.instrument-picker-popover {
}
.studio-heading h1 {
font-size: 36px;
font-size: clamp(20px, 5.5vw, 32px);
letter-spacing: -0.75px;
}
.template-prompt {
@@ -1259,12 +1327,6 @@ ion-popover.instrument-picker-popover {
}
@media (max-width: 360px) {
.header-tag {
max-width: 90px;
font-size: 8px;
text-align: right;
}
.transport-inner {
gap: 5px;
padding-right: 10px;
+6 -2
View File
@@ -10,7 +10,7 @@ export function StudioView({ studio }: StudioViewProps) {
return (
<main id="studio" className="studio">
<div className="studio-heading">
<h1>Build a beat.</h1>
<h1>Sharpen your sense of rhythm</h1>
<p className="template-prompt">Choose a dance template</p>
<BeatTemplateSelector onSelectTemplate={studio.applyTemplate} />
<p
@@ -21,7 +21,11 @@ export function StudioView({ studio }: StudioViewProps) {
</p>
</div>
<BeatLoopPanel sequencer={studio.sequencer} soundPalette={studio.soundPalette} />
<BeatLoopPanel
sequencer={studio.sequencer}
soundPalette={studio.soundPalette}
categoryLabels={studio.categoryLabels}
/>
{studio.sequencer.audioError && (
<p className="audio-error" role="alert">{studio.sequencer.audioError}</p>