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

AssistantCitationCommentEditor.tsx

97 lines2.9 KB

1import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
2import { useState, type Ref } from "react";
3​
4import { Button } from "../ui/button";
5​
6export function AssistantCitationCommentEditor({
7 citation,
8 inputRef,
9 onSubmit,
10 onSubmitAndSend,
11 onCancel,
12}: {
13 citation: AssistantCitation;
14 inputRef?: Ref<HTMLTextAreaElement>;
15 onSubmit: (comment: string) => boolean;
16 onSubmitAndSend?: (comment: string) => boolean;
17 onCancel: () => void;
18}) {
19 const [comment, setComment] = useState(citation.comment ?? "");
20 const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
21 const submit = () => {
22 if (!commentTooLong) onSubmit(comment);
23 };
24 const submitAndSend = () => {
25 if (commentTooLong) return;
26 if (onSubmitAndSend) {
27 onSubmitAndSend(comment);
28 } else {
29 onSubmit(comment);
30 }
31 };
32​
33 return (
34 <div
35 data-citation-comment-editor="true"
36 onKeyDown={(event) => {
37 event.stopPropagation();
38 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
39 if (event.key === "Escape") {
40 event.preventDefault();
41 onCancel();
42 }
43 }}
44 >
45 <textarea
46 ref={inputRef}
47 aria-label="Comment on selected text"
48 aria-description="Enter to save the citation comment; Command/Ctrl+Enter to save and send; Shift+Enter for a new line."
49 aria-invalid={commentTooLong || undefined}
50 placeholder="Add an optional comment..."
51 rows={2}
52 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"
53 value={comment}
54 onChange={(event) => setComment(event.currentTarget.value)}
55 onKeyDown={(event) => {
56 if (
57 event.key === "Enter" &&
58 !event.shiftKey &&
59 !event.nativeEvent.isComposing &&
60 event.keyCode !== 229
61 ) {
62 event.preventDefault();
63 if (event.metaKey || event.ctrlKey) {
64 submitAndSend();
65 } else {
66 submit();
67 }
68 }
69 }}
70 />
71 {commentTooLong ? (
72 <p role="status" className="pt-1 text-xs text-destructive">
73 Comments can contain up to {ASSISTANT_CITATION_MAX_COMMENT_LENGTH.toLocaleString()}{" "}
74 characters.
75 </p>
76 ) : null}
77 <div className="mt-2 flex items-center justify-end gap-2">
78 <Button
79 variant="outline"
80 size="xs"
81 onPointerDown={(event) => event.preventDefault()}
82 onClick={onCancel}
83 >
84 Cancel
85 </Button>
86 <Button
87 size="xs"
88 disabled={commentTooLong}
89 onPointerDown={(event) => event.preventDefault()}
90 onClick={submit}
91 >
92 {commentTooLong ? "Shorten comment" : "Save"}
93 </Button>
94 </div>
95 </div>
96 );