import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; import CodeMirror, { markEvent, markParens } from './CodeMirror'; import cx from './cx'; import { evaluate } from '../eval/evaluate.mjs'; // import logo from './logo.svg'; import playStatic from './static.mjs'; import { defaultSynth } from '../tone/tone.mjs'; import * as tunes from '../tunes/tunes'; import useRepl from '../../repl/src/useRepl'; import { useWebMidi } from './useWebMidi'; // TODO: use https://www.npmjs.com/package/@monaco-editor/react const [_, codeParam] = window.location.href.split('#'); let decoded; try { decoded = atob(decodeURIComponent(codeParam || '')); } catch (err) { console.warn('failed to decode', err); } function getRandomTune() { const allTunes = Object.values(tunes); const randomItem = (arr) => arr[Math.floor(Math.random() * arr.length)]; return randomItem(allTunes); } const randomTune = getRandomTune(); function App() { const [editor, setEditor] = useState(); const { setCode, setPattern, error, code, cycle, dirty, log, togglePlay, activateCode, pattern, pushLog, pending } = useRepl({ tune: decoded || randomTune, defaultSynth, onDraw: useCallback(markEvent(editor), [editor]), }); const [uiHidden, setUiHidden] = useState(false); const logBox = useRef(); // scroll log box to bottom when log changes useLayoutEffect(() => { logBox.current.scrollTop = logBox.current?.scrollHeight; }, [log]); // set active pattern on ctrl+enter useLayoutEffect(() => { // TODO: make sure this is only fired when editor has focus const handleKeyPress = async (e) => { if (e.ctrlKey || e.altKey) { switch (e.code) { case 'Enter': await activateCode(); break; case 'Period': cycle.stop(); } } }; window.addEventListener('keydown', handleKeyPress); return () => window.removeEventListener('keydown', handleKeyPress); }, [pattern, code]); useWebMidi({ ready: useCallback(({ outputs }) => { pushLog(`WebMidi ready! Just add .midi(${outputs.map((o) => `'${o.name}'`).join(' | ')}) to the pattern. `); }, []), connected: useCallback(({ outputs }) => { pushLog(`Midi device connected! Available: ${outputs.map((o) => `'${o.name}'`).join(', ')}`); }, []), disconnected: useCallback(({ outputs }) => { pushLog(`Midi device disconnected! Available: ${outputs.map((o) => `'${o.name}'`).join(', ')}`); }, []), }); return (