fix: prompt editor

This commit is contained in:
StyleZhang
2024-03-29 16:08:10 +08:00
parent d7be9c0afc
commit b50e897aa0
10 changed files with 77 additions and 15 deletions

View File

@ -68,3 +68,4 @@ WorkflowVariableBlock.displayName = 'WorkflowVariableBlock'
export { WorkflowVariableBlock }
export { WorkflowVariableBlockNode } from './node'
export { default as WorkflowVariableBlockReplacementBlock } from './workflow-variable-block-replacement-block'

View File

@ -0,0 +1,61 @@
import {
memo,
useCallback,
useEffect,
} from 'react'
import type { TextNode } from 'lexical'
import { $applyNodeReplacement } from 'lexical'
import { mergeRegister } from '@lexical/utils'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { decoratorTransform } from '../../utils'
import type { WorkflowVariableBlockType } from '../../types'
import { CustomTextNode } from '../custom-text/node'
import { $createWorkflowVariableBlockNode } from './node'
import { WorkflowVariableBlockNode } from './index'
const REGEX = /\{\{#(\d+|sys)(\.[a-zA-Z_][a-zA-Z0-9_]{0,29})+#\}\}/gi
const WorkflowVariableBlockReplacementBlock = ({
getWorkflowNode = () => undefined,
onInsert,
}: WorkflowVariableBlockType) => {
const [editor] = useLexicalComposerContext()
useEffect(() => {
if (!editor.hasNodes([WorkflowVariableBlockNode]))
throw new Error('WorkflowVariableBlockNodePlugin: WorkflowVariableBlockNode not registered on editor')
}, [editor])
const createWorkflowVariableBlockNode = useCallback((textNode: TextNode): WorkflowVariableBlockNode => {
if (onInsert)
onInsert()
const nodePathString = textNode.getTextContent().slice(3, -3)
return $applyNodeReplacement($createWorkflowVariableBlockNode(nodePathString.split('.'), getWorkflowNode))
}, [onInsert, getWorkflowNode])
const getMatch = useCallback((text: string) => {
const matchArr = REGEX.exec(text)
if (matchArr === null)
return null
console.log(matchArr, 'ma')
const startOffset = matchArr.index
const endOffset = startOffset + matchArr[0].length
return {
end: endOffset,
start: startOffset,
}
}, [])
useEffect(() => {
return mergeRegister(
editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getMatch, createWorkflowVariableBlockNode)),
)
}, [])
return null
}
export default memo(WorkflowVariableBlockReplacementBlock)