tiptap/packages/suggestion/src/suggestion.ts

286 lines
7.9 KiB
TypeScript
Raw Normal View History

import { Editor, Range } from '@tiptap/core'
import { EditorState, Plugin, PluginKey } from 'prosemirror-state'
2021-01-19 17:09:32 +08:00
import { Decoration, DecorationSet, EditorView } from 'prosemirror-view'
2021-01-15 21:49:28 +08:00
import { findSuggestionMatch } from './findSuggestionMatch'
2020-12-17 00:47:17 +08:00
export interface SuggestionOptions<I = any> {
pluginKey?: PluginKey,
2021-01-15 22:58:39 +08:00
editor: Editor,
char?: string,
allowSpaces?: boolean,
allowedPrefixes?: string[] | null,
2021-01-15 22:58:39 +08:00
startOfLine?: boolean,
decorationTag?: string,
decorationClass?: string,
2021-01-20 16:23:44 +08:00
command?: (props: {
editor: Editor,
range: Range,
props: I,
2021-01-20 16:23:44 +08:00
}) => void,
items?: (props: {
query: string,
editor: Editor,
}) => I[] | Promise<I[]>,
2021-01-19 06:41:38 +08:00
render?: () => {
onBeforeStart?: (props: SuggestionProps<I>) => void
onStart?: (props: SuggestionProps<I>) => void,
onBeforeUpdate?: (props: SuggestionProps<I>) => void
onUpdate?: (props: SuggestionProps<I>) => void,
onExit?: (props: SuggestionProps<I>) => void,
2021-01-19 17:09:32 +08:00
onKeyDown?: (props: SuggestionKeyDownProps) => boolean,
2021-01-18 19:40:13 +08:00
},
allow?: (props: {
editor: Editor,
state: EditorState,
range: Range,
}) => boolean,
2021-01-15 22:58:39 +08:00
}
export interface SuggestionProps<I = any> {
2021-01-19 17:09:32 +08:00
editor: Editor,
range: Range,
query: string,
text: string,
items: I[],
command: (props: I) => void,
2021-01-19 17:09:32 +08:00
decorationNode: Element | null,
clientRect?: (() => DOMRect | null) | null,
2021-01-19 17:09:32 +08:00
}
export interface SuggestionKeyDownProps {
view: EditorView,
event: KeyboardEvent,
range: Range,
}
export const SuggestionPluginKey = new PluginKey('suggestion')
export function Suggestion<I = any>({
pluginKey = SuggestionPluginKey,
2021-01-19 17:09:32 +08:00
editor,
2021-01-15 16:25:50 +08:00
char = '@',
allowSpaces = false,
2022-11-04 19:32:01 +08:00
allowedPrefixes = [' '],
2021-01-15 16:25:50 +08:00
startOfLine = false,
decorationTag = 'span',
decorationClass = 'suggestion',
2021-01-15 22:58:39 +08:00
command = () => null,
items = () => [],
2021-01-19 06:41:38 +08:00
render = () => ({}),
allow = () => true,
}: SuggestionOptions<I>) {
2021-01-18 19:40:13 +08:00
let props: SuggestionProps<I> | undefined
2021-01-19 06:41:38 +08:00
const renderer = render?.()
2020-12-17 00:47:17 +08:00
const plugin: Plugin<any> = new Plugin({
key: pluginKey,
2020-12-17 00:47:17 +08:00
view() {
return {
update: async (view, prevState) => {
const prev = this.key?.getState(prevState)
const next = this.key?.getState(view.state)
// See how the state changed
const moved = prev.active && next.active && prev.range.from !== next.range.from
const started = !prev.active && next.active
const stopped = prev.active && !next.active
const changed = !started && !stopped && prev.query !== next.query
const handleStart = started || moved
const handleChange = changed && !moved
const handleExit = stopped || moved
// Cancel when suggestion isn't active
if (!handleStart && !handleChange && !handleExit) {
return
}
2021-08-09 21:21:44 +08:00
const state = handleExit && !handleStart
? prev
: next
const decorationNode = view.dom.querySelector(`[data-decoration-id="${state.decorationId}"]`)
props = {
2021-01-19 17:09:32 +08:00
editor,
2020-12-17 00:47:17 +08:00
range: state.range,
query: state.query,
text: state.text,
items: [],
2021-01-21 19:28:58 +08:00
command: commandProps => {
2021-01-20 16:23:44 +08:00
command({
editor,
range: state.range,
2021-01-21 19:28:58 +08:00
props: commandProps,
2021-01-20 16:23:44 +08:00
})
2021-01-19 06:41:38 +08:00
},
2020-12-17 00:47:17 +08:00
decorationNode,
2021-01-19 19:28:33 +08:00
// virtual node for popper.js or tippy.js
2021-01-15 21:49:28 +08:00
// this can be used for building popups without a DOM node
2021-04-17 05:33:30 +08:00
clientRect: decorationNode
? () => {
// because of `items` can be asynchrounous well search for the current docoration node
const { decorationId } = this.key?.getState(editor.state) // eslint-disable-line
const currentDecorationNode = view.dom.querySelector(`[data-decoration-id="${decorationId}"]`)
return currentDecorationNode?.getBoundingClientRect() || null
}
2021-04-17 05:33:30 +08:00
: null,
2020-12-17 00:47:17 +08:00
}
if (handleStart) {
renderer?.onBeforeStart?.(props)
}
if (handleChange) {
renderer?.onBeforeUpdate?.(props)
}
if (handleChange || handleStart) {
props.items = await items({
editor,
query: state.query,
})
}
if (handleExit) {
renderer?.onExit?.(props)
2020-12-17 00:47:17 +08:00
}
if (handleChange) {
2021-01-19 06:41:38 +08:00
renderer?.onUpdate?.(props)
2020-12-17 00:47:17 +08:00
}
if (handleStart) {
renderer?.onStart?.(props)
2020-12-17 00:47:17 +08:00
}
},
destroy: () => {
if (!props) {
return
}
renderer?.onExit?.(props)
},
2020-12-17 00:47:17 +08:00
}
},
state: {
// Initialize the plugin's internal state.
init() {
const state: {
active: boolean,
range: Range,
query: null | string
text: null | string
composing: boolean
decorationId?: string | null
} = {
2020-12-17 00:47:17 +08:00
active: false,
range: {
from: 0,
to: 0,
},
2020-12-17 00:47:17 +08:00
query: null,
text: null,
composing: false,
2020-12-17 00:47:17 +08:00
}
return state
2020-12-17 00:47:17 +08:00
},
// Apply changes to the plugin state from a view transaction.
apply(transaction, prev, oldState, state) {
const { isEditable } = editor
const { composing } = editor.view
2021-01-19 06:41:38 +08:00
const { selection } = transaction
const { empty, from } = selection
2020-12-17 00:47:17 +08:00
const next = { ...prev }
next.composing = composing
// We can only be suggesting if the view is editable, and:
// * there is no selection, or
// * a composition is active (see: https://github.com/ueberdosis/tiptap/issues/1449)
if (isEditable && (empty || editor.view.composing)) {
2020-12-17 00:47:17 +08:00
// Reset active state if we just left the previous suggestion range
if (
((from < prev.range.from) || from > prev.range.to)
&& !composing
&& !prev.composing
) {
2020-12-17 00:47:17 +08:00
next.active = false
}
// Try to match against where our cursor currently is
2021-01-15 21:49:28 +08:00
const match = findSuggestionMatch({
2021-01-15 16:25:50 +08:00
char,
allowSpaces,
allowedPrefixes,
2021-01-15 16:25:50 +08:00
startOfLine,
2021-01-15 16:55:15 +08:00
$position: selection.$from,
2021-01-15 16:25:50 +08:00
})
2021-01-15 21:49:28 +08:00
const decorationId = `id_${Math.floor(Math.random() * 0xFFFFFFFF)}`
2021-01-15 16:25:50 +08:00
2020-12-17 00:47:17 +08:00
// If we found a match, update the current state to show it
if (match && allow({ editor, state, range: match.range })) {
2020-12-17 00:47:17 +08:00
next.active = true
next.decorationId = prev.decorationId ? prev.decorationId : decorationId
next.range = match.range
next.query = match.query
next.text = match.text
} else {
next.active = false
}
} else {
next.active = false
}
// Make sure to empty the range if suggestion is inactive
if (!next.active) {
next.decorationId = null
next.range = { from: 0, to: 0 }
2020-12-17 00:47:17 +08:00
next.query = null
next.text = null
}
return next
},
},
props: {
// Call the keydown hook if suggestion is active.
handleKeyDown(view, event) {
const { active, range } = plugin.getState(view.state)
2020-12-17 00:47:17 +08:00
2021-01-15 21:49:28 +08:00
if (!active) {
return false
}
2020-12-17 00:47:17 +08:00
2021-01-19 06:41:38 +08:00
return renderer?.onKeyDown?.({ view, event, range }) || false
2020-12-17 00:47:17 +08:00
},
// Setup decorator on the currently active suggestion.
2021-01-15 21:49:28 +08:00
decorations(state) {
const { active, range, decorationId } = plugin.getState(state)
2020-12-17 00:47:17 +08:00
2021-01-15 21:49:28 +08:00
if (!active) {
return null
}
2020-12-17 00:47:17 +08:00
2021-01-15 21:49:28 +08:00
return DecorationSet.create(state.doc, [
2020-12-17 00:47:17 +08:00
Decoration.inline(range.from, range.to, {
nodeName: decorationTag,
class: decorationClass,
2020-12-17 00:47:17 +08:00
'data-decoration-id': decorationId,
}),
])
},
},
})
return plugin
2020-12-17 00:47:17 +08:00
}