Open History to see the last commit
1import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
2import type { AssistantCitation } from "@t3tools/contracts";
3import {
4 serializeAssistantCitation,
5 withAssistantCitationComment,
6} from "@t3tools/shared/assistantCitations";
7import {
8 $applyNodeReplacement,
9 $getNodeByKey,
10 $getRoot,
11 $isElementNode,
12 DecoratorNode,
13 HISTORY_PUSH_TAG,
14 SKIP_DOM_SELECTION_TAG,
15 type NodeKey,
16 type SerializedLexicalNode,
17 type Spread,
18} from "lexical";
19import { createContext, use, type ReactElement } from "react";
20import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
21
22import { AssistantCitationChip } from "./chat/AssistantCitationChip";
23import { COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME } from "./composerInlineChip";
24
25type SerializedComposerCitationNode = Spread<
26 {
27 citation: AssistantCitation;
28 source: string;
29 type: "composer-citation";
30 version: 1;
31 },
32 SerializedLexicalNode
33>;
34
35export type ComposerCitationCommentRequest = {
36 previousValue: string;
37 value: string;
38 citationStart: number;
39 sourceAnchor: AssistantCitationSourceAnchor;
40};
41
42export type ComposerCitationCommentTarget = {
43 nodeKey: NodeKey;
44 sourceAnchor?: AssistantCitationSourceAnchor;
45 removeOnCancel?: boolean;
46};
47
48export const ComposerCitationCommentContext = createContext<{
49 openComment: ComposerCitationCommentTarget | null;
50 onOpenChange: (nodeKey: NodeKey, open: boolean) => void;
51 onSubmitAndSend: () => void;
52}>({ openComment: null, onOpenChange: () => {}, onSubmitAndSend: () => {} });
53
54/** Consume a cite action once its controlled prompt has been committed to the editor. */
55export function $consumeComposerCitationCommentRequest(requestRef: {
56 current: ComposerCitationCommentRequest | null;
57}): ComposerCitationCommentTarget | null {
58 const request = requestRef.current;
59 if (!request) return null;
60 const root = $getRoot();
61 const value = root.getTextContent();
62 if (value === request.previousValue) return null;
63 requestRef.current = null;
64 if (value !== request.value) return null;
65
66 // Controlled prompts use one paragraph with inline nodes and explicit line breaks.
67 const paragraph = root.getFirstChild();
68 if (!$isElementNode(paragraph)) return null;
69 let offset = 0;
70 for (const node of paragraph.getChildren()) {
71 if (offset === request.citationStart && node instanceof ComposerCitationNode) {
72 return {
73 nodeKey: node.getKey(),
74 sourceAnchor: request.sourceAnchor,
75 removeOnCancel: true,
76 };
77 }
78 offset += node.getTextContentSize();
79 }
80 return null;
81}
82
83function ComposerCitationDecorator(props: { citation: AssistantCitation; nodeKey: NodeKey }) {
84 const [editor] = useLexicalComposerContext();
85 const commentContext = use(ComposerCitationCommentContext);
86 const commentTarget =
87 commentContext.openComment?.nodeKey === props.nodeKey ? commentContext.openComment : null;
88 const onSaveComment = (comment: string): boolean => {
89 if (!editor.isEditable()) return false;
90 let accepted = false;
91 editor.update(
92 () => {
93 const node = $getNodeByKey(props.nodeKey);
94 if (node instanceof ComposerCitationNode && node.isAttached()) {
95 node.setComment(comment);
96 accepted = true;
97 }
98 },
99 { discrete: true, tag: [HISTORY_PUSH_TAG, SKIP_DOM_SELECTION_TAG] },
100 );
101 return accepted;
102 };
103 const onRemove = () => {
104 if (!editor.isEditable()) return;
105 editor.update(
106 () => {
107 const node = $getNodeByKey(props.nodeKey);
108 if (node instanceof ComposerCitationNode) {
109 node.selectPrevious();
110 node.remove();
111 }
112 },
113 { tag: HISTORY_PUSH_TAG },
114 );
115 editor.getRootElement()?.focus({ preventScroll: true });
116 };
117
118 return (
119 <span
120 className="inline-flex min-w-0 max-w-full"
121 contentEditable={false}
122 spellCheck={false}
123 data-composer-citation-chip="true"
124 >
125 <AssistantCitationChip
126 citation={props.citation}
127 commentEditor={{
128 open: commentTarget !== null,
129 sourceAnchor: commentTarget?.sourceAnchor,
130 onOpenChange: (open) => {
131 if (open && !editor.isEditable()) return;
132 commentContext.onOpenChange(props.nodeKey, open);
133 },
134 ...(commentTarget?.removeOnCancel ? { onCancel: onRemove } : {}),
135 onSave: onSaveComment,
136 onSaveAndSend: (comment) => {
137 if (!onSaveComment(comment)) return false;
138 commentContext.onSubmitAndSend();
139 return true;
140 },
141 }}
142 onRemove={onRemove}
143 />
144 </span>
145 );
146}
147
148export class ComposerCitationNode extends DecoratorNode<ReactElement> {
149 __citation: AssistantCitation;
150 __source: string;
151
152 static override getType(): string {
153 return "composer-citation";
154 }
155
156 static override clone(node: ComposerCitationNode): ComposerCitationNode {
157 return new ComposerCitationNode(node.__citation, node.__source, node.__key);
158 }
159
160 static override importJSON(serializedNode: SerializedComposerCitationNode): ComposerCitationNode {
161 return $createComposerCitationNode(
162 serializedNode.citation,
163 serializedNode.source,
164 ).updateFromJSON(serializedNode);
165 }
166
167 constructor(citation: AssistantCitation, source: string, key?: NodeKey) {
168 super(key);
169 this.__citation = citation;
170 this.__source = source;
171 }
172
173 override exportJSON(): SerializedComposerCitationNode {
174 const node = this.getLatest();
175 return {
176 ...super.exportJSON(),
177 citation: node.__citation,
178 source: node.__source,
179 type: "composer-citation",
180 version: 1,
181 };
182 }
183
184 override createDOM(): HTMLElement {
185 const dom = document.createElement("span");
186 dom.className = `${COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME} max-w-full`;
187 return dom;
188 }
189
190 override updateDOM(): false {
191 return false;
192 }
193
194 override getTextContent(): string {
195 return this.getLatest().__source;
196 }
197
198 setComment(comment: string): this {
199 const latest = this.getLatest();
200 const citation = withAssistantCitationComment(latest.__citation, comment);
201 if (citation.comment === latest.__citation.comment) return latest;
202 const source = serializeAssistantCitation(citation);
203 const writable = this.getWritable();
204 writable.__citation = citation;
205 writable.__source = source;
206 return writable;
207 }
208
209 override isInline(): true {
210 return true;
211 }
212
213 override decorate(): ReactElement {
214 return <ComposerCitationDecorator citation={this.__citation} nodeKey={this.__key} />;
215 }
216}
217
218export function $createComposerCitationNode(
219 citation: AssistantCitation,
220 source: string,
221): ComposerCitationNode {
222 return $applyNodeReplacement(new ComposerCitationNode(citation, source));
223}