Spaces:
Running
Running
File size: 18,482 Bytes
bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 0d1eaa3 bc04957 | 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 | import React, { useState, useRef, useEffect } from 'react';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Card } from './ui/card';
import { Separator } from './ui/separator';
import { Textarea } from './ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
import {
LogIn,
LogOut,
Download,
Sparkles,
Bookmark,
Copy,
Volume2,
Podcast
} from 'lucide-react';
import { apiTts, apiPodcast, TTS_VOICES } from '../lib/api';
import { Document, HeadingLevel, Packer, Paragraph, TextRun } from 'docx';
import type { User, SavedItem } from '../App';
import { toast } from 'sonner';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
DialogFooter,
} from './ui/dialog';
interface RightPanelProps {
user: User | null;
onLogin: (user: User) => void;
onLogout: () => void;
isLoggedIn: boolean;
onClose?: () => void;
exportResult: string;
setExportResult: (result: string) => void;
resultType: 'export' | 'quiz' | 'summary' | null;
setResultType: (type: 'export' | 'quiz' | 'summary' | null) => void;
onExport: () => void;
onSummary: () => void;
onSave: (content: string, type: 'export' | 'quiz' | 'summary') => void;
savedItems: SavedItem[];
}
export function RightPanel({ user, onLogin, onLogout, isLoggedIn, onClose, exportResult, setExportResult, resultType, setResultType, onExport, onSummary, onSave, savedItems }: RightPanelProps) {
const [showLoginForm, setShowLoginForm] = useState(false);
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [isExpanded, setIsExpanded] = useState(true);
const [isDownloading, setIsDownloading] = useState(false);
const [copied, setCopied] = useState(false);
const [audioUrl, setAudioUrl] = useState<string | null>(null);
const [loadingTts, setLoadingTts] = useState(false);
const [loadingPodcast, setLoadingPodcast] = useState(false);
const [ttsVoice, setTtsVoice] = useState<string>('nova');
const [podcastTitle, setPodcastTitle] = useState<string>('');
const lastAudioBlobRef = useRef<{ blob: Blob; kind: 'tts' | 'podcast'; label?: string } | null>(null);
const audioRef = useRef<HTMLAudioElement>(null);
// Revoke object URL on unmount or when changing
useEffect(() => {
return () => {
if (audioUrl) URL.revokeObjectURL(audioUrl);
};
}, [audioUrl]);
const handleDownloadAudio = () => {
const cur = lastAudioBlobRef.current;
if (!cur?.blob) return;
const base = cur.kind === 'podcast' ? 'clare-podcast' : 'clare-tts';
const label = cur.kind === 'podcast' && cur.label ? `-${cur.label.replace(/\s+/g, '-').slice(0, 30)}` : '';
const name = `${base}${label}-${formatDateStamp()}.mp3`;
downloadBlob(cur.blob, name);
toast.success('Audio downloaded');
};
// Check if current result is already saved
const isSaved = exportResult && resultType
? savedItems.some(item => item.content === exportResult && item.type === resultType)
: false;
const handleLogin = () => {
if (!name.trim() || !email.trim()) {
toast.error('Please fill in all fields');
return;
}
onLogin({ name: name.trim(), email: email.trim() });
setShowLoginForm(false);
setName('');
setEmail('');
toast.success(`Welcome, ${name}!`);
};
const handleLogout = () => {
onLogout();
setShowLoginForm(false);
toast.success('Logged out successfully');
};
const scrollContainerRef = useRef<HTMLDivElement>(null);
// Use native event listeners to prevent scroll propagation
useEffect(() => {
const container = scrollContainerRef.current;
if (!container) return;
const handleWheel = (e: WheelEvent) => {
// Always stop propagation to prevent scrolling other panels
e.stopPropagation();
e.stopImmediatePropagation();
// Only prevent default if we're at the boundaries
const { scrollTop, scrollHeight, clientHeight } = container;
const isScrollable = scrollHeight > clientHeight;
const isAtTop = scrollTop === 0;
const isAtBottom = scrollTop + clientHeight >= scrollHeight - 1;
// If scrolling up at top or down at bottom, prevent default to stop propagation
if (isScrollable && ((isAtTop && e.deltaY < 0) || (isAtBottom && e.deltaY > 0))) {
e.preventDefault();
}
};
container.addEventListener('wheel', handleWheel, { passive: false, capture: true });
return () => {
container.removeEventListener('wheel', handleWheel, { capture: true });
};
}, []);
const downloadBlob = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
};
const formatDateStamp = () => {
const d = new Date();
const yyyy = d.getFullYear();
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}`;
};
const getDefaultFilenameBase = () => {
const kind =
resultType === 'export' ? 'export' :
resultType === 'summary' ? 'summary' :
'result';
return `clare-${kind}-${formatDateStamp()}`;
};
const handleDownloadMd = async () => {
if (!exportResult) return;
try {
setIsDownloading(true);
toast.message('Preparing .md…');
const blob = new Blob([exportResult], { type: 'text/markdown;charset=utf-8' });
downloadBlob(blob, `${getDefaultFilenameBase()}.md`);
toast.success('Downloaded .md');
} catch (e) {
console.error(e);
toast.error('Failed to download .md');
} finally {
setIsDownloading(false);
}
};
const handleListenTts = async () => {
if (!exportResult?.trim() || !user?.email) return;
if (audioUrl) URL.revokeObjectURL(audioUrl);
setAudioUrl(null);
lastAudioBlobRef.current = null;
try {
setLoadingTts(true);
toast.message('Generating speech…');
const blob = await apiTts({ user_id: user.email, text: exportResult, voice: ttsVoice });
lastAudioBlobRef.current = { blob, kind: 'tts' };
const url = URL.createObjectURL(blob);
setAudioUrl(url);
toast.success('Ready. Use the player below or download.');
setTimeout(() => audioRef.current?.play(), 100);
} catch (e) {
console.error(e);
toast.error(e instanceof Error ? e.message : 'TTS failed');
} finally {
setLoadingTts(false);
}
};
const handleGeneratePodcast = async (source: 'summary' | 'conversation') => {
if (!user?.email) return;
if (audioUrl) URL.revokeObjectURL(audioUrl);
setAudioUrl(null);
lastAudioBlobRef.current = null;
try {
setLoadingPodcast(true);
toast.message(source === 'summary' ? '正在从摘要生成播客…' : '正在从对话生成播客…');
const blob = await apiPodcast({
user_id: user.email,
source,
voice: ttsVoice,
title: podcastTitle.trim() || undefined,
});
lastAudioBlobRef.current = {
blob,
kind: 'podcast',
label: source === 'summary' ? 'summary' : 'conversation',
};
const url = URL.createObjectURL(blob);
setAudioUrl(url);
toast.success('Podcast ready. Use the player below or download .mp3.');
setTimeout(() => audioRef.current?.play(), 100);
} catch (e) {
console.error(e);
toast.error(e instanceof Error ? e.message : '播客生成失败');
} finally {
setLoadingPodcast(false);
}
};
const handleDownloadDocx = async () => {
if (!exportResult) return;
try {
setIsDownloading(true);
toast.message('Preparing .docx…');
const lines = exportResult.split('\n');
const paragraphs: Paragraph[] = lines.map((line) => {
const trimmed = line.trim();
if (!trimmed) return new Paragraph({ text: '' });
// Basic markdown-ish heading support
if (trimmed.startsWith('### ')) {
return new Paragraph({ text: trimmed.replace(/^###\s+/, ''), heading: HeadingLevel.HEADING_3 });
}
if (trimmed.startsWith('## ')) {
return new Paragraph({ text: trimmed.replace(/^##\s+/, ''), heading: HeadingLevel.HEADING_2 });
}
if (trimmed.startsWith('# ')) {
return new Paragraph({ text: trimmed.replace(/^#\s+/, ''), heading: HeadingLevel.HEADING_1 });
}
return new Paragraph({ children: [new TextRun({ text: line })] });
});
const doc = new Document({
sections: [{ properties: {}, children: paragraphs }],
});
const blob = await Packer.toBlob(doc);
downloadBlob(blob, `${getDefaultFilenameBase()}.docx`);
toast.success('Downloaded .docx');
} catch (e) {
console.error(e);
toast.error('Failed to download .docx');
} finally {
setIsDownloading(false);
}
};
return (
<div
ref={scrollContainerRef}
className="flex-1 overflow-auto overscroll-contain flex flex-col"
style={{ overscrollBehavior: 'contain' }}
>
<div className="p-4 space-y-4">
{isExpanded && (
<>
{/* Actions Section with Results */}
<div className="space-y-3">
<h3 className="text-base font-medium">Export / Summarize Conversation</h3>
<Card className="p-4 bg-muted/30">
<div className="flex flex-col gap-3">
<Button
variant="outline"
className="w-full h-12 rounded-lg justify-start gap-3"
onClick={onExport}
disabled={!isLoggedIn}
>
<Download className="h-5 w-5" />
<span>Export</span>
</Button>
<Button
variant="outline"
className="w-full h-12 rounded-lg justify-start gap-3"
onClick={onSummary}
disabled={!isLoggedIn}
>
<Sparkles className="h-5 w-5" />
<span>Summarize</span>
</Button>
<Separator className="my-1" />
<h4 className="text-sm font-medium text-muted-foreground">Listen & Podcast</h4>
<p className="text-xs text-muted-foreground">Generate audio from export/summary (TTS) or turn your session into a podcast.</p>
<div className="flex items-center gap-2">
<Label className="text-xs shrink-0">Voice</Label>
<Select value={ttsVoice} onValueChange={setTtsVoice}>
<SelectTrigger className="h-9 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
{TTS_VOICES.map((v) => (
<SelectItem key={v} value={v} className="text-xs">
{v}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<Button
variant="outline"
className="w-full h-10 rounded-lg justify-start gap-3"
onClick={handleListenTts}
disabled={!isLoggedIn || !exportResult?.trim() || loadingTts}
>
<Volume2 className="h-4 w-4" />
<span>{loadingTts ? 'Generating…' : 'Listen (TTS)'}</span>
</Button>
<p className="text-xs text-muted-foreground">Convert current export/summary to speech. Export or summarize first.</p>
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">Podcast intro title (optional)</Label>
<Input
placeholder="e.g. Module 10 Review Podcast"
value={podcastTitle}
onChange={(e) => setPodcastTitle(e.target.value)}
className="h-9 text-xs"
/>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
className="flex-1 h-10 rounded-lg justify-center gap-2"
onClick={() => handleGeneratePodcast('summary')}
disabled={!isLoggedIn || loadingPodcast}
title="Generate podcast from session summary"
>
<Podcast className="h-4 w-4" />
{loadingPodcast ? '…' : 'Podcast (Summary)'}
</Button>
<Button
variant="outline"
size="sm"
className="flex-1 h-10 rounded-lg justify-center gap-2"
onClick={() => handleGeneratePodcast('conversation')}
disabled={!isLoggedIn || loadingPodcast}
title="Generate podcast from full Q&A"
>
<Podcast className="h-4 w-4" />
{loadingPodcast ? '…' : 'Podcast (Chat)'}
</Button>
</div>
<p className="text-xs text-muted-foreground">Summary: summarize then read aloud. Chat: full conversation as Q&A podcast.</p>
{audioUrl && (
<div className="pt-2 space-y-2">
<audio
ref={audioRef}
src={audioUrl}
controls
className="w-full h-10"
/>
<Button
variant="secondary"
size="sm"
className="w-full gap-2"
onClick={handleDownloadAudio}
>
<Download className="h-4 w-4" />
Download .mp3
</Button>
</div>
)}
{/* Results - Expanded from buttons */}
{exportResult && (
<>
<Separator className="my-2" />
<div className="space-y-3">
<div className="flex items-center justify-between gap-2">
<h4 className="text-base font-bold">
{resultType === 'export' && 'Exported Conversation'}
{resultType === 'quiz' && 'Micro-Quiz'}
{resultType === 'summary' && 'Summarization'}
</h4>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={isDownloading}
onClick={handleDownloadMd}
title="Download as .md"
className="h-7 px-2 text-xs gap-1.5"
>
<Download className="h-3 w-3" />
.md
</Button>
<Button
variant="outline"
size="sm"
disabled={isDownloading}
onClick={handleDownloadDocx}
title="Download as .docx"
className="h-7 px-2 text-xs gap-1.5"
>
<Download className="h-3 w-3" />
.docx
</Button>
<Button
variant="outline"
size="sm"
onClick={async () => {
await navigator.clipboard.writeText(exportResult);
setCopied(true);
toast.success('Copied to clipboard!');
setTimeout(() => setCopied(false), 2000);
}}
disabled={isDownloading}
className="h-7 px-2 text-xs gap-1.5"
title="Copy"
>
<Copy className="h-3 w-3" />
</Button>
{resultType && (
<Button
variant="outline"
size="sm"
onClick={() => {
if (resultType) {
onSave(exportResult, resultType);
}
}}
disabled={isDownloading || !resultType}
className={`h-7 px-2 text-xs gap-1.5 ${isSaved ? 'bg-red-50 dark:bg-red-950/20 border-red-300 dark:border-red-800' : ''}`}
title={isSaved ? 'Unsave' : 'Save for later'}
>
<Bookmark className={`h-3 w-3 ${isSaved ? 'fill-red-600 text-red-600' : ''}`} />
</Button>
)}
</div>
</div>
<div className={`text-sm whitespace-pre-wrap text-foreground p-3 rounded-lg ${
isSaved ? 'bg-red-50/50 dark:bg-red-950/10' : ''
}`}>
{exportResult}
</div>
</div>
</>
)}
</div>
</Card>
</div>
</>
)}
</div>
</div>
);
} |