80 lines
2.2 KiB
TypeScript
Raw Normal View History

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";
import { defaultHighlightStyle, StreamLanguage, syntaxHighlighting } from "@codemirror/language";
import { Compartment } from "@codemirror/state";
import byMimeType from "./syntax_highlighting.js";
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;
private languageCompartment: Compartment;
2025-05-10 20:07:53 +03:00
constructor(config: EditorConfig) {
const languageCompartment = new Compartment();
2025-05-10 20:07:53 +03:00
let extensions = [
2025-05-10 20:20:38 +03:00
keymap.of([
...defaultKeymap,
indentWithTab
]),
languageCompartment.of([]),
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;
this.languageCompartment = languageCompartment;
2025-05-10 20:07:53 +03:00
}
#onDocumentUpdated(v: ViewUpdate) {
if (v.docChanged) {
this.config.onContentChanged?.();
}
}
getText() {
return this.state.doc.toString();
2025-05-10 19:10:30 +03:00
}
setText(content: string) {
this.dispatch({
changes: {
from: 0,
to: this.state.doc.length,
insert: content || "",
}
})
}
async setMimeType(mime: string) {
const newExtension = [];
const correspondingSyntax = byMimeType[mime];
if (correspondingSyntax) {
const extension = StreamLanguage.define(await correspondingSyntax());
newExtension.push(extension);
}
this.dispatch({
effects: this.languageCompartment.reconfigure(newExtension)
});
}
2025-05-10 19:10:30 +03:00
}