55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import { useCallback, useMemo, useState } from 'react';
|
|
import { INSTRUMENT_BY_ID } from '../domain/instruments';
|
|
import type { InstrumentCategoryId, InstrumentId } from '../domain/instruments';
|
|
import { generateUniqueSoundColor } from '../domain/soundColors';
|
|
|
|
export interface PaletteSound {
|
|
id: InstrumentId;
|
|
color: string;
|
|
}
|
|
|
|
export interface SoundPalette {
|
|
activeSounds: PaletteSound[];
|
|
colorBySoundId: Partial<Record<InstrumentId, string>>;
|
|
colorByCategoryId: Partial<Record<InstrumentCategoryId, string>>;
|
|
activateSounds: (instrumentIds: readonly InstrumentId[]) => void;
|
|
}
|
|
|
|
export function useSoundPalette(): SoundPalette {
|
|
const [activeSounds, setActiveSounds] = useState<PaletteSound[]>([]);
|
|
|
|
const activateSounds = useCallback((instrumentIds: readonly InstrumentId[]): void => {
|
|
setActiveSounds((currentSounds) => {
|
|
const nextSounds = [...currentSounds];
|
|
instrumentIds.forEach((instrumentId) => {
|
|
if (nextSounds.some((sound) => sound.id === instrumentId)) return;
|
|
|
|
nextSounds.push({
|
|
id: instrumentId,
|
|
color: generateUniqueSoundColor(nextSounds.map((sound) => sound.color)),
|
|
});
|
|
});
|
|
return nextSounds.length === currentSounds.length ? currentSounds : nextSounds;
|
|
});
|
|
}, []);
|
|
|
|
const colorBySoundId = useMemo(() => {
|
|
const colors: Partial<Record<InstrumentId, string>> = {};
|
|
activeSounds.forEach((sound) => {
|
|
colors[sound.id] = sound.color;
|
|
});
|
|
return colors;
|
|
}, [activeSounds]);
|
|
|
|
const colorByCategoryId = useMemo(() => {
|
|
const colors: Partial<Record<InstrumentCategoryId, string>> = {};
|
|
activeSounds.forEach((sound) => {
|
|
const categoryId = INSTRUMENT_BY_ID[sound.id].categoryId;
|
|
if (colors[categoryId] === undefined) colors[categoryId] = sound.color;
|
|
});
|
|
return colors;
|
|
}, [activeSounds]);
|
|
|
|
return { activeSounds, colorBySoundId, colorByCategoryId, activateSounds };
|
|
}
|