Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerPromptEditor.tsx

812 lines23.1 KB

1import { LexicalComposer, type InitialConfigType } from "@lexical/react/LexicalComposer";
2import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
3import { ContentEditable } from "@lexical/react/LexicalContentEditable";
4import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";
5import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";
6import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
7import { PlainTextPlugin } from "@lexical/react/LexicalPlainTextPlugin";
8import {
9 $applyNodeReplacement,
10 $createRangeSelection,
11 $getSelection,
12 $setSelection,
13 $isElementNode,
14 $isLineBreakNode,
15 $isRangeSelection,
16 $isTextNode,
17 $createLineBreakNode,
18 $createParagraphNode,
19 $createTextNode,
20 KEY_ARROW_DOWN_COMMAND,
21 KEY_ARROW_LEFT_COMMAND,
22 KEY_ARROW_RIGHT_COMMAND,
23 KEY_ARROW_UP_COMMAND,
24 KEY_ENTER_COMMAND,
25 KEY_TAB_COMMAND,
26 COMMAND_PRIORITY_HIGH,
27 KEY_BACKSPACE_COMMAND,
28 $getRoot,
29 type ElementNode,
30 type LexicalNode,
31 TextNode,
32 type EditorConfig,
33 type EditorState,
34 type NodeKey,
35 type SerializedTextNode,
36 type Spread,
37} from "lexical";
38import {
39 forwardRef,
40 useCallback,
41 useEffect,
42 useImperativeHandle,
43 useLayoutEffect,
44 useMemo,
45 useRef,
46 type ClipboardEventHandler,
47 type Ref,
48} from "react";
49​
50import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
51import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
52import { cn } from "~/lib/utils";
53import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
54​
55const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
56​
57type SerializedComposerMentionNode = Spread<
58 {
59 path: string;
60 type: "composer-mention";
61 version: 1;
62 },
63 SerializedTextNode
64>;
65​
66class ComposerMentionNode extends TextNode {
67 __path: string;
68​
69 static override getType(): string {
70 return "composer-mention";
71 }
72​
73 static override clone(node: ComposerMentionNode): ComposerMentionNode {
74 return new ComposerMentionNode(node.__path, node.__key);
75 }
76​
77 static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
78 return $createComposerMentionNode(serializedNode.path);
79 }
80​
81 constructor(path: string, key?: NodeKey) {
82 const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
83 super(`@${normalizedPath}`, key);
84 this.__path = normalizedPath;
85 }
86​
87 override exportJSON(): SerializedComposerMentionNode {
88 return {
89 ...super.exportJSON(),
90 path: this.__path,
91 type: "composer-mention",
92 version: 1,
93 };
94 }
95​
96 override createDOM(_config: EditorConfig): HTMLElement {
97 const dom = document.createElement("span");
98 dom.className =
99 "inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
100 dom.contentEditable = "false";
101 dom.setAttribute("spellcheck", "false");
102 renderMentionChipDom(dom, this.__path);
103 return dom;
104 }
105​
106 override updateDOM(
107 prevNode: ComposerMentionNode,
108 dom: HTMLElement,
109 _config: EditorConfig,
110 ): boolean {
111 dom.contentEditable = "false";
112 if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
113 renderMentionChipDom(dom, this.__path);
114 }
115 return false;
116 }
117​
118 override canInsertTextBefore(): false {
119 return false;
120 }
121​
122 override canInsertTextAfter(): false {
123 return false;
124 }
125​
126 override isTextEntity(): true {
127 return true;
128 }
129​
130 override isToken(): true {
131 return true;
132 }
134​
135function $createComposerMentionNode(path: string): ComposerMentionNode {
136 return $applyNodeReplacement(new ComposerMentionNode(path));
138​
139function inferMentionPathKind(pathValue: string): "file" | "directory" {
140 const base = basenameOfPath(pathValue);
141 if (base.startsWith(".") && !base.slice(1).includes(".")) {
142 return "directory";
143 }
144 if (base.includes(".")) {
145 return "file";
146 }
147 return "directory";
149​
150function resolvedThemeFromDocument(): "light" | "dark" {
151 return document.documentElement.classList.contains("dark") ? "dark" : "light";
153​
154function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
155 container.textContent = "";
156 container.style.setProperty("user-select", "none");
157 container.style.setProperty("-webkit-user-select", "none");
158​
159 const theme = resolvedThemeFromDocument();
160 const icon = document.createElement("img");
161 icon.alt = "";
162 icon.ariaHidden = "true";
163 icon.className = "size-3.5 shrink-0 opacity-85";
164 icon.loading = "lazy";
165 icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
166​
167 const label = document.createElement("span");
168 label.className = "truncate select-none leading-tight";
169 label.textContent = basenameOfPath(pathValue);
170​
171 container.append(icon, label);
173​
174function clampCursor(value: string, cursor: number): number {
175 if (!Number.isFinite(cursor)) return value.length;
176 return Math.max(0, Math.min(value.length, Math.floor(cursor)));
178​
179function getComposerNodeTextLength(node: LexicalNode): number {
180 if (node instanceof ComposerMentionNode) {
181 return 1;
182 }
183 if ($isTextNode(node)) {
184 return node.getTextContentSize();
185 }
186 if ($isLineBreakNode(node)) {
187 return 1;
188 }
189 if ($isElementNode(node)) {
190 return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
191 }
192 return 0;
194​
195function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
196 let offset = 0;
197 let current: LexicalNode | null = node;
198​
199 while (current) {
200 const nextParent = current.getParent() as LexicalNode | null;
201 if (!nextParent || !$isElementNode(nextParent)) {
202 break;
203 }
204 const siblings = nextParent.getChildren();
205 const index = current.getIndexWithinParent();
206 for (let i = 0; i < index; i += 1) {
207 const sibling = siblings[i];
208 if (!sibling) continue;
209 offset += getComposerNodeTextLength(sibling);
210 }
211 current = nextParent;
212 }
213​
214 if ($isTextNode(node)) {
215 if (node instanceof ComposerMentionNode) {
216 return offset + (pointOffset > 0 ? 1 : 0);
217 }
218 return offset + Math.min(pointOffset, node.getTextContentSize());
219 }
220​
221 if ($isLineBreakNode(node)) {
222 return offset + Math.min(pointOffset, 1);
223 }
224​
225 if ($isElementNode(node)) {
226 const children = node.getChildren();
227 const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
228 for (let i = 0; i < clampedOffset; i += 1) {
229 const child = children[i];
230 if (!child) continue;
231 offset += getComposerNodeTextLength(child);
232 }
233 return offset;
234 }
235​
236 return offset;
238​
239function findSelectionPointAtOffset(
240 node: LexicalNode,
241 remainingRef: { value: number },
242): { key: string; offset: number; type: "text" | "element" } | null {
243 if (node instanceof ComposerMentionNode) {
244 const parent = node.getParent();
245 if (!parent || !$isElementNode(parent)) return null;
246 const index = node.getIndexWithinParent();
247 if (remainingRef.value === 0) {
248 return {
249 key: parent.getKey(),
250 offset: index,
251 type: "element",
252 };
253 }
254 if (remainingRef.value === 1) {
255 return {
256 key: parent.getKey(),
257 offset: index + 1,
258 type: "element",
259 };
260 }
261 remainingRef.value -= 1;
262 return null;
263 }
264​
265 if ($isTextNode(node)) {
266 const size = node.getTextContentSize();
267 if (remainingRef.value <= size) {
268 return {
269 key: node.getKey(),
270 offset: remainingRef.value,
271 type: "text",
272 };
273 }
274 remainingRef.value -= size;
275 return null;
276 }
277​
278 if ($isLineBreakNode(node)) {
279 const parent = node.getParent();
280 if (!parent) return null;
281 const index = node.getIndexWithinParent();
282 if (remainingRef.value === 0) {
283 return {
284 key: parent.getKey(),
285 offset: index,
286 type: "element",
287 };
288 }
289 if (remainingRef.value === 1) {
290 return {
291 key: parent.getKey(),
292 offset: index + 1,
293 type: "element",
294 };
295 }
296 remainingRef.value -= 1;
297 return null;
298 }
299​
300 if ($isElementNode(node)) {
301 const children = node.getChildren();
302 for (const child of children) {
303 const point = findSelectionPointAtOffset(child, remainingRef);
304 if (point) {
305 return point;
306 }
307 }
308 if (remainingRef.value === 0) {
309 return {
310 key: node.getKey(),
311 offset: children.length,
312 type: "element",
313 };
314 }
315 }
316​
317 return null;
319​
320function $getComposerRootLength(): number {
321 const root = $getRoot();
322 const children = root.getChildren();
323 return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
325​
326function $setSelectionAtComposerOffset(nextOffset: number): void {
327 const root = $getRoot();
328 const composerLength = $getComposerRootLength();
329 const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
330 const remainingRef = { value: boundedOffset };
331 const point = findSelectionPointAtOffset(root, remainingRef) ?? {
332 key: root.getKey(),
333 offset: root.getChildren().length,
334 type: "element" as const,
335 };
336 const selection = $createRangeSelection();
337 selection.anchor.set(point.key, point.offset, point.type);
338 selection.focus.set(point.key, point.offset, point.type);
339 $setSelection(selection);
341​
342function $readSelectionOffsetFromEditorState(fallback: number): number {
343 const selection = $getSelection();
344 if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
345 return fallback;
346 }
347 const anchorNode = selection.anchor.getNode();
348 const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
349 const composerLength = $getComposerRootLength();
350 return Math.max(0, Math.min(offset, composerLength));
352​
353function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
354 const lines = text.split("\n");
355 for (let index = 0; index < lines.length; index += 1) {
356 const line = lines[index] ?? "";
357 if (line.length > 0) {
358 parent.append($createTextNode(line));
359 }
360 if (index < lines.length - 1) {
361 parent.append($createLineBreakNode());
362 }
363 }
365​
366function $setComposerEditorPrompt(prompt: string): void {
367 const root = $getRoot();
368 root.clear();
369 const paragraph = $createParagraphNode();
370 root.append(paragraph);
371​
372 const segments = splitPromptIntoComposerSegments(prompt);
373 for (const segment of segments) {
374 if (segment.type === "mention") {
375 paragraph.append($createComposerMentionNode(segment.path));
376 continue;
377 }
378 $appendTextWithLineBreaks(paragraph, segment.text);
379 }
381​
382export interface ComposerPromptEditorHandle {
383 focus: () => void;
384 focusAt: (cursor: number) => void;
385 focusAtEnd: () => void;
386 readSnapshot: () => { value: string; cursor: number };
388​
389interface ComposerPromptEditorProps {
390 value: string;
391 cursor: number;
392 disabled: boolean;
393 placeholder: string;
394 className?: string;
395 onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
396 onCommandKeyDown?: (
397 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
398 event: KeyboardEvent,
399 ) => boolean;
400 onPaste: ClipboardEventHandler<HTMLElement>;
402​
403interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
404 editorRef: Ref<ComposerPromptEditorHandle>;
406​
407function ComposerCommandKeyPlugin(props: {
408 onCommandKeyDown?: (
409 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
410 event: KeyboardEvent,
411 ) => boolean;
412}) {
413 const [editor] = useLexicalComposerContext();
414​
415 useEffect(() => {
416 const handleCommand = (
417 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
418 event: KeyboardEvent | null,
419 ): boolean => {
420 if (!props.onCommandKeyDown || !event) {
421 return false;
422 }
423 const handled = props.onCommandKeyDown(key, event);
424 if (handled) {
425 event.preventDefault();
426 event.stopPropagation();
427 }
428 return handled;
429 };
430​
431 const unregisterArrowDown = editor.registerCommand(
432 KEY_ARROW_DOWN_COMMAND,
433 (event) => handleCommand("ArrowDown", event),
434 COMMAND_PRIORITY_HIGH,
435 );
436 const unregisterArrowUp = editor.registerCommand(
437 KEY_ARROW_UP_COMMAND,
438 (event) => handleCommand("ArrowUp", event),
439 COMMAND_PRIORITY_HIGH,
440 );
441 const unregisterEnter = editor.registerCommand(
442 KEY_ENTER_COMMAND,
443 (event) => handleCommand("Enter", event),
444 COMMAND_PRIORITY_HIGH,
445 );
446 const unregisterTab = editor.registerCommand(
447 KEY_TAB_COMMAND,
448 (event) => handleCommand("Tab", event),
449 COMMAND_PRIORITY_HIGH,
450 );
451​
452 return () => {
453 unregisterArrowDown();
454 unregisterArrowUp();
455 unregisterEnter();
456 unregisterTab();
457 };
458 }, [editor, props]);
459​
460 return null;
462​
463function ComposerMentionArrowPlugin() {
464 const [editor] = useLexicalComposerContext();
465​
466 useEffect(() => {
467 const unregisterLeft = editor.registerCommand(
468 KEY_ARROW_LEFT_COMMAND,
469 (event) => {
470 let nextOffset: number | null = null;
471 editor.getEditorState().read(() => {
472 const selection = $getSelection();
473 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
474 const currentOffset = $readSelectionOffsetFromEditorState(0);
475 if (currentOffset <= 0) return;
476 const promptValue = $getRoot().getTextContent();
477 if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
478 return;
479 }
480 nextOffset = currentOffset - 1;
481 });
482 if (nextOffset === null) return false;
483 const selectionOffset = nextOffset;
484 event?.preventDefault();
485 event?.stopPropagation();
486 editor.update(() => {
487 $setSelectionAtComposerOffset(selectionOffset);
488 });
489 return true;
490 },
491 COMMAND_PRIORITY_HIGH,
492 );
493 const unregisterRight = editor.registerCommand(
494 KEY_ARROW_RIGHT_COMMAND,
495 (event) => {
496 let nextOffset: number | null = null;
497 editor.getEditorState().read(() => {
498 const selection = $getSelection();
499 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
500 const currentOffset = $readSelectionOffsetFromEditorState(0);
501 const composerLength = $getComposerRootLength();
502 if (currentOffset >= composerLength) return;
503 const promptValue = $getRoot().getTextContent();
504 if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
505 return;
506 }
507 nextOffset = currentOffset + 1;
508 });
509 if (nextOffset === null) return false;
510 const selectionOffset = nextOffset;
511 event?.preventDefault();
512 event?.stopPropagation();
513 editor.update(() => {
514 $setSelectionAtComposerOffset(selectionOffset);
515 });
516 return true;
517 },
518 COMMAND_PRIORITY_HIGH,
519 );
520 return () => {
521 unregisterLeft();
522 unregisterRight();
523 };
524 }, [editor]);
525​
526 return null;
528​
529function ComposerMentionSelectionNormalizePlugin() {
530 const [editor] = useLexicalComposerContext();
531​
532 useEffect(() => {
533 return editor.registerUpdateListener(({ editorState }) => {
534 let afterOffset: number | null = null;
535 editorState.read(() => {
536 const selection = $getSelection();
537 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
538 const anchorNode = selection.anchor.getNode();
539 if (!(anchorNode instanceof ComposerMentionNode)) return;
540 if (selection.anchor.offset === 0) return;
541 const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
542 afterOffset = beforeOffset + 1;
543 });
544 if (afterOffset !== null) {
545 queueMicrotask(() => {
546 editor.update(() => {
547 $setSelectionAtComposerOffset(afterOffset!);
548 });
549 });
550 }
551 });
552 }, [editor]);
553​
554 return null;
556​
557function ComposerMentionBackspacePlugin() {
558 const [editor] = useLexicalComposerContext();
559​
560 useEffect(() => {
561 return editor.registerCommand(
562 KEY_BACKSPACE_COMMAND,
563 (event) => {
564 const selection = $getSelection();
565 if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
566 return false;
567 }
568​
569 const anchorNode = selection.anchor.getNode();
570 const removeMentionNode = (candidate: unknown): boolean => {
571 if (!(candidate instanceof ComposerMentionNode)) {
572 return false;
573 }
574 const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
575 candidate.remove();
576 $setSelectionAtComposerOffset(mentionStart);
577 event?.preventDefault();
578 return true;
579 };
580​
581 if (removeMentionNode(anchorNode)) {
582 return true;
583 }
584​
585 if ($isTextNode(anchorNode)) {
586 if (selection.anchor.offset > 0) {
587 return false;
588 }
589 if (removeMentionNode(anchorNode.getPreviousSibling())) {
590 return true;
591 }
592 const parent = anchorNode.getParent();
593 if ($isElementNode(parent)) {
594 const index = anchorNode.getIndexWithinParent();
595 if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
596 return true;
597 }
598 }
599 return false;
600 }
601​
602 if ($isElementNode(anchorNode)) {
603 const childIndex = selection.anchor.offset - 1;
604 if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
605 return true;
606 }
607 }
608​
609 return false;
610 },
611 COMMAND_PRIORITY_HIGH,
612 );
613 }, [editor]);
614​
615 return null;
617​
618function ComposerPromptEditorInner({
619 value,
620 cursor,
621 disabled,
622 placeholder,
623 className,
624 onChange,
625 onCommandKeyDown,
626 onPaste,
627 editorRef,
628}: ComposerPromptEditorInnerProps) {
629 const [editor] = useLexicalComposerContext();
630 const onChangeRef = useRef(onChange);
631 const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
632​
633 useEffect(() => {
634 onChangeRef.current = onChange;
635 }, [onChange]);
636​
637 useEffect(() => {
638 editor.setEditable(!disabled);
639 }, [disabled, editor]);
640​
641 useLayoutEffect(() => {
642 const normalizedCursor = clampCursor(value, cursor);
643 const previousSnapshot = snapshotRef.current;
644 if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
645 return;
646 }
647​
648 if (previousSnapshot.value !== value) {
649 editor.update(() => {
650 $setComposerEditorPrompt(value);
651 });
652 }
653​
654 snapshotRef.current = { value, cursor: normalizedCursor };
655​
656 const rootElement = editor.getRootElement();
657 if (!rootElement || document.activeElement !== rootElement) {
658 return;
659 }
660​
661 editor.update(() => {
662 $setSelectionAtComposerOffset(normalizedCursor);
663 });
664 }, [cursor, editor, value]);
665​
666 const focusAt = useCallback(
667 (nextCursor: number) => {
668 const rootElement = editor.getRootElement();
669 if (!rootElement) return;
670 const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
671 rootElement.focus();
672 editor.update(() => {
673 $setSelectionAtComposerOffset(boundedCursor);
674 });
675 snapshotRef.current = {
676 value: snapshotRef.current.value,
677 cursor: boundedCursor,
678 };
679 onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
680 },
681 [editor],
682 );
683​
684 const readSnapshot = useCallback((): { value: string; cursor: number } => {
685 let snapshot = snapshotRef.current;
686 editor.getEditorState().read(() => {
687 const nextValue = $getRoot().getTextContent();
688 const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
689 const nextCursor = clampCursor(
690 nextValue,
691 $readSelectionOffsetFromEditorState(fallbackCursor),
692 );
693 snapshot = {
694 value: nextValue,
695 cursor: nextCursor,
696 };
697 });
698 snapshotRef.current = snapshot;
699 return snapshot;
700 }, [editor]);
701​
702 useImperativeHandle(
703 editorRef,
704 () => ({
705 focus: () => {
706 focusAt(snapshotRef.current.cursor);
707 },
708 focusAt: (nextCursor: number) => {
709 focusAt(nextCursor);
710 },
711 focusAtEnd: () => {
712 focusAt(snapshotRef.current.value.length);
713 },
714 readSnapshot,
715 }),
716 [focusAt, readSnapshot],
717 );
718​
719 const handleEditorChange = useCallback((editorState: EditorState) => {
720 editorState.read(() => {
721 const nextValue = $getRoot().getTextContent();
722 const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
723 const nextCursor = clampCursor(
724 nextValue,
725 $readSelectionOffsetFromEditorState(fallbackCursor),
726 );
727 const previousSnapshot = snapshotRef.current;
728 if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
729 return;
730 }
731 snapshotRef.current = {
732 value: nextValue,
733 cursor: nextCursor,
734 };
735 const cursorAdjacentToMention =
736 isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
737 isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
738 onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
739 });
740 }, []);
741​
742 return (
743 <div className="relative">
744 <PlainTextPlugin
745 contentEditable={
746 <ContentEditable
747 className={cn(
748 "block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
749 className,
750 )}
751 data-testid="composer-editor"
752 aria-placeholder={placeholder}
753 placeholder={<span />}
754 onPaste={onPaste}
755 />
756 }
757 placeholder={
758 <div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
759 {placeholder}
760 </div>
761 }
762 ErrorBoundary={LexicalErrorBoundary}
763 />
764 <OnChangePlugin onChange={handleEditorChange} />
765 <ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
766 <ComposerMentionArrowPlugin />
767 <ComposerMentionSelectionNormalizePlugin />
768 <ComposerMentionBackspacePlugin />
769 <HistoryPlugin />
770 </div>
771 );
773​
774export const ComposerPromptEditor = forwardRef<
775 ComposerPromptEditorHandle,
776 ComposerPromptEditorProps
777>(function ComposerPromptEditor(
778 { value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
779 ref,
780) {
781 const initialValueRef = useRef(value);
782 const initialConfig = useMemo<InitialConfigType>(
783 () => ({
784 namespace: "t3tools-composer-editor",
785 editable: true,
786 nodes: [ComposerMentionNode],
787 editorState: () => {
788 $setComposerEditorPrompt(initialValueRef.current);
789 },
790 onError: (error) => {
791 throw error;
792 },
793 }),
794 [],
795 );
796​
797 return (
798 <LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
799 <ComposerPromptEditorInner
800 value={value}
801 cursor={cursor}
802 disabled={disabled}
803 placeholder={placeholder}
804 onChange={onChange}
805 onPaste={onPaste}
806 editorRef={ref}
807 {...(onCommandKeyDown ? { onCommandKeyDown } : {})}
808 {...(className ? { className } : {})}
809 />
810 </LexicalComposer>
811 );
812});