Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

2.4 KB
Raw Blame
import { useCallback, useEffect, useRef, useState } from 'react';
import { createMidiPlayer } from '../lib/midiPlayback.js';

// React wrapper over lib/midiPlayback.js for the MIDI visualization (#2490):
// owns one player per parsed view-model, exposes play/pause + seek + a stable
// getPosition for the <MidiPianoRoll> rAF playhead, and tears the player down
// when the data changes or the host unmounts so oscillators never outlive the
// file they preview. No audio is touched until the first toggle — the player
// only reaches for the AudioContext inside play().

/**
 * @param {object|null} data — parseMidiFile view-model (null while loading/collapsed).
 * @returns {{ playing:boolean, toggle:()=>void, seek:(sec:number)=>void,
 *   getPosition:()=>number }}
 */
export default function useMidiPlayer(data) {
  const [playing, setPlaying] = useState(false);
  const playerRef = useRef(null);
  // Intent mirror of the `playing` state. Toggle branches on THIS, not
  // player.isPlaying(): during a first play the player's flag only flips after
  // its `await ctx.resume()`, so a rapid double-toggle would read false twice
  // and start playback instead of netting out to a cancel.
  const playingRef = useRef(false);
  const setPlayingBoth = useCallback((v) => {
    playingRef.current = v;
    setPlaying(v);
  }, []);

  useEffect(() => {
    if (!data) return undefined;
    const player = createMidiPlayer(data, { onEnded: () => setPlayingBoth(false) });
    playerRef.current = player;
    return () => {
      player.stop();
      playerRef.current = null;
      setPlayingBoth(false);
    };
  }, [data, setPlayingBoth]);

  const toggle = useCallback(() => {
    const player = playerRef.current;
    if (!player) return;
    if (playingRef.current) {
      // pause() also aborts a play() still awaiting ctx.resume() (playToken).
      player.pause();
      setPlayingBoth(false);
    } else {
      setPlayingBoth(true);
      // play() resolves once playback has STARTED; a resume failure (autoplay
      // policy edge) lands here — reset the button instead of lying "playing".
      player.play().catch((err) => {
        console.error(`🎹 MIDI preview failed to start: ${err.message}`);
        setPlayingBoth(false);
      });
    }
  }, [setPlayingBoth]);

  const seek = useCallback((sec) => { playerRef.current?.seek(sec); }, []);
  const getPosition = useCallback(() => playerRef.current?.position() ?? 0, []);

  return { playing, toggle, seek, getPosition };
}