File
Blob: src/client/components/editor/lib/page-mention/can-insert.ts
| 1 | import type { Editor, Range } from "@tiptap/core"; |
| 2 | import { Fragment } from "@tiptap/pm/model"; |
| 3 | |
| 4 | interface CanInsertPageMentionsOpts { |
| 5 | editable: boolean; |
| 6 | workspaceId: string | undefined; |
| 7 | shareToken: string | undefined; |
| 8 | } |
| 9 | |
| 10 | export function canInsertPageMentions(opts: CanInsertPageMentionsOpts): boolean { |
| 11 | return opts.editable && !!opts.workspaceId && !opts.shareToken; |
| 12 | } |
| 13 | |
| 14 | export function canInsertPageMentionAtRange(editor: Editor, range?: Range): boolean { |
| 15 | if (!editor.isEditable) return false; |
| 16 | |
| 17 | const pageMention = editor.schema.nodes.pageMention; |
| 18 | if (!pageMention) return false; |
| 19 | |
| 20 | const from = range ? Math.min(range.from, range.to) : editor.state.selection.from; |
| 21 | const to = range ? Math.max(range.from, range.to) : editor.state.selection.to; |
| 22 | const tr = editor.state.tr; |
| 23 | |
| 24 | if (from !== to) { |
| 25 | tr.deleteRange(from, to); |
| 26 | } |
| 27 | |
| 28 | const insertPos = tr.mapping.map(from, -1); |
| 29 | const $pos = tr.doc.resolve(insertPos); |
| 30 | const mentionNode = pageMention.create({ pageId: "__page-mention-probe__" }); |
| 31 | const probe = Fragment.fromArray([mentionNode, editor.schema.text(" ")]); |
| 32 | |
| 33 | return $pos.parent.canReplace($pos.index(), $pos.index(), probe); |
| 34 | } |