feat: implement inline autocomplete suggestions with FastAPI backend and Milkdown editor integration
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<div v-if="visible" class="ghost-text-overlay" :style="overlayStyle"
|
||||
@click="acceptSuggestion"
|
||||
>{{ suggestion }}
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
suggestion: { type: String, default: '' },
|
||||
position: { type: Object, required: true },
|
||||
})
|
||||
|
||||
const emit = defineEmits(['accept', 'dismiss'])
|
||||
|
||||
const visible = computed(() => props.suggestion && props.position)
|
||||
|
||||
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,
|
||||
}))
|
||||
|
||||
const acceptSuggestion = () => emit('accept')
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.ghost-text-overlay {
|
||||
opacity: 0.6;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.ghost-text-overlay:hover {
|
||||
opacity: 1;
|
||||
color: #666;
|
||||
}
|
||||
</style>
|
||||
@@ -1,97 +1,286 @@
|
||||
<template>
|
||||
<div class="editor-container">
|
||||
<div class="editor-container" ref="containerRef">
|
||||
<button class="export-btn" @click="exportMarkdown">导出文件</button>
|
||||
|
||||
<div ref="root" class="milkdown-editor"></div>
|
||||
|
||||
GhostTextOverlay
|
||||
v-if="suggestion && cursorRect"
|
||||
:suggestion="suggestion"
|
||||
:position="cursorRect"
|
||||
@accept="acceptSuggestion"
|
||||
@dismiss="dismissSuggestion"
|
||||
/GhostTextOverlay
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { Crepe } from '@milkdown/crepe'
|
||||
import GhostTextOverlay from './GhostTextOverlay.vue'
|
||||
|
||||
const root = ref(null)
|
||||
const containerRef = ref(null)
|
||||
let crepe = null
|
||||
|
||||
const suggestion = ref('')
|
||||
const cursorRect = ref(null)
|
||||
let debounceTimer = null
|
||||
let lastPos = -1
|
||||
|
||||
const API_URL = 'http://localhost:8000/v1/completions'
|
||||
const DEBOUNCE_MS = 150
|
||||
|
||||
onMounted(async () => {
|
||||
if (!root.value) return
|
||||
|
||||
crepe = new Crepe({
|
||||
root: root.value,
|
||||
defaultValue: '# Welcome to Milkdown\n\nStart writing your markdown content here...',
|
||||
})
|
||||
|
||||
await crepe.create()
|
||||
console.log('[Debug] onMounted called')
|
||||
if (!root.value) {
|
||||
console.log('[Debug] root.value is null')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[Debug] Creating Crepe editor...')
|
||||
crepe = new Crepe({
|
||||
root: root.value,
|
||||
defaultValue: '# Welcome to Milkdown\n\nStart writing your markdown content here...',
|
||||
})
|
||||
|
||||
await crepe.create()
|
||||
console.log('[Debug] Crepe editor created')
|
||||
})
|
||||
|
||||
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)
|
||||
const getCursorPosition = async () => {
|
||||
if (!crepe) {
|
||||
console.log('[Debug] getCursorPosition: crepe is null')
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const ctx = crepe.ctx.get()
|
||||
const view = ctx.get('view')
|
||||
const { from } = view.state.selection
|
||||
console.log('[Debug] Cursor position:', from)
|
||||
|
||||
const coords = view.coordsAtPos(from)
|
||||
const containerRect = containerRef.value?.getBoundingClientRect()
|
||||
if (!containerRect) {
|
||||
console.log('[Debug] containerRect is null')
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
left: coords.left - containerRect.left,
|
||||
top: coords.top - containerRect.top + window.scrollY,
|
||||
fontSize: 16,
|
||||
fontFamily: 'monospace',
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[Debug] getCursorPosition error:', e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const fetchSuggestion = async (prefix, suffix) => {
|
||||
console.log('[Debug] fetchSuggestion called with prefix length:', prefix.length, 'suffix length:', suffix.length)
|
||||
try {
|
||||
const res = await fetch(API_URL, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ prefix, suffix, languageId: 'markdown' }),
|
||||
})
|
||||
|
||||
console.log('[Debug] fetchSuggestion response status:', res.status)
|
||||
if (!res.ok) {
|
||||
console.log('[Debug] Response not ok')
|
||||
return ''
|
||||
}
|
||||
|
||||
const reader = res.body?.getReader()
|
||||
if (!reader) {
|
||||
console.log('[Debug] No reader available')
|
||||
return ''
|
||||
}
|
||||
|
||||
let text = ''
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
const chunk = new TextDecoder().decode(value)
|
||||
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
|
||||
console.log('[Debug] Added content:', data.content)
|
||||
}
|
||||
if (data.done || data.error) break
|
||||
} catch (e) {
|
||||
console.warn('[Debug] JSON parse error:', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[Debug] Final suggestion text:', text.substring(0, 100))
|
||||
return text
|
||||
} catch (e) {
|
||||
console.error('[Debug] fetchSuggestion error:', e)
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const onInput = async () => {
|
||||
if (!crepe) {
|
||||
console.log('[Debug] onInput: crepe is null')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const ctx = crepe.ctx.get()
|
||||
const view = ctx.get('view')
|
||||
const { from } = view.state.selection
|
||||
|
||||
if (from === lastPos) {
|
||||
console.log('[Debug] Same position, skipping')
|
||||
return
|
||||
}
|
||||
lastPos = from
|
||||
|
||||
console.log('[Debug] onInput triggered at position:', from)
|
||||
|
||||
const prefix = view.state.doc.textBetween(0, from)
|
||||
const suffix = view.state.doc.textBetween(from, view.state.doc.content.size)
|
||||
|
||||
console.log('[Debug] Prefix preview:', prefix.substring(-50))
|
||||
|
||||
clearTimeout(debounceTimer)
|
||||
debounceTimer = setTimeout(async () => {
|
||||
cursorRect.value = await getCursorPosition()
|
||||
suggestion.value = await fetchSuggestion(prefix, suffix)
|
||||
console.log('[Debug] Suggestion updated:', suggestion.value ? 'yes' : 'no')
|
||||
}, DEBOUNCE_MS)
|
||||
} catch (e) {
|
||||
console.error('[Debug] onInput error:', e)
|
||||
}
|
||||
}
|
||||
|
||||
const handleTab = () => {
|
||||
if (suggestion.value) {
|
||||
const ctx = crepe.ctx.get()
|
||||
const view = ctx.get('view')
|
||||
view.dispatch(view.state.tr.insertText(suggestion.value))
|
||||
suggestion.value = ''
|
||||
console.log('[Debug] Tab pressed, accepted suggestion')
|
||||
}
|
||||
}
|
||||
|
||||
const dismissSuggestion = () => {
|
||||
suggestion.value = ''
|
||||
console.log('[Debug] Suggestion dismissed')
|
||||
}
|
||||
|
||||
const acceptSuggestion = () => {
|
||||
if (suggestion.value) {
|
||||
const ctx = crepe.ctx.get()
|
||||
const view = ctx.get('view')
|
||||
view.dispatch(view.state.tr.insertText(suggestion.value))
|
||||
suggestion.value = ''
|
||||
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)
|
||||
}
|
||||
|
||||
// 监听 crepe 创建完成后绑定事件
|
||||
const initEditorEvents = () => {
|
||||
if (!crepe) return
|
||||
|
||||
try {
|
||||
const ctx = crepe.ctx.get()
|
||||
const view = ctx.get('view')
|
||||
console.log('[Debug] Binding input event to editor DOM')
|
||||
|
||||
// 直接在编辑器 DOM 上监听输入事件
|
||||
view.dom.addEventListener('input', onInput)
|
||||
view.dom.addEventListener('keydown', (e) => {
|
||||
console.log('[Debug] Keydown:', e.key, 'code:', e.code)
|
||||
if (e.key === 'Tab') {
|
||||
handleTab()
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[Debug] Failed to bind events:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 延迟初始化事件绑定
|
||||
setTimeout(initEditorEvents, 500)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.editor-container {
|
||||
position: relative;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.export-btn {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 8px 16px;
|
||||
background-color: #4a90d9;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
z-index: 1000;
|
||||
export-btn {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 8px 16px;
|
||||
background-color: #4a90d9;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.export-btn:hover {
|
||||
background-color: #3a7bc8;
|
||||
export-btn:hover {
|
||||
background-color: #3a7bc8;
|
||||
}
|
||||
|
||||
.milkdown-editor {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background-color: #ffffff;
|
||||
overflow-y: auto;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background-color: #ffffff;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* 当内容不超过视口时隐藏滚动条 */
|
||||
.milkdown-editor::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.milkdown-editor::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.milkdown-editor::-webkit-scrollbar-thumb {
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* 编辑器内容容器样式 */
|
||||
.milkdown-editor :deep(.milkdown) {
|
||||
max-width: 900px;
|
||||
margin: 0 auto !important;
|
||||
padding: 20px 40px !important;
|
||||
min-height: calc(100vh - 40px);
|
||||
max-width: 900px;
|
||||
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;
|
||||
margin-top: 0 !important;
|
||||
margin-bottom: 0 !important;
|
||||
padding-top: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user