333 lines
13 KiB
TypeScript
333 lines
13 KiB
TypeScript
import { useState, useEffect, useRef, useCallback } from 'react'
|
|
import { TrendingUp, Clock, Sparkles, MessageSquarePlus, Loader2, Plus, X, Send } from 'lucide-react'
|
|
import { summariesApi, type Summary } from '@/api/summaries'
|
|
import { reportsApi } from '@/api/reports'
|
|
import { assetsApi, type Asset } from '@/api/assets'
|
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { Spinner } from '@/components/ui/spinner'
|
|
import { useAuth } from '@/lib/auth'
|
|
|
|
// ── Text-selection floating button ─────────────────────────────────────────
|
|
|
|
function useTextSelection(containerRef: React.RefObject<HTMLElement>) {
|
|
const [selection, setSelection] = useState<{ text: string; x: number; y: number } | null>(null)
|
|
|
|
useEffect(() => {
|
|
function onMouseUp() {
|
|
const sel = window.getSelection()
|
|
const text = sel?.toString().trim()
|
|
if (!text || !containerRef.current) { setSelection(null); return }
|
|
const range = sel!.getRangeAt(0)
|
|
const rect = range.getBoundingClientRect()
|
|
const containerRect = containerRef.current.getBoundingClientRect()
|
|
setSelection({
|
|
text,
|
|
x: rect.left - containerRect.left + rect.width / 2,
|
|
y: rect.top - containerRect.top - 8,
|
|
})
|
|
}
|
|
function onMouseDown(e: MouseEvent) {
|
|
if (!(e.target as Element).closest('[data-context-action]')) setSelection(null)
|
|
}
|
|
document.addEventListener('mouseup', onMouseUp)
|
|
document.addEventListener('mousedown', onMouseDown)
|
|
return () => {
|
|
document.removeEventListener('mouseup', onMouseUp)
|
|
document.removeEventListener('mousedown', onMouseDown)
|
|
}
|
|
}, [containerRef])
|
|
|
|
return selection
|
|
}
|
|
|
|
// ── Context panel (extraits + question) ────────────────────────────────────
|
|
|
|
function ContextPanel({
|
|
excerpts,
|
|
onRemove,
|
|
onClear,
|
|
onSubmit,
|
|
}: {
|
|
excerpts: string[]
|
|
onRemove: (i: number) => void
|
|
onClear: () => void
|
|
onSubmit: (question: string) => Promise<void>
|
|
}) {
|
|
const [question, setQuestion] = useState('')
|
|
const [submitting, setSubmitting] = useState(false)
|
|
const [submitted, setSubmitted] = useState(false)
|
|
|
|
async function submit() {
|
|
if (!question.trim() || submitting) return
|
|
setSubmitting(true)
|
|
try {
|
|
await onSubmit(question)
|
|
setSubmitted(true)
|
|
setQuestion('')
|
|
setTimeout(() => setSubmitted(false), 2000)
|
|
} finally {
|
|
setSubmitting(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className="fixed bottom-4 right-4 z-40 w-96 max-h-[70vh] flex flex-col bg-card border rounded-xl shadow-2xl overflow-hidden">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between px-4 py-3 border-b bg-primary/5">
|
|
<span className="text-sm font-semibold flex items-center gap-2">
|
|
<MessageSquarePlus className="h-4 w-4 text-primary" />
|
|
Contexte ({excerpts.length} extrait{excerpts.length > 1 ? 's' : ''})
|
|
</span>
|
|
<button onClick={onClear} className="text-xs text-muted-foreground hover:text-destructive transition-colors">
|
|
Tout effacer
|
|
</button>
|
|
</div>
|
|
|
|
{/* Extraits */}
|
|
<div className="flex-1 overflow-y-auto px-4 py-3 space-y-2 min-h-0">
|
|
{excerpts.map((e, i) => (
|
|
<div key={i} className="flex items-start gap-2 group">
|
|
<div className="flex-1 rounded bg-muted/60 px-2 py-1.5 text-xs text-muted-foreground italic line-clamp-3">
|
|
« {e} »
|
|
</div>
|
|
<button
|
|
onClick={() => onRemove(i)}
|
|
className="mt-1 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground hover:text-destructive"
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
|
|
{/* Question */}
|
|
<div className="border-t px-4 py-3 space-y-2">
|
|
<textarea
|
|
className="w-full rounded border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring resize-none"
|
|
rows={2}
|
|
placeholder="Votre question…"
|
|
value={question}
|
|
onChange={e => setQuestion(e.target.value)}
|
|
onKeyDown={e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit() }}
|
|
/>
|
|
<Button size="sm" className="w-full" onClick={submit} disabled={!question.trim() || submitting || submitted}>
|
|
{submitting
|
|
? <><Loader2 className="h-3 w-3 animate-spin" /> Envoi…</>
|
|
: submitted
|
|
? 'Envoyé !'
|
|
: <><Send className="h-3 w-3" /> Envoyer (Ctrl+Entrée)</>}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ── Summary content renderer ────────────────────────────────────────────────
|
|
|
|
function SummaryContent({ content }: { content: string }) {
|
|
const lines = content.split('\n')
|
|
return (
|
|
<div className="space-y-2 text-sm leading-relaxed select-text">
|
|
{lines.map((line, i) => {
|
|
if (line.startsWith('## ')) return <h2 key={i} className="text-base font-semibold mt-4 first:mt-0">{line.slice(3)}</h2>
|
|
if (line.startsWith('### ')) return <h3 key={i} className="font-medium mt-3">{line.slice(4)}</h3>
|
|
if (line.startsWith('- ')) return <li key={i} className="ml-4 text-muted-foreground">{line.slice(2)}</li>
|
|
if (line.startsWith('**') && line.endsWith('**')) return <p key={i} className="font-semibold">{line.slice(2, -2)}</p>
|
|
if (line.trim() === '') return <div key={i} className="h-1" />
|
|
return <p key={i} className="text-muted-foreground">{line}</p>
|
|
})}
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// ── Dashboard ───────────────────────────────────────────────────────────────
|
|
|
|
export function Dashboard() {
|
|
const { user } = useAuth()
|
|
const [summaries, setSummaries] = useState<Summary[]>([])
|
|
const [assets, setAssets] = useState<Asset[]>([])
|
|
const [loading, setLoading] = useState(true)
|
|
const [generating, setGenerating] = useState(false)
|
|
const [current, setCurrent] = useState<Summary | null>(null)
|
|
const [excerpts, setExcerpts] = useState<string[]>([])
|
|
|
|
const summaryRef = useRef<HTMLDivElement>(null)
|
|
const textSel = useTextSelection(summaryRef as React.RefObject<HTMLElement>)
|
|
|
|
useEffect(() => { load() }, [])
|
|
|
|
// Poll generating status every 5s
|
|
useEffect(() => {
|
|
const interval = setInterval(async () => {
|
|
try {
|
|
const status = await summariesApi.status()
|
|
const wasGenerating = generating
|
|
setGenerating(status.generating)
|
|
if (wasGenerating && !status.generating) load()
|
|
} catch { /* ignore */ }
|
|
}, 5000)
|
|
return () => clearInterval(interval)
|
|
}, [generating])
|
|
|
|
async function load() {
|
|
setLoading(true)
|
|
try {
|
|
const [s, a] = await Promise.all([summariesApi.list(5), assetsApi.list()])
|
|
setSummaries(s ?? [])
|
|
setAssets(a ?? [])
|
|
setCurrent(s?.[0] ?? null)
|
|
} finally { setLoading(false) }
|
|
}
|
|
|
|
async function generate() {
|
|
setGenerating(true)
|
|
try {
|
|
const s = await summariesApi.generate()
|
|
setSummaries(prev => [s, ...prev])
|
|
setCurrent(s)
|
|
} catch (e) {
|
|
alert(e instanceof Error ? e.message : 'Erreur lors de la génération')
|
|
} finally { setGenerating(false) }
|
|
}
|
|
|
|
const addExcerpt = useCallback(() => {
|
|
if (!textSel) return
|
|
setExcerpts(prev => [...prev, textSel.text])
|
|
window.getSelection()?.removeAllRanges()
|
|
}, [textSel])
|
|
|
|
async function submitQuestion(question: string) {
|
|
await reportsApi.create({
|
|
summary_id: current?.id,
|
|
excerpts,
|
|
question,
|
|
})
|
|
setExcerpts([])
|
|
}
|
|
|
|
return (
|
|
<div className="p-4 md:p-6 space-y-6">
|
|
{/* Generating banner */}
|
|
{generating && (
|
|
<div className="flex items-center gap-3 rounded-md bg-primary/10 border border-primary/20 px-4 py-3 text-sm text-primary">
|
|
<Loader2 className="h-4 w-4 animate-spin shrink-0" />
|
|
Génération d'un résumé IA en cours — cela peut prendre plusieurs minutes…
|
|
</div>
|
|
)}
|
|
|
|
{/* Header */}
|
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
|
<div>
|
|
<h1 className="text-2xl font-bold">Bonjour 👋</h1>
|
|
<p className="text-muted-foreground text-sm">{user?.email}</p>
|
|
</div>
|
|
<Button onClick={generate} disabled={generating || assets.length === 0}>
|
|
{generating ? <><Spinner className="h-4 w-4" /> Génération…</> : <><Sparkles className="h-4 w-4" /> Générer un résumé</>}
|
|
</Button>
|
|
</div>
|
|
|
|
{assets.length === 0 && !loading && (
|
|
<Card className="border-dashed">
|
|
<CardContent className="py-8 text-center">
|
|
<TrendingUp className="h-10 w-10 mx-auto text-muted-foreground mb-3" />
|
|
<p className="font-medium">Votre watchlist est vide</p>
|
|
<p className="text-sm text-muted-foreground mt-1">Ajoutez des symboles dans la section Watchlist pour obtenir des résumés personnalisés</p>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
{assets.length > 0 && (
|
|
<div className="flex flex-wrap gap-2">
|
|
{assets.map(a => (
|
|
<Badge key={a.id} variant="secondary" className="font-mono">{a.symbol}</Badge>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{/* Résumé actuel */}
|
|
<div className="grid gap-6 lg:grid-cols-3">
|
|
<div className="lg:col-span-2 space-y-4">
|
|
{loading ? (
|
|
<div className="flex justify-center py-20"><Spinner /></div>
|
|
) : current ? (
|
|
<Card>
|
|
<CardHeader>
|
|
<div className="flex items-center justify-between">
|
|
<CardTitle className="flex items-center gap-2">
|
|
<Sparkles className="h-5 w-5 text-primary" /> Résumé IA
|
|
</CardTitle>
|
|
<div className="flex items-center gap-1 text-xs text-muted-foreground">
|
|
<Clock className="h-3 w-3" />
|
|
{new Date(current.generated_at).toLocaleString('fr-FR')}
|
|
</div>
|
|
</div>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<div ref={summaryRef} className="relative">
|
|
<SummaryContent content={current.content} />
|
|
{textSel && (
|
|
<button
|
|
data-context-action
|
|
onClick={addExcerpt}
|
|
className="absolute z-10 flex items-center gap-1 rounded-full bg-primary text-primary-foreground text-xs px-2 py-1 shadow-lg hover:bg-primary/90 transition-colors"
|
|
style={{ left: textSel.x, top: textSel.y, transform: 'translate(-50%, -100%)' }}
|
|
>
|
|
<Plus className="h-3 w-3" />
|
|
Ajouter au contexte
|
|
</button>
|
|
)}
|
|
</div>
|
|
<p className="text-xs text-muted-foreground mt-4 italic">
|
|
Sélectionnez du texte pour l'ajouter au contexte, puis posez une question dans le panneau qui apparaît.
|
|
</p>
|
|
</CardContent>
|
|
</Card>
|
|
) : (
|
|
<Card className="border-dashed">
|
|
<CardContent className="py-12 text-center text-muted-foreground">
|
|
<Sparkles className="h-8 w-8 mx-auto mb-3 opacity-50" />
|
|
<p>Aucun résumé disponible</p>
|
|
<p className="text-xs mt-1">Cliquez sur "Générer un résumé" pour commencer</p>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
</div>
|
|
|
|
{/* Historique résumés */}
|
|
{summaries.length > 1 && (
|
|
<div className="space-y-3">
|
|
<h2 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">Historique</h2>
|
|
{summaries.slice(1).map(s => (
|
|
<Card
|
|
key={s.id}
|
|
className={`cursor-pointer transition-colors hover:border-primary/50 ${current?.id === s.id ? 'border-primary/50' : ''}`}
|
|
onClick={() => setCurrent(s)}
|
|
>
|
|
<CardContent className="py-3">
|
|
<div className="flex items-center gap-1 text-xs text-muted-foreground mb-1">
|
|
<Clock className="h-3 w-3" />
|
|
{new Date(s.generated_at).toLocaleString('fr-FR')}
|
|
</div>
|
|
<p className="text-sm line-clamp-3">{s.content.slice(0, 120)}…</p>
|
|
</CardContent>
|
|
</Card>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Panneau contexte flottant */}
|
|
{excerpts.length > 0 && (
|
|
<ContextPanel
|
|
excerpts={excerpts}
|
|
onRemove={i => setExcerpts(prev => prev.filter((_, idx) => idx !== i))}
|
|
onClear={() => setExcerpts([])}
|
|
onSubmit={submitQuestion}
|
|
/>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|