2023-11-01 13:56:52 -04:00
|
|
|
import {Compartment, EditorState} from '@codemirror/state';
|
2023-04-18 17:20:02 -04:00
|
|
|
import {EditorView} from '@codemirror/view';
|
|
|
|
import {getLanguageExtension} from './languages';
|
2022-08-03 14:40:16 -04:00
|
|
|
|
|
|
|
const viewLangCompartments = new WeakMap();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new editor view.
|
|
|
|
*
|
2023-11-01 13:56:52 -04:00
|
|
|
* @param {String} usageType
|
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}
|
|
|
|
*/
|
2023-11-01 13:56:52 -04:00
|
|
|
export function createView(usageType, config) {
|
2022-08-03 14:40:16 -04:00
|
|
|
const langCompartment = new Compartment();
|
|
|
|
config.extensions.push(langCompartment.of([]));
|
|
|
|
|
2023-11-01 13:56:52 -04:00
|
|
|
const commonEventData = {
|
|
|
|
usage: usageType,
|
|
|
|
editorViewConfig: config,
|
|
|
|
libEditorView: EditorView,
|
|
|
|
libEditorState: EditorState,
|
|
|
|
libCompartment: Compartment,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Emit a pre-init public event so the user can tweak the config before instance creation
|
|
|
|
window.$events.emitPublic(config.parent, 'library-cm6::pre-init', commonEventData);
|
2022-08-03 14:40:16 -04:00
|
|
|
|
2023-11-01 13:56:52 -04:00
|
|
|
const ev = new EditorView(config);
|
2022-08-03 14:40:16 -04:00
|
|
|
viewLangCompartments.set(ev, langCompartment);
|
|
|
|
|
2023-11-01 13:56:52 -04:00
|
|
|
// Emit a post-init public event so the user can gain a reference to the EditorView
|
|
|
|
window.$events.emitPublic(config.parent, 'library-cm6::post-init', {editorView: ev, ...commonEventData});
|
|
|
|
|
2022-08-03 14:40:16 -04:00
|
|
|
return ev;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Set the language mode of an EditorView.
|
|
|
|
*
|
|
|
|
* @param {EditorView} ev
|
|
|
|
* @param {string} modeSuggestion
|
|
|
|
* @param {string} content
|
|
|
|
*/
|
2023-04-14 13:08:57 -04:00
|
|
|
export async function updateViewLanguage(ev, modeSuggestion, content) {
|
2022-08-03 14:40:16 -04:00
|
|
|
const compartment = viewLangCompartments.get(ev);
|
2023-04-14 13:08:57 -04:00
|
|
|
const language = await getLanguageExtension(modeSuggestion, content);
|
2022-08-03 14:40:16 -04:00
|
|
|
|
|
|
|
ev.dispatch({
|
2023-04-18 17:20:02 -04:00
|
|
|
effects: compartment.reconfigure(language || []),
|
2023-04-16 11:05:16 -04:00
|
|
|
});
|
2023-04-18 17:20:02 -04:00
|
|
|
}
|