Affect-Atlas / code /frontend /apps /web /src /components /emotion-timeline-chart.tsx
Jiali9's picture
Publish Affect-Atlas manuscript, figures, and demo source
891fa77 verified
Raw History Blame Contribute Delete
15.3 kB
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Info } from 'lucide-react'
import { Alert, AlertDescription, AlertTitle } from '@workspace/ui/components/alert'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@workspace/ui/components/card'
import type { Prediction, TimelinePoint } from '@/lib/api'
import { formatSeconds, formatScore } from '@/lib/timeline'
interface Props {
result: Prediction | null
currentTime: number
onSeek: (time: number) => void
lang?: 'zh' | 'en' // kept for compatibility but now uses i18next directly
}
interface Tooltip {
x: number
y: number
time: number
arousal: number
visible: boolean
}
export function EmotionTimelineChart({ result, currentTime, onSeek }: Props) {
const { t } = useTranslation()
const points = result?.timeline?.points ?? []
const svgRef = useRef<SVGSVGElement>(null)
const [tooltip, setTooltip] = useState<Tooltip>({ x: 0, y: 0, time: 0, arousal: 0, visible: false })
// Calculate dimensions
const duration = Math.max(1, result?.duration_seconds ?? 1, ...points.map(p => p.end_seconds))
const viewBox = { width: 1000, height: 300 }
const margin = { left: 60, right: 40, top: 30, bottom: 50 }
const graphWidth = viewBox.width - margin.left - margin.right
const graphHeight = viewBox.height - margin.top - margin.bottom
// Get Arousal data range
const arousalValues = points.map(p => p.arousal)
const minArousal = arousalValues.length ? Math.min(-1, ...arousalValues) : -1
const maxArousal = arousalValues.length ? Math.max(1, ...arousalValues) : 1
const arousalRange = maxArousal - minArousal
// Transform functions
const xScale = (time: number) => margin.left + (time / duration) * graphWidth
const yScale = (arousal: number) => margin.top + graphHeight - ((arousal - minArousal) / arousalRange) * graphHeight
// Generate smooth curve path
const generateCurvePath = () => {
if (points.length === 0) return ''
if (points.length === 1) {
const x = xScale(points[0].center_seconds)
const y = yScale(points[0].arousal)
return `M ${x} ${y}`
}
let path = ''
for (let i = 0; i < points.length; i++) {
const p = points[i]
const x = xScale(p.center_seconds)
const y = yScale(p.arousal)
if (i === 0) {
path += `M ${x} ${y}`
} else {
// Quadratic Bezier curve for smooth connection
const prevP = points[i - 1]
const prevX = xScale(prevP.center_seconds)
const prevY = yScale(prevP.arousal)
const ctrlX = (prevX + x) / 2
const ctrlY = (prevY + y) / 2
path += ` Q ${ctrlX} ${ctrlY} ${x} ${y}`
}
}
return path
}
// Generate gradient fill path (closed area)
const generateFillPath = () => {
if (points.length === 0) return ''
let path = generateCurvePath()
const lastX = xScale(points[points.length - 1].center_seconds)
const bottomY = margin.top + graphHeight
path += ` L ${lastX} ${bottomY}`
if (points.length > 0) {
const firstX = xScale(points[0].center_seconds)
path += ` L ${firstX} ${bottomY} Z`
}
return path
}
// Handle mouse move for tooltip
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
if (!svgRef.current || points.length === 0) return
const rect = svgRef.current.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const mouseY = e.clientY - rect.top
// Convert mouse position to SVG coordinates
const svgX = (mouseX / rect.width) * viewBox.width
const svgY = (mouseY / rect.height) * viewBox.height
// Check if within graph area
if (
svgX < margin.left ||
svgX > margin.left + graphWidth ||
svgY < margin.top ||
svgY > margin.top + graphHeight
) {
setTooltip(prev => ({ ...prev, visible: false }))
return
}
// Find nearest point
let nearestPoint: TimelinePoint | null = null
let minDist = Infinity
for (const p of points) {
const pX = xScale(p.center_seconds)
const dist = Math.abs(pX - svgX)
if (dist < minDist && dist < 30) {
minDist = dist
nearestPoint = p
}
}
if (nearestPoint) {
const pX = xScale(nearestPoint.center_seconds)
const pY = yScale(nearestPoint.arousal)
setTooltip({
x: pX,
y: pY,
time: nearestPoint.center_seconds,
arousal: nearestPoint.arousal,
visible: true,
})
} else {
setTooltip(prev => ({ ...prev, visible: false }))
}
}
const handleMouseLeave = () => {
setTooltip(prev => ({ ...prev, visible: false }))
}
// Handle click to seek
const handleClick = (e: React.MouseEvent<SVGSVGElement>) => {
if (!svgRef.current) return
const rect = svgRef.current.getBoundingClientRect()
const mouseX = e.clientX - rect.left
const svgX = (mouseX / rect.width) * viewBox.width
if (svgX < margin.left || svgX > margin.left + graphWidth) return
const seekTime = ((svgX - margin.left) / graphWidth) * duration
onSeek(Math.max(0, Math.min(duration, seekTime)))
}
// Remove old labels object since we now use t() directly
// Current playhead position
const playheadX = xScale(Math.max(0, Math.min(duration, currentTime)))
const playheadY = margin.top + graphHeight
// Find arousal value at current time (interpolated or from nearest point)
const getCurrentArousal = () => {
if (points.length === 0) return null
if (points.length === 1) return points[0].arousal
for (let i = 0; i < points.length - 1; i++) {
if (currentTime >= points[i].center_seconds && currentTime <= points[i + 1].center_seconds) {
const ratio =
(currentTime - points[i].center_seconds) / (points[i + 1].center_seconds - points[i].center_seconds)
return points[i].arousal + ratio * (points[i + 1].arousal - points[i].arousal)
}
}
return points[points.length - 1].arousal
}
const currentArousal = getCurrentArousal()
const currentArousalY = currentArousal !== null ? yScale(currentArousal) : playheadY
return (
<section aria-label={t('timeline.title')} className="timeline-section" style={{ marginTop: 24 }}>
<Card className="panel timeline-chart-panel">
<CardHeader>
<div className="result-heading">
<div>
<div className="section-number">04 / {t('timeline.title')}</div>
<CardTitle>{t('timeline.title')}</CardTitle>
</div>
</div>
<CardDescription>{t('timeline.desc')}</CardDescription>
</CardHeader>
<CardContent>
<Alert className="timeline-notice">
<Info />
<AlertTitle>{t('timeline.arousal')}</AlertTitle>
<AlertDescription>{t('timeline.helpText')}</AlertDescription>
</Alert>
{points.length === 0 ? (
<div
className="timeline-empty"
style={{
minHeight: 200,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--ocean-text-dim)',
textAlign: 'center',
}}
>
{result ? result.timeline ? t('timeline.empty') : t('timeline.waiting') : t('timeline.waiting')}
</div>
) : (
<div
className="timeline-chart-container"
style={{
overflowX: 'auto',
marginTop: 16,
marginBottom: 16,
border: '1px solid var(--chart-grid)',
borderRadius: 8,
background: 'var(--ocean-surface)',
}}
>
<svg
ref={svgRef}
viewBox={`0 0 ${viewBox.width} ${viewBox.height}`}
role="img"
aria-label={`${t('timeline.title')}: ${t('timeline.time')} (s), ${t('timeline.arousal')} (${minArousal.toFixed(2)} - ${maxArousal.toFixed(2)})`}
className="timeline-chart"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={handleClick}
style={{
cursor: 'crosshair',
display: 'block',
minWidth: '100%',
height: 'auto',
}}
>
<defs>
<linearGradient id="arousal-gradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="var(--chart-arousal)" stopOpacity="0.2" />
<stop offset="1" stopColor="var(--chart-arousal)" stopOpacity="0" />
</linearGradient>
</defs>
{/* Grid lines */}
{[0, 1, 2, 3, 4].map(i => {
const arousal = minArousal + (arousalRange * i) / 4
const y = yScale(arousal)
return (
<g key={`grid-${i}`}>
<line
x1={margin.left}
x2={margin.left + graphWidth}
y1={y}
y2={y}
stroke="var(--chart-grid)"
strokeWidth="1"
strokeDasharray="4 4"
/>
<text x={margin.left - 8} y={y + 4} textAnchor="end" className="tick" fontSize="12" fill="var(--ocean-text-muted)">
{arousal.toFixed(2)}
</text>
</g>
)
})}
{/* Time labels */}
{[0, 1, 2, 3, 4].map(i => {
const time = (duration * i) / 4
const x = xScale(time)
return (
<text
key={`time-${i}`}
x={x}
y={margin.top + graphHeight + 20}
textAnchor="middle"
className="tick"
fontSize="12"
fill="var(--ocean-text-muted)"
>
{time.toFixed(1)}s
</text>
)
})}
{/* Y-axis */}
<line
x1={margin.left}
y1={margin.top}
x2={margin.left}
y2={margin.top + graphHeight}
stroke="var(--chart-axis)"
strokeWidth="1.5"
/>
{/* X-axis */}
<line
x1={margin.left}
y1={margin.top + graphHeight}
x2={margin.left + graphWidth}
y2={margin.top + graphHeight}
stroke="var(--chart-axis)"
strokeWidth="1.5"
/>
{/* Arousal curve fill */}
{points.length > 0 && (
<path d={generateFillPath()} fill="url(#arousal-gradient)" />
)}
{/* Arousal curve */}
{points.length > 0 && (
<path
d={generateCurvePath()}
fill="none"
stroke="var(--chart-arousal)"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
)}
{/* Data points */}
{points.map(point => (
<circle
key={point.index}
cx={xScale(point.center_seconds)}
cy={yScale(point.arousal)}
r="4"
fill="var(--chart-arousal)"
stroke="var(--pearl)"
strokeWidth="2"
style={{ cursor: 'pointer' }}
/>
))}
{/* Playhead line */}
<line
x1={playheadX}
x2={playheadX}
y1={margin.top}
y2={margin.top + graphHeight}
stroke="var(--chart-arousal)"
strokeWidth="1.5"
strokeDasharray="4 4"
opacity="0.7"
data-testid="timeline-playhead"
/>
{/* Playhead dot at curve intersection */}
{currentArousal !== null && (
<circle
cx={playheadX}
cy={currentArousalY}
r="5"
fill="var(--chart-arousal)"
stroke="var(--pearl)"
strokeWidth="2"
opacity="0.9"
/>
)}
{/* Tooltip */}
{tooltip.visible && (
<g>
<rect
x={tooltip.x + 10}
y={tooltip.y - 40}
width="120"
height="36"
rx="4"
fill="var(--pearl)"
stroke="var(--chart-grid)"
strokeWidth="1"
/>
<text
x={tooltip.x + 16}
y={tooltip.y - 24}
fontSize="12"
fill="var(--ocean-text)"
fontWeight="500"
>
{formatSeconds(tooltip.time)}
</text>
<text x={tooltip.x + 16} y={tooltip.y - 12} fontSize="12" fill="var(--ocean-text-muted)">
A: {formatScore(tooltip.arousal)}
</text>
</g>
)}
{/* Axis labels */}
<text
x={margin.left + graphWidth / 2}
y={viewBox.height - 8}
textAnchor="middle"
className="axis"
fontSize="13"
fill="var(--ocean-text-muted)"
fontWeight="500"
>
{t('timeline.time')}
</text>
<text
x={16}
y={margin.top + graphHeight / 2}
textAnchor="middle"
transform={`rotate(-90 16 ${margin.top + graphHeight / 2})`}
className="axis"
fontSize="13"
fill="var(--ocean-text-muted)"
fontWeight="500"
>
{t('timeline.arousal')}
</text>
</svg>
</div>
)}
{points.length > 0 && (
<p
className="window-help"
style={{
fontSize: '13px',
color: 'var(--ocean-text-dim)',
marginTop: 12,
}}
>
{t('timeline.clickHelp')}
</p>
)}
</CardContent>
</Card>
</section>
)
}