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
// codemirror esm react hook
import { defaultKeymap } from "https://esm.sh/@codemirror/commands";
import { history } from "https://esm.sh/@codemirror/commands";
import { Extension } from "https://esm.sh/@codemirror/state";
import {
crosshairCursor,
drawSelection,
dropCursor,
EditorView,
keymap,
rectangularSelection,
} from "https://esm.sh/@codemirror/view";
import { useEffect, useRef, useState } from "https://esm.sh/react";
const baseExtensions = [
EditorView.lineWrapping,
drawSelection(),
history(),
dropCursor(),
rectangularSelection(),
crosshairCursor(),
keymap.of(defaultKeymap),
];
export function useCodemirror(initialValue: string = "", extensions: Extension[] = []) {
const ref = useRef<HTMLDivElement>(null);
const [view, setView] = useState<EditorView | null>(null);
useEffect(() => {
if (!ref.current || view) return;
let v = new EditorView({
doc: initialValue,
extensions: [
...baseExtensions,
...extensions,
],
parent: ref.current,
});
console.log("useCodemirror view", v);
setView(v);
}, [ref, view]);
function append(str: string) {
if (!view) return;
const t = view.state.update({
changes: {
from: view.state.doc.length,
to: view.state.doc.length,
insert: str,
},
scrollIntoView: true,
});
view.dispatch(t);
}
console.log("useCodemirror", view);
return [ref, view, append];
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 30, 2024