2022-08-04 09:19:04 -04:00
|
|
|
import {getLanguageExtension} from "./languages"
|
2022-08-03 14:40:16 -04:00
|
|
|
import {Compartment} from "@codemirror/state"
|
|
|
|
import {EditorView} from "@codemirror/view"
|
2022-08-04 09:19:04 -04:00
|
|
|
import {oneDark} from "@codemirror/theme-one-dark"
|
2022-08-03 14:40:16 -04:00
|
|
|
|
|
|
|
const viewLangCompartments = new WeakMap();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new editor view.
|
|
|
|
*
|
2022-08-04 09:19:04 -04:00
|
|
|
* @param {{parent: Element, doc: String, extensions: Array}} config
|
2022-08-03 14:40:16 -04:00
|
|
|
* @returns {EditorView}
|
|
|
|
*/
|
|
|
|
export function createView(config) {
|
|
|
|
const langCompartment = new Compartment();
|
|
|
|
config.extensions.push(langCompartment.of([]));
|
2022-08-04 09:19:04 -04:00
|
|
|
config.extensions.push(getTheme(config.parent));
|
2022-08-03 14:40:16 -04:00
|
|
|
|
|
|
|
const ev = new EditorView(config);
|
|
|
|
|
|
|
|
viewLangCompartments.set(ev, langCompartment);
|
|
|
|
|
|
|
|
return ev;
|
|
|
|
}
|
|
|
|
|
2022-08-04 09:19:04 -04:00
|
|
|
/**
|
|
|
|
* Ge the theme extension to use for editor view instance.
|
|
|
|
* @returns {Extension}
|
|
|
|
*/
|
|
|
|
function getTheme(viewParentEl) {
|
|
|
|
const darkMode = document.documentElement.classList.contains('dark-mode');
|
|
|
|
|
|
|
|
const eventData = {
|
|
|
|
darkMode: darkMode,
|
|
|
|
theme: null,
|
|
|
|
};
|
|
|
|
|
|
|
|
window.$events.emitPublic(viewParentEl, 'library-cm6::configure-theme', eventData);
|
|
|
|
|
|
|
|
return eventData.theme || (darkMode ? oneDark : []);
|
|
|
|
}
|
|
|
|
|
2022-08-03 14:40:16 -04:00
|
|
|
/**
|
|
|
|
* Set the language mode of an EditorView.
|
|
|
|
*
|
|
|
|
* @param {EditorView} ev
|
|
|
|
* @param {string} modeSuggestion
|
|
|
|
* @param {string} content
|
|
|
|
*/
|
|
|
|
export function updateViewLanguage(ev, modeSuggestion, content) {
|
|
|
|
const compartment = viewLangCompartments.get(ev);
|
|
|
|
const language = getLanguageExtension(modeSuggestion, content);
|
|
|
|
|
|
|
|
ev.dispatch({
|
|
|
|
effects: compartment.reconfigure(language ? language : [])
|
|
|
|
})
|
|
|
|
}
|