Feat: Add VariablePickerMenuPlugin to select variables in the prompt text box by menu #4764 (#4765)

### What problem does this PR solve?

Feat: Add VariablePickerMenuPlugin to select variables in the prompt
text box by menu #4764

### Type of change


- [x] New Feature (non-breaking change which adds functionality)
This commit is contained in:
balibabu
2025-02-08 18:09:13 +08:00
committed by GitHub
parent f64ae9dc33
commit bfcc2abe47
19 changed files with 1058 additions and 126 deletions

View File

@ -0,0 +1,83 @@
import { CodeHighlightNode, CodeNode } from '@lexical/code';
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import {
InitialConfigType,
LexicalComposer,
} from '@lexical/react/LexicalComposer';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { HeadingNode, QuoteNode } from '@lexical/rich-text';
import {
$getRoot,
$nodesOfType,
EditorState,
Klass,
LexicalNode,
} from 'lexical';
import { useTranslation } from 'react-i18next';
import theme from './theme';
import { VariableNode } from './variable-node';
import VariablePickerMenuPlugin from './variable-picker-plugin';
// Catch any errors that occur during Lexical updates and log them
// or throw them as needed. If you don't throw them, Lexical will
// try to recover gracefully without losing user data.
function onError(error: Error) {
console.error(error);
}
const Nodes: Array<Klass<LexicalNode>> = [
HeadingNode,
QuoteNode,
CodeHighlightNode,
CodeNode,
VariableNode,
];
type IProps = {
value?: string;
onChange?: (value?: string) => void;
};
export function PromptEditor({ value, onChange }: IProps) {
const { t } = useTranslation();
const initialConfig: InitialConfigType = {
namespace: 'PromptEditor',
theme,
onError,
nodes: Nodes,
};
function onValueChange(editorState: EditorState) {
editorState?.read(() => {
const listNodes = $nodesOfType(VariableNode); // to be removed
// const allNodes = $dfs();
console.log('🚀 ~ onChange ~ allNodes:', listNodes);
const text = $getRoot().getTextContent();
onChange?.(text);
});
}
return (
<LexicalComposer initialConfig={initialConfig}>
<RichTextPlugin
contentEditable={
<ContentEditable className="min-h-40 relative px-2 py-1 border" />
}
placeholder={
<div className="absolute top-2 left-2">{t('common.pleaseInput')}</div>
}
ErrorBoundary={LexicalErrorBoundary}
/>
<HistoryPlugin />
<AutoFocusPlugin />
<VariablePickerMenuPlugin value={value}></VariablePickerMenuPlugin>
<OnChangePlugin onChange={onValueChange}></OnChangePlugin>
</LexicalComposer>
);
}