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

ComposerPromptEditor.tsx

819 lines23.4 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 const isApplyingControlledUpdateRef = useRef(false);
633​
634 useEffect(() => {
635 onChangeRef.current = onChange;
636 }, [onChange]);
637​
638 useEffect(() => {
639 editor.setEditable(!disabled);
640 }, [disabled, editor]);
641​
642 useLayoutEffect(() => {
643 const normalizedCursor = clampCursor(value, cursor);
644 const previousSnapshot = snapshotRef.current;
645 if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
646 return;
647 }
648​
649 snapshotRef.current = { value, cursor: normalizedCursor };
650​
651 const rootElement = editor.getRootElement();
652 const isFocused = Boolean(rootElement && document.activeElement === rootElement);
653 if (previousSnapshot.value === value && !isFocused) {
654 return;
655 }
656​
657 isApplyingControlledUpdateRef.current = true;
658 editor.update(() => {
659 const valueChanged = previousSnapshot.value !== value;
660 if (previousSnapshot.value !== value) {
661 $setComposerEditorPrompt(value);
662 }
663 if (valueChanged || isFocused) {
664 $setSelectionAtComposerOffset(normalizedCursor);
665 }
666 });
667 queueMicrotask(() => {
668 isApplyingControlledUpdateRef.current = false;
669 });
670 }, [cursor, editor, value]);
671​
672 const focusAt = useCallback(
673 (nextCursor: number) => {
674 const rootElement = editor.getRootElement();
675 if (!rootElement) return;
676 const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
677 rootElement.focus();
678 editor.update(() => {
679 $setSelectionAtComposerOffset(boundedCursor);
680 });
681 snapshotRef.current = {
682 value: snapshotRef.current.value,
683 cursor: boundedCursor,
684 };
685 onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
686 },
687 [editor],
688 );
689​
690 const readSnapshot = useCallback((): { value: string; cursor: number } => {
691 let snapshot = snapshotRef.current;
692 editor.getEditorState().read(() => {
693 const nextValue = $getRoot().getTextContent();
694 const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
695 const nextCursor = clampCursor(
696 nextValue,
697 $readSelectionOffsetFromEditorState(fallbackCursor),
698 );
699 snapshot = {
700 value: nextValue,
701 cursor: nextCursor,
702 };
703 });
704 snapshotRef.current = snapshot;
705 return snapshot;
706 }, [editor]);
707​
708 useImperativeHandle(
709 editorRef,
710 () => ({
711 focus: () => {
712 focusAt(snapshotRef.current.cursor);
713 },
714 focusAt,
715 focusAtEnd: () => {
716 focusAt(snapshotRef.current.value.length);
717 },
718 readSnapshot,
719 }),
720 [focusAt, readSnapshot],
721 );
722​
723 const handleEditorChange = useCallback((editorState: EditorState) => {
724 editorState.read(() => {
725 const nextValue = $getRoot().getTextContent();
726 const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
727 const nextCursor = clampCursor(
728 nextValue,
729 $readSelectionOffsetFromEditorState(fallbackCursor),
730 );
731 const previousSnapshot = snapshotRef.current;
732 if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
733 return;
734 }
735 if (isApplyingControlledUpdateRef.current) {
736 return;
737 }
738 snapshotRef.current = {
739 value: nextValue,
740 cursor: nextCursor,
741 };
742 const cursorAdjacentToMention =
743 isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
744 isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
745 onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
746 });
747 }, []);
748​
749 return (
750 <div className="relative">
751 <PlainTextPlugin
752 contentEditable={
753 <ContentEditable
754 className={cn(
755 "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",
756 className,
757 )}
758 data-testid="composer-editor"
759 aria-placeholder={placeholder}
760 placeholder={<span />}
761 onPaste={onPaste}
762 />
763 }
764 placeholder={
765 <div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
766 {placeholder}
767 </div>
768 }
769 ErrorBoundary={LexicalErrorBoundary}
770 />
771 <OnChangePlugin onChange={handleEditorChange} />
772 <ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
773 <ComposerMentionArrowPlugin />
774 <ComposerMentionSelectionNormalizePlugin />
775 <ComposerMentionBackspacePlugin />
776 <HistoryPlugin />
777 </div>
778 );
780​
781export const ComposerPromptEditor = forwardRef<
782 ComposerPromptEditorHandle,
783 ComposerPromptEditorProps
784>(function ComposerPromptEditor(
785 { value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
786 ref,
787) {
788 const initialValueRef = useRef(value);
789 const initialConfig = useMemo<InitialConfigType>(
790 () => ({
791 namespace: "t3tools-composer-editor",
792 editable: true,
793 nodes: [ComposerMentionNode],
794 editorState: () => {
795 $setComposerEditorPrompt(initialValueRef.current);
796 },
797 onError: (error) => {
798 throw error;
799 },
800 }),
801 [],
802 );
803​
804 return (
805 <LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
806 <ComposerPromptEditorInner
807 value={value}
808 cursor={cursor}
809 disabled={disabled}
810 placeholder={placeholder}
811 onChange={onChange}
812 onPaste={onPaste}
813 editorRef={ref}
814 {...(onCommandKeyDown ? { onCommandKeyDown } : {})}
815 {...(className ? { className } : {})}
816 />
817 </LexicalComposer>
818 );
819});