import React, { useMemo, useState, useEffect } from 'react'; import './InstrumentSelection.css'; import { useProjectStore } from '../stores/projectStore'; import { INSTRUMENT_GROUPS, FLUIDR3_INSTRUMENT_MAP } from '../constants/generalMidiConstants'; import { KGMidiTrack, type InstrumentType } from '../core/track/KGMidiTrack'; const InstrumentSelection: React.FC = () => { const { tracks, selectedTrackId, closeInstrumentSelection, setTrackInstrument } = useProjectStore(); const targetTrack = useMemo(() => { return tracks.find(t => t.getId().toString() === selectedTrackId) || null; }, [tracks, selectedTrackId]); const currentInstrumentKey: InstrumentType = (targetTrack && targetTrack instanceof KGMidiTrack) ? (targetTrack.getInstrument() as InstrumentType) : 'acoustic_grand_piano'; const currentInstrumentDef = FLUIDR3_INSTRUMENT_MAP[currentInstrumentKey] || FLUIDR3_INSTRUMENT_MAP['acoustic_grand_piano']; // Maintain selected group in local state; selected instrument derives from model const [selectedGroupKey, setSelectedGroupKey] = useState(currentInstrumentDef?.group || 'PIANO_AND_KEYBOARDS'); useEffect(() => { // Sync when the target track or its instrument changes setSelectedGroupKey(currentInstrumentDef?.group || 'PIANO_AND_KEYBOARDS'); }, [selectedTrackId, currentInstrumentKey, currentInstrumentDef]); const groups = useMemo(() => Object.entries(INSTRUMENT_GROUPS) as Array<[string, string]>, []); const instrumentsInGroup = useMemo(() => { return Object.entries(FLUIDR3_INSTRUMENT_MAP) .filter((entry) => entry[1].group === selectedGroupKey) .map((entry) => ({ key: entry[0], label: entry[1].displayName })); }, [selectedGroupKey]); const handleSelectGroup = (groupKey: string) => { setSelectedGroupKey(groupKey); }; const handleSelectInstrument = async (instrumentKey: string) => { // If no valid target track, ignore user interaction if (!targetTrack || !(targetTrack instanceof KGMidiTrack)) return; const instrument = instrumentKey as InstrumentType; try { await setTrackInstrument(targetTrack.getId(), instrument); } catch (err) { console.error('Failed to change instrument from panel:', err); } }; const previewImage = FLUIDR3_INSTRUMENT_MAP[currentInstrumentKey]?.image || 'piano.png'; const previewAlt = FLUIDR3_INSTRUMENT_MAP[currentInstrumentKey]?.displayName || currentInstrumentKey; const hasTargetTrack = !!targetTrack; return (

{hasTargetTrack ? `${previewAlt.toString()}` : ''}

{hasTargetTrack && (
{previewAlt.toString()}
)}
{hasTargetTrack ? targetTrack.getName() : ''}
{groups.map(([key, label]) => (
handleSelectGroup(key)} > {label}
))}
{instrumentsInGroup.map((inst) => (
handleSelectInstrument(inst.key)} > {inst.label}
))}
); }; export default InstrumentSelection;