From 7404b9488295c1e071637053f5c0010351a36493 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=B6=E8=BF=9C=E6=96=B9?= Date: Mon, 14 Aug 2023 21:11:29 +0800 Subject: [PATCH 1/5] refactor: save the code with `ctrl + s` --- src/codemirror/CodeMirror.vue | 22 +++++++++++++++++++--- src/editor/CodeMirrorEditor.vue | 11 ++++++++--- src/editor/EditorContainer.vue | 7 +++---- src/editor/MonacoEditor.vue | 6 +++--- src/editor/types.ts | 2 +- src/monaco/Monaco.vue | 22 ++++++++++++++++++---- test/main.ts | 4 ++-- 7 files changed, 54 insertions(+), 20 deletions(-) diff --git a/src/codemirror/CodeMirror.vue b/src/codemirror/CodeMirror.vue index b0d6d721..3b1704fe 100644 --- a/src/codemirror/CodeMirror.vue +++ b/src/codemirror/CodeMirror.vue @@ -20,7 +20,7 @@ const props = withDefaults(defineProps(), { readonly: false, }) -const emit = defineEmits<(e: 'change', value: string) => void>() +const emit = defineEmits<(e: 'save', value: string) => void>() const el = ref() const needAutoResize = inject('autoresize') @@ -36,6 +36,10 @@ onMounted(() => { keyMap: 'sublime', } + function save() { + emit('save', editor.getValue()) + } + const editor = CodeMirror(el.value!, { value: '', mode: props.mode, @@ -46,8 +50,20 @@ onMounted(() => { ...addonOptions, }) - editor.on('change', () => { - emit('change', editor.getValue()) + let changeTimer: NodeJS.Timeout + editor.on('change', (e) => { + clearTimeout(changeTimer) // clear previous timer + + changeTimer = setTimeout(() => { + save() + }, 5000) + }) + + el.value.addEventListener('keydown', (e) => { + if ((e.ctrlKey || e.metaKey) && e.which == 83) { + e.preventDefault() + save() + } }) watchEffect(() => { diff --git a/src/editor/CodeMirrorEditor.vue b/src/editor/CodeMirrorEditor.vue index cb7d941f..926da175 100644 --- a/src/editor/CodeMirrorEditor.vue +++ b/src/editor/CodeMirrorEditor.vue @@ -10,8 +10,8 @@ defineOptions({ const props = defineProps() const emit = defineEmits() -const onChange = (code: string) => { - emit('change', code) +const onSave = (code: string) => { + emit('save', code) } const modes: Record = { @@ -39,5 +39,10 @@ const activeMode = computed(() => { diff --git a/src/editor/EditorContainer.vue b/src/editor/EditorContainer.vue index fb06a160..c2faff1b 100644 --- a/src/editor/EditorContainer.vue +++ b/src/editor/EditorContainer.vue @@ -1,7 +1,6 @@