What is @tiptap/suggestion?
@tiptap/suggestion is a plugin for the Tiptap editor that provides a way to add suggestions to your editor. This can be used for implementing features like mentions, hashtags, or any other type of inline suggestions.
Basic Suggestion Setup
This code sets up a basic suggestion plugin that triggers on the '@' character. When a suggestion is selected, it inserts a mention node at the current position.
import { Suggestion } from '@tiptap/suggestion';
const suggestion = Suggestion({
char: '@',
startOfLine: false,
command: ({ editor, range, props }) => {
editor.chain().focus().insertContentAt(range, [
{
type: 'mention',
attrs: props,
},
{
type: 'text',
text: ' ',
},
]).run();
},
});
Customizing Suggestion Menu
This code customizes the suggestion menu to trigger on the '#' character and filter items based on the query. It uses Vue and Tippy.js to render and manage the suggestion list.
import { Suggestion } from '@tiptap/suggestion';
const suggestion = Suggestion({
char: '#',
startOfLine: false,
items: ({ query }) => {
return [
{ title: 'JavaScript', id: 1 },
{ title: 'TypeScript', id: 2 },
{ title: 'React', id: 3 },
].filter(item => item.title.toLowerCase().includes(query.toLowerCase()));
},
render: () => {
let component;
let popup;
return {
onStart: props => {
component = new Vue({
render: h => h(SuggestionList, { props }),
}).$mount();
popup = tippy('body', {
getReferenceClientRect: props.clientRect,
appendTo: () => document.body,
content: component.$el,
showOnCreate: true,
});
},
onUpdate: props => {
component.$props = props;
popup[0].setProps({
getReferenceClientRect: props.clientRect,
});
},
onExit: () => {
popup[0].destroy();
component.$destroy();
},
};
},
});