Open History to see the last commit
1import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
2import { T, useGT, Var } from "gt-react";
3import {
4 use,
5 useEffect,
6 useImperativeHandle,
7 useRef,
8 useState,
9 type Ref,
10 type RefObject,
11} from "react";
12
13import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech";
14import { textDirection } from "~/textDirection";
15
16import { ComposerContextActionsContext } from "../composerContextActions";
17import { Button } from "../ui/button";
18
19/** Lets the popover finish a running dictation, instead of discarding it, when it is dismissed. */
20export type AssistantCitationCommentDictation = {
21 /** False when nothing is being dictated; otherwise `settle` gets the comment once it is transcribed. */
22 finish: (settle: (comment: string) => void) => boolean;
23};
24
25export function AssistantCitationCommentEditor({
26 citation,
27 inputRef,
28 onSubmit,
29 onSubmitAndSend,
30 onCancel,
31 onDraftChange,
32 onVoiceSetupOpenChange,
33 dictationRef,
34}: {
35 citation: AssistantCitation;
36 inputRef?: RefObject<HTMLTextAreaElement | null>;
37 onSubmit: (comment: string) => boolean;
38 onSubmitAndSend?: (comment: string) => boolean;
39 onCancel: () => void;
40 onDraftChange?: (comment: string) => void;
41 onVoiceSetupOpenChange?: (open: boolean) => void;
42 dictationRef?: Ref<AssistantCitationCommentDictation>;
43}) {
44 const gt = useGT();
45 const [comment, setComment] = useState(citation.comment ?? "");
46 const localInputRef = useRef<HTMLTextAreaElement | null>(null);
47 const textareaRef = inputRef ?? localInputRef;
48 const { environmentId, projectId } = use(ComposerContextActionsContext);
49 const updateComment = (text: string) => {
50 setComment(text);
51 onDraftChange?.(text);
52 };
53 const speech = useTextFieldSpeech({
54 environmentId: environmentId ?? citation.environmentId,
55 projectId,
56 ownerKey: JSON.stringify([
57 "citation",
58 environmentId,
59 citation.threadId,
60 citation.messageId,
61 citation.start,
62 citation.end,
63 ]),
64 text: comment,
65 textareaRef,
66 onTextChange: updateComment,
67 });
68 const setupOpen = speech.setup.open;
69 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the citation popover open while the voice setup dialog owns focus
70 useEffect(() => {
71 onVoiceSetupOpenChange?.(setupOpen);
72 return () => onVoiceSetupOpenChange?.(false);
73 }, [onVoiceSetupOpenChange, setupOpen]);
74 useImperativeHandle(dictationRef, () => ({
75 finish: (settle) => {
76 if (!speech.blocksSubmission || speech.preparing) return false;
77 speech.submitAfterDictation(settle);
78 return true;
79 },
80 }));
81 const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
82 const submit = () => {
83 speech.submitAfterDictation((text) => {
84 if (text.length <= ASSISTANT_CITATION_MAX_COMMENT_LENGTH) onSubmit(text);
85 });
86 };
87 const submitAndSend = () => {
88 speech.submitAfterDictation((text) => {
89 if (text.length <= ASSISTANT_CITATION_MAX_COMMENT_LENGTH) (onSubmitAndSend ?? onSubmit)(text);
90 });
91 };
92
93 return (
94 <div
95 data-citation-comment-editor="true"
96 onKeyDown={(event) => {
97 event.stopPropagation();
98 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
99 if (event.key === "Escape") {
100 event.preventDefault();
101 if (speech.state.phase !== "idle") speech.cancel();
102 else onCancel();
103 }
104 }}
105 >
106 <textarea
107 ref={textareaRef}
108 readOnly={speech.freezesEditor}
109 aria-label={gt("Comment on selected text")}
110 aria-description={gt(
111 "Enter to save the citation comment; Command/Ctrl+Enter to save and send; Shift+Enter for a new line.",
112 )}
113 aria-invalid={commentTooLong || undefined}
114 placeholder={gt("Add an optional comment...")}
115 rows={2}
116 dir={textDirection(comment)}
117 className="field-sizing-content block max-h-40 min-h-16 w-full resize-none bg-transparent px-1 py-1.5 text-base outline-none placeholder:text-muted-foreground sm:text-sm"
118 value={comment}
119 onChange={(event) => updateComment(event.currentTarget.value)}
120 onKeyDown={(event) => {
121 if (
122 event.key === "Enter" &&
123 !event.shiftKey &&
124 !event.nativeEvent.isComposing &&
125 event.keyCode !== 229
126 ) {
127 event.preventDefault();
128 if (event.metaKey || event.ctrlKey) {
129 submitAndSend();
130 } else {
131 submit();
132 }
133 }
134 }}
135 />
136 {commentTooLong ? (
137 <p role="status" className="pt-1 text-xs text-destructive">
138 <T>
139 Comments can contain up to{" "}
140 <Var>{ASSISTANT_CITATION_MAX_COMMENT_LENGTH.toLocaleString()}</Var> characters.
141 </T>
142 </p>
143 ) : null}
144 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
145 <TextFieldSpeechControls speech={speech} />
146 {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */}
147 <div className="flex gap-2">
148 <Button
149 variant="outline"
150 size="xs"
151 // Escape cancels; keep Tab from the comment on Save so Enter cannot discard a new citation.
152 tabIndex={-1}
153 onPointerDown={(event) => event.preventDefault()}
154 onClick={onCancel}
155 >
156 <T>Cancel</T>
157 </Button>
158 <Button
159 size="xs"
160 disabled={speech.preparing || (commentTooLong && !speech.blocksSubmission)}
161 onPointerDown={(event) => event.preventDefault()}
162 onClick={submit}
163 >
164 {commentTooLong
165 ? gt("Shorten comment")
166 : gt("Save", { $context: "verb, saves the comment" })}
167 </Button>
168 </div>
169 </div>
170 </div>
171 );
172}