Files
sb-front/src/components/editor/MarkdownEditor.vue
T

88 lines
2.9 KiB
Vue
Raw Normal View History

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import Editor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight-all'
import 'prismjs/themes/prism-tomorrow.css'
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css'
const props = defineProps({
modelValue: { type: String, default: '' },
height: { type: String, default: '400px' },
placeholder: { type: String, default: '' },
initialEditType: { type: String, default: 'wysiwyg' }, // 'markdown' | 'wysiwyg'
})
const emit = defineEmits(['update:modelValue'])
const el = ref(null)
let editor = null
// 에디터가 마지막으로 emit 한 값. 부모가 되돌려준 echo 를 구분해 한글 조합(IME)이 깨지지 않게 한다.
let lastEmitted = props.modelValue || ''
// IME(한글 등) 조합 중 여부. 조합 중에는 getMarkdown/emit 을 보류해 첫 자음이 중복되는 문제를 막는다.
let composing = false
function emitValue() {
if (!editor) return
lastEmitted = editor.getMarkdown()
emit('update:modelValue', lastEmitted)
}
function onCompStart() {
composing = true
}
function onCompEnd() {
composing = false
emitValue() // 조합 완료 시 한 번만 반영
}
onMounted(() => {
editor = new Editor({
el: el.value,
height: props.height,
initialEditType: props.initialEditType,
hideModeSwitch: true, // 마크다운/위지윅 전환 탭 숨김 (WYSIWYG 전용)
plugins: [codeSyntaxHighlight], // 코드 구문 강조
initialValue: props.modelValue || '',
placeholder: props.placeholder,
usageStatistics: false,
autofocus: false,
events: {
change: () => {
// 조합 중에는 보류 — 조합 중 getMarkdown 호출이 IME 를 끊어 자음 중복을 유발한다.
if (composing) return
emitValue()
},
},
})
// 조합 이벤트는 contenteditable 에서 버블링되어 래퍼(el)에서 잡힌다.
el.value.addEventListener('compositionstart', onCompStart)
el.value.addEventListener('compositionend', onCompEnd)
})
// 외부 값 변경(수정 로드, 제출 후 초기화 등)만 에디터에 반영.
// 에디터 자신이 방금 emit 한 값(echo)이거나 조합 중이면 무시 → 입력 중 setMarkdown 으로 IME 조합이 끊기지 않게 한다.
watch(
() => props.modelValue,
(val) => {
const v = val || ''
if (composing || v === lastEmitted) return
if (editor && v !== editor.getMarkdown()) {
lastEmitted = v
editor.setMarkdown(v)
}
},
)
onBeforeUnmount(() => {
if (el.value) {
el.value.removeEventListener('compositionstart', onCompStart)
el.value.removeEventListener('compositionend', onCompEnd)
}
editor?.destroy()
editor = null
})
</script>
<template>
<div ref="el"></div>
</template>