feat: add renderLabel option to mention extension, see #1322

This commit is contained in:
Philipp Kühn
2021-06-14 16:40:17 +02:00
parent c64761a9e5
commit 3b78af44a0
2 changed files with 21 additions and 6 deletions

View File

@@ -43,8 +43,9 @@ Its also possible to use Vanilla JavaScript, but that is probably a lot more
## Settings ## Settings
| Option | Type | Default | Description | | Option | Type | Default | Description |
| -------------- | -------- | ------- | --------------------------------------------------------------------- | | -------------- | -------- | -------------------------- | --------------------------------------------------------------------- |
| HTMLAttributes | `Object` | `{}` | Custom HTML attributes that should be added to the rendered HTML tag. | | HTMLAttributes | `Object` | `{}` | Custom HTML attributes that should be added to the rendered HTML tag. |
| renderLabel | `String` | `({ options, node }) => …` | Define how a mention label should be rendered. |
| suggestion | `Object` | `{ … }` | [Read more](/api/utilities/suggestion) | | suggestion | `Object` | `{ … }` | [Read more](/api/utilities/suggestion) |
## Source code ## Source code

View File

@@ -1,8 +1,13 @@
import { Node, mergeAttributes } from '@tiptap/core' import { Node, mergeAttributes } from '@tiptap/core'
import { Node as ProseMirrorNode } from 'prosemirror-model'
import Suggestion, { SuggestionOptions } from '@tiptap/suggestion' import Suggestion, { SuggestionOptions } from '@tiptap/suggestion'
export type MentionOptions = { export type MentionOptions = {
HTMLAttributes: Record<string, any>, HTMLAttributes: Record<string, any>,
renderLabel: (props: {
options: MentionOptions,
node: ProseMirrorNode,
}) => string,
suggestion: Omit<SuggestionOptions, 'editor'>, suggestion: Omit<SuggestionOptions, 'editor'>,
} }
@@ -11,6 +16,9 @@ export const Mention = Node.create<MentionOptions>({
defaultOptions: { defaultOptions: {
HTMLAttributes: {}, HTMLAttributes: {},
renderLabel({ options, node }) {
return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`
},
suggestion: { suggestion: {
char: '@', char: '@',
command: ({ editor, range, props }) => { command: ({ editor, range, props }) => {
@@ -95,12 +103,18 @@ export const Mention = Node.create<MentionOptions>({
return [ return [
'span', 'span',
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
`${this.options.suggestion.char}${node.attrs.label ?? node.attrs.id}`, this.options.renderLabel({
options: this.options,
node,
}),
] ]
}, },
renderText({ node }) { renderText({ node }) {
return `${this.options.suggestion.char}${node.attrs.label ?? node.attrs.id}` return this.options.renderLabel({
options: this.options,
node,
})
}, },
addKeyboardShortcuts() { addKeyboardShortcuts() {