import type { SlashMenuState } from '@admin/utils/editor/slash-menu-state' import type { Editor } from '@tiptap/react' const SLASH_QUERY_LIMIT = 48 export function getSlashMenuState(editor: Editor): SlashMenuState | null { const { selection } = editor.state if (!selection.empty || !editor.isEditable) return null const { $from } = selection const parent = $from.parent if (!parent.isTextblock || parent.type.name === 'codeBlock') return null const textBeforeCursor = parent.textBetween(0, $from.parentOffset, '\n', '\ufffc') const slashIndex = textBeforeCursor.lastIndexOf('/') if (slashIndex === -1) return null if (slashIndex > 0 && !/\s/.test(textBeforeCursor[slashIndex - 1])) { return null } const query = textBeforeCursor.slice(slashIndex + 1) if (query.includes('/') || query.length > SLASH_QUERY_LIMIT) return null const from = $from.start() + slashIndex const to = selection.from try { const coords = editor.view.coordsAtPos(from) return { from, to, query, rect: new DOMRect( coords.left, coords.top, Math.max(1, coords.right - coords.left), Math.max(1, coords.bottom - coords.top) ) } } catch { return null } }