refactor(editor): migrate to Milkdown with LaTeX support and clean up legacy code
- Removed old contenteditable-based MarkdownEditor component - Integrated Milkdown Crepe with LaTeX (KaTeX) rendering support - Simplified inline suggestion plugin using ProseMirror decorations - Removed debug logging and unused components (HelloWorld, plan files) - Increased debounce from 150ms to 500ms for better performance - Fixed SSE JSON serialization in backend main.py
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
<template>
|
||||
<div v-if="visible" class="ghost-text-overlay" :style="overlayStyle"
|
||||
@click="acceptSuggestion"
|
||||
>{{ truncatedSuggestion }}
|
||||
<div v-if="visible" class="ghost-text-overlay" :style="overlayStyle" @click="acceptSuggestion">
|
||||
{{ displayText }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -9,39 +8,37 @@
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
suggestion: { type: String, default: '' },
|
||||
position: {
|
||||
type: Object,
|
||||
required: true,
|
||||
validator: (value) => typeof value.left === 'number' && typeof value.top === 'number'
|
||||
}
|
||||
suggestion: { type: String, default: '' },
|
||||
position: {
|
||||
type: Object,
|
||||
required: true,
|
||||
validator: (value) => typeof value.left === 'number' && typeof value.top === 'number'
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['accept', 'dismiss'])
|
||||
|
||||
const MAX_SUGGESTION_LENGTH = 200
|
||||
const MAX_LENGTH = 200
|
||||
|
||||
const visible = computed(() => props.suggestion && props.position)
|
||||
const visible = computed(() => props.suggestion && props.suggestion.length > 0)
|
||||
|
||||
const truncatedSuggestion = computed(() => {
|
||||
if (props.suggestion.length > MAX_SUGGESTION_LENGTH) {
|
||||
return props.suggestion.slice(0, MAX_SUGGESTION_LENGTH) + '...'
|
||||
}
|
||||
return props.suggestion
|
||||
const displayText = computed(() => {
|
||||
const text = props.suggestion
|
||||
return text.length > MAX_LENGTH ? text.slice(0, MAX_LENGTH) + '...' : text
|
||||
})
|
||||
|
||||
const overlayStyle = computed(() => ({
|
||||
position: 'absolute',
|
||||
left: `${props.position.left}px`,
|
||||
top: `${props.position.top}px`,
|
||||
fontSize: `${props.position.fontSize || 16}px`,
|
||||
fontFamily: props.position.fontFamily || 'monospace',
|
||||
color: '#999',
|
||||
backgroundColor: 'transparent',
|
||||
pointerEvents: 'auto',
|
||||
cursor: 'text',
|
||||
whiteSpace: 'pre-wrap',
|
||||
zIndex: 1000,
|
||||
position: 'absolute',
|
||||
left: `${props.position.left}px`,
|
||||
top: `${props.position.top}px`,
|
||||
fontSize: `${props.position.fontSize || 16}px`,
|
||||
fontFamily: props.position.fontFamily || 'monospace',
|
||||
color: '#999',
|
||||
backgroundColor: 'transparent',
|
||||
pointerEvents: 'auto',
|
||||
cursor: 'text',
|
||||
whiteSpace: 'pre-wrap',
|
||||
zIndex: 1000,
|
||||
}))
|
||||
|
||||
const acceptSuggestion = () => emit('accept')
|
||||
@@ -49,12 +46,12 @@ const acceptSuggestion = () => emit('accept')
|
||||
|
||||
<style scoped>
|
||||
.ghost-text-overlay {
|
||||
opacity: 0.6;
|
||||
user-select: none;
|
||||
opacity: 0.6;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ghost-text-overlay:hover {
|
||||
opacity: 1;
|
||||
color: #666;
|
||||
opacity: 1;
|
||||
color: #666;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
<script setup>
|
||||
import { ref } from 'vue'
|
||||
|
||||
defineProps({
|
||||
msg: String,
|
||||
})
|
||||
|
||||
const count = ref(0)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>{{ msg }}</h1>
|
||||
|
||||
<div class="card">
|
||||
<button type="button" @click="count++">count is {{ count }}</button>
|
||||
<p>
|
||||
Edit
|
||||
<code>components/HelloWorld.vue</code> to test HMR
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Check out
|
||||
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
|
||||
>create-vue</a
|
||||
>, the official Vue + Vite starter
|
||||
</p>
|
||||
<p>
|
||||
Learn more about IDE Support for Vue in the
|
||||
<a
|
||||
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
|
||||
target="_blank"
|
||||
>Vue Docs Scaling up Guide</a
|
||||
>.
|
||||
</p>
|
||||
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
</style>
|
||||
@@ -1,642 +0,0 @@
|
||||
<template>
|
||||
<div class="editor-wrapper" ref="wrapperRef">
|
||||
<!-- Ghost Text 建议覆盖层 -->
|
||||
<GhostTextOverlay
|
||||
v-if="suggestion"
|
||||
:suggestion="suggestion"
|
||||
:position="suggestionPosition"
|
||||
@accept="acceptSuggestion"
|
||||
@dismiss="dismissSuggestion"
|
||||
/>
|
||||
|
||||
<!-- 单栏编辑器 -->
|
||||
<div
|
||||
ref="editorRef"
|
||||
contenteditable="true"
|
||||
class="editor"
|
||||
:class="{ 'editing-code': editingCodeBlock }"
|
||||
@input="onInput"
|
||||
@keydown="handleKeydown"
|
||||
@click="onEditorClick"
|
||||
@paste="handlePaste"
|
||||
spellcheck="false"
|
||||
></div>
|
||||
|
||||
<!-- 代码块编辑弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="editingCodeBlock" class="code-modal" @click.self="closeCodeBlock">
|
||||
<div class="code-editor">
|
||||
<textarea
|
||||
ref="codeTextareaRef"
|
||||
v-model="codeBlockContent"
|
||||
placeholder="Enter code..."
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
<button class="save-btn" @click="saveCodeBlock">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- 图片预览弹窗 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="expandedImage" class="image-modal" @click="expandedImage = null">
|
||||
<img :src="expandedImage.src" :alt="expandedImage.alt" />
|
||||
</div>
|
||||
</Teleport>
|
||||
|
||||
<!-- 插件挂载点 -->
|
||||
<PluginHost />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, onMounted, nextTick } from 'vue'
|
||||
import { plugins } from '../plugins/index'
|
||||
import PluginHost from './PluginHost.vue'
|
||||
import GhostTextOverlay from './GhostTextOverlay.vue'
|
||||
import markdownIt from 'markdown-it'
|
||||
import Prism from 'prismjs'
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000'
|
||||
|
||||
const emit = defineEmits(['update:html'])
|
||||
|
||||
/* ---------- 插件挂载点 ---------- */
|
||||
const pluginContext = {}
|
||||
onMounted(() => {
|
||||
plugins.forEach(p => {
|
||||
if (p.onSetup) p.onSetup(pluginContext)
|
||||
})
|
||||
})
|
||||
|
||||
/* ---------- Markdown 解析器 ---------- */
|
||||
const md = markdownIt({
|
||||
highlight: (code, lang) => {
|
||||
if (lang && Prism.languages[lang]) {
|
||||
return `<pre class="language-${lang}" data-code="${encodeURIComponent(code)}"><code>${Prism.highlight(code, Prism.languages[lang], lang)}</code></pre>`
|
||||
}
|
||||
return `<pre class="language-text" data-code="${encodeURIComponent(code)}"><code>${md.utils.escapeHtml(code)}</code></pre>`
|
||||
}
|
||||
})
|
||||
|
||||
/* ---------- 编辑器状态 ---------- */
|
||||
const editorRef = ref(null)
|
||||
const codeTextareaRef = ref(null)
|
||||
const wrapperRef = ref(null)
|
||||
const markdown = ref('')
|
||||
const renderedHtml = ref('')
|
||||
let debounceTimer = null
|
||||
|
||||
/* ---------- 编辑状态标记 ---------- */
|
||||
const isEditing = ref(false)
|
||||
|
||||
/* ---------- 代码块编辑状态 ---------- */
|
||||
const editingCodeBlock = ref(false)
|
||||
const codeBlockContent = ref('')
|
||||
const currentCodeElement = ref(null)
|
||||
|
||||
/* ---------- Ghost Text 建议 ---------- */
|
||||
const suggestion = ref('')
|
||||
const suggestionPosition = ref({ left: 0, top: 0 })
|
||||
let completionController = null
|
||||
|
||||
/* ---------- 图片预览 ---------- */
|
||||
const expandedImage = ref(null)
|
||||
|
||||
/* ---------- 光标位置管理 ---------- */
|
||||
function getCursorPosition() {
|
||||
const sel = window.getSelection()
|
||||
if (!sel.rangeCount || !editorRef.value) return null
|
||||
|
||||
try {
|
||||
const range = sel.getRangeAt(0)
|
||||
if (!range) return null
|
||||
|
||||
// 检查是否在代码块内(使用 commonAncestorContainer.closest)
|
||||
const container = range.commonAncestorContainer
|
||||
const codeBlock = container.nodeType === Node.ELEMENT_NODE
|
||||
? container.closest('pre')
|
||||
: container.parentElement?.closest('pre')
|
||||
if (codeBlock) {
|
||||
return { type: 'code', element: codeBlock }
|
||||
}
|
||||
|
||||
// 获取光标位置的坐标
|
||||
const rect = range.getBoundingClientRect()
|
||||
const editorRect = editorRef.value.getBoundingClientRect()
|
||||
|
||||
return {
|
||||
type: 'text',
|
||||
range: range.cloneRange(),
|
||||
left: rect.left - editorRect.left,
|
||||
top: rect.top - editorRect.top + window.scrollY
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('getCursorPosition error:', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function getPrefixSuffix(cursorRange) {
|
||||
const fullText = markdown.value
|
||||
if (!cursorRange || !cursorRange.range) return { prefix: fullText, suffix: '' }
|
||||
|
||||
// 获取光标在纯文本中的位置
|
||||
const preCaretRange = cursorRange.range.cloneRange()
|
||||
preCaretRange.selectNodeContents(editorRef.value)
|
||||
preCaretRange.setEnd(cursorRange.range.startContainer, cursorRange.range.startOffset)
|
||||
const prefix = preCaretRange.toString()
|
||||
|
||||
// 获取 suffix(光标后的内容)
|
||||
const postCaretRange = cursorRange.range.cloneRange()
|
||||
postCaretRange.setStartAfter(cursorRange.range.endContainer, cursorRange.range.endOffset)
|
||||
const suffix = postCaretRange.toString()
|
||||
|
||||
return { prefix, suffix }
|
||||
}
|
||||
|
||||
function saveSelection() {
|
||||
const sel = window.getSelection()
|
||||
if (!sel.rangeCount) return null
|
||||
|
||||
try {
|
||||
const range = sel.getRangeAt(0)
|
||||
if (!range) return null
|
||||
|
||||
// 检查是否在代码块内
|
||||
const container = range.commonAncestorContainer
|
||||
const codeBlock = container.nodeType === Node.ELEMENT_NODE
|
||||
? container.closest('pre')
|
||||
: container.parentElement?.closest('pre')
|
||||
if (codeBlock) {
|
||||
return { type: 'code', element: codeBlock }
|
||||
}
|
||||
|
||||
return { type: 'text', range: range.cloneRange() }
|
||||
} catch (e) {
|
||||
console.error('saveSelection error:', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function restoreSelection(saved) {
|
||||
if (!saved || !editorRef.value) return
|
||||
|
||||
const sel = window.getSelection()
|
||||
sel.removeAllRanges()
|
||||
|
||||
if (saved.type === 'code') {
|
||||
// 代码块不需要恢复光标
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
sel.addRange(saved.range)
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
/* ---------- Ghost Text 请求 ---------- */
|
||||
async function requestCompletion(prefix, suffix) {
|
||||
if (completionController) {
|
||||
completionController.abort()
|
||||
}
|
||||
|
||||
try {
|
||||
completionController = new AbortController()
|
||||
const response = await fetch(`${API_URL}/v1/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefix, suffix, languageId: 'markdown' }),
|
||||
signal: completionController.signal
|
||||
})
|
||||
|
||||
if (!response.ok) throw new Error('Completion request failed')
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let content = ''
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
const chunk = decoder.decode(value)
|
||||
const lines = chunk.split('\n').filter(l => l.startsWith('data: '))
|
||||
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6))
|
||||
if (data.content) content += data.content
|
||||
if (data.done) break
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
return content
|
||||
} catch (e) {
|
||||
if (e.name !== 'AbortError') console.error('Completion error:', e)
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function onInput(e) {
|
||||
isEditing.value = true
|
||||
const content = getPlainText()
|
||||
markdown.value = content
|
||||
|
||||
clearTimeout(debounceTimer)
|
||||
debounceTimer = setTimeout(async () => {
|
||||
renderMarkdown()
|
||||
|
||||
// 请求补全建议
|
||||
const cursorPos = getCursorPosition()
|
||||
if (cursorPos && cursorPos.type === 'text') {
|
||||
const { prefix, suffix } = getPrefixSuffix(cursorPos)
|
||||
suggestion.value = await requestCompletion(prefix, suffix)
|
||||
if (suggestion.value) {
|
||||
suggestionPosition.value = { left: cursorPos.left, top: cursorPos.top }
|
||||
}
|
||||
}
|
||||
|
||||
isEditing.value = false
|
||||
}, 300)
|
||||
}
|
||||
|
||||
function acceptSuggestion() {
|
||||
if (!suggestion.value) return
|
||||
insertAtCursor(suggestion.value)
|
||||
suggestion.value = ''
|
||||
onInput()
|
||||
}
|
||||
|
||||
function dismissSuggestion() {
|
||||
suggestion.value = ''
|
||||
}
|
||||
|
||||
/* ---------- 防抖渲染 ---------- */
|
||||
function renderMarkdown() {
|
||||
let html = md.render(markdown.value)
|
||||
|
||||
const afterPayload = { markdown: markdown.value, html }
|
||||
plugins.forEach(p => {
|
||||
if (p.onAfterParse) {
|
||||
const res = p.onAfterParse(afterPayload)
|
||||
if (res && res.html) afterPayload.html = res.html
|
||||
}
|
||||
})
|
||||
|
||||
const beforePayload = { html: afterPayload.html }
|
||||
plugins.forEach(p => {
|
||||
if (p.onBeforeRender) {
|
||||
const res = p.onBeforeRender(beforePayload)
|
||||
if (res && res.html) beforePayload.html = res.html
|
||||
}
|
||||
})
|
||||
|
||||
renderedHtml.value = beforePayload.html
|
||||
|
||||
nextTick(() => {
|
||||
bindImageClick()
|
||||
emit('update:html', beforePayload.html)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/* ---------- 从 contenteditable 获取纯文本 ---------- */
|
||||
function getPlainText() {
|
||||
if (!editorRef.value) return ''
|
||||
|
||||
let text = ''
|
||||
const walker = document.createTreeWalker(
|
||||
editorRef.value,
|
||||
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
|
||||
null,
|
||||
false
|
||||
)
|
||||
|
||||
while (walker.nextNode()) {
|
||||
const node = walker.currentNode
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
text += node.textContent
|
||||
} else if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const tag = node.tagName.toLowerCase()
|
||||
|
||||
// 处理代码块
|
||||
if (tag === 'pre') {
|
||||
const code = decodeURIComponent(node.dataset.code || '')
|
||||
text += `\`\`\`\n${code}\n\`\`\`\n`
|
||||
}
|
||||
// 处理标题
|
||||
else if (tag.startsWith('h') && tag.length === 2) {
|
||||
const level = parseInt(tag[1])
|
||||
text += '#'.repeat(level) + ' ' + node.textContent + '\n'
|
||||
}
|
||||
// 处理粗体
|
||||
else if (tag === 'strong' || tag === 'b') {
|
||||
text += `**${node.textContent}**`
|
||||
}
|
||||
// 处理斜体
|
||||
else if (tag === 'em' || tag === 'i') {
|
||||
text += `_${node.textContent}_`
|
||||
}
|
||||
// 处理删除线
|
||||
else if (tag === 'del' || tag === 's') {
|
||||
text += `~~${node.textContent}~~`
|
||||
}
|
||||
// 处理行内代码
|
||||
else if (tag === 'code' && !node.closest('pre')) {
|
||||
text += `\`${node.textContent}\``
|
||||
}
|
||||
// 处理链接
|
||||
else if (tag === 'a') {
|
||||
text += `[${node.textContent}](${node.href})`
|
||||
}
|
||||
// 处理图片
|
||||
else if (tag === 'img') {
|
||||
text += ``
|
||||
}
|
||||
// 处理段落和换行
|
||||
else if (['p', 'div', 'blockquote'].includes(tag)) {
|
||||
text += '\n'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return text.trim()
|
||||
}
|
||||
|
||||
/* ---------- 图片点击预览 ---------- */
|
||||
function bindImageClick() {
|
||||
const editor = editorRef.value
|
||||
if (!editor) return
|
||||
|
||||
editor.onclick = (e) => {
|
||||
if (e.target.tagName === 'IMG') {
|
||||
expandedImage.value = { src: e.target.src, alt: e.target.alt }
|
||||
} else if (e.target.tagName === 'PRE' && !editingCodeBlock.value) {
|
||||
// 点击代码块进入编辑模式
|
||||
openCodeBlock(e.target)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onEditorClick(e) {
|
||||
bindImageClick()
|
||||
}
|
||||
|
||||
/* ---------- 代码块编辑 ---------- */
|
||||
function openCodeBlock(preElement) {
|
||||
isEditing.value = true
|
||||
currentCodeElement.value = preElement
|
||||
codeBlockContent.value = decodeURIComponent(preElement.dataset.code || '')
|
||||
editingCodeBlock.value = true
|
||||
|
||||
nextTick(() => {
|
||||
if (codeTextareaRef.value) {
|
||||
codeTextareaRef.value.focus()
|
||||
codeTextareaRef.value.select()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function closeCodeBlock() {
|
||||
editingCodeBlock.value = false
|
||||
isEditing.value = false
|
||||
currentCodeElement.value = null
|
||||
}
|
||||
|
||||
function saveCodeBlock() {
|
||||
isEditing.value = true
|
||||
if (!currentCodeElement) return
|
||||
|
||||
const newHtml = md.options.highlight(codeBlockContent.value, '')
|
||||
currentCodeElement.innerHTML = newHtml.replace(/<pre class="[^"]*"><code>.*<\/code><\/pre>/,
|
||||
`<code>${md.utils.escapeHtml(codeBlockContent.value)}</code>`)
|
||||
currentCodeElement.dataset.code = encodeURIComponent(codeBlockContent.value)
|
||||
|
||||
// 更新 markdown 内容
|
||||
const codeMatch = markdown.value.match(/```[\s\S]*?```/)
|
||||
if (codeMatch) {
|
||||
markdown.value = markdown.value.replace(codeMatch[0], `\`\`\`\n${codeBlockContent.value}\n\`\`\``)
|
||||
}
|
||||
|
||||
closeCodeBlock()
|
||||
isEditing.value = false
|
||||
}
|
||||
|
||||
/* ---------- 粘贴处理 ---------- */
|
||||
function handlePaste(e) {
|
||||
e.preventDefault()
|
||||
const text = (e.clipboardData || window.clipboardData).getData('text/plain')
|
||||
|
||||
document.execCommand('insertText', false, text)
|
||||
}
|
||||
|
||||
/* ---------- 快捷键 ---------- */
|
||||
function insertAtCursor(text) {
|
||||
const sel = window.getSelection()
|
||||
if (!sel.rangeCount) return
|
||||
|
||||
const range = sel.getRangeAt(0)
|
||||
range.deleteContents()
|
||||
const textNode = document.createTextNode(text)
|
||||
range.insertNode(textNode)
|
||||
|
||||
range.setStartAfter(textNode)
|
||||
range.collapse(true)
|
||||
sel.removeAllRanges()
|
||||
sel.addRange(range)
|
||||
}
|
||||
|
||||
function handleKeydown(e) {
|
||||
// 代码块编辑模式下不处理快捷键
|
||||
if (editingCodeBlock.value) return
|
||||
|
||||
if (e.ctrlKey && !e.shiftKey) {
|
||||
const key = e.key.toLowerCase()
|
||||
|
||||
if (key >= '1' && key <= '6') {
|
||||
e.preventDefault()
|
||||
insertAtCursor('#'.repeat(parseInt(key)) + ' ')
|
||||
onInput()
|
||||
return
|
||||
}
|
||||
|
||||
switch (key) {
|
||||
case 'b':
|
||||
e.preventDefault()
|
||||
insertAtCursor('**粗体**')
|
||||
break
|
||||
case 'i':
|
||||
e.preventDefault()
|
||||
insertAtCursor('_斜体_')
|
||||
break
|
||||
case 'k':
|
||||
e.preventDefault()
|
||||
insertAtCursor('[链接文本](url)')
|
||||
break
|
||||
}
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
insertAtCursor(' ')
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- 初始化 ---------- */
|
||||
onMounted(() => {
|
||||
const initialMarkdown = '# Welcome to Markdown Editor\n\nStart typing...'
|
||||
markdown.value = initialMarkdown
|
||||
renderMarkdown()
|
||||
})
|
||||
|
||||
/* ---------- 插件钩子 ---------- */
|
||||
watch(markdown, () => {
|
||||
if (!editingCodeBlock.value) {
|
||||
clearTimeout(debounceTimer)
|
||||
debounceTimer = setTimeout(() => {
|
||||
renderMarkdown()
|
||||
}, 100)
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
/* ---------- 渲染结果应用到编辑器 ---------- */
|
||||
watch(renderedHtml, (newHtml) => {
|
||||
if (editorRef.value && newHtml && !isEditing.value) {
|
||||
editorRef.value.innerHTML = newHtml
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.editor-wrapper {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 1.5rem 2rem;
|
||||
outline: none;
|
||||
overflow-y: auto;
|
||||
box-sizing: border-box;
|
||||
font-size: 16px;
|
||||
line-height: 1.8;
|
||||
}
|
||||
|
||||
/* 代码块样式 */
|
||||
.editor :deep(pre) {
|
||||
background: #f5f5f5;
|
||||
padding: 1rem;
|
||||
border-radius: 4px;
|
||||
overflow-x: auto;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.editor :deep(pre):hover::after {
|
||||
content: '点击编辑';
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 8px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
background: rgba(255,255,255,0.9);
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.editor :deep(code) {
|
||||
font-family: 'Monaco', 'Menlo', monospace;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 行内代码 */
|
||||
.editor :deep(p > code),
|
||||
.editor :deep(a > code) {
|
||||
background: #f0f0f0;
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
font-family: 'Monaco', 'Menlo', monospace;
|
||||
}
|
||||
|
||||
/* 图片样式 */
|
||||
.editor :deep(img) {
|
||||
max-width: 100%;
|
||||
cursor: zoom-in;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.editor :deep(a) {
|
||||
color: #0066cc;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.editor :deep(blockquote) {
|
||||
border-left: 4px solid #ddd;
|
||||
margin: 0;
|
||||
padding-left: 1rem;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
/* 代码块编辑弹窗 */
|
||||
.code-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.code-editor {
|
||||
background: #1e1e1e;
|
||||
border-radius: 8px;
|
||||
padding: 1rem;
|
||||
width: 80%;
|
||||
max-width: 800px;
|
||||
height: 60vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.code-editor textarea {
|
||||
flex: 1;
|
||||
background: #1e1e1e;
|
||||
color: #d4d4d4;
|
||||
border: none;
|
||||
outline: none;
|
||||
resize: none;
|
||||
font-family: 'Monaco', 'Menlo', monospace;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.save-btn {
|
||||
margin-top: 0.5rem;
|
||||
padding: 8px 16px;
|
||||
background: #0066cc;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
/* 图片弹窗 */
|
||||
.image-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.9);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.image-modal img {
|
||||
max-width: 90vw;
|
||||
max-height: 90vh;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,191 @@
|
||||
<template>
|
||||
<div class="preview-container" v-html="renderedContent"></div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import katex from 'katex'
|
||||
import 'katex/dist/katex.min.css'
|
||||
|
||||
const props = defineProps({
|
||||
content: {
|
||||
type: String,
|
||||
default: ''
|
||||
}
|
||||
})
|
||||
|
||||
const md = new MarkdownIt({
|
||||
html: true,
|
||||
linkify: true,
|
||||
typographer: true
|
||||
})
|
||||
|
||||
// 预处理 markdown,转换 $...$ 为 <span class="math-inline">...</span>
|
||||
const preprocessLatex = (text) => {
|
||||
// 处理 $$...$$ 块级公式
|
||||
text = text.replace(/\$\$([\s\S]*?)\$\$/g, (match, content) => {
|
||||
try {
|
||||
const html = katex.renderToString(content.trim(), {
|
||||
displayMode: true,
|
||||
throwOnError: false
|
||||
})
|
||||
return `<div class="math-block">${html}</div>`
|
||||
} catch (e) {
|
||||
return `<div class="math-error">$$${content}$$</div>`
|
||||
}
|
||||
})
|
||||
|
||||
// 处理 $...$ 行内公式
|
||||
// 使用负向前瞻和负向后瞻来避免与 $$ 冲突
|
||||
text = text.replace(/(?<!\$)\$(?!\$)([^\$\n]+?)\$(?!\$)/g, (match, content) => {
|
||||
try {
|
||||
const html = katex.renderToString(content.trim(), {
|
||||
displayMode: false,
|
||||
throwOnError: false
|
||||
})
|
||||
return `<span class="math-inline">${html}</span>`
|
||||
} catch (e) {
|
||||
return `<span class="math-error">${match}</span>`
|
||||
}
|
||||
})
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
const renderedContent = computed(() => {
|
||||
if (!props.content) return '<p></p>'
|
||||
|
||||
// 先预处理 LaTeX
|
||||
const processed = preprocessLatex(props.content)
|
||||
|
||||
// 然后渲染 markdown
|
||||
return md.render(processed)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.preview-container {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 20px 40px;
|
||||
overflow-y: auto;
|
||||
background-color: #ffffff;
|
||||
color: #333;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.preview-container :deep(.math-block) {
|
||||
display: block;
|
||||
margin: 1em 0;
|
||||
text-align: center;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(.math-inline) {
|
||||
font-size: 1.1em;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.preview-container :deep(.math-error) {
|
||||
color: #dc3545;
|
||||
background-color: #f8d7da;
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.preview-container :deep(h1),
|
||||
.preview-container :deep(h2),
|
||||
.preview-container :deep(h3),
|
||||
.preview-container :deep(h4),
|
||||
.preview-container :deep(h5),
|
||||
.preview-container :deep(h6) {
|
||||
margin-top: 1em;
|
||||
margin-bottom: 0.5em;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.preview-container :deep(p) {
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(code) {
|
||||
background-color: #f5f5f5;
|
||||
padding: 0.2em 0.4em;
|
||||
border-radius: 3px;
|
||||
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.preview-container :deep(pre) {
|
||||
background-color: #f5f5f5;
|
||||
padding: 16px;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.preview-container :deep(pre code) {
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(blockquote) {
|
||||
border-left: 4px solid #ddd;
|
||||
margin: 1em 0;
|
||||
padding-left: 16px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.preview-container :deep(ul),
|
||||
.preview-container :deep(ol) {
|
||||
padding-left: 2em;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(li) {
|
||||
margin: 0.25em 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(a) {
|
||||
color: #4a90d9;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.preview-container :deep(a:hover) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.preview-container :deep(img) {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.preview-container :deep(table) {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.preview-container :deep(th),
|
||||
.preview-container :deep(td) {
|
||||
border: 1px solid #ddd;
|
||||
padding: 8px 12px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.preview-container :deep(th) {
|
||||
background-color: #f5f5f5;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.preview-container :deep(hr) {
|
||||
border: none;
|
||||
border-top: 1px solid #ddd;
|
||||
margin: 2em 0;
|
||||
}
|
||||
</style>
|
||||
+107
-391
@@ -2,17 +2,7 @@
|
||||
<div class="editor-container" ref="containerRef">
|
||||
<div ref="root" class="milkdown-editor"></div>
|
||||
|
||||
<GhostTextOverlay
|
||||
v-if="suggestion && cursorRect"
|
||||
:suggestion="suggestion"
|
||||
:position="cursorRect"
|
||||
@accept="acceptSuggestion"
|
||||
@dismiss="dismissSuggestion"
|
||||
/>
|
||||
|
||||
<!-- 底部按钮组 -->
|
||||
<div class="action-buttons">
|
||||
<!-- 上传按钮 -->
|
||||
<button class="action-btn" @click="triggerUpload">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
||||
@@ -22,7 +12,6 @@
|
||||
</button>
|
||||
<input type="file" ref="fileInputRef" @change="handleFileUpload" accept=".md" style="display:none">
|
||||
|
||||
<!-- 导出按钮 -->
|
||||
<button class="action-btn" @click="exportMarkdown">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
||||
@@ -31,378 +20,143 @@
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="isLoading" class="loading-indicator">正在获取建议...</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { replaceAll } from '@milkdown/kit/utils'
|
||||
import { Crepe } from '@milkdown/crepe'
|
||||
import GhostTextOverlay from './GhostTextOverlay.vue'
|
||||
import { fetchSuggestion } from '../utils/api.js'
|
||||
import { DEBUG } from '../utils/config.js'
|
||||
import { createInlineSuggestionPlugin } from '../plugins/inlineSuggestionPlugin.js'
|
||||
|
||||
const root = ref(null)
|
||||
const containerRef = ref(null)
|
||||
const fileInputRef = ref(null)
|
||||
let crepe = null
|
||||
let editorElement = null
|
||||
|
||||
const suggestion = ref('')
|
||||
const cursorRect = ref(null)
|
||||
const isLoading = ref(false)
|
||||
const lastFetchedContent = ref('')
|
||||
let debounceTimer = null
|
||||
|
||||
const DEBOUNCE_MS = 500
|
||||
|
||||
onMounted(async () => {
|
||||
if (DEBUG) console.log('[Debug] onMounted called')
|
||||
if (!root.value) throw new Error('root.value is null')
|
||||
|
||||
if (DEBUG) console.log('[Debug] Creating Crepe editor...')
|
||||
crepe = new Crepe({
|
||||
root: root.value,
|
||||
defaultValue: '# Welcome to LLM in text\n\nStart writing your content here...',
|
||||
// 禁用行号
|
||||
config: {
|
||||
showLineNumber: false,
|
||||
}
|
||||
})
|
||||
|
||||
await crepe.create()
|
||||
if (DEBUG) console.log('[Debug] Crepe editor created')
|
||||
|
||||
observeEditor()
|
||||
if (!root.value) return
|
||||
|
||||
const plugin = createInlineSuggestionPlugin()
|
||||
|
||||
crepe = new Crepe({
|
||||
root: root.value,
|
||||
defaultValue: '# Welcome to LLM in text\n\nStart writing your content here...',
|
||||
features: { [Crepe.Feature.Latex]: true },
|
||||
featureConfigs: {
|
||||
[Crepe.Feature.Latex]: { katexOptions: {}, inlineEditConfirm: 'Escape' }
|
||||
},
|
||||
config: { showLineNumber: false },
|
||||
markdown: {
|
||||
plugins: [plugin]
|
||||
}
|
||||
})
|
||||
|
||||
await crepe.create()
|
||||
})
|
||||
|
||||
const observeEditor = () => {
|
||||
if (!containerRef.value) throw new Error('containerRef.value is null')
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
const editorEl = containerRef.value?.querySelector('.milkdown .editor') ||
|
||||
containerRef.value?.querySelector('.milkdown')
|
||||
if (editorEl) {
|
||||
editorElement = editorEl
|
||||
bindEditorEvents(editorEl)
|
||||
observer.disconnect()
|
||||
if (DEBUG) console.log('[Debug] Editor element found and events bound')
|
||||
}
|
||||
})
|
||||
|
||||
observer.observe(containerRef.value, {
|
||||
childList: true,
|
||||
subtree: true
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
const existingEl = containerRef.value?.querySelector('.milkdown .editor') ||
|
||||
containerRef.value?.querySelector('.milkdown')
|
||||
if (existingEl) {
|
||||
editorElement = existingEl
|
||||
bindEditorEvents(existingEl)
|
||||
observer.disconnect()
|
||||
if (DEBUG) console.log('[Debug] Editor element found immediately')
|
||||
}
|
||||
}, 100)
|
||||
}
|
||||
|
||||
const bindEditorEvents = (editorEl) => {
|
||||
editorEl.addEventListener('input', onInput)
|
||||
editorEl.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Tab') {
|
||||
e.preventDefault()
|
||||
handleTab()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const getEditorContent = () => {
|
||||
if (!editorElement) throw new Error('editorElement is null')
|
||||
return editorElement.innerText || ''
|
||||
}
|
||||
|
||||
const getCursorPositionFromDOM = () => {
|
||||
if (!editorElement) throw new Error('editorElement is null')
|
||||
const selection = window.getSelection()
|
||||
if (!selection.rangeCount) throw new Error('No selection')
|
||||
|
||||
const range = selection.getRangeAt(0)
|
||||
const rect = range.getBoundingClientRect()
|
||||
const containerRect = containerRef.value?.getBoundingClientRect()
|
||||
if (!containerRect) throw new Error('containerRect is null')
|
||||
|
||||
return {
|
||||
left: rect.left - containerRect.left,
|
||||
top: rect.top - containerRect.top + window.scrollY,
|
||||
fontSize: 16,
|
||||
fontFamily: 'monospace',
|
||||
}
|
||||
}
|
||||
|
||||
const getCursorPosition = async () => {
|
||||
return getCursorPositionFromDOM()
|
||||
}
|
||||
|
||||
const onInput = async () => {
|
||||
if (!editorElement) throw new Error('editorElement is null')
|
||||
|
||||
const selection = window.getSelection()
|
||||
if (!selection.rangeCount) return
|
||||
|
||||
const range = selection.getRangeAt(0)
|
||||
const from = range.startOffset
|
||||
|
||||
const content = getEditorContent()
|
||||
const prefix = content.slice(0, from)
|
||||
const suffix = content.slice(from)
|
||||
|
||||
if (DEBUG) console.log('[Debug] onInput triggered at position:', from)
|
||||
|
||||
// 清除之前的定时器
|
||||
if (debounceTimer) {
|
||||
clearTimeout(debounceTimer)
|
||||
}
|
||||
|
||||
// 设置新的定时器 - 只有停止输入后才触发
|
||||
debounceTimer = setTimeout(async () => {
|
||||
if (DEBUG) console.log('[Debug] Debounce timeout reached, fetching suggestion...')
|
||||
|
||||
// 检查是否已经有建议在显示,如果内容没变则跳过
|
||||
if (suggestion.value && content === lastFetchedContent.value) {
|
||||
if (DEBUG) console.log('[Debug] Content unchanged, skipping fetch')
|
||||
return
|
||||
}
|
||||
|
||||
isLoading.value = true
|
||||
try {
|
||||
cursorRect.value = await getCursorPosition()
|
||||
suggestion.value = await fetchSuggestion(prefix, suffix)
|
||||
lastFetchedContent.value = content
|
||||
if (DEBUG) console.log('[Debug] Suggestion updated:', suggestion.value ? 'yes' : 'no')
|
||||
} catch (e) {
|
||||
console.error('[Error] Fetch suggestion failed:', e)
|
||||
throw e
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
debounceTimer = null
|
||||
}
|
||||
}, DEBOUNCE_MS)
|
||||
}
|
||||
|
||||
const handleTab = () => {
|
||||
if (suggestion.value) {
|
||||
const selection = window.getSelection()
|
||||
if (!selection.rangeCount) return
|
||||
|
||||
const range = selection.getRangeAt(0)
|
||||
range.deleteContents()
|
||||
|
||||
const textNode = document.createTextNode(suggestion.value)
|
||||
range.insertNode(textNode)
|
||||
|
||||
range.setStartAfter(textNode)
|
||||
range.setEndAfter(textNode)
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(range)
|
||||
|
||||
suggestion.value = ''
|
||||
if (DEBUG) console.log('[Debug] Tab pressed, accepted suggestion')
|
||||
}
|
||||
}
|
||||
|
||||
const dismissSuggestion = () => {
|
||||
suggestion.value = ''
|
||||
if (DEBUG) console.log('[Debug] Suggestion dismissed')
|
||||
}
|
||||
|
||||
const acceptSuggestion = () => {
|
||||
if (suggestion.value) {
|
||||
const selection = window.getSelection()
|
||||
if (!selection.rangeCount) return
|
||||
|
||||
const range = selection.getRangeAt(0)
|
||||
range.deleteContents()
|
||||
|
||||
const textNode = document.createTextNode(suggestion.value)
|
||||
range.insertNode(textNode)
|
||||
|
||||
range.setStartAfter(textNode)
|
||||
range.setEndAfter(textNode)
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(range)
|
||||
|
||||
suggestion.value = ''
|
||||
if (DEBUG) console.log('[Debug] Suggestion accepted via click')
|
||||
}
|
||||
}
|
||||
|
||||
const exportMarkdown = async () => {
|
||||
if (!crepe) return
|
||||
const markdown = await crepe.getMarkdown()
|
||||
const blob = new Blob([markdown], { type: 'text/markdown' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `document-${Date.now()}.md`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
if (!crepe) return
|
||||
const markdown = await crepe.getMarkdown()
|
||||
const blob = new Blob([markdown], { type: 'text/markdown' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `document-${Date.now()}.md`
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const triggerUpload = () => {
|
||||
fileInputRef.value?.click()
|
||||
}
|
||||
const triggerUpload = () => fileInputRef.value?.click()
|
||||
|
||||
const handleFileUpload = async (event) => {
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
try {
|
||||
const text = await file.text()
|
||||
if (crepe) {
|
||||
await crepe.get().actions.replaceAll(text)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[Error] Upload failed:', e)
|
||||
const file = event.target.files?.[0]
|
||||
if (!file) return
|
||||
|
||||
try {
|
||||
const text = await file.text()
|
||||
if (crepe?.editor) {
|
||||
crepe.editor.action(replaceAll(text))
|
||||
}
|
||||
|
||||
event.target.value = ''
|
||||
} catch (e) {
|
||||
console.error('[Error] Upload failed:', e)
|
||||
}
|
||||
|
||||
event.target.value = ''
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
if (debounceTimer) {
|
||||
clearTimeout(debounceTimer)
|
||||
debounceTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.editor-container {
|
||||
position: relative;
|
||||
position: relative;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.action-buttons {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
right: 20px;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
z-index: 1000;
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
right: 20px;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
z-index: 9999;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 10px;
|
||||
background-color: #f5f5f5;
|
||||
color: #666;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 10px;
|
||||
background-color: #fff;
|
||||
color: #666;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.action-btn:hover {
|
||||
background-color: #4a90d9;
|
||||
color: white;
|
||||
border-color: #4a90d9;
|
||||
background-color: #4a90d9;
|
||||
color: white;
|
||||
border-color: #4a90d9;
|
||||
}
|
||||
|
||||
.milkdown-editor {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background-color: #ffffff;
|
||||
overflow-y: auto;
|
||||
/* 强制覆盖所有可能的内边距和左边距 */
|
||||
padding-left: 0 !important;
|
||||
margin-left: 0 !important;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
.milkdown-editor :deep(.milkdown) {
|
||||
max-width: none;
|
||||
margin: 0 auto !important;
|
||||
padding: 20px 40px !important;
|
||||
min-height: calc(100vh - 40px);
|
||||
/* 覆盖主容器 */
|
||||
padding-left: 0 !important;
|
||||
max-width: none;
|
||||
margin: 0 auto !important;
|
||||
padding: 20px 40px !important;
|
||||
min-height: calc(100vh - 40px);
|
||||
}
|
||||
|
||||
.milkdown-editor :deep(.milkdown__main) {
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
width: 100% !important;
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.milkdown-editor :deep(.milkdown__editor) {
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏所有可能的行号和侧边元素 */
|
||||
.milkdown-editor :deep(*) {
|
||||
margin-top: 0 !important;
|
||||
margin-bottom: 0 !important;
|
||||
padding-top: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
}
|
||||
|
||||
/* 覆盖 Milkdown 主题变量 */
|
||||
.milkdown-editor :deep(.milkdown) {
|
||||
--margin: 0 !important;
|
||||
--padding: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏特定元素 */
|
||||
.milkdown-editor :deep(.milkdown__aside),
|
||||
.milkdown-editor :deep(.milkdown__aside-wrapper),
|
||||
.milkdown-editor :deep([class*="aside"]),
|
||||
.milkdown-editor :deep([class*="line-number"]),
|
||||
.milkdown-editor :deep([class*="gutter"]),
|
||||
.milkdown-editor :deep([class*="sidebar"]) {
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
min-width: 0 !important;
|
||||
max-width: 0 !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
border: none !important;
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
}
|
||||
|
||||
.milkdown-editor::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.milkdown-editor::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.milkdown-editor::-webkit-scrollbar-thumb {
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.milkdown-editor :deep(.milkdown) {
|
||||
max-width: none;
|
||||
margin: 0 auto !important;
|
||||
padding: 20px 40px !important;
|
||||
min-height: calc(100vh - 40px);
|
||||
}
|
||||
|
||||
.milkdown-editor :deep(*) {
|
||||
margin-top: 0 !important;
|
||||
margin-bottom: 0 !important;
|
||||
padding-top: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏所有 Milkdown 工具栏 */
|
||||
.milkdown-editor :deep(.milkdown__toolbar),
|
||||
.milkdown-editor :deep(.milkdown__menu),
|
||||
.milkdown-editor :deep(.milkdown__statusbar),
|
||||
@@ -410,86 +164,48 @@ onUnmounted(() => {
|
||||
.milkdown-editor :deep(.milkdown-bubble-menu),
|
||||
.milkdown-editor :deep([class*="toolbar"]),
|
||||
.milkdown-editor :deep([class*="menu"]) {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
height: 0 !important;
|
||||
width: 0 !important;
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
height: 0 !important;
|
||||
width: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏 block handle(+ 和 :: 按钮) */
|
||||
.milkdown-editor :deep(.milkdown__block-handle),
|
||||
.milkdown-editor :deep([class*="block-handle"]),
|
||||
.milkdown-editor :deep([class*="blockHandle"]) {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
width: 0 !important;
|
||||
min-width: 0 !important;
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
width: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏行号和侧边栏 */
|
||||
.milkdown-editor :deep(.milkdown__aside),
|
||||
.milkdown-editor :deep(.milkdown__aside-wrapper) {
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
.milkdown-editor::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.milkdown-editor :deep([class*="line-number"]),
|
||||
.milkdown-editor :deep([class*="gutter"]) {
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
.milkdown-editor::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.loading-indicator {
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
right: 20px;
|
||||
padding: 8px 16px;
|
||||
background-color: #4a90d9;
|
||||
color: white;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
z-index: 1000;
|
||||
.milkdown-editor::-webkit-scrollbar-thumb {
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- 全局样式覆盖 Crepe 主题 -->
|
||||
<style>
|
||||
/* 隐藏所有 Milkdown 工具栏 */
|
||||
.milkdown__toolbar,
|
||||
.milkdown__menu,
|
||||
.milkdown__statusbar,
|
||||
.milkdown-slate-toolbar,
|
||||
.milkdown-bubble-menu {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
.ghost-text-decoration {
|
||||
color: #999 !important;
|
||||
opacity: 0.7 !important;
|
||||
font-family: inherit !important;
|
||||
font-size: inherit !important;
|
||||
line-height: inherit !important;
|
||||
user-select: none !important;
|
||||
pointer-events: auto !important;
|
||||
cursor: text !important;
|
||||
}
|
||||
|
||||
/* 隐藏 block handle(+ 和 :: 按钮) */
|
||||
.milkdown__block-handle,
|
||||
[class*="block-handle"],
|
||||
[class*="blockHandle"] {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
width: 0 !important;
|
||||
}
|
||||
|
||||
/* 隐藏行号区域 */
|
||||
.milkdown__aside,
|
||||
.milkdown__aside-wrapper,
|
||||
.ProseMirror-gutter,
|
||||
.ProseMirror-gutter-wrapper {
|
||||
display: none !important;
|
||||
width: 0 !important;
|
||||
min-width: 0 !important;
|
||||
}
|
||||
|
||||
/* 移除编辑器左边距 */
|
||||
.milkdown__main {
|
||||
margin-left: 0 !important;
|
||||
padding-left: 0 !important;
|
||||
}
|
||||
|
||||
.ProseMirror {
|
||||
padding-left: 0 !important;
|
||||
.ghost-text-decoration:hover {
|
||||
color: #666 !important;
|
||||
opacity: 1 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,96 +1,124 @@
|
||||
import { Plugin, PluginKey } from '@milkdown/prose/state';
|
||||
import { EditorView } from '@milkdown/prose/view';
|
||||
import { fetchSuggestion } from '../utils/api.js';
|
||||
import { DEBUG, API_URL } from '../utils/config.js';
|
||||
import { Plugin, PluginKey, Decoration, DecorationSet } from '@milkdown/prose/state'
|
||||
import { EditorView } from '@milkdown/prose/view'
|
||||
import { fetchSuggestion } from '../utils/api.js'
|
||||
import { API_URL } from '../utils/config.js'
|
||||
|
||||
const INLINE_SUGGESTION_KEY = new PluginKey('inline-suggestion');
|
||||
const DEBOUNCE_MS = 150;
|
||||
|
||||
interface InlineSuggestionOptions {
|
||||
apiUrl?: string;
|
||||
}
|
||||
const INLINE_SUGGESTION_KEY = new PluginKey('inline-suggestion')
|
||||
const DEBOUNCE_MS = 300
|
||||
|
||||
interface InlineSuggestionState {
|
||||
suggestion: string;
|
||||
visible: boolean;
|
||||
debounceTimer: ReturnType<typeof setTimeout> | null;
|
||||
currentSuggestion: string;
|
||||
suggestionPos: { from: number; to: number };
|
||||
suggestion: string
|
||||
suggestionPos: { from: number; to: number }
|
||||
}
|
||||
|
||||
function createInlineSuggestionPlugin(options: InlineSuggestionOptions = {}) {
|
||||
const apiUrl = options.apiUrl || API_URL;
|
||||
function createGhostTextDecoration(from: number, to: number, text: string) {
|
||||
return Decoration.inline(from, to, {
|
||||
class: 'ghost-text-decoration',
|
||||
'data-suggestion': text,
|
||||
}, { side: 1 })
|
||||
}
|
||||
|
||||
return new Plugin<InlineSuggestionState>({
|
||||
key: INLINE_SUGGESTION_KEY,
|
||||
state: {
|
||||
init: () => ({
|
||||
suggestion: '',
|
||||
visible: false,
|
||||
debounceTimer: null,
|
||||
currentSuggestion: '',
|
||||
suggestionPos: { from: 0, to: 0 }
|
||||
}),
|
||||
apply: (tr, value) => {
|
||||
if (!tr.docChanged) return value;
|
||||
const { from, to } = tr.selection;
|
||||
if (from === value.suggestionPos.from && to === value.suggestionPos.to) {
|
||||
return value;
|
||||
}
|
||||
return { ...value, suggestion: '', visible: false };
|
||||
},
|
||||
},
|
||||
props: {
|
||||
handleKeyDown: (view: EditorView, event: KeyboardEvent) => {
|
||||
const state = INLINE_SUGGESTION_KEY.getState(view.state);
|
||||
if (event.key === 'Tab' && state.visible) {
|
||||
event.preventDefault();
|
||||
if (state.suggestion) {
|
||||
view.dispatch(view.state.tr.insertText(state.suggestion, view.state.selection.from));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
if (state.visible) {
|
||||
view.dispatch(view.state.tr.setMeta(INLINE_SUGGESTION_KEY, { ...state, suggestion: '', visible: false }));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
appendTransaction: (transactions, oldState, newState) => {
|
||||
const lastTr = transactions[transactions.length - 1];
|
||||
if (!lastTr || !lastTr.docChanged) return null;
|
||||
export function createInlineSuggestionPlugin(options: { apiUrl?: string } = {}) {
|
||||
const apiUrl = options.apiUrl || API_URL
|
||||
|
||||
const currentState = INLINE_SUGGESTION_KEY.getState(newState);
|
||||
return new Plugin({
|
||||
key: INLINE_SUGGESTION_KEY,
|
||||
state: {
|
||||
init: (): InlineSuggestionState => ({
|
||||
suggestion: '',
|
||||
suggestionPos: { from: 0, to: 0 }
|
||||
}),
|
||||
apply: (tr, value): InlineSuggestionState => {
|
||||
if (!tr.docChanged) return value
|
||||
|
||||
const { from, to } = tr.selection
|
||||
if (from === value.suggestionPos.from && to === value.suggestionPos.to) {
|
||||
return value
|
||||
}
|
||||
return { suggestion: '', suggestionPos: { from: 0, to: 0 } }
|
||||
},
|
||||
},
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const pluginState = INLINE_SUGGESTION_KEY.getState(state)
|
||||
if (!pluginState.suggestion) {
|
||||
return DecorationSet.empty
|
||||
}
|
||||
return DecorationSet.create(state.doc, [
|
||||
createGhostTextDecoration(
|
||||
pluginState.suggestionPos.from,
|
||||
pluginState.suggestionPos.from + pluginState.suggestion.length,
|
||||
pluginState.suggestion
|
||||
)
|
||||
])
|
||||
},
|
||||
handleKeyDown: (view: EditorView, event: KeyboardEvent) => {
|
||||
const state = INLINE_SUGGESTION_KEY.getState(view.state)
|
||||
|
||||
if (event.key === 'Tab' && state.suggestion) {
|
||||
event.preventDefault()
|
||||
const { state: currentState, dispatch } = view
|
||||
dispatch(currentState.tr.insertText(state.suggestion, currentState.selection.from))
|
||||
dispatch(currentState.tr.setMeta(INLINE_SUGGESTION_KEY, {
|
||||
suggestion: '',
|
||||
suggestionPos: { from: 0, to: 0 }
|
||||
}))
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.key === 'Escape' && state.suggestion) {
|
||||
event.preventDefault()
|
||||
view.dispatch(view.state.tr.setMeta(INLINE_SUGGESTION_KEY, {
|
||||
suggestion: '',
|
||||
suggestionPos: { from: 0, to: 0 }
|
||||
}))
|
||||
return true
|
||||
}
|
||||
|
||||
if (state.suggestion) {
|
||||
view.dispatch(view.state.tr.setMeta(INLINE_SUGGESTION_KEY, {
|
||||
suggestion: '',
|
||||
suggestionPos: { from: 0, to: 0 }
|
||||
}))
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
},
|
||||
appendTransaction: (transactions, oldState, newState) => {
|
||||
const lastTr = transactions[transactions.length - 1]
|
||||
if (!lastTr || !lastTr.docChanged) return null
|
||||
|
||||
const currentState = INLINE_SUGGESTION_KEY.getState(newState)
|
||||
const { from, to } = newState.selection
|
||||
|
||||
if (currentState.suggestion && from === currentState.suggestionPos.from) {
|
||||
return null
|
||||
}
|
||||
|
||||
setTimeout(async () => {
|
||||
const prefix = newState.doc.textBetween(0, from)
|
||||
const suffix = newState.doc.textBetween(to, newState.doc.content.size)
|
||||
|
||||
try {
|
||||
const text = await fetchSuggestion(prefix, suffix, apiUrl)
|
||||
|
||||
if (text && newState.selection.from === from) {
|
||||
const newPluginState = {
|
||||
suggestion: text,
|
||||
suggestionPos: { from, to: from + text.length }
|
||||
}
|
||||
|
||||
clearTimeout(currentState.debounceTimer);
|
||||
currentState.debounceTimer = setTimeout(async () => {
|
||||
const { from, to } = newState.selection;
|
||||
const prefix = newState.doc.textBetween(0, from);
|
||||
const suffix = newState.doc.textBetween(to, newState.doc.content.size);
|
||||
newState.apply(newState.tr.setMeta(INLINE_SUGGESTION_KEY, newPluginState))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Inline suggestion error:', e)
|
||||
}
|
||||
}, DEBOUNCE_MS)
|
||||
|
||||
try {
|
||||
const text = await fetchSuggestion(prefix, suffix, apiUrl);
|
||||
|
||||
if (text && newState.selection.from === from) {
|
||||
newState.apply(newState.tr.setMeta(INLINE_SUGGESTION_KEY, {
|
||||
...currentState,
|
||||
currentSuggestion: text,
|
||||
suggestionPos: { from, to: from + text.length },
|
||||
suggestion: text,
|
||||
visible: true
|
||||
}));
|
||||
}
|
||||
} catch (e) {
|
||||
if (DEBUG) console.error('Inline suggestion error:', e);
|
||||
}
|
||||
}, DEBOUNCE_MS);
|
||||
|
||||
return null;
|
||||
},
|
||||
});
|
||||
return null
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export { createInlineSuggestionPlugin, INLINE_SUGGESTION_KEY };
|
||||
export { INLINE_SUGGESTION_KEY }
|
||||
|
||||
+25
-47
@@ -1,52 +1,30 @@
|
||||
import { DEBUG, API_URL } from './config.js'
|
||||
export async function fetchSuggestion(prefix, suffix, apiUrl = 'http://localhost:8000/v1/completions') {
|
||||
const res = await fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefix, suffix, languageId: 'markdown' }),
|
||||
})
|
||||
|
||||
export async function fetchSuggestion(prefix, suffix, apiUrl = API_URL) {
|
||||
if (DEBUG) console.log('[Debug] fetchSuggestion called with prefix length:', prefix.length, 'suffix length:', suffix.length)
|
||||
try {
|
||||
const res = await fetch(apiUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefix, suffix, languageId: 'markdown' }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`)
|
||||
}
|
||||
|
||||
if (DEBUG) console.log('[Debug] fetchSuggestion response status:', res.status)
|
||||
if (!res.ok) {
|
||||
const errorText = await res.text()
|
||||
throw new Error(`HTTP ${res.status}: ${errorText}`)
|
||||
}
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) throw new Error('No reader available')
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) {
|
||||
if (DEBUG) console.log('[Debug] No reader available')
|
||||
throw new Error('No reader available')
|
||||
}
|
||||
|
||||
let text = ''
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
const chunk = new TextDecoder().decode(value)
|
||||
if (DEBUG) console.log('[Debug] Received chunk:', chunk.substring(0, 100))
|
||||
|
||||
const lines = chunk.split('\n').filter(l => l.startsWith('data: '))
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6))
|
||||
if (data.content) {
|
||||
text += data.content
|
||||
if (DEBUG) console.log('[Debug] Added content:', data.content)
|
||||
}
|
||||
if (data.done || data.error) break
|
||||
} catch (e) {
|
||||
if (DEBUG) console.warn('[Debug] JSON parse error:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (DEBUG) console.log('[Debug] Final suggestion text:', text.substring(0, 100))
|
||||
return text
|
||||
} catch (e) {
|
||||
if (DEBUG) console.error('[Debug] fetchSuggestion error:', e)
|
||||
throw e
|
||||
let text = ''
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
const chunk = new TextDecoder().decode(value)
|
||||
const lines = chunk.split('\n').filter(l => l.startsWith('data: '))
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6))
|
||||
if (data.content) text += data.content
|
||||
if (data.done || data.error) break
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user