This commit is contained in:
Timothy Jaeryang Baek 2024-11-28 23:24:16 -08:00
parent 95000c7b15
commit fa5e1f7452
2 changed files with 40 additions and 30 deletions

View File

@ -153,10 +153,10 @@
Placeholder.configure({ placeholder }), Placeholder.configure({ placeholder }),
AIAutocompletion.configure({ AIAutocompletion.configure({
generateCompletion: async (text) => { generateCompletion: async (text) => {
// Implement your AI text generation logic here if (text.trim().length === 0) {
// This should return a Promise that resolves to the suggested text return null;
}
console.log(text);
return 'AI-generated suggestion'; return 'AI-generated suggestion';
} }
}) })

View File

@ -50,8 +50,6 @@ export const AIAutocompletion = Extension.create({
key: new PluginKey('aiAutocompletion'), key: new PluginKey('aiAutocompletion'),
props: { props: {
handleKeyDown: (view, event) => { handleKeyDown: (view, event) => {
if (event.key !== 'Tab') return false
const { state, dispatch } = view const { state, dispatch } = view
const { selection } = state const { selection } = state
const { $head } = selection const { $head } = selection
@ -59,35 +57,47 @@ export const AIAutocompletion = Extension.create({
if ($head.parent.type.name !== 'paragraph') return false if ($head.parent.type.name !== 'paragraph') return false
const node = $head.parent const node = $head.parent
const prompt = node.textContent
if (!node.attrs['data-suggestion']) { if (event.key === 'Tab') {
// Generate completion if (!node.attrs['data-suggestion']) {
this.options.generateCompletion(prompt).then(suggestion => { // Generate completion
if (suggestion && suggestion.trim() !== '') { const prompt = node.textContent
dispatch(state.tr.setNodeMarkup($head.before(), null, { this.options.generateCompletion(prompt).then(suggestion => {
...node.attrs, if (suggestion && suggestion.trim() !== '') {
class: 'ai-autocompletion', dispatch(state.tr.setNodeMarkup($head.before(), null, {
'data-prompt': prompt, ...node.attrs,
'data-suggestion': suggestion, class: 'ai-autocompletion',
})) 'data-prompt': prompt,
} 'data-suggestion': suggestion,
}) }))
} else { }
// Accept suggestion // If suggestion is empty or null, do nothing
const suggestion = node.attrs['data-suggestion']
dispatch(state.tr
.insertText(suggestion, $head.pos)
.setNodeMarkup($head.before(), null, {
...node.attrs,
class: null,
'data-prompt': null,
'data-suggestion': null,
}) })
) } else {
// Accept suggestion
const suggestion = node.attrs['data-suggestion']
dispatch(state.tr
.insertText(suggestion, $head.pos)
.setNodeMarkup($head.before(), null, {
...node.attrs,
class: null,
'data-prompt': null,
'data-suggestion': null,
})
)
}
return true
} else if (node.attrs['data-suggestion']) {
// Reset suggestion on any other key press
dispatch(state.tr.setNodeMarkup($head.before(), null, {
...node.attrs,
class: null,
'data-prompt': null,
'data-suggestion': null,
}))
} }
return true return false
}, },
}, },
}), }),