Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Work on Codemirror 6 highlighting #102

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 26 additions & 2 deletions repl/src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useCallback, useLayoutEffect, useRef, useState, useEffect } from 'react';
import CodeMirror6, { highlightEvent } from './CodeMirror6';
import CodeMirror6, { setHighlights } from './CodeMirror6';
import cx from './cx';
import logo from './logo.svg';
import playStatic from './static.mjs';
Expand Down Expand Up @@ -91,7 +91,8 @@ function App() {
tune: decoded || randomTune,
defaultSynth,
// onDraw: useCallback((time, event) => markEvent(editor)(time, event), [editor]),
onDraw: useCallback((_, e, code) => code && highlightEvent(e, view, code), [view]),
// onDraw: useCallback((_, e, code) => code && highlightEvent(e, view, code), [view]),
onDraw: () => {},
});
const [uiHidden, setUiHidden] = useState(false);
const logBox = useRef();
Expand All @@ -118,6 +119,29 @@ function App() {
return () => window.removeEventListener('keydown', handleKeyPress);
}, [pattern, code, activateCode, cycle]);

useEffect(() => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good! we could also move this to a custom hook like useHighlights({pattern,view,started}) or similar, then we could reuse it in the mini repl

if (view) {
if (pattern && cycle.started) {
let frame = requestAnimationFrame(updateHighlights);

function updateHighlights() {
let audioTime = Tone.Transport.seconds;
let timespan = new strudel.TimeSpan(audioTime, audioTime + 1 / 60);
let events = pattern.query(new strudel.State(timespan));
view.dispatch({ effects: setHighlights.of(events) });

frame = requestAnimationFrame(updateHighlights);
}

return () => {
cancelAnimationFrame(frame);
};
} else {
view.dispatch({ effects: setHighlights.of([]) });
}
}
}, [pattern, cycle.started]);

useWebMidi({
ready: useCallback(
({ outputs }) => {
Expand Down
60 changes: 15 additions & 45 deletions repl/src/CodeMirror6.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import { javascript } from '@codemirror/lang-javascript';
import { materialPalenight } from './themes/material-palenight';

const highlightMark = Decoration.mark({ class: 'cm-highlight' });
const addHighlight = StateEffect.define();
const removeHighlight = StateEffect.define();
export const setHighlights = StateEffect.define();
const highlightTheme = EditorView.baseTheme({
'.cm-highlight': { outline: '1px solid #FFCA28' },
// '.cm-highlight': { background: '#FFCA28' },
Expand All @@ -19,60 +18,29 @@ const highlightField = StateField.define({
},
update(highlights, tr) {
try {
highlights = highlights.map(tr.changes);
for (let e of tr.effects) {
if (e.is(addHighlight)) {
highlights = highlights.update({
add: [highlightMark.range(e.value.from, e.value.to)],
});
}
if (e.is(removeHighlight)) {
highlights = highlights.update({
filter: (f, t, value) => {
if (f === e.value.from && t === e.value.to) {
return false;
}
return true;
// console.log('filter', f,t,value, e.value.from, e.value.to);
},
});
if (e.is(setHighlights)) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that looks much simpler than what I fabricated :D didn't know you could just set the Decorations directly

highlights = Decoration.set(
e.value
.flatMap((event) => event.context.locations || [])
.map(({ start, end }) => {
let from = tr.newDoc.line(start.line).from + start.column;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should make offsetToPosition/ positionToOffset obsolete :)

let to = tr.newDoc.line(end.line).from + end.column;
return highlightMark.range(from, to);
}),
true,
);
}
}
return highlights;
} catch (err) {
// console.warn('highlighting error', err);
console.warn('highlighting error', err);
return highlights;
}
},
provide: (f) => EditorView.decorations.from(f),
});

// let timeouts = [];

export const highlightEvent = (event, view, code) => {
if (!view) {
return;
}
const ranges = event.context?.locations?.map(({ start, end }) => {
return [start, end].map(({ line, column }) => positionToOffset({ line: line - 1, ch: column }, code));
});
const effects = ranges.map(([from, to]) => addHighlight.of({ from, to }));

if (!effects.length) return false;
if (!view.state.field(highlightField, false)) {
effects.push(StateEffect.appendConfig.of([highlightField, highlightTheme]));
}
view.dispatch({ effects });
// const index = timeouts.length;
// timeouts = timeouts.filter(time)
/* const timeout = */ setTimeout(() => {
const effects = ranges.map(([from, to]) => removeHighlight.of({ from, to }));
view.dispatch({ effects });
// timeouts.splice(index, 1);
}, event.duration * 1000);
// timeouts.pusn({timeout,);
};

export default function CodeMirror({ value, onChange, onViewChanged, onCursor, options, editorDidMount }) {
return (
<>
Expand All @@ -88,6 +56,8 @@ export default function CodeMirror({ value, onChange, onViewChanged, onCursor, o
extensions={[
javascript(),
materialPalenight,
highlightField,
highlightTheme,
// theme, language, ...
]}
/>
Expand Down