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

ComposerCitationNode.tsx

218 lines6.5 KB

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