2023-04-16 17:05:16 +02:00
|
|
|
import {Compartment} from "@codemirror/state";
|
|
|
|
import {EditorView} from "@codemirror/view";
|
|
|
|
import {getLanguageExtension} from "./languages";
|
2022-08-03 20:40:16 +02:00
|
|
|
|
|
|
|
const viewLangCompartments = new WeakMap();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new editor view.
|
|
|
|
*
|
2022-08-04 15:19:04 +02:00
|
|
|
* @param {{parent: Element, doc: String, extensions: Array}} config
|
2022-08-03 20:40:16 +02:00
|
|
|
* @returns {EditorView}
|
|
|
|
*/
|
|
|
|
export function createView(config) {
|
|
|
|
const langCompartment = new Compartment();
|
|
|
|
config.extensions.push(langCompartment.of([]));
|
|
|
|
|
|
|
|
const ev = new EditorView(config);
|
|
|
|
|
|
|
|
viewLangCompartments.set(ev, langCompartment);
|
|
|
|
|
|
|
|
return ev;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set the language mode of an EditorView.
|
|
|
|
*
|
|
|
|
* @param {EditorView} ev
|
|
|
|
* @param {string} modeSuggestion
|
|
|
|
* @param {string} content
|
|
|
|
*/
|
2023-04-14 19:08:57 +02:00
|
|
|
export async function updateViewLanguage(ev, modeSuggestion, content) {
|
2022-08-03 20:40:16 +02:00
|
|
|
const compartment = viewLangCompartments.get(ev);
|
2023-04-14 19:08:57 +02:00
|
|
|
const language = await getLanguageExtension(modeSuggestion, content);
|
2022-08-03 20:40:16 +02:00
|
|
|
|
|
|
|
ev.dispatch({
|
|
|
|
effects: compartment.reconfigure(language ? language : [])
|
2023-04-16 17:05:16 +02:00
|
|
|
});
|
2022-08-03 20:40:16 +02:00
|
|
|
}
|