From d90082a2e44956e08fc64d296661b30ea4590506 Mon Sep 17 00:00:00 2001 From: Hongkun Peng Date: Sun, 8 Sep 2024 07:19:17 +0800 Subject: [PATCH] feat: reactivity `autoSave` option (#266) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 三咲智子 Kevin Deng --- src/codemirror/CodeMirror.vue | 43 +++++++++++++++++++++++------------ src/monaco/Monaco.vue | 37 ++++++++++++++++++------------ test/main.ts | 1 + 3 files changed, 53 insertions(+), 28 deletions(-) diff --git a/src/codemirror/CodeMirror.vue b/src/codemirror/CodeMirror.vue index 2aa328ca..faf78e3c 100644 --- a/src/codemirror/CodeMirror.vue +++ b/src/codemirror/CodeMirror.vue @@ -1,10 +1,22 @@ diff --git a/src/monaco/Monaco.vue b/src/monaco/Monaco.vue index fdf27e3f..7687f760 100644 --- a/src/monaco/Monaco.vue +++ b/src/monaco/Monaco.vue @@ -5,6 +5,7 @@ import { nextTick, onBeforeUnmount, onMounted, + onWatcherCleanup, ref, shallowRef, useTemplateRef, @@ -47,6 +48,11 @@ initMonaco(store.value) const lang = computed(() => (props.mode === 'css' ? 'css' : 'javascript')) +let editorInstance: monaco.editor.IStandaloneCodeEditor +function emitChangeEvent() { + emit('change', editorInstance.getValue()) +} + onMounted(async () => { const theme = await import('./highlight').then((r) => r.registerHighlighter()) ready.value = true @@ -55,8 +61,7 @@ onMounted(async () => { if (!containerRef.value) { throw new Error('Cannot find containerRef') } - - const editorInstance = monaco.editor.create(containerRef.value, { + editorInstance = monaco.editor.create(containerRef.value, { ...(props.readonly ? { value: props.value, language: lang.value } : { model: null }), @@ -146,18 +151,17 @@ onMounted(async () => { // ignore save event }) - if (autoSave) { - editorInstance.onDidChangeModelContent(() => { - emit('change', editorInstance.getValue()) - }) - } else { - containerRef.value.addEventListener('keydown', (e: KeyboardEvent) => { - if (e.ctrlKey && e.key === 's') { - e.preventDefault() - emit('change', editorInstance.getValue()) + watch( + autoSave, + (autoSave) => { + if (autoSave) { + const disposable = + editorInstance.onDidChangeModelContent(emitChangeEvent) + onWatcherCleanup(() => disposable.dispose()) } - }) - } + }, + { immediate: true }, + ) // update theme watch(replTheme, (n) => { @@ -173,7 +177,12 @@ onBeforeUnmount(() => {