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