Open History to see the last commit
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 DecoratorNode,
30 type ElementNode,
31 type LexicalNode,
32 type SerializedLexicalNode,
33 TextNode,
34 type EditorConfig,
35 type EditorState,
36 type NodeKey,
37 type SerializedTextNode,
38 type Spread,
39} from "lexical";
40import {
41 createContext,
42 forwardRef,
43 useCallback,
44 useContext,
45 useEffect,
46 useImperativeHandle,
47 useLayoutEffect,
48 useMemo,
49 useRef,
50 type ClipboardEventHandler,
51 type ReactElement,
52 type Ref,
53} from "react";
54
55import {
56 clampCollapsedComposerCursor,
57 collapseExpandedComposerCursor,
58 expandCollapsedComposerCursor,
59 isCollapsedCursorAdjacentToInlineToken,
60} from "~/composer-logic";
61import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
62import {
63 INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
64 type TerminalContextDraft,
65} from "~/lib/terminalContext";
66import { cn } from "~/lib/utils";
67import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
68import {
69 COMPOSER_INLINE_CHIP_CLASS_NAME,
70 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
71 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
72} from "./composerInlineChip";
73import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
74
75const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
76
77type SerializedComposerMentionNode = Spread<
78 {
79 path: string;
80 type: "composer-mention";
81 version: 1;
82 },
83 SerializedTextNode
84>;
85
86type SerializedComposerTerminalContextNode = Spread<
87 {
88 context: TerminalContextDraft;
89 type: "composer-terminal-context";
90 version: 1;
91 },
92 SerializedLexicalNode
93>;
94
95const ComposerTerminalContextActionsContext = createContext<{
96 onRemoveTerminalContext: (contextId: string) => void;
97}>({
98 onRemoveTerminalContext: () => {},
99});
100
101class ComposerMentionNode extends TextNode {
102 __path: string;
103
104 static override getType(): string {
105 return "composer-mention";
106 }
107
108 static override clone(node: ComposerMentionNode): ComposerMentionNode {
109 return new ComposerMentionNode(node.__path, node.__key);
110 }
111
112 static override importJSON(serializedNode: SerializedComposerMentionNode): ComposerMentionNode {
113 return $createComposerMentionNode(serializedNode.path);
114 }
115
116 constructor(path: string, key?: NodeKey) {
117 const normalizedPath = path.startsWith("@") ? path.slice(1) : path;
118 super(`@${normalizedPath}`, key);
119 this.__path = normalizedPath;
120 }
121
122 override exportJSON(): SerializedComposerMentionNode {
123 return {
124 ...super.exportJSON(),
125 path: this.__path,
126 type: "composer-mention",
127 version: 1,
128 };
129 }
130
131 override createDOM(_config: EditorConfig): HTMLElement {
132 const dom = document.createElement("span");
133 dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
134 dom.contentEditable = "false";
135 dom.setAttribute("spellcheck", "false");
136 renderMentionChipDom(dom, this.__path);
137 return dom;
138 }
139
140 override updateDOM(
141 prevNode: ComposerMentionNode,
142 dom: HTMLElement,
143 _config: EditorConfig,
144 ): boolean {
145 dom.contentEditable = "false";
146 if (prevNode.__text !== this.__text || prevNode.__path !== this.__path) {
147 renderMentionChipDom(dom, this.__path);
148 }
149 return false;
150 }
151
152 override canInsertTextBefore(): false {
153 return false;
154 }
155
156 override canInsertTextAfter(): false {
157 return false;
158 }
159
160 override isTextEntity(): true {
161 return true;
162 }
163
164 override isToken(): true {
165 return true;
166 }
167}
168
169function $createComposerMentionNode(path: string): ComposerMentionNode {
170 return $applyNodeReplacement(new ComposerMentionNode(path));
171}
172
173function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
174 return <ComposerPendingTerminalContextChip context={props.context} />;
175}
176
177class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
178 __context: TerminalContextDraft;
179
180 static override getType(): string {
181 return "composer-terminal-context";
182 }
183
184 static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
185 return new ComposerTerminalContextNode(node.__context, node.__key);
186 }
187
188 static override importJSON(
189 serializedNode: SerializedComposerTerminalContextNode,
190 ): ComposerTerminalContextNode {
191 return $createComposerTerminalContextNode(serializedNode.context);
192 }
193
194 constructor(context: TerminalContextDraft, key?: NodeKey) {
195 super(key);
196 this.__context = context;
197 }
198
199 override exportJSON(): SerializedComposerTerminalContextNode {
200 return {
201 ...super.exportJSON(),
202 context: this.__context,
203 type: "composer-terminal-context",
204 version: 1,
205 };
206 }
207
208 override createDOM(): HTMLElement {
209 const dom = document.createElement("span");
210 dom.className = "inline-flex align-middle leading-none";
211 return dom;
212 }
213
214 override updateDOM(): false {
215 return false;
216 }
217
218 override getTextContent(): string {
219 return INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
220 }
221
222 override isInline(): true {
223 return true;
224 }
225
226 override decorate(): ReactElement {
227 return <ComposerTerminalContextDecorator context={this.__context} />;
228 }
229}
230
231function $createComposerTerminalContextNode(
232 context: TerminalContextDraft,
233): ComposerTerminalContextNode {
234 return $applyNodeReplacement(new ComposerTerminalContextNode(context));
235}
236
237type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
238
239function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
240 return (
241 candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
242 );
243}
244
245function resolvedThemeFromDocument(): "light" | "dark" {
246 return document.documentElement.classList.contains("dark") ? "dark" : "light";
247}
248
249function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
250 container.textContent = "";
251 container.style.setProperty("user-select", "none");
252 container.style.setProperty("-webkit-user-select", "none");
253
254 const theme = resolvedThemeFromDocument();
255 const icon = document.createElement("img");
256 icon.alt = "";
257 icon.ariaHidden = "true";
258 icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
259 icon.loading = "lazy";
260 icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
261
262 const label = document.createElement("span");
263 label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
264 label.textContent = basenameOfPath(pathValue);
265
266 container.append(icon, label);
267}
268
269function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
270 return contexts
271 .map((context) =>
272 [
273 context.id,
274 context.threadId,
275 context.terminalId,
276 context.terminalLabel,
277 context.lineStart,
278 context.lineEnd,
279 context.createdAt,
280 context.text,
281 ].join("\u001f"),
282 )
283 .join("\u001e");
284}
285
286function clampExpandedCursor(value: string, cursor: number): number {
287 if (!Number.isFinite(cursor)) return value.length;
288 return Math.max(0, Math.min(value.length, Math.floor(cursor)));
289}
290
291function getComposerInlineTokenTextLength(_node: ComposerInlineTokenNode): 1 {
292 return 1;
293}
294
295function getComposerInlineTokenExpandedTextLength(node: ComposerInlineTokenNode): number {
296 return node.getTextContentSize();
297}
298
299function getAbsoluteOffsetForInlineTokenPoint(
300 node: ComposerInlineTokenNode,
301 absoluteOffset: number,
302 pointOffset: number,
303): number {
304 return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenTextLength(node) : 0);
305}
306
307function getExpandedAbsoluteOffsetForInlineTokenPoint(
308 node: ComposerInlineTokenNode,
309 absoluteOffset: number,
310 pointOffset: number,
311): number {
312 return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenExpandedTextLength(node) : 0);
313}
314
315function findSelectionPointForInlineToken(
316 node: ComposerInlineTokenNode,
317 remainingRef: { value: number },
318): { key: string; offset: number; type: "element" } | null {
319 const parent = node.getParent();
320 if (!parent || !$isElementNode(parent)) return null;
321 const index = node.getIndexWithinParent();
322 if (remainingRef.value === 0) {
323 return {
324 key: parent.getKey(),
325 offset: index,
326 type: "element",
327 };
328 }
329 if (remainingRef.value === getComposerInlineTokenTextLength(node)) {
330 return {
331 key: parent.getKey(),
332 offset: index + 1,
333 type: "element",
334 };
335 }
336 remainingRef.value -= getComposerInlineTokenTextLength(node);
337 return null;
338}
339
340function getComposerNodeTextLength(node: LexicalNode): number {
341 if (isComposerInlineTokenNode(node)) {
342 return getComposerInlineTokenTextLength(node);
343 }
344 if ($isTextNode(node)) {
345 return node.getTextContentSize();
346 }
347 if ($isLineBreakNode(node)) {
348 return 1;
349 }
350 if ($isElementNode(node)) {
351 return node.getChildren().reduce((total, child) => total + getComposerNodeTextLength(child), 0);
352 }
353 return 0;
354}
355
356function getComposerNodeExpandedTextLength(node: LexicalNode): number {
357 if (isComposerInlineTokenNode(node)) {
358 return getComposerInlineTokenExpandedTextLength(node);
359 }
360 if ($isTextNode(node)) {
361 return node.getTextContentSize();
362 }
363 if ($isLineBreakNode(node)) {
364 return 1;
365 }
366 if ($isElementNode(node)) {
367 return node
368 .getChildren()
369 .reduce((total, child) => total + getComposerNodeExpandedTextLength(child), 0);
370 }
371 return 0;
372}
373
374function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
375 let offset = 0;
376 let current: LexicalNode | null = node;
377
378 while (current) {
379 const nextParent = current.getParent() as LexicalNode | null;
380 if (!nextParent || !$isElementNode(nextParent)) {
381 break;
382 }
383 const siblings = nextParent.getChildren();
384 const index = current.getIndexWithinParent();
385 for (let i = 0; i < index; i += 1) {
386 const sibling = siblings[i];
387 if (!sibling) continue;
388 offset += getComposerNodeTextLength(sibling);
389 }
390 current = nextParent;
391 }
392
393 if ($isTextNode(node)) {
394 if (node instanceof ComposerMentionNode) {
395 return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
396 }
397 return offset + Math.min(pointOffset, node.getTextContentSize());
398 }
399 if (node instanceof ComposerTerminalContextNode) {
400 return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
401 }
402
403 if ($isLineBreakNode(node)) {
404 return offset + Math.min(pointOffset, 1);
405 }
406
407 if ($isElementNode(node)) {
408 const children = node.getChildren();
409 const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
410 for (let i = 0; i < clampedOffset; i += 1) {
411 const child = children[i];
412 if (!child) continue;
413 offset += getComposerNodeTextLength(child);
414 }
415 return offset;
416 }
417
418 return offset;
419}
420
421function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
422 let offset = 0;
423 let current: LexicalNode | null = node;
424
425 while (current) {
426 const nextParent = current.getParent() as LexicalNode | null;
427 if (!nextParent || !$isElementNode(nextParent)) {
428 break;
429 }
430 const siblings = nextParent.getChildren();
431 const index = current.getIndexWithinParent();
432 for (let i = 0; i < index; i += 1) {
433 const sibling = siblings[i];
434 if (!sibling) continue;
435 offset += getComposerNodeExpandedTextLength(sibling);
436 }
437 current = nextParent;
438 }
439
440 if ($isTextNode(node)) {
441 if (node instanceof ComposerMentionNode) {
442 return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
443 }
444 return offset + Math.min(pointOffset, node.getTextContentSize());
445 }
446 if (node instanceof ComposerTerminalContextNode) {
447 return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
448 }
449
450 if ($isLineBreakNode(node)) {
451 return offset + Math.min(pointOffset, 1);
452 }
453
454 if ($isElementNode(node)) {
455 const children = node.getChildren();
456 const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
457 for (let i = 0; i < clampedOffset; i += 1) {
458 const child = children[i];
459 if (!child) continue;
460 offset += getComposerNodeExpandedTextLength(child);
461 }
462 return offset;
463 }
464
465 return offset;
466}
467
468function findSelectionPointAtOffset(
469 node: LexicalNode,
470 remainingRef: { value: number },
471): { key: string; offset: number; type: "text" | "element" } | null {
472 if (node instanceof ComposerMentionNode) {
473 return findSelectionPointForInlineToken(node, remainingRef);
474 }
475 if (node instanceof ComposerTerminalContextNode) {
476 return findSelectionPointForInlineToken(node, remainingRef);
477 }
478
479 if ($isTextNode(node)) {
480 const size = node.getTextContentSize();
481 if (remainingRef.value <= size) {
482 return {
483 key: node.getKey(),
484 offset: remainingRef.value,
485 type: "text",
486 };
487 }
488 remainingRef.value -= size;
489 return null;
490 }
491
492 if ($isLineBreakNode(node)) {
493 const parent = node.getParent();
494 if (!parent) return null;
495 const index = node.getIndexWithinParent();
496 if (remainingRef.value === 0) {
497 return {
498 key: parent.getKey(),
499 offset: index,
500 type: "element",
501 };
502 }
503 if (remainingRef.value === 1) {
504 return {
505 key: parent.getKey(),
506 offset: index + 1,
507 type: "element",
508 };
509 }
510 remainingRef.value -= 1;
511 return null;
512 }
513
514 if ($isElementNode(node)) {
515 const children = node.getChildren();
516 for (const child of children) {
517 const point = findSelectionPointAtOffset(child, remainingRef);
518 if (point) {
519 return point;
520 }
521 }
522 if (remainingRef.value === 0) {
523 return {
524 key: node.getKey(),
525 offset: children.length,
526 type: "element",
527 };
528 }
529 }
530
531 return null;
532}
533
534function $getComposerRootLength(): number {
535 const root = $getRoot();
536 const children = root.getChildren();
537 return children.reduce((sum, child) => sum + getComposerNodeTextLength(child), 0);
538}
539
540function $setSelectionAtComposerOffset(nextOffset: number): void {
541 const root = $getRoot();
542 const composerLength = $getComposerRootLength();
543 const boundedOffset = Math.max(0, Math.min(nextOffset, composerLength));
544 const remainingRef = { value: boundedOffset };
545 const point = findSelectionPointAtOffset(root, remainingRef) ?? {
546 key: root.getKey(),
547 offset: root.getChildren().length,
548 type: "element" as const,
549 };
550 const selection = $createRangeSelection();
551 selection.anchor.set(point.key, point.offset, point.type);
552 selection.focus.set(point.key, point.offset, point.type);
553 $setSelection(selection);
554}
555
556function $readSelectionOffsetFromEditorState(fallback: number): number {
557 const selection = $getSelection();
558 if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
559 return fallback;
560 }
561 const anchorNode = selection.anchor.getNode();
562 const offset = getAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
563 const composerLength = $getComposerRootLength();
564 return Math.max(0, Math.min(offset, composerLength));
565}
566
567function $readExpandedSelectionOffsetFromEditorState(fallback: number): number {
568 const selection = $getSelection();
569 if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
570 return fallback;
571 }
572 const anchorNode = selection.anchor.getNode();
573 const offset = getExpandedAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
574 const expandedLength = $getRoot().getTextContent().length;
575 return Math.max(0, Math.min(offset, expandedLength));
576}
577
578function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
579 const lines = text.split("\n");
580 for (let index = 0; index < lines.length; index += 1) {
581 const line = lines[index] ?? "";
582 if (line.length > 0) {
583 parent.append($createTextNode(line));
584 }
585 if (index < lines.length - 1) {
586 parent.append($createLineBreakNode());
587 }
588 }
589}
590
591function $setComposerEditorPrompt(
592 prompt: string,
593 terminalContexts: ReadonlyArray<TerminalContextDraft>,
594): void {
595 const root = $getRoot();
596 root.clear();
597 const paragraph = $createParagraphNode();
598 root.append(paragraph);
599
600 const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
601 for (const segment of segments) {
602 if (segment.type === "mention") {
603 paragraph.append($createComposerMentionNode(segment.path));
604 continue;
605 }
606 if (segment.type === "terminal-context") {
607 if (segment.context) {
608 paragraph.append($createComposerTerminalContextNode(segment.context));
609 }
610 continue;
611 }
612 $appendTextWithLineBreaks(paragraph, segment.text);
613 }
614}
615
616function collectTerminalContextIds(node: LexicalNode): string[] {
617 if (node instanceof ComposerTerminalContextNode) {
618 return [node.__context.id];
619 }
620 if ($isElementNode(node)) {
621 return node.getChildren().flatMap((child) => collectTerminalContextIds(child));
622 }
623 return [];
624}
625
626export interface ComposerPromptEditorHandle {
627 focus: () => void;
628 focusAt: (cursor: number) => void;
629 focusAtEnd: () => void;
630 readSnapshot: () => {
631 value: string;
632 cursor: number;
633 expandedCursor: number;
634 terminalContextIds: string[];
635 };
636}
637
638interface ComposerPromptEditorProps {
639 value: string;
640 cursor: number;
641 terminalContexts: ReadonlyArray<TerminalContextDraft>;
642 disabled: boolean;
643 placeholder: string;
644 className?: string;
645 onRemoveTerminalContext: (contextId: string) => void;
646 onChange: (
647 nextValue: string,
648 nextCursor: number,
649 expandedCursor: number,
650 cursorAdjacentToMention: boolean,
651 terminalContextIds: string[],
652 ) => void;
653 onCommandKeyDown?: (
654 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
655 event: KeyboardEvent,
656 ) => boolean;
657 onPaste: ClipboardEventHandler<HTMLElement>;
658}
659
660interface ComposerPromptEditorInnerProps extends ComposerPromptEditorProps {
661 editorRef: Ref<ComposerPromptEditorHandle>;
662}
663
664function ComposerCommandKeyPlugin(props: {
665 onCommandKeyDown?: (
666 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
667 event: KeyboardEvent,
668 ) => boolean;
669}) {
670 const [editor] = useLexicalComposerContext();
671
672 useEffect(() => {
673 const handleCommand = (
674 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
675 event: KeyboardEvent | null,
676 ): boolean => {
677 if (!props.onCommandKeyDown || !event) {
678 return false;
679 }
680 const handled = props.onCommandKeyDown(key, event);
681 if (handled) {
682 event.preventDefault();
683 event.stopPropagation();
684 }
685 return handled;
686 };
687
688 const unregisterArrowDown = editor.registerCommand(
689 KEY_ARROW_DOWN_COMMAND,
690 (event) => handleCommand("ArrowDown", event),
691 COMMAND_PRIORITY_HIGH,
692 );
693 const unregisterArrowUp = editor.registerCommand(
694 KEY_ARROW_UP_COMMAND,
695 (event) => handleCommand("ArrowUp", event),
696 COMMAND_PRIORITY_HIGH,
697 );
698 const unregisterEnter = editor.registerCommand(
699 KEY_ENTER_COMMAND,
700 (event) => handleCommand("Enter", event),
701 COMMAND_PRIORITY_HIGH,
702 );
703 const unregisterTab = editor.registerCommand(
704 KEY_TAB_COMMAND,
705 (event) => handleCommand("Tab", event),
706 COMMAND_PRIORITY_HIGH,
707 );
708
709 return () => {
710 unregisterArrowDown();
711 unregisterArrowUp();
712 unregisterEnter();
713 unregisterTab();
714 };
715 }, [editor, props]);
716
717 return null;
718}
719
720function ComposerInlineTokenArrowPlugin() {
721 const [editor] = useLexicalComposerContext();
722
723 useEffect(() => {
724 const unregisterLeft = editor.registerCommand(
725 KEY_ARROW_LEFT_COMMAND,
726 (event) => {
727 let nextOffset: number | null = null;
728 editor.getEditorState().read(() => {
729 const selection = $getSelection();
730 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
731 const currentOffset = $readSelectionOffsetFromEditorState(0);
732 if (currentOffset <= 0) return;
733 const promptValue = $getRoot().getTextContent();
734 if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
735 return;
736 }
737 nextOffset = currentOffset - 1;
738 });
739 if (nextOffset === null) return false;
740 const selectionOffset = nextOffset;
741 event?.preventDefault();
742 event?.stopPropagation();
743 editor.update(() => {
744 $setSelectionAtComposerOffset(selectionOffset);
745 });
746 return true;
747 },
748 COMMAND_PRIORITY_HIGH,
749 );
750 const unregisterRight = editor.registerCommand(
751 KEY_ARROW_RIGHT_COMMAND,
752 (event) => {
753 let nextOffset: number | null = null;
754 editor.getEditorState().read(() => {
755 const selection = $getSelection();
756 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
757 const currentOffset = $readSelectionOffsetFromEditorState(0);
758 const composerLength = $getComposerRootLength();
759 if (currentOffset >= composerLength) return;
760 const promptValue = $getRoot().getTextContent();
761 if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
762 return;
763 }
764 nextOffset = currentOffset + 1;
765 });
766 if (nextOffset === null) return false;
767 const selectionOffset = nextOffset;
768 event?.preventDefault();
769 event?.stopPropagation();
770 editor.update(() => {
771 $setSelectionAtComposerOffset(selectionOffset);
772 });
773 return true;
774 },
775 COMMAND_PRIORITY_HIGH,
776 );
777 return () => {
778 unregisterLeft();
779 unregisterRight();
780 };
781 }, [editor]);
782
783 return null;
784}
785
786function ComposerInlineTokenSelectionNormalizePlugin() {
787 const [editor] = useLexicalComposerContext();
788
789 useEffect(() => {
790 return editor.registerUpdateListener(({ editorState }) => {
791 let afterOffset: number | null = null;
792 editorState.read(() => {
793 const selection = $getSelection();
794 if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
795 const anchorNode = selection.anchor.getNode();
796 if (!isComposerInlineTokenNode(anchorNode)) return;
797 if (selection.anchor.offset === 0) return;
798 const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
799 afterOffset = beforeOffset + 1;
800 });
801 if (afterOffset !== null) {
802 queueMicrotask(() => {
803 editor.update(() => {
804 $setSelectionAtComposerOffset(afterOffset!);
805 });
806 });
807 }
808 });
809 }, [editor]);
810
811 return null;
812}
813
814function ComposerInlineTokenBackspacePlugin() {
815 const [editor] = useLexicalComposerContext();
816 const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
817
818 useEffect(() => {
819 return editor.registerCommand(
820 KEY_BACKSPACE_COMMAND,
821 (event) => {
822 const selection = $getSelection();
823 if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
824 return false;
825 }
826
827 const anchorNode = selection.anchor.getNode();
828 const selectionOffset = $readSelectionOffsetFromEditorState(0);
829 const removeInlineTokenNode = (candidate: unknown): boolean => {
830 if (!isComposerInlineTokenNode(candidate)) {
831 return false;
832 }
833 const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
834 candidate.remove();
835 if (candidate instanceof ComposerTerminalContextNode) {
836 onRemoveTerminalContext(candidate.__context.id);
837 $setSelectionAtComposerOffset(selectionOffset);
838 } else {
839 $setSelectionAtComposerOffset(tokenStart);
840 }
841 event?.preventDefault();
842 return true;
843 };
844 if (removeInlineTokenNode(anchorNode)) {
845 return true;
846 }
847
848 if ($isTextNode(anchorNode)) {
849 if (selection.anchor.offset > 0) {
850 return false;
851 }
852 if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
853 return true;
854 }
855 const parent = anchorNode.getParent();
856 if ($isElementNode(parent)) {
857 const index = anchorNode.getIndexWithinParent();
858 if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
859 return true;
860 }
861 }
862 return false;
863 }
864
865 if ($isElementNode(anchorNode)) {
866 const childIndex = selection.anchor.offset - 1;
867 if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
868 return true;
869 }
870 }
871
872 return false;
873 },
874 COMMAND_PRIORITY_HIGH,
875 );
876 }, [editor, onRemoveTerminalContext]);
877
878 return null;
879}
880
881function ComposerPromptEditorInner({
882 value,
883 cursor,
884 terminalContexts,
885 disabled,
886 placeholder,
887 className,
888 onRemoveTerminalContext,
889 onChange,
890 onCommandKeyDown,
891 onPaste,
892 editorRef,
893}: ComposerPromptEditorInnerProps) {
894 const [editor] = useLexicalComposerContext();
895 const onChangeRef = useRef(onChange);
896 const initialCursor = clampCollapsedComposerCursor(value, cursor);
897 const terminalContextsSignature = terminalContextSignature(terminalContexts);
898 const terminalContextsSignatureRef = useRef(terminalContextsSignature);
899 const snapshotRef = useRef({
900 value,
901 cursor: initialCursor,
902 expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
903 terminalContextIds: terminalContexts.map((context) => context.id),
904 });
905 const isApplyingControlledUpdateRef = useRef(false);
906 const terminalContextActions = useMemo(
907 () => ({ onRemoveTerminalContext }),
908 [onRemoveTerminalContext],
909 );
910
911 useEffect(() => {
912 onChangeRef.current = onChange;
913 }, [onChange]);
914
915 useEffect(() => {
916 editor.setEditable(!disabled);
917 }, [disabled, editor]);
918
919 useLayoutEffect(() => {
920 const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
921 const previousSnapshot = snapshotRef.current;
922 const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
923 if (
924 previousSnapshot.value === value &&
925 previousSnapshot.cursor === normalizedCursor &&
926 !contextsChanged
927 ) {
928 return;
929 }
930
931 snapshotRef.current = {
932 value,
933 cursor: normalizedCursor,
934 expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
935 terminalContextIds: terminalContexts.map((context) => context.id),
936 };
937 terminalContextsSignatureRef.current = terminalContextsSignature;
938
939 const rootElement = editor.getRootElement();
940 const isFocused = Boolean(rootElement && document.activeElement === rootElement);
941 if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
942 return;
943 }
944
945 isApplyingControlledUpdateRef.current = true;
946 editor.update(() => {
947 const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
948 if (shouldRewriteEditorState) {
949 $setComposerEditorPrompt(value, terminalContexts);
950 }
951 if (shouldRewriteEditorState || isFocused) {
952 $setSelectionAtComposerOffset(normalizedCursor);
953 }
954 });
955 queueMicrotask(() => {
956 isApplyingControlledUpdateRef.current = false;
957 });
958 }, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
959
960 const focusAt = useCallback(
961 (nextCursor: number) => {
962 const rootElement = editor.getRootElement();
963 if (!rootElement) return;
964 const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
965 rootElement.focus();
966 editor.update(() => {
967 $setSelectionAtComposerOffset(boundedCursor);
968 });
969 snapshotRef.current = {
970 value: snapshotRef.current.value,
971 cursor: boundedCursor,
972 expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
973 terminalContextIds: snapshotRef.current.terminalContextIds,
974 };
975 onChangeRef.current(
976 snapshotRef.current.value,
977 boundedCursor,
978 snapshotRef.current.expandedCursor,
979 false,
980 snapshotRef.current.terminalContextIds,
981 );
982 },
983 [editor],
984 );
985
986 const readSnapshot = useCallback((): {
987 value: string;
988 cursor: number;
989 expandedCursor: number;
990 terminalContextIds: string[];
991 } => {
992 let snapshot = snapshotRef.current;
993 editor.getEditorState().read(() => {
994 const nextValue = $getRoot().getTextContent();
995 const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
996 const nextCursor = clampCollapsedComposerCursor(
997 nextValue,
998 $readSelectionOffsetFromEditorState(fallbackCursor),
999 );
1000 const fallbackExpandedCursor = clampExpandedCursor(
1001 nextValue,
1002 snapshotRef.current.expandedCursor,
1003 );
1004 const nextExpandedCursor = clampExpandedCursor(
1005 nextValue,
1006 $readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
1007 );
1008 const terminalContextIds = collectTerminalContextIds($getRoot());
1009 snapshot = {
1010 value: nextValue,
1011 cursor: nextCursor,
1012 expandedCursor: nextExpandedCursor,
1013 terminalContextIds,
1014 };
1015 });
1016 snapshotRef.current = snapshot;
1017 return snapshot;
1018 }, [editor]);
1019
1020 useImperativeHandle(
1021 editorRef,
1022 () => ({
1023 focus: () => {
1024 focusAt(snapshotRef.current.cursor);
1025 },
1026 focusAt,
1027 focusAtEnd: () => {
1028 focusAt(
1029 collapseExpandedComposerCursor(
1030 snapshotRef.current.value,
1031 snapshotRef.current.value.length,
1032 ),
1033 );
1034 },
1035 readSnapshot,
1036 }),
1037 [focusAt, readSnapshot],
1038 );
1039
1040 const handleEditorChange = useCallback((editorState: EditorState) => {
1041 editorState.read(() => {
1042 const nextValue = $getRoot().getTextContent();
1043 const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
1044 const nextCursor = clampCollapsedComposerCursor(
1045 nextValue,
1046 $readSelectionOffsetFromEditorState(fallbackCursor),
1047 );
1048 const fallbackExpandedCursor = clampExpandedCursor(
1049 nextValue,
1050 snapshotRef.current.expandedCursor,
1051 );
1052 const nextExpandedCursor = clampExpandedCursor(
1053 nextValue,
1054 $readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
1055 );
1056 const terminalContextIds = collectTerminalContextIds($getRoot());
1057 const previousSnapshot = snapshotRef.current;
1058 if (
1059 previousSnapshot.value === nextValue &&
1060 previousSnapshot.cursor === nextCursor &&
1061 previousSnapshot.expandedCursor === nextExpandedCursor &&
1062 previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
1063 previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
1064 ) {
1065 return;
1066 }
1067 if (isApplyingControlledUpdateRef.current) {
1068 return;
1069 }
1070 snapshotRef.current = {
1071 value: nextValue,
1072 cursor: nextCursor,
1073 expandedCursor: nextExpandedCursor,
1074 terminalContextIds,
1075 };
1076 const cursorAdjacentToMention =
1077 isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
1078 isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
1079 onChangeRef.current(
1080 nextValue,
1081 nextCursor,
1082 nextExpandedCursor,
1083 cursorAdjacentToMention,
1084 terminalContextIds,
1085 );
1086 });
1087 }, []);
1088
1089 return (
1090 <ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
1091 <div className="relative">
1092 <PlainTextPlugin
1093 contentEditable={
1094 <ContentEditable
1095 className={cn(
1096 "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",
1097 className,
1098 )}
1099 data-testid="composer-editor"
1100 aria-placeholder={placeholder}
1101 placeholder={<span />}
1102 onPaste={onPaste}
1103 />
1104 }
1105 placeholder={
1106 terminalContexts.length > 0 ? null : (
1107 <div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
1108 {placeholder}
1109 </div>
1110 )
1111 }
1112 ErrorBoundary={LexicalErrorBoundary}
1113 />
1114 <OnChangePlugin onChange={handleEditorChange} />
1115 <ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
1116 <ComposerInlineTokenArrowPlugin />
1117 <ComposerInlineTokenSelectionNormalizePlugin />
1118 <ComposerInlineTokenBackspacePlugin />
1119 <HistoryPlugin />
1120 </div>
1121 </ComposerTerminalContextActionsContext.Provider>
1122 );
1123}
1124
1125export const ComposerPromptEditor = forwardRef<
1126 ComposerPromptEditorHandle,
1127 ComposerPromptEditorProps
1128>(function ComposerPromptEditor(
1129 {
1130 value,
1131 cursor,
1132 terminalContexts,
1133 disabled,
1134 placeholder,
1135 className,
1136 onRemoveTerminalContext,
1137 onChange,
1138 onCommandKeyDown,
1139 onPaste,
1140 },
1141 ref,
1142) {
1143 const initialValueRef = useRef(value);
1144 const initialTerminalContextsRef = useRef(terminalContexts);
1145 const initialConfig = useMemo<InitialConfigType>(
1146 () => ({
1147 namespace: "t3tools-composer-editor",
1148 editable: true,
1149 nodes: [ComposerMentionNode, ComposerTerminalContextNode],
1150 editorState: () => {
1151 $setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
1152 },
1153 onError: (error) => {
1154 throw error;
1155 },
1156 }),
1157 [],
1158 );
1159
1160 return (
1161 <LexicalComposer key={COMPOSER_EDITOR_HMR_KEY} initialConfig={initialConfig}>
1162 <ComposerPromptEditorInner
1163 value={value}
1164 cursor={cursor}
1165 terminalContexts={terminalContexts}
1166 disabled={disabled}
1167 placeholder={placeholder}
1168 onRemoveTerminalContext={onRemoveTerminalContext}
1169 onChange={onChange}
1170 onPaste={onPaste}
1171 editorRef={ref}
1172 {...(onCommandKeyDown ? { onCommandKeyDown } : {})}
1173 {...(className ? { className } : {})}
1174 />
1175 </LexicalComposer>
1176 );
1177});