Merge branch 'codemirror-6' into reset
This commit is contained in:
commit
21a1fe5056
10 changed files with 929 additions and 139 deletions
|
|
@ -4,8 +4,8 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
|||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import CodeMirror6, { setHighlights } from './CodeMirror6';
|
||||
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import CodeMirror, { markEvent, markParens } from './CodeMirror';
|
||||
import cx from './cx';
|
||||
import logo from './logo.svg';
|
||||
import playStatic from './static.mjs';
|
||||
|
|
@ -39,6 +39,7 @@ import '@strudel.cycles/osc/osc.mjs';
|
|||
import '@strudel.cycles/webaudio/webaudio.mjs';
|
||||
import '@strudel.cycles/serial/serial.mjs';
|
||||
import controls from '@strudel.cycles/core/controls.mjs';
|
||||
import useHighlighting from './useHighlighting';
|
||||
|
||||
extend(
|
||||
Tone,
|
||||
|
|
@ -56,7 +57,6 @@ extend(
|
|||
Tone,
|
||||
},
|
||||
);
|
||||
// eval stuff end
|
||||
|
||||
const codeParam = window.location.href.split('#')[1];
|
||||
let decoded;
|
||||
|
|
@ -76,14 +76,27 @@ const randomTune = getRandomTune();
|
|||
const defaultSynth = getDefaultSynth();
|
||||
|
||||
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((time, event) => markEvent(editor)(time, event), [editor]),
|
||||
});
|
||||
const [uiHidden, setUiHidden] = useState(false);
|
||||
// const [editor, setEditor] = useState();
|
||||
const [view, setView] = useState();
|
||||
const {
|
||||
setCode,
|
||||
setPattern,
|
||||
error,
|
||||
code,
|
||||
cycle,
|
||||
dirty,
|
||||
log,
|
||||
togglePlay,
|
||||
activeCode,
|
||||
setActiveCode,
|
||||
activateCode,
|
||||
pattern,
|
||||
pushLog,
|
||||
pending,
|
||||
} = useRepl({
|
||||
tune: decoded || randomTune,
|
||||
defaultSynth,
|
||||
});
|
||||
const logBox = useRef();
|
||||
// scroll log box to bottom when log changes
|
||||
useLayoutEffect(() => {
|
||||
|
|
@ -108,6 +121,8 @@ function App() {
|
|||
return () => window.removeEventListener('keydown', handleKeyPress);
|
||||
}, [pattern, code, activateCode, cycle]);
|
||||
|
||||
useHighlighting({ view, pattern, started: cycle.started });
|
||||
|
||||
useWebMidi({
|
||||
ready: useCallback(
|
||||
({ outputs }) => {
|
||||
|
|
@ -133,17 +148,14 @@ function App() {
|
|||
<div className="min-h-screen flex flex-col">
|
||||
<header
|
||||
id="header"
|
||||
className={cx(
|
||||
'flex-none w-full h-14 px-2 flex border-b border-gray-200 justify-between z-[10]',
|
||||
uiHidden ? 'bg-transparent text-white' : 'bg-white',
|
||||
)}
|
||||
className="flex-none w-full h-14 px-2 flex border-b border-gray-200 justify-between z-[10] bg-gray-100"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<img src={logo} className="Tidal-logo w-12 h-12" alt="logo" />
|
||||
<h1 className="text-2xl">Strudel REPL</h1>
|
||||
<img src={logo} className="Tidal-logo w-10 h-10" alt="logo" />
|
||||
<h1 className="text-xl">Strudel REPL</h1>
|
||||
</div>
|
||||
<div className="flex space-x-4">
|
||||
<button onClick={() => togglePlay()}>
|
||||
<div className="flex">
|
||||
<button onClick={() => togglePlay()} className="hover:bg-gray-300 p-2">
|
||||
{!pending ? (
|
||||
<span className="flex items-center w-16">
|
||||
{cycle.started ? (
|
||||
|
|
@ -170,6 +182,7 @@ function App() {
|
|||
)}
|
||||
</button>
|
||||
<button
|
||||
className="hover:bg-gray-300 p-2"
|
||||
onClick={async () => {
|
||||
const _code = getRandomTune();
|
||||
console.log('tune', _code); // uncomment this to debug when random code fails
|
||||
|
|
@ -178,42 +191,23 @@ function App() {
|
|||
uiHelpers.cleanup();
|
||||
const parsed = await evaluate(_code);
|
||||
setPattern(parsed.pattern);
|
||||
setActiveCode(_code);
|
||||
}}
|
||||
>
|
||||
🎲 random
|
||||
</button>
|
||||
<button>
|
||||
<button className="hover:bg-gray-300 p-2">
|
||||
<a href="./tutorial">📚 tutorial</a>
|
||||
</button>
|
||||
<button onClick={() => setUiHidden((c) => !c)}>👀 {uiHidden ? 'show ui' : 'hide ui'}</button>
|
||||
</div>
|
||||
</header>
|
||||
<section className="grow flex flex-col text-gray-100">
|
||||
<div className="grow relative" id="code">
|
||||
<div
|
||||
className={cx(
|
||||
'h-full transition-opacity',
|
||||
error ? 'focus:ring-red-500' : 'focus:ring-slate-800',
|
||||
uiHidden ? 'opacity-0' : 'opacity-100',
|
||||
)}
|
||||
>
|
||||
<CodeMirror
|
||||
value={code}
|
||||
editorDidMount={setEditor}
|
||||
options={{
|
||||
mode: 'javascript',
|
||||
theme: 'material',
|
||||
lineNumbers: false,
|
||||
styleSelectedText: true,
|
||||
cursorBlinkRate: 0,
|
||||
}}
|
||||
onCursor={markParens}
|
||||
onChange={(_, __, value) => setCode(value)}
|
||||
/>
|
||||
<span className="p-4 absolute top-0 right-0 text-xs whitespace-pre text-right pointer-events-none">
|
||||
{!cycle.started ? `press ctrl+enter to play\n` : dirty ? `ctrl+enter to update\n` : 'no changes\n'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grow relative flex overflow-auto" id="code">
|
||||
{/* onCursor={markParens} */}
|
||||
<CodeMirror6 value={code} onChange={setCode} onViewChanged={setView} />
|
||||
<span className="p-4 absolute top-0 right-0 text-xs whitespace-pre text-right pointer-events-none">
|
||||
{!cycle.started ? `press ctrl+enter to play\n` : dirty ? `ctrl+enter to update\n` : 'no changes\n'}
|
||||
</span>
|
||||
{error && (
|
||||
<div className={cx('absolute right-2 bottom-2 px-2', 'text-red-500')}>
|
||||
{error?.message || 'unknown error'}
|
||||
|
|
|
|||
|
|
@ -1,53 +1,72 @@
|
|||
import React from 'react';
|
||||
import { Controlled as CodeMirror2 } from 'react-codemirror2';
|
||||
import 'codemirror/mode/javascript/javascript';
|
||||
import 'codemirror/mode/pegjs/pegjs';
|
||||
// import 'codemirror/theme/material.css';
|
||||
import 'codemirror/lib/codemirror.css';
|
||||
import 'codemirror/theme/material.css';
|
||||
import { CodeMirror as _CodeMirror } from 'react-codemirror6';
|
||||
import { EditorView, Decoration } from '@codemirror/view';
|
||||
import { StateField, StateEffect } from '@codemirror/state';
|
||||
import { javascript } from '@codemirror/lang-javascript';
|
||||
// import { materialPalenight } from 'codemirror6-themes';
|
||||
import { materialPalenight } from './themes/material-palenight';
|
||||
|
||||
export default function CodeMirror({ value, onChange, onCursor, options, editorDidMount }) {
|
||||
options = options || {
|
||||
mode: 'javascript',
|
||||
theme: 'material',
|
||||
lineNumbers: true,
|
||||
styleSelectedText: true,
|
||||
cursorBlinkRate: 500,
|
||||
};
|
||||
export const setHighlights = StateEffect.define();
|
||||
const highlightField = StateField.define({
|
||||
create() {
|
||||
return Decoration.none;
|
||||
},
|
||||
update(highlights, tr) {
|
||||
try {
|
||||
for (let e of tr.effects) {
|
||||
if (e.is(setHighlights)) {
|
||||
highlights = Decoration.set(
|
||||
e.value
|
||||
.flatMap((hap) =>
|
||||
(hap.context.locations || []).map(({ start, end }) => {
|
||||
const color = hap.context.color || '#FFCA28';
|
||||
let from = tr.newDoc.line(start.line).from + start.column;
|
||||
let to = tr.newDoc.line(end.line).from + end.column;
|
||||
const l = tr.newDoc.length;
|
||||
if (from > l || to > l) {
|
||||
return; // dont mark outside of range, as it will throw an error
|
||||
}
|
||||
const mark = Decoration.mark({ attributes: { style: `outline: 1px solid ${color}` } });
|
||||
return mark.range(from, to);
|
||||
}),
|
||||
)
|
||||
.filter(Boolean),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
return highlights;
|
||||
} catch (err) {
|
||||
console.warn('highlighting error', err);
|
||||
return highlights;
|
||||
}
|
||||
},
|
||||
provide: (f) => EditorView.decorations.from(f),
|
||||
});
|
||||
|
||||
export default function CodeMirror({ value, onChange, onViewChanged, onCursor, options, editorDidMount }) {
|
||||
return (
|
||||
<CodeMirror2
|
||||
value={value}
|
||||
options={options}
|
||||
onBeforeChange={onChange}
|
||||
editorDidMount={editorDidMount}
|
||||
onCursor={(editor, data) => onCursor?.(editor, data)}
|
||||
/>
|
||||
<>
|
||||
<_CodeMirror
|
||||
onViewChange={onViewChanged}
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flex: '1 0 auto',
|
||||
}}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
extensions={[
|
||||
javascript(),
|
||||
materialPalenight,
|
||||
highlightField,
|
||||
// theme, language, ...
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const markEvent = (editor) => (time, event) => {
|
||||
const locs = event.context.locations;
|
||||
if (!locs || !editor) {
|
||||
return;
|
||||
}
|
||||
const col = event.context?.color || '#FFCA28';
|
||||
// mark active event
|
||||
const marks = locs.map(({ start, end }) =>
|
||||
editor.getDoc().markText(
|
||||
{ line: start.line - 1, ch: start.column },
|
||||
{ line: end.line - 1, ch: end.column },
|
||||
//{ css: 'background-color: #FFCA28; color: black' } // background-color is now used by parent marking
|
||||
{ css: 'outline: 1px solid ' + col + '; box-sizing:border-box' },
|
||||
//{ css: `background-color: ${col};border-radius:5px` },
|
||||
),
|
||||
);
|
||||
//Tone.Transport.schedule(() => { // problem: this can be cleared by scheduler...
|
||||
setTimeout(() => {
|
||||
marks.forEach((mark) => mark.clear());
|
||||
// }, '+' + event.duration.valueOf() * 0.5);
|
||||
}, event.duration.valueOf() /* * 0.9 */ * 1000);
|
||||
};
|
||||
|
||||
let parenMark;
|
||||
export const markParens = (editor, data) => {
|
||||
const v = editor.getDoc().getValue();
|
||||
|
|
@ -75,6 +94,10 @@ export function offsetToPosition(offset, code) {
|
|||
// returns absolute character offset from { line, ch }
|
||||
export function positionToOffset(position, code) {
|
||||
const lines = code.split('\n');
|
||||
if (position.line > lines.length) {
|
||||
// throw new Error('positionToOffset: position.line > lines.length');
|
||||
return 0;
|
||||
}
|
||||
let offset = 0;
|
||||
for (let i = 0; i < position.line; i++) {
|
||||
offset += lines[i].length + 1;
|
||||
|
|
@ -119,3 +142,27 @@ export function getCurrentParenArea(code, caretPosition) {
|
|||
end = i;
|
||||
return [begin, end].map((o) => offsetToPosition(o, code));
|
||||
}
|
||||
|
||||
/*
|
||||
export const markEvent = (editor) => (time, event) => {
|
||||
const locs = event.context.locations;
|
||||
if (!locs || !editor) {
|
||||
return;
|
||||
}
|
||||
const col = event.context?.color || '#FFCA28';
|
||||
// mark active event
|
||||
const marks = locs.map(({ start, end }) =>
|
||||
editor.getDoc().markText(
|
||||
{ line: start.line - 1, ch: start.column },
|
||||
{ line: end.line - 1, ch: end.column },
|
||||
//{ css: 'background-color: #FFCA28; color: black' } // background-color is now used by parent marking
|
||||
{ css: 'outline: 1px solid ' + col + '; box-sizing:border-box' },
|
||||
//{ css: `background-color: ${col};border-radius:5px` },
|
||||
),
|
||||
);
|
||||
//Tone.Transport.schedule(() => { // problem: this can be cleared by scheduler...
|
||||
setTimeout(() => {
|
||||
marks.forEach((mark) => mark.clear());
|
||||
// }, '+' + event.duration * 0.5);
|
||||
}, event.duration * 1000);
|
||||
}; */
|
||||
135
repl/src/themes/material-palenight.js
Normal file
135
repl/src/themes/material-palenight.js
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
import { EditorView } from '@codemirror/view';
|
||||
import { HighlightStyle, tags as t } from '@codemirror/highlight';
|
||||
|
||||
/*
|
||||
Credits for color palette:
|
||||
|
||||
Author: Mattia Astorino (http://github.com/equinusocio)
|
||||
Website: https://material-theme.site/
|
||||
*/
|
||||
|
||||
const ivory = '#abb2bf',
|
||||
stone = '#7d8799', // Brightened compared to original to increase contrast
|
||||
invalid = '#ffffff',
|
||||
darkBackground = '#21252b',
|
||||
highlightBackground = 'rgba(0, 0, 0, 0.5)',
|
||||
// background = '#292d3e',
|
||||
background = 'transparent',
|
||||
tooltipBackground = '#353a42',
|
||||
selection = 'rgba(128, 203, 196, 0.2)',
|
||||
cursor = '#ffcc00';
|
||||
|
||||
/// The editor theme styles for Material Palenight.
|
||||
export const materialPalenightTheme = EditorView.theme(
|
||||
{
|
||||
// done
|
||||
'&': {
|
||||
color: '#ffffff',
|
||||
backgroundColor: background,
|
||||
fontSize: '15px',
|
||||
'z-index': 11,
|
||||
},
|
||||
|
||||
// done
|
||||
'.cm-content': {
|
||||
caretColor: cursor,
|
||||
lineHeight: '22px',
|
||||
},
|
||||
'.cm-line': {
|
||||
background: '#2C323699',
|
||||
},
|
||||
// done
|
||||
'&.cm-focused .cm-cursor': {
|
||||
borderLeftColor: cursor,
|
||||
},
|
||||
|
||||
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': {
|
||||
backgroundColor: selection,
|
||||
},
|
||||
|
||||
'.cm-panels': { backgroundColor: darkBackground, color: '#ffffff' },
|
||||
'.cm-panels.cm-panels-top': { borderBottom: '2px solid black' },
|
||||
'.cm-panels.cm-panels-bottom': { borderTop: '2px solid black' },
|
||||
|
||||
// done, use onedarktheme
|
||||
'.cm-searchMatch': {
|
||||
backgroundColor: '#72a1ff59',
|
||||
outline: '1px solid #457dff',
|
||||
},
|
||||
'.cm-searchMatch.cm-searchMatch-selected': {
|
||||
backgroundColor: '#6199ff2f',
|
||||
},
|
||||
|
||||
'.cm-activeLine': { backgroundColor: highlightBackground },
|
||||
'.cm-selectionMatch': { backgroundColor: '#aafe661a' },
|
||||
|
||||
'&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket': {
|
||||
backgroundColor: '#bad0f847',
|
||||
outline: '1px solid #515a6b',
|
||||
},
|
||||
|
||||
// done
|
||||
'.cm-gutters': {
|
||||
background: '#2C323699',
|
||||
color: '#676e95',
|
||||
border: 'none',
|
||||
},
|
||||
|
||||
'.cm-activeLineGutter': {
|
||||
backgroundColor: highlightBackground,
|
||||
},
|
||||
|
||||
'.cm-foldPlaceholder': {
|
||||
backgroundColor: 'transparent',
|
||||
border: 'none',
|
||||
color: '#ddd',
|
||||
},
|
||||
|
||||
'.cm-tooltip': {
|
||||
border: 'none',
|
||||
backgroundColor: tooltipBackground,
|
||||
},
|
||||
'.cm-tooltip .cm-tooltip-arrow:before': {
|
||||
borderTopColor: 'transparent',
|
||||
borderBottomColor: 'transparent',
|
||||
},
|
||||
'.cm-tooltip .cm-tooltip-arrow:after': {
|
||||
borderTopColor: tooltipBackground,
|
||||
borderBottomColor: tooltipBackground,
|
||||
},
|
||||
'.cm-tooltip-autocomplete': {
|
||||
'& > ul > li[aria-selected]': {
|
||||
backgroundColor: highlightBackground,
|
||||
color: ivory,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ dark: true },
|
||||
);
|
||||
|
||||
/// The highlighting style for code in the Material Palenight theme.
|
||||
export const materialPalenightHighlightStyle = HighlightStyle.define([
|
||||
{ tag: t.keyword, color: '#c792ea' },
|
||||
{ tag: t.operator, color: '#89ddff' },
|
||||
{ tag: t.special(t.variableName), color: '#eeffff' },
|
||||
{ tag: t.typeName, color: '#f07178' },
|
||||
{ tag: t.atom, color: '#f78c6c' },
|
||||
{ tag: t.number, color: '#ff5370' },
|
||||
{ tag: t.definition(t.variableName), color: '#82aaff' },
|
||||
{ tag: t.string, color: '#c3e88d' },
|
||||
{ tag: t.special(t.string), color: '#f07178' },
|
||||
{ tag: t.comment, color: stone },
|
||||
{ tag: t.variableName, color: '#f07178' },
|
||||
{ tag: t.tagName, color: '#ff5370' },
|
||||
{ tag: t.bracket, color: '#a2a1a4' },
|
||||
{ tag: t.meta, color: '#ffcb6b' },
|
||||
{ tag: t.attributeName, color: '#c792ea' },
|
||||
{ tag: t.propertyName, color: '#c792ea' },
|
||||
{ tag: t.className, color: '#decb6b' },
|
||||
{ tag: t.invalid, color: invalid },
|
||||
]);
|
||||
|
||||
/// Extension to enable the Material Palenight theme (both the editor theme and
|
||||
/// the highlight style).
|
||||
// : Extension
|
||||
export const materialPalenight = [materialPalenightTheme, materialPalenightHighlightStyle];
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { Tone } from '@strudel.cycles/tone';
|
||||
import useRepl from '../useRepl.mjs';
|
||||
import CodeMirror, { markEvent } from '../CodeMirror';
|
||||
import cx from '../cx';
|
||||
import useHighlighting from '../useHighlighting';
|
||||
import { useInView } from 'react-hook-inview';
|
||||
|
||||
// eval stuff start
|
||||
import { extend } from '@strudel.cycles/eval';
|
||||
|
|
@ -24,6 +25,7 @@ import '@strudel.cycles/xen/tune.mjs';
|
|||
import '@strudel.cycles/core/euclid.mjs';
|
||||
import '@strudel.cycles/tone/pianoroll.mjs';
|
||||
import '@strudel.cycles/tone/draw.mjs';
|
||||
import CodeMirror6 from '../CodeMirror6';
|
||||
|
||||
extend(Tone, strudel, strudel.Pattern.prototype.bootstrap(), toneHelpers, voicingHelpers, drawHelpers, uiHelpers, {
|
||||
gist,
|
||||
|
|
@ -43,17 +45,19 @@ const defaultSynth = new Tone.PolySynth().chain(new Tone.Gain(0.5), Tone.Destina
|
|||
// "balanced" | "interactive" | "playback";
|
||||
// Tone.setContext(new Tone.Context({ latencyHint: 'playback', lookAhead: 1 }));
|
||||
function MiniRepl({ tune, maxHeight = 500 }) {
|
||||
const [editor, setEditor] = useState();
|
||||
const { code, setCode, activateCode, activeCode, setPattern, error, cycle, dirty, log, togglePlay, hash } = useRepl({
|
||||
const { code, setCode, pattern, activateCode, error, cycle, dirty, togglePlay } = useRepl({
|
||||
tune,
|
||||
defaultSynth,
|
||||
autolink: false,
|
||||
onDraw: useCallback(markEvent(editor), [editor]),
|
||||
});
|
||||
const lines = code.split('\n').length;
|
||||
const height = Math.min(lines * 30 + 30, maxHeight);
|
||||
const [view, setView] = useState();
|
||||
const [ref, isVisible] = useInView({
|
||||
threshold: 0.01,
|
||||
});
|
||||
useHighlighting({ view, pattern, started: cycle.started });
|
||||
return (
|
||||
<div className="rounded-md overflow-hidden">
|
||||
<div className="rounded-md overflow-hidden bg-[#444C57]" ref={ref}>
|
||||
<div className="flex justify-between bg-slate-700 border-t border-slate-500">
|
||||
<div className="flex">
|
||||
<button
|
||||
|
|
@ -101,18 +105,8 @@ function MiniRepl({ tune, maxHeight = 500 }) {
|
|||
</div>
|
||||
<div className="text-right p-1 text-sm">{error && <span className="text-red-200">{error.message}</span>}</div>{' '}
|
||||
</div>
|
||||
<div className="flex space-y-0 overflow-auto" style={{ height }}>
|
||||
<CodeMirror
|
||||
className="w-full"
|
||||
value={code}
|
||||
editorDidMount={setEditor}
|
||||
options={{
|
||||
mode: 'javascript',
|
||||
theme: 'material',
|
||||
lineNumbers: true,
|
||||
}}
|
||||
onChange={(_, __, value) => setCode(value)}
|
||||
/>
|
||||
<div className="flex space-y-0 overflow-auto relative">
|
||||
{isVisible && <CodeMirror6 value={code} onChange={setCode} onViewChanged={setView} />}
|
||||
</div>
|
||||
{/* <div className="bg-slate-700 border-t border-slate-500 content-right pr-2 text-right">
|
||||
<a href={`https://strudel.tidalcycles.org/#${hash}`} className="text-white items-center inline-flex">
|
||||
|
|
|
|||
|
|
@ -2,10 +2,8 @@
|
|||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
.react-codemirror2,
|
||||
.CodeMirror {
|
||||
width: 100% !important;
|
||||
height: inherit !important;
|
||||
.cm-editor {
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
main {
|
||||
|
|
|
|||
33
repl/src/useHighlighting.js
Normal file
33
repl/src/useHighlighting.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { useEffect } from 'react';
|
||||
import { setHighlights } from './CodeMirror6';
|
||||
import { Tone } from '@strudel.cycles/tone';
|
||||
|
||||
let highlights = []; // actively highlighted events
|
||||
|
||||
function useHighlighting({ view, pattern, started }) {
|
||||
useEffect(() => {
|
||||
if (view) {
|
||||
if (pattern && started) {
|
||||
let frame = requestAnimationFrame(updateHighlights);
|
||||
|
||||
function updateHighlights() {
|
||||
const audioTime = Tone.getTransport().seconds;
|
||||
highlights = highlights.filter((hap) => hap.whole.end > audioTime); // keep only highlights that are still active
|
||||
const haps = pattern.queryArc(audioTime, audioTime + 1 / 60).filter((hap) => hap.hasOnset());
|
||||
highlights = highlights.concat(haps); // add potential new onsets
|
||||
view.dispatch({ effects: setHighlights.of(highlights) }); // highlight all still active + new active haps
|
||||
frame = requestAnimationFrame(updateHighlights);
|
||||
}
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
};
|
||||
} else {
|
||||
highlights = [];
|
||||
view.dispatch({ effects: setHighlights.of([]) });
|
||||
}
|
||||
}
|
||||
}, [pattern, started, view]);
|
||||
}
|
||||
|
||||
export default useHighlighting;
|
||||
|
|
@ -17,7 +17,7 @@ let s4 = () => {
|
|||
};
|
||||
const generateHash = (code) => encodeURIComponent(btoa(code));
|
||||
|
||||
function useRepl({ tune, defaultSynth, autolink = true, onEvent, onDraw }) {
|
||||
function useRepl({ tune, defaultSynth, autolink = true, onEvent, onDraw: onDrawProp }) {
|
||||
const id = useMemo(() => s4(), []);
|
||||
const [code, setCode] = useState(tune);
|
||||
const [activeCode, setActiveCode] = useState();
|
||||
|
|
@ -30,11 +30,11 @@ function useRepl({ tune, defaultSynth, autolink = true, onEvent, onDraw }) {
|
|||
const pushLog = useCallback((message) => setLog((log) => log + `${log ? '\n\n' : ''}${message}`), []);
|
||||
|
||||
// below block allows disabling the highlighting by including "strudel disable-highlighting" in the code (as comment)
|
||||
onDraw = useMemo(() => {
|
||||
const onDraw = useMemo(() => {
|
||||
if (activeCode && !activeCode.includes('strudel disable-highlighting')) {
|
||||
return onDraw;
|
||||
return (time, event) => onDrawProp?.(time, event, activeCode);
|
||||
}
|
||||
}, [activeCode, onDraw]);
|
||||
}, [activeCode, onDrawProp]);
|
||||
|
||||
// cycle hook to control scheduling
|
||||
const cycle = useCycle({
|
||||
|
|
@ -146,6 +146,7 @@ function useRepl({ tune, defaultSynth, autolink = true, onEvent, onDraw }) {
|
|||
dirty,
|
||||
log,
|
||||
togglePlay,
|
||||
setActiveCode,
|
||||
activateCode,
|
||||
activeCode,
|
||||
pushLog,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue