2025-05-10 20:20:38 +03:00
|
|
|
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
|
|
|
|
import { EditorView, keymap, lineNumbers, ViewUpdate, type EditorViewConfig, type KeyBinding } from "@codemirror/view";
|
2025-05-10 21:38:12 +03:00
|
|
|
import { defaultHighlightStyle, syntaxHighlighting } from "@codemirror/language";
|
2025-05-10 20:07:53 +03:00
|
|
|
|
|
|
|
type ContentChangedListener = () => void;
|
|
|
|
|
|
|
|
export interface EditorConfig extends EditorViewConfig {
|
|
|
|
onContentChanged?: ContentChangedListener;
|
|
|
|
}
|
2025-05-10 19:10:30 +03:00
|
|
|
|
|
|
|
export default class CodeMirror extends EditorView {
|
2025-05-10 20:07:53 +03:00
|
|
|
|
|
|
|
private config: EditorConfig;
|
|
|
|
|
|
|
|
constructor(config: EditorConfig) {
|
|
|
|
let extensions = [
|
2025-05-10 20:20:38 +03:00
|
|
|
keymap.of([
|
|
|
|
...defaultKeymap,
|
|
|
|
indentWithTab
|
|
|
|
]),
|
2025-05-10 21:38:12 +03:00
|
|
|
syntaxHighlighting(defaultHighlightStyle),
|
2025-05-10 20:07:53 +03:00
|
|
|
lineNumbers()
|
|
|
|
];
|
|
|
|
|
|
|
|
if (Array.isArray(config.extensions)) {
|
|
|
|
extensions = [...extensions, ...config.extensions];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (config.onContentChanged) {
|
|
|
|
extensions.push(EditorView.updateListener.of((v) => this.#onDocumentUpdated(v)));
|
|
|
|
}
|
|
|
|
|
2025-05-10 19:10:30 +03:00
|
|
|
super({
|
|
|
|
...config,
|
2025-05-10 20:07:53 +03:00
|
|
|
extensions
|
2025-05-10 19:10:30 +03:00
|
|
|
});
|
2025-05-10 20:07:53 +03:00
|
|
|
this.config = config;
|
|
|
|
}
|
|
|
|
|
|
|
|
#onDocumentUpdated(v: ViewUpdate) {
|
|
|
|
if (v.docChanged) {
|
|
|
|
this.config.onContentChanged?.();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getText() {
|
|
|
|
return this.state.doc.toString();
|
2025-05-10 19:10:30 +03:00
|
|
|
}
|
2025-05-10 19:22:57 +03:00
|
|
|
|
|
|
|
setText(content: string) {
|
|
|
|
this.dispatch({
|
|
|
|
changes: {
|
|
|
|
from: 0,
|
|
|
|
to: this.state.doc.length,
|
|
|
|
insert: content || "",
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2025-05-10 19:10:30 +03:00
|
|
|
}
|