| 1 | import { Editor } from "@tiptap/core"; |
| 2 | import { ContextProviderDescription } from "core"; |
| 3 | import { Mention } from "../extensions"; |
| 4 | |
| 5 | function isEditorContentEmpty(editor: Editor): boolean { |
| 6 | const editorContent = editor.getJSON(); |
| 7 | |
| 8 | if (!editorContent.content || editorContent.content.length === 0) { |
| 9 | return true; |
| 10 | } |
| 11 | |
| 12 | const firstNode = editorContent.content[0]; |
| 13 | if ( |
| 14 | firstNode.type === "paragraph" && |
| 15 | (firstNode.content || []).length === 0 |
| 16 | ) { |
| 17 | return true; |
| 18 | } |
| 19 | |
| 20 | return false; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * inserts the current file context as a removable mention in the editor area |
| 25 | * |
| 26 | * skips if there is any other content in the editor |
| 27 | * |
| 28 | * uses tiptap's `create` method to create a new node under the hood |
| 29 | */ |
| 30 | export function insertCurrentFileContextMention( |
| 31 | editor: Editor, |
| 32 | contextProviders: ContextProviderDescription[], |
| 33 | ) { |
| 34 | if (!isEditorContentEmpty(editor)) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | const foundCurrentFileProvider = contextProviders.find( |
| 39 | (provider) => provider.title === "currentFile", |
| 40 | ); |
| 41 | |
| 42 | if (foundCurrentFileProvider) { |
| 43 | const node = editor.schema.nodes[Mention.name].create({ |
| 44 | name: foundCurrentFileProvider.displayTitle, |
| 45 | description: foundCurrentFileProvider.description, |
| 46 | id: foundCurrentFileProvider.title, |
| 47 | label: foundCurrentFileProvider.displayTitle, |
| 48 | renderInlineAs: foundCurrentFileProvider.renderInlineAs, |
| 49 | type: foundCurrentFileProvider.type, |
| 50 | itemType: "contextProvider", |
| 51 | }); |
| 52 | |
| 53 | editor |
| 54 | .chain() |
| 55 | .insertContent([node.toJSON(), { type: "text", text: " " }]) // add a space after the mention |
| 56 | .run(); |
| 57 | } |
| 58 | } |