-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser-input.tsx
More file actions
306 lines (279 loc) · 10.3 KB
/
user-input.tsx
File metadata and controls
306 lines (279 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"use client";
import { Button } from "@/components/ui/button";
import ImageBlock from "@/components/custom/image-block";
import { Send } from "lucide-react";
import React from "react";
import * as ServerTypes from "@/sdk/types/IServer";
import { cn } from "@/lib/utils";
const readBlobAsDataUrl = (blob: Blob) => new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
});
const reencodeImageToJpeg = (file: File) => new Promise<string>((resolve, reject) => {
const objectUrl = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
try {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
const ctx = canvas.getContext("2d");
if (!ctx) {
reject(new Error("Canvas context unavailable"));
return;
}
ctx.drawImage(img, 0, 0);
canvas.toBlob((blob) => {
URL.revokeObjectURL(objectUrl);
if (!blob) {
reject(new Error("Failed to encode JPEG"));
return;
}
readBlobAsDataUrl(blob).then(resolve).catch(reject);
}, "image/jpeg", 0.92);
} catch (err) {
URL.revokeObjectURL(objectUrl);
reject(err);
}
};
img.onerror = () => {
URL.revokeObjectURL(objectUrl);
reject(new Error("Failed to load pasted image"));
};
img.src = objectUrl;
});
const ensureJpegDataUrl = (file: File) => {
if (file.type === "image/jpeg") {
return readBlobAsDataUrl(file);
}
return reencodeImageToJpeg(file).catch(() => readBlobAsDataUrl(file));
};
interface UserInputProps {
onUserMessage: (message: ServerTypes.Message) => void;
/** This controls the send button. Not the editor. */
inputEnabled: boolean;
initialMessage?: ServerTypes.Message;
/** Optional controlled height for the editor. */
editorHeight?: number;
onEditorHeightChange?: (height: number) => void;
}
export function UserInput({ onUserMessage, inputEnabled, initialMessage, editorHeight: controlledHeight, onEditorHeightChange }: UserInputProps) {
/** Text input */
const [inputValue, setInputValue] = React.useState(
initialMessage?.content
.filter(c => c.type === 'text' || c.type === 'refusal')
.map(c => c.data).join('\n') ?? ""
);
/** Image data urls */
const [imageUrls, setImageUrls] = React.useState<string[]>(
initialMessage?.content
.filter(c => c.type === 'image_url')
.map(c => c.data) ?? []
);
const MIN_HEIGHT = 80;
const MAX_HEIGHT = 400;
const [uncontrolledEditorHeight, setUncontrolledEditorHeight] = React.useState<number>(MIN_HEIGHT);
const startYRef = React.useRef<number | null>(null);
const startHeightRef = React.useRef<number>(0);
const draggingRef = React.useRef(false);
const textAreaRef = React.useRef<HTMLTextAreaElement | null>(null);
const scrollContainerRef = React.useRef<HTMLDivElement | null>(null);
const isControlled = controlledHeight !== undefined;
const editorHeight = isControlled ? controlledHeight as number : uncontrolledEditorHeight;
const setEditorHeight = React.useCallback((height: number) => {
const clamped = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, height));
if (isControlled) {
onEditorHeightChange?.(clamped);
} else {
setUncontrolledEditorHeight(clamped);
}
}, [isControlled, onEditorHeightChange]);
const beginDrag = (e: React.MouseEvent) => {
startYRef.current = e.clientY;
startHeightRef.current = editorHeight;
draggingRef.current = true;
// Prevent text selection while dragging.
document.body.style.userSelect = "none";
};
React.useEffect(() => {
if (!initialMessage) {
return;
}
setInputValue(
initialMessage.content
.filter(c => c.type === 'text' || c.type === 'refusal')
.map(c => c.data).join('\n') ?? ""
);
setImageUrls(
initialMessage.content
.filter(c => c.type === 'image_url')
.map(c => c.data) ?? []
);
}, [initialMessage]);
React.useEffect(() => {
const onMove = (e: MouseEvent) => {
if (!draggingRef.current || startYRef.current === null) {
return;
}
const delta = startYRef.current - e.clientY; // dragging up increases height
const newHeight = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, startHeightRef.current + delta));
setEditorHeight(newHeight);
};
const onUp = () => {
draggingRef.current = false;
startYRef.current = null;
document.body.style.userSelect = "";
};
window.addEventListener("mousemove", onMove);
window.addEventListener("mouseup", onUp);
return () => {
window.removeEventListener("mousemove", onMove);
window.removeEventListener("mouseup", onUp);
};
}, [editorHeight, setEditorHeight]);
React.useLayoutEffect(() => {
const ta = textAreaRef.current;
const scrollEl = scrollContainerRef.current;
if (!ta || !scrollEl) return;
const wasAtBottom = scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight < 8;
const previousScrollTop = scrollEl.scrollTop;
ta.style.height = "auto";
const parentRect = scrollEl.getBoundingClientRect();
const childRect = ta.getBoundingClientRect();
const maxVisibleHeight = parentRect.height - (childRect.top - parentRect.top) - 8;
const targetHeight = Math.max(ta.scrollHeight, maxVisibleHeight);
ta.style.height = `${targetHeight}px`;
// Restore scroll to where the user was, or keep the caret visible at the bottom.
if (wasAtBottom) {
scrollEl.scrollTop = scrollEl.scrollHeight;
} else {
scrollEl.scrollTop = previousScrollTop;
}
}, [editorHeight, inputValue, imageUrls]);
const handleSend = () => {
const trimmed = inputValue.trim();
if (imageUrls.length === 0 && !trimmed) {
return;
}
const content: ServerTypes.Message["content"] = [];
if (imageUrls.length > 0) {
for (const url of imageUrls) {
content.push({ type: "image_url", data: url });
}
}
if (trimmed) {
content.push({ type: "text", data: trimmed });
}
onUserMessage({ role: "user", content });
setImageUrls([]);
setInputValue("");
// Refocus for subsequent typing.
requestAnimationFrame(() => textAreaRef.current?.focus());
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && e.altKey) {
e.preventDefault();
if (inputEnabled) {
handleSend();
}
}
};
const handlePaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
if (!e.clipboardData) {
return;
}
const items = e.clipboardData.items;
const filePromises: Promise<string>[] = [];
for (const item of items) {
if (item.kind === "file" && item.type.startsWith("image/")) {
const file = item.getAsFile();
if (!file) continue;
filePromises.push(ensureJpegDataUrl(file));
}
}
if (filePromises.length > 0) {
e.preventDefault(); // Prevent any text insertion from clipboard when images are present.
Promise.all(filePromises)
.then(dataUrls => {
if (dataUrls.length === 0) {
return;
}
setImageUrls(prev => [...prev, ...dataUrls]);
})
.catch(() => {/* swallow errors; user can retry paste */});
}
};
const sendDisabled = !inputEnabled || (imageUrls.length === 0 && !inputValue.trim());
return (
<div className="border-t border-border p-4 relative select-none">
{/* Drag handle (top edge) */}
<div
className="absolute top-0 left-0 right-0 h-2 cursor-row-resize"
onMouseDown={beginDrag}
aria-label="调整输入区域高度"
>
<div className="mx-auto h-full w-24">
{/* visual hint - subtle line */}
<div className="h-[2px] mt-[6px] rounded bg-muted-foreground/30" />
</div>
</div>
<div className="max-w-[900px] mx-auto flex flex-col justify-end">
<div className="flex items-end">
<div className="flex-1 relative" style={{ height: editorHeight }}>
<div
className={cn(
"absolute inset-0 flex flex-col overflow-y-auto rounded-md border border-input bg-transparent",
"scrollbar-thin scrollbar-thumb-muted-foreground/30 scrollbar-track-transparent"
)}
ref={scrollContainerRef}
>
{imageUrls.length > 0 && (
<div className="p-2 flex flex-wrap gap-2">
{imageUrls.map((src, idx) => (
<ImageBlock
key={idx}
src={src}
alt={`粘贴图片 ${idx + 1}`}
removable
onRemove={() => setImageUrls(prev => prev.filter((_, i) => i !== idx))}
/>
))}
</div>
)}
<textarea
ref={textAreaRef}
placeholder="请输入内容,Alt + Enter 发送"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
className={cn(
"w-full resize-none",
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground",
"dark:bg-input/30 bg-transparent px-3 py-2 text-sm outline-none flex-shrink-0",
"focus-visible:border-none focus-visible:ring-0",
imageUrls.length > 0 ? "pt-1" : "",
)}
rows={1}
/>
</div>
<div className="absolute right-2 bottom-2 flex items-center space-x-1">
<Button
variant="ghost"
size="sm"
onClick={handleSend}
disabled={sendDisabled}
aria-label={sendDisabled ? "发送不可用" : "发送消息 (Alt+Enter)"}
>
<Send className="size-4 mr-1" />
<span className="text-[10px] leading-none text-muted-foreground">Alt+Enter</span>
</Button>
</div>
</div>
</div>
</div>
</div>
);
}