-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathp5ViewPlugin.js
64 lines (54 loc) · 1.56 KB
/
p5ViewPlugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { syntaxTree } from '@codemirror/language';
import { Decoration, EditorView, ViewPlugin } from '@codemirror/view';
import {
p5FunctionKeywords,
p5VariableKeywords
} from '../../../utils/p5-keywords';
function createP5Decoration(node, text) {
const isFunction = text in p5FunctionKeywords;
const isVariable = text in p5VariableKeywords;
if (isFunction || isVariable) {
const className = isFunction ? 'cm-p5-function' : 'cm-p5-variable';
return [Decoration.mark({ class: className }).range(node.from, node.to)];
}
return [];
}
function createDecorations(view) {
const decorations = [];
view.visibleRanges.forEach(({ from, to }) => {
syntaxTree(view.state).iterate({
from,
to,
enter: (node) => {
const text = view.state.doc.sliceString(node.from, node.to);
if (
node.name === 'VariableName' ||
node.name === 'VariableDefinition'
) {
decorations.push(...createP5Decoration(node, text));
}
}
});
});
return Decoration.set(decorations);
}
const p5ViewPlugin = ViewPlugin.fromClass(
class {
constructor(view) {
this.decorations = createDecorations(view);
}
update(update) {
if (update.docChanged || update.viewportChanged) {
this.decorations = createDecorations(update.view);
}
}
},
{
decorations: (instance) => instance.decorations,
provide: (plugin) =>
EditorView.atomicRanges.of(
(view) => view.plugin(plugin)?.decorations || Decoration.none
)
}
);
export default p5ViewPlugin;