forked from coder/agentapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage-list.tsx
More file actions
216 lines (186 loc) · 7.04 KB
/
message-list.tsx
File metadata and controls
216 lines (186 loc) · 7.04 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
"use client";
import React, {useLayoutEffect, useRef, useEffect, useCallback, useMemo, useState} from "react";
interface Message {
role: string;
content: string;
id: number;
}
// Draft messages are used to optmistically update the UI
// before the server responds.
interface DraftMessage extends Omit<Message, "id"> {
id?: number;
}
interface MessageListProps {
messages: (Message | DraftMessage)[];
}
export default function MessageList({ messages }: MessageListProps) {
const scrollAreaRef = useRef<HTMLDivElement>(null);
// Avoid the message list to change its height all the time. It causes some
// flickering in the screen because some messages, as the ones displaying
// progress statuses, are changing the content(the number of lines) and size
// constantily. To minimize it, we keep track of the biggest scroll height of
// the content, and use that as the min height of the scroll area.
const contentMinHeight = useRef(0);
// Track if user is at bottom - default to true for initial scroll
const isAtBottomRef = useRef(true);
// Track the last known scroll height to detect new content
const lastScrollHeightRef = useRef(0);
const checkIfAtBottom = useCallback(() => {
if (!scrollAreaRef.current) return false;
const { scrollTop, scrollHeight, clientHeight } = scrollAreaRef.current;
return scrollTop + clientHeight >= scrollHeight - 10; // 10px tolerance
}, []);
// Regex to find URLs
// https://stackoverflow.com/a/17773849
const urlRegex = useMemo<RegExp>(() => /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/g, []);
const [modifierPressed, setModifierPressed] = useState(false);
// Track Ctrl (Windows/Linux) or Cmd (Mac) key state
// This is so that underline is only visible when hover + cmd/ctrl
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey || e.metaKey) setModifierPressed(true);
};
const handleKeyUp = (e: KeyboardEvent) => {
if (!e.ctrlKey && !e.metaKey) setModifierPressed(false);
};
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
}, []);
// Update isAtBottom on scroll
useEffect(() => {
const scrollContainer = scrollAreaRef.current;
if (!scrollContainer) return;
const handleScroll = () => {
isAtBottomRef.current = checkIfAtBottom();
};
// Initial check
handleScroll();
scrollContainer.addEventListener("scroll", handleScroll);
return () => scrollContainer.removeEventListener("scroll", handleScroll);
}, [checkIfAtBottom]);
// Handle auto-scrolling when messages change
useLayoutEffect(() => {
if (!scrollAreaRef.current) return;
const scrollContainer = scrollAreaRef.current;
const currentScrollHeight = scrollContainer.scrollHeight;
// Check if this is new content (scroll height increased)
const hasNewContent = currentScrollHeight > lastScrollHeightRef.current;
const isFirstRender = lastScrollHeightRef.current === 0;
const isNewUserMessage =
messages.length > 0 && messages[messages.length - 1].role === "user";
// Update content min height if needed
if (currentScrollHeight > contentMinHeight.current) {
contentMinHeight.current = currentScrollHeight;
}
// Auto-scroll only if:
// 1. It's the first render, OR
// 2. There's new content AND user was at the bottom, OR
// 3. The user sent a new message
if (
hasNewContent &&
(isFirstRender || isAtBottomRef.current || isNewUserMessage)
) {
scrollContainer.scrollTo({
top: currentScrollHeight,
behavior: isFirstRender ? "instant" : "smooth",
});
// After scrolling, we're at the bottom
isAtBottomRef.current = true;
}
// Update the last known scroll height
lastScrollHeightRef.current = currentScrollHeight;
}, [messages]);
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>, url: string) => {
if (e.metaKey || e.ctrlKey) {
window.open(url, "_blank");
} else {
e.preventDefault(); // disable normal click to emulate terminal behaviour
}
};
const buildClickableLinks = useCallback((message: string, msg_index: number) => {
const linkedContent = message.split(urlRegex).map((content, index) => {
if (urlRegex.test(content)) {
return (
<a
key={`${msg_index}-${index}`}
href={content}
onClick={(e) => handleClick(e, content)}
className={`${
modifierPressed ? "hover:underline cursor-pointer" : "cursor-default"
}`}
>
{content}
</a>
);
}
return <span key={`${msg_index}-${index}`}>{content}</span>;
})
return <>
{linkedContent}
</>
}, [modifierPressed, urlRegex])
// If no messages, show a placeholder
if (messages.length === 0) {
return (
<div className="flex-1 p-6 flex items-center justify-center text-muted-foreground">
<p>No messages yet. Start the conversation!</p>
</div>
);
}
return (
<div className="overflow-y-auto flex-1" ref={scrollAreaRef}>
<div
className="p-4 flex flex-col gap-4 max-w-4xl mx-auto"
style={{ minHeight: contentMinHeight.current }}
>
{messages.map((message, index) => (
<div
key={message.id ?? "draft"}
className={`${message.role === "user" ? "text-right" : ""}`}
>
<div
className={`inline-block rounded-lg ${
message.role === "user"
? "bg-accent-foreground rounded-lg max-w-[90%] px-4 py-3 text-accent"
: "max-w-[80ch]"
} ${message.id === undefined ? "animate-pulse" : ""}`}
>
<div
className={`whitespace-pre-wrap break-words text-left text-xs md:text-sm leading-relaxed md:leading-normal ${
message.role === "user" ? "" : "font-mono"
}`}
>
{message.role !== "user" && message.content === "" ? (
<LoadingDots />
) : (
buildClickableLinks(message.content.trimEnd(), index)
)}
</div>
</div>
</div>
))}
</div>
</div>
);
}
const LoadingDots = () => (
<div className="flex space-x-1">
<div
aria-hidden="true"
className={`size-2 rounded-full bg-foreground animate-pulse [animation-delay:0ms]`}
/>
<div
aria-hidden="true"
className={`size-2 rounded-full bg-foreground animate-pulse [animation-delay:300ms]`}
/>
<div
aria-hidden="true"
className={`size-2 rounded-full bg-foreground animate-pulse [animation-delay:600ms]`}
/>
<span className="sr-only">Loading...</span>
</div>
);