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