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};
46
47export const ComposerCitationCommentContext = createContext<{
48 openComment: ComposerCitationCommentTarget | null;
49 onOpenChange: (nodeKey: NodeKey, open: boolean) => void;
50}>({ openComment: null, onOpenChange: () => {} });
51
52/** Consume a cite action once its controlled prompt has been committed to the editor. */
53export function $consumeComposerCitationCommentRequest(requestRef: {
54 current: ComposerCitationCommentRequest | null;
55}): ComposerCitationCommentTarget | null {
56 const request = requestRef.current;
57 if (!request) return null;
58 const root = $getRoot();
59 const value = root.getTextContent();
60 if (value === request.previousValue) return null;
61 requestRef.current = null;
62 if (value !== request.value) return null;
63
64 // Controlled prompts use one paragraph with inline nodes and explicit line breaks.
65 const paragraph = root.getFirstChild();
66 if (!$isElementNode(paragraph)) return null;
67 let offset = 0;
68 for (const node of paragraph.getChildren()) {
69 if (offset === request.citationStart && node instanceof ComposerCitationNode) {
70 return { nodeKey: node.getKey(), sourceAnchor: request.sourceAnchor };
71 }
72 offset += node.getTextContentSize();
73 }
74 return null;
75}
76
77function ComposerCitationDecorator(props: { citation: AssistantCitation; nodeKey: NodeKey }) {
78 const [editor] = useLexicalComposerContext();
79 const commentContext = use(ComposerCitationCommentContext);
80 const onSaveComment = (comment: string): boolean => {
81 if (!editor.isEditable()) return false;
82 let accepted = false;
83 editor.update(
84 () => {
85 const node = $getNodeByKey(props.nodeKey);
86 if (node instanceof ComposerCitationNode && node.isAttached()) {
87 node.setComment(comment);
88 accepted = true;
89 }
90 },
91 { discrete: true, tag: [HISTORY_PUSH_TAG, SKIP_DOM_SELECTION_TAG] },
92 );
93 return accepted;
94 };
95 const onRemove = () => {
96 if (!editor.isEditable()) return;
97 editor.update(
98 () => {
99 const node = $getNodeByKey(props.nodeKey);
100 if (node instanceof ComposerCitationNode) {
101 node.selectPrevious();
102 node.remove();
103 }
104 },
105 { tag: HISTORY_PUSH_TAG },
106 );
107 editor.getRootElement()?.focus({ preventScroll: true });
108 };
109
110 return (
111 <span
112 className="inline-flex min-w-0 max-w-full"
113 contentEditable={false}
114 spellCheck={false}
115 data-composer-citation-chip="true"
116 >
117 <AssistantCitationChip
118 citation={props.citation}
119 commentEditor={{
120 open: commentContext.openComment?.nodeKey === props.nodeKey,
121 sourceAnchor:
122 commentContext.openComment?.nodeKey === props.nodeKey
123 ? commentContext.openComment.sourceAnchor
124 : undefined,
125 onOpenChange: (open) => {
126 if (open && !editor.isEditable()) return;
127 commentContext.onOpenChange(props.nodeKey, open);
128 },
129 onSave: onSaveComment,
130 }}
131 onRemove={onRemove}
132 />
133 </span>
134 );
135}
136
137export class ComposerCitationNode extends DecoratorNode<ReactElement> {
138 __citation: AssistantCitation;
139 __source: string;
140
141 static override getType(): string {
142 return "composer-citation";
143 }
144
145 static override clone(node: ComposerCitationNode): ComposerCitationNode {
146 return new ComposerCitationNode(node.__citation, node.__source, node.__key);
147 }
148
149 static override importJSON(serializedNode: SerializedComposerCitationNode): ComposerCitationNode {
150 return $createComposerCitationNode(
151 serializedNode.citation,
152 serializedNode.source,
153 ).updateFromJSON(serializedNode);
154 }
155
156 constructor(citation: AssistantCitation, source: string, key?: NodeKey) {
157 super(key);
158 this.__citation = citation;
159 this.__source = source;
160 }
161
162 override exportJSON(): SerializedComposerCitationNode {
163 const node = this.getLatest();
164 return {
165 ...super.exportJSON(),
166 citation: node.__citation,
167 source: node.__source,
168 type: "composer-citation",
169 version: 1,
170 };
171 }
172
173 override createDOM(): HTMLElement {
174 const dom = document.createElement("span");
175 dom.className = `${COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME} max-w-full`;
176 return dom;
177 }
178
179 override updateDOM(): false {
180 return false;
181 }
182
183 override getTextContent(): string {
184 return this.getLatest().__source;
185 }
186
187 setComment(comment: string): this {
188 const latest = this.getLatest();
189 const citation = withAssistantCitationComment(latest.__citation, comment);
190 if (citation.comment === latest.__citation.comment) return latest;
191 const source = serializeAssistantCitation(citation);
192 const writable = this.getWritable();
193 writable.__citation = citation;
194 writable.__source = source;
195 return writable;
196 }
197
198 override isInline(): true {
199 return true;
200 }
201
202 override decorate(): ReactElement {
203 return <ComposerCitationDecorator citation={this.__citation} nodeKey={this.__key} />;
204 }
205}
206
207export function $createComposerCitationNode(
208 citation: AssistantCitation,
209 source: string,
210): ComposerCitationNode {
211 return $applyNodeReplacement(new ComposerCitationNode(citation, source));
212}