File size: 10,286 Bytes
a0e379d
28f05af
760b33c
a0e379d
 
 
 
 
 
 
 
760b33c
a0e379d
 
8c6e3e1
28f05af
760b33c
 
 
 
d79f925
28f05af
4936922
d79f925
28f05af
 
 
760b33c
 
 
 
a0e379d
4c4a8cf
a0e379d
760b33c
a0e379d
 
 
 
 
 
 
4936922
28f05af
a0e379d
 
 
 
 
 
 
4c4a8cf
a0e379d
 
 
 
760b33c
28f05af
 
 
 
 
 
 
a0e379d
 
 
760b33c
a0e379d
 
 
760b33c
4c4a8cf
a0e379d
28f05af
 
 
a0e379d
 
 
 
 
 
760b33c
a0e379d
 
 
 
 
 
 
 
760b33c
 
a0e379d
 
 
 
 
760b33c
 
a0e379d
 
 
 
 
 
760b33c
 
a0e379d
 
 
 
 
 
 
 
 
 
760b33c
a0e379d
 
 
 
 
 
 
 
6fd4b72
a0e379d
 
 
 
 
760b33c
a0e379d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760b33c
a0e379d
760b33c
a0e379d
 
28f05af
4936922
b8a3531
 
4936922
b8a3531
 
4936922
28f05af
b8a3531
4936922
a0e379d
4c4a8cf
a0e379d
 
 
 
 
 
 
 
 
 
4c4a8cf
 
a0e379d
 
760b33c
a0e379d
760b33c
 
4c4a8cf
a0e379d
 
 
 
 
 
 
 
 
 
 
 
4c4a8cf
a0e379d
 
 
 
 
 
 
 
 
 
 
 
4c4a8cf
a0e379d
 
 
 
 
 
 
28f05af
a0e379d
28f05af
 
 
a0e379d
28f05af
a0e379d
 
 
 
4c4a8cf
a0e379d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c4a8cf
 
a0e379d
760b33c
 
a0e379d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760b33c
 
6fd4b72
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
// web/src/components/ChatArea.tsx
import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Button } from './ui/button';
import { Textarea } from './ui/textarea';
import { Send, ArrowDown, Trash2, Share2 } from 'lucide-react';
import { Message } from './Message';
import { FileUploadArea } from './FileUploadArea';
import { MemoryLine } from './MemoryLine';
import type { Message as MessageType, LearningMode, UploadedFile, FileType, SpaceType } from '../App';
import { toast } from 'sonner';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './ui/dropdown-menu';

interface ChatAreaProps {
  messages: MessageType[];
  onSendMessage: (content: string) => void;

  uploadedFiles: UploadedFile[];
  onFileUpload: (files: File[]) => void;
  onRemoveFile: (index: number) => void;
  onFileTypeChange: (index: number, type: FileType) => void;

  // ✅ feedback 需要 userId
  userId?: string;

  // ✅ 由 App.tsx 传入 currentDocTypeForChat
  docType?: string;

  memoryProgress: number;
  isLoggedIn: boolean;
  learningMode: LearningMode;
  onClearConversation: () => void;
  onLearningModeChange: (mode: LearningMode) => void;
  spaceType: SpaceType;
}

export function ChatArea({
  messages,
  onSendMessage,
  uploadedFiles,
  onFileUpload,
  onRemoveFile,
  onFileTypeChange,
  userId,
  docType = 'Other',
  memoryProgress,
  isLoggedIn,
  learningMode,
  onClearConversation,
  onLearningModeChange,
  spaceType,
}: ChatAreaProps) {
  const [input, setInput] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [showScrollButton, setShowScrollButton] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const lastUserMessageContent = useMemo(() => {
    for (let i = messages.length - 1; i >= 0; i--) {
      if (messages[i].role === 'user' && messages[i].content?.trim()) return messages[i].content;
    }
    return '';
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  useEffect(() => {
    const handleScroll = () => {
      if (!scrollContainerRef.current) return;
      const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
      setShowScrollButton(scrollHeight - scrollTop - clientHeight > 100);
    };

    const container = scrollContainerRef.current;
    container?.addEventListener('scroll', handleScroll);
    return () => container?.removeEventListener('scroll', handleScroll);
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || !isLoggedIn) return;

    onSendMessage(input);
    setInput('');
    setIsTyping(true);
    setTimeout(() => setIsTyping(false), 1200);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e);
    }
  };

  const modeLabels: Record<LearningMode, string> = {
    concept: 'Concept Explainer',
    socratic: 'Socratic Tutor',
    exam: 'Exam Prep',
    assignment: 'Assignment Helper',
    summary: 'Quick Summary',
  };

  const handleClearClick = () => {
    if (messages.length <= 1) {
      toast.info('No conversation to clear');
      return;
    }
    if (window.confirm('Are you sure you want to clear the conversation? This cannot be undone.')) {
      onClearConversation();
      toast.success('Conversation cleared');
    }
  };

  const handleShareClick = () => {
    if (messages.length <= 1) {
      toast.info('No conversation to share');
      return;
    }
    const conversationText = messages
      .map((msg) => `${msg.role === 'user' ? 'You' : 'Clare'}: ${msg.content}`)
      .join('\n\n');

    navigator.clipboard
      .writeText(conversationText)
      .then(() => toast.success('Conversation copied to clipboard!'))
      .catch(() => toast.error('Failed to copy conversation'));
  };

  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 relative border-b-2 border-border">
        {messages.length > 1 && (
          <div className="absolute top-4 right-12 z-10 flex gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleShareClick}
              disabled={!isLoggedIn}
              className="gap-2 bg-background/95 backdrop-blur-sm shadow-sm hover:shadow-md transition-all group"
            >
              <Share2 className="h-4 w-4" />
              <span className="hidden group-hover:inline">Share</span>
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleClearClick}
              disabled={!isLoggedIn}
              className="gap-2 bg-background/95 backdrop-blur-sm shadow-sm hover:shadow-md transition-all group"
            >
              <Trash2 className="h-4 w-4" />
              <span className="hidden group-hover:inline">Clear</span>
            </Button>
          </div>
        )}

        <div ref={scrollContainerRef} className="h-full max-h-[600px] overflow-y-auto px-4 py-6 pb-36">
          <div className="max-w-4xl mx-auto space-y-6">
            {messages.map((m) => (
              <Message
                key={m.id}
                message={m}
                showSenderInfo={spaceType === 'group'}
                userId={userId}
                isLoggedIn={isLoggedIn}
                learningMode={learningMode}
                docType={docType}
                lastUserText={lastUserMessageContent}
              />
            ))}

            {isTyping && (
              <div className="flex gap-3">
                <div className="w-8 h-8 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center flex-shrink-0">
                  <span className="text-white text-sm">C</span>
                </div>
                <div className="bg-muted rounded-2xl px-4 py-3">
                  <div className="flex gap-1">
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/50 animate-bounce" style={{ animationDelay: '0ms' }} />
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/50 animate-bounce" style={{ animationDelay: '150ms' }} />
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/50 animate-bounce" style={{ animationDelay: '300ms' }} />
                  </div>
                </div>
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>
        </div>

        {showScrollButton && (
          <div className="absolute bottom-24 left-1/2 -translate-x-1/2 z-20">
            <Button
              variant="secondary"
              size="icon"
              className="rounded-full shadow-lg hover:shadow-xl transition-shadow bg-background"
              onClick={scrollToBottom}
            >
              <ArrowDown className="h-4 w-4" />
            </Button>
          </div>
        )}

        <div className="absolute bottom-0 left-0 right-0 bg-background/95 backdrop-blur-sm z-10">
          <div className="max-w-4xl mx-auto px-4 py-4">
            <form onSubmit={handleSubmit}>
              <div className="relative">
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="absolute bottom-3 left-2 gap-1.5 h-8 px-2 text-xs z-10 hover:bg-muted/50"
                      disabled={!isLoggedIn}
                      type="button"
                    >
                      <span>{modeLabels[learningMode]}</span>
                      <svg className="h-3 w-3 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="start" className="w-56">
                    {(['concept', 'socratic', 'exam', 'assignment', 'summary'] as LearningMode[]).map((mode) => (
                      <DropdownMenuItem
                        key={mode}
                        onClick={() => onLearningModeChange(mode)}
                        className={learningMode === mode ? 'bg-accent' : ''}
                      >
                        <span className="font-medium">{modeLabels[mode]}</span>
                      </DropdownMenuItem>
                    ))}
                  </DropdownMenuContent>
                </DropdownMenu>

                <Textarea
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder={
                    isLoggedIn
                      ? spaceType === 'group'
                        ? 'Type a message... (mention @Clare to get AI assistance)'
                        : 'Ask Clare anything about the course...'
                      : 'Please log in on the right to start chatting...'
                  }
                  disabled={!isLoggedIn}
                  className="min-h-[80px] pl-4 pr-12 resize-none bg-background border-2 border-border"
                />
                <Button type="submit" size="icon" disabled={!input.trim() || !isLoggedIn} className="absolute bottom-2 right-2 rounded-full">
                  <Send className="h-4 w-4" />
                </Button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div className="bg-card">
        <div className="max-w-4xl mx-auto px-4 py-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <FileUploadArea
              uploadedFiles={uploadedFiles}
              onFileUpload={onFileUpload}
              onRemoveFile={onRemoveFile}
              onFileTypeChange={onFileTypeChange}
              disabled={!isLoggedIn}
            />
            <MemoryLine progress={memoryProgress} />
          </div>
        </div>
      </div>
    </div>
  );
}