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

AssistantCitationCommentEditor.tsx

170 lines5.8 KB

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`Enter to save the citation comment; Command/Ctrl+Enter to save and send; Shift+Enter for a new line.`}
111 aria-invalid={commentTooLong || undefined}
112 placeholder={gt`Add an optional comment...`}
113 rows={2}
114 dir={textDirection(comment)}
115 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"
116 value={comment}
117 onChange={(event) => updateComment(event.currentTarget.value)}
118 onKeyDown={(event) => {
119 if (
120 event.key === "Enter" &&
121 !event.shiftKey &&
122 !event.nativeEvent.isComposing &&
123 event.keyCode !== 229
124 ) {
125 event.preventDefault();
126 if (event.metaKey || event.ctrlKey) {
127 submitAndSend();
128 } else {
129 submit();
130 }
131 }
132 }}
133 />
134 {commentTooLong ? (
135 <p role="status" className="pt-1 text-xs text-destructive">
136 <T>
137 Comments can contain up to{" "}
138 <Var>{ASSISTANT_CITATION_MAX_COMMENT_LENGTH.toLocaleString()}</Var> characters.
139 </T>
140 </p>
141 ) : null}
142 <div className="mt-2 flex flex-wrap items-center justify-end gap-2">
143 <TextFieldSpeechControls speech={speech} />
144 {/* Wrap as a pair so the recording pill never pushes Save alone onto a new row under Cancel. */}
145 <div className="flex gap-2">
146 <Button
147 variant="outline"
148 size="xs"
149 // Escape cancels; keep Tab from the comment on Save so Enter cannot discard a new citation.
150 tabIndex={-1}
151 onPointerDown={(event) => event.preventDefault()}
152 onClick={onCancel}
153 >
154 <T>Cancel</T>
155 </Button>
156 <Button
157 size="xs"
158 disabled={speech.preparing || (commentTooLong && !speech.blocksSubmission)}
159 onPointerDown={(event) => event.preventDefault()}
160 onClick={submit}
161 >
162 {commentTooLong
163 ? gt`Shorten comment`
164 : gt({ context: "verb, saves the comment" })`Save`}
165 </Button>
166 </div>
167 </div>
168 </div>
169 );