index.tsx
Overview
This file defines a rich text editor component named PromptEditor built on top of the Lexical framework, a modern extensible text editor library by Facebook. The editor supports advanced text editing features including rich text nodes (headings, quotes, code blocks), variables insertion via a custom node (VariableNode), and custom plugins for variable picking, paste handling, and reacting to variable changes.
The PromptEditor component is highly customizable with props such as the initial value, change handlers, placeholder, toolbar visibility, and multi-line editing. It integrates UI elements such as tooltips and icons to enhance user interaction, and uses internationalization (react-i18next) for text strings.
This file is primarily responsible for:
Configuring Lexical editor with custom nodes and error handling.
Rendering the editor UI with a toolbar and content editable area.
Managing user interactions such as variable insertion and focus/blur state.
Plugging in custom Lexical plugins for variable management and paste handling.
Detailed Explanations
Imports and Dependencies
Lexical nodes and plugins:
HeadingNode,QuoteNode,CodeHighlightNode,CodeNode, and customVariableNode.Lexical React Components:
LexicalComposer,RichTextPlugin,ContentEditable,LexicalErrorBoundary.Custom Plugins:
VariablePickerMenuPlugin,PasteHandlerPlugin,VariableOnChangePlugin.UI Components: Tooltip components (
Tooltip,TooltipTrigger,TooltipContent), icon (Variablefrom lucide-react).Utility:
cnfor conditional classNames,useTranslationfor i18n.React hooks:
useState,useCallback.
Types
PromptContentPropstype PromptContentProps = { showToolbar?: boolean; multiLine?: boolean; };Props for the internal content editable component controlling toolbar visibility and line mode.
IPropstype IProps = { value?: string; onChange?: (value?: string) => void; placeholder?: ReactNode; } & PromptContentProps & Pick<VariablePickerMenuPluginProps, 'extraOptions'>;Props for the
PromptEditorcomponent including value, change handler, placeholder, and extra options for the variable picker plugin.
Functions and Components
1. onError(error: Error): void
Purpose: Centralized error handler for Lexical editor errors.
Parameters:
error- the error object caught during editor operations.Behavior: Logs the error to the console. Lexical will attempt to recover without user data loss if no error is thrown.
Usage: Passed to Lexical's config to handle runtime errors gracefully.
2. PromptContent
function PromptContent({
showToolbar = true,
multiLine = true,
}: PromptContentProps)
Purpose: Renders the editable content area and optional toolbar with variable insertion button.
Parameters:
showToolbar(boolean, defaulttrue): Whether to display the toolbar with the variable insertion button.multiLine(boolean, defaulttrue): Whether the content area supports multiple lines (affects styling).
State:
isBlur(boolean): Tracks if the editor is blurred (unfocused) to style border color.
Hooks Used:
useLexicalComposerContextto access the Lexical editor instance.useTranslationfor internationalized tooltip text.
Key Methods:
insertTextAtCursor: Inserts the string" /"at the current cursor position.handleVariableIconClick: Triggers the insertion of variable trigger text.handleBlurandhandleFocus: UpdateisBlurstate for styling.
Return: JSX containing a bordered section with optional toolbar and a
ContentEditablearea.
Usage Example:
<PromptContent showToolbar={false} multiLine={false} />
3. PromptEditor
export function PromptEditor({
value,
onChange,
placeholder,
showToolbar,
multiLine = true,
extraOptions,
}: IProps)
Purpose: Main exported editor component that wraps the LexicalComposer and integrates all plugins and UI.
Parameters:
value(optional string): Initial text content.onChange(optional callback): Callback invoked with updated text content.placeholder(optional ReactNode): Placeholder content shown when editor is empty.showToolbar(boolean): Whether to display the toolbar inPromptContent.multiLine(boolean, defaulttrue): Controls multi-line mode and styling.extraOptions(optional): Additional options passed to theVariablePickerMenuPlugin.
Implementation Details:
Defines an
initialConfigfor Lexical with namespace, theme, error handler, and nodes.Defines
onValueChangecallback to extract plain text content from editor state and invokeonChange.Uses
LexicalComposerto provide editor context.Renders
RichTextPluginwith:contentEditableset toPromptContent.placeholderwith conditional styling.LexicalErrorBoundaryfor error catching.
Injects custom plugins:
VariablePickerMenuPluginfor variable insertion UI.PasteHandlerPluginfor custom paste behavior.VariableOnChangePluginto monitor variable changes and triggeronValueChange.
Return: JSX containing the fully configured editor component.
Usage Example:
<PromptEditor
value="Hello world"
onChange={(val) => console.log(val)}
placeholder="Type your prompt..."
showToolbar={true}
multiLine={false}
/>
Important Implementation Details
Custom Nodes: The editor registers a set of Lexical nodes including standard rich text nodes and a custom
VariableNodethat presumably handles variable placeholders in the text.Variable Insertion: Clicking the variable icon inserts
" /"at the cursor, presumably triggering the variable picker menu (managed byVariablePickerMenuPlugin).Plugins:
VariablePickerMenuPlugin: Manages UI for picking variables to insert.PasteHandlerPlugin: Handles paste events, likely sanitizing or transforming pasted content.VariableOnChangePlugin: Monitors changes to variables and triggers external callbacks.
Error Handling: Uses
LexicalErrorBoundaryReact component and theonErrorfunction to catch and log errors without crashing.Styling: Uses
cnutility to conditionally apply Tailwind CSS classes for visual states like focus and multi-line support.Internationalization: Text strings like tooltips and placeholders use
useTranslationhook for localization.
Interaction With Other System Parts
UI Components: Utilizes tooltip components from
@/components/ui/tooltipto enhance the user interface.Custom Nodes and Plugins: Imports
VariableNode,VariablePickerMenuPlugin,PasteHandlerPlugin, andVariableOnChangePluginfrom local files, indicating tight integration with the variable insertion and management system.Theme: Applies a custom theme imported from
./themeto style the editor.Utilities: Uses utility functions like
cnfor className management.Internationalization: Depends on the i18n setup (
react-i18next) for dynamic text rendering.Iconography: Uses the
Variableicon fromlucide-reactfor UI affordance.
Mermaid Diagram
The following diagram shows the component structure and plugin relationships within this file:
componentDiagram
component PromptEditor {
+value?: string
+onChange?: (string) => void
+placeholder?: ReactNode
+showToolbar?: boolean
+multiLine?: boolean
+extraOptions?: any
--
+initialConfig: InitialConfigType
+onValueChange(editorState)
}
component PromptContent {
+showToolbar?: boolean
+multiLine?: boolean
--
+insertTextAtCursor()
+handleVariableIconClick()
+handleBlur()
+handleFocus()
}
component RichTextPlugin
component LexicalComposer
component VariablePickerMenuPlugin
component PasteHandlerPlugin
component VariableOnChangePlugin
component LexicalErrorBoundary
component ContentEditable
component Tooltip
PromptEditor --> LexicalComposer
LexicalComposer --> RichTextPlugin
RichTextPlugin --> PromptContent
PromptContent --> ContentEditable
PromptContent --> Tooltip
PromptEditor --> VariablePickerMenuPlugin
PromptEditor --> PasteHandlerPlugin
PromptEditor --> VariableOnChangePlugin
RichTextPlugin --> LexicalErrorBoundary
Summary
This file provides a rich text prompt editor (
PromptEditor) capable of handling variable placeholders and rich content.It extends Lexical editor with custom nodes and plugins to support domain-specific features.
The UI includes a toolbar with a variable insertion button and tooltips.
It supports single-line or multi-line editing modes with configurable placeholder text.
Error handling and i18n are integrated for robustness and localization.
The component is designed for integration into larger systems requiring advanced text editing with dynamic variables.
Additional Notes
To fully understand variable insertion and behavior, review the implementations of
VariableNode,VariablePickerMenuPlugin,PasteHandlerPlugin, andVariableOnChangePlugin.The
themeimported from./themecontrols visual styling and should be consistent with the application's design system.The editor is wrapped in a div with
relativepositioning, likely to support absolute positioning of dropdowns or tooltips.The insertion of
" /"text on variable icon click suggests a command or trigger convention for opening the variable picker.