Files
trumpsignal-monorepo/apps/web/components/dashboard/PostCards.tsx
T

419 lines
15 KiB
TypeScript

'use client'
import { memo, useEffect, useState } from 'react'
import type { TrumpPost } from '@/types'
/**
* Was this post actually AI-scored, or filtered as off-topic noise before any
* AI call? Single source of truth — used both by the card (to de-emphasise
* noise) and by list views (to offer a "collapse off-topic" toggle), so the
* two can never disagree about what counts as noise.
*/
export function isAiScored(post: Pick<TrumpPost, 'ai_confidence' | 'ai_reasoning'>): boolean {
return (post.ai_confidence ?? 0) > 0 || !!post.ai_reasoning
}
function fmtPct(n: number | null | undefined) {
if (n == null || isNaN(n)) return '—' // null = window not yet closed
const s = n.toFixed(2) + '%'
return n >= 0 ? '+' + s : s
}
function fmtImpactPct(v: number | null | undefined) {
if (v == null || isNaN(v)) return '—'
const s = Math.abs(v).toFixed(2) + '%'
return v >= 0 ? '+' + s : '-' + s
}
function timeAgo(iso: string) {
const diff = Date.now() - new Date(iso).getTime()
const m = Math.floor(diff / 60000)
if (m < 1) return 'just now'
if (m < 60) return m + 'm'
const h = Math.floor(m / 60)
if (h < 24) return h + 'h'
return Math.floor(h / 24) + 'd'
}
/**
* Hydration-safe wrapper for relative time. Returns an empty placeholder on
* SSR / first client render, then the real relative time after mount. Prevents
* the SSR/CSR "5m vs 6m" mismatch error.
*/
function TimeAgo({ iso, suffix = '' }: { iso: string; suffix?: string }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return (
<span>
{timeAgo(iso)}
{suffix}
</span>
)
}
/**
* Hydration-safe absolute date formatter. Uses fixed 'en-US' locale + options
* so the server/client outputs match once mounted; renders a placeholder before
* mount to avoid timezone mismatches.
*/
function LocalDateTime({ iso, opts }: { iso: string; opts?: Intl.DateTimeFormatOptions }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return <span>{new Date(iso).toLocaleString('en-US', opts)}</span>
}
// Visual identity per signal source. The post stream now mixes Trump posts
// with scanner-emitted technical signals — operators need to tell them
// apart at a glance without reading the text.
//
// When adding a new scanner source, register it here too — otherwise it
// falls through to the generic "first letter" fallback which has no title
// or accent colour.
export const SOURCE_DISPLAY: Record<
string,
{ glyph: string; cls: string; title: string; label: string }
> = {
truth: { glyph: 'T', cls: 'truth', title: 'Trump · Truth Social', label: '@realDonaldTrump' },
breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
vcp_breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
reversal: { glyph: '⇋', cls: 'reversal', title: 'Reversal scanner', label: 'Reversal scanner' },
btc_bottom_reversal: {
glyph: '₿',
cls: 'reversal',
title: 'BTC Macro Bottom scanner',
label: 'BTC Macro Bottom',
},
funding_reversal: {
glyph: 'ƒ',
cls: 'reversal',
title: 'BTC Funding Rate Reversal scanner',
label: 'Funding Reversal',
},
kol_divergence: {
glyph: '⚖',
cls: 'whale',
title: 'KOL Talks-vs-Trades Divergence',
label: 'KOL Divergence',
},
sma_reclaim: { glyph: '〽', cls: 'breakout', title: 'SMA reclaim scanner', label: 'SMA Reclaim' },
rsi_reversal: {
glyph: '⇋',
cls: 'reversal',
title: 'RSI reversal scanner',
label: 'RSI Reversal',
},
whale: { glyph: '🐋', cls: 'whale', title: 'On-chain whale alert', label: 'Whale alert' },
manual: { glyph: '✋', cls: 'manual', title: 'Manual entry', label: 'Manual' },
}
function SourceIcon({ source }: { source: string }) {
const d = SOURCE_DISPLAY[source.toLowerCase()]
if (d) {
return (
<div className={`src-ico ${d.cls}`} title={d.title}>
{d.glyph}
</div>
)
}
// Unknown source — show first letter so user can still tell it apart.
return (
<div className="src-ico external" title={`Source: ${source}`}>
{source.charAt(0).toUpperCase()}
</div>
)
}
function SignalPill({ signal }: { signal: string | null }) {
if (!signal || signal === 'hold') return <span className="sig hold">HOLD</span>
if (signal === 'buy') return <span className="sig buy">BUY</span>
if (signal === 'short') return <span className="sig short">SHORT</span>
if (signal === 'sell') return <span className="sig sell">SELL</span>
return <span className={`sig ${signal}`}>{signal.toUpperCase()}</span>
}
interface PostRowProps {
post: TrumpPost
selected?: boolean
onClick?: () => void
}
const PostRow = memo(function PostRow({ post, selected, onClick }: PostRowProps) {
const [expanded, setExpanded] = useState(false)
const impact = post.price_impact
function handleClick() {
if (!onClick) setExpanded((e) => !e)
onClick?.()
}
// Off-topic Trump posts (most of them) are filtered before any AI call, so
// they carry confidence 0 + no reasoning. Treat those as un-scored noise and
// de-emphasise them. Shared helper so list-level "collapse off-topic" agrees.
const aiScored = isAiScored(post)
return (
<div
className={`post-row ${selected ? 'selected' : ''} ${aiScored ? '' : 'noise'} ${post.signal === 'buy' ? 'signal-buy' : post.signal === 'short' ? 'signal-short' : ''}`}
onClick={handleClick}
>
{/* ── main row ── */}
<div className="post-row-main">
<SourceIcon source={post.source} />
<div className="post-body">
<div className="meta">
{/* Author label depends on source — non-Trump signals come from
technical scanners or external modules, not @realDonaldTrump. */}
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{SOURCE_DISPLAY[post.source?.toLowerCase?.()]?.label ?? post.source ?? 'Signal'}
</span>
<span>·</span>
<TimeAgo iso={post.published_at} suffix=" ago" />
<span>·</span>
{aiScored ? (
<span
className={`chip ${post.sentiment === 'bullish' ? 'up' : post.sentiment === 'bearish' ? 'down' : 'neutral'}`}
style={{ padding: '2px 8px', fontSize: 11 }}
>
{post.sentiment}
</span>
) : (
<span
style={{
padding: '2px 8px',
fontSize: 11,
fontWeight: 600,
borderRadius: 4,
color: 'var(--ink-4)',
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
letterSpacing: '0.02em',
}}
>
off-topic · not crypto
</span>
)}
</div>
<p
className="text"
style={{
...(expanded
? { display: 'block', overflow: 'visible', WebkitLineClamp: 'unset' }
: {}),
// Noise posts are de-emphasised: dimmer text + shorter preview so
// the reader can skip them at a glance without opening.
...(aiScored ? {} : { color: 'var(--ink-4)' }),
}}
>
{expanded
? post.text
: post.text.slice(0, aiScored ? 180 : 90) +
(post.text.length > (aiScored ? 180 : 90) ? '…' : '')}
</p>
</div>
{/* Aside (signal pill / target / impact / AI%) only for scored posts.
Noise posts render as a compact two-column row (no aside) — the
'off-topic · not crypto' tag in the meta line is enough. */}
{aiScored && (
<div className="post-aside">
<SignalPill signal={post.signal} />
{/* Target asset chip for actionable signals */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<span
style={{
fontSize: 10,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '2px 6px',
borderRadius: 4,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
letterSpacing: '0.04em',
}}
>
{post.target_asset}
{post.expected_move_pct ? ` +${post.expected_move_pct}%` : ''}
</span>
)}
<div className="impact-mini">
{impact ? (
<>
<span className="tf">1h move</span>
<span
className={`delta ${impact.m1h == null ? '' : impact.m1h >= 0 ? 'up' : 'down'}`}
>
{impact.m1h == null ? '…' : fmtPct(impact.m1h)}
</span>
</>
) : (
<span className="tf">no data</span>
)}
</div>
<div className="row gap-s" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
<span>AI</span>
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{post.ai_confidence}%
</span>
</div>
</div>
)}
</div>
{/* ── expanded detail ── */}
{expanded && (
<div className="post-row-detail" onClick={(e) => e.stopPropagation()}>
{/* AI confidence bar — only when the post was actually AI-scored.
Off-topic/noise posts (relevant=false, conf 0, no reasoning) show
a neutral note instead of a misleading empty 0% bar. */}
{aiScored ? (
<div>
<div className="ai-metric-head">
<span>AI confidence</span>
<strong>{post.ai_confidence}%</strong>
</div>
<div className="confidence-bar">
<div style={{ width: post.ai_confidence + '%' }} />
</div>
</div>
) : (
<div style={{ fontSize: 12, color: 'var(--ink-3)', padding: '4px 0' }}>
Not crypto-relevant — skipped AI scoring.
</div>
)}
{/* Trade routing — target asset + expected move */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
<span className="tiny">Trade</span>
<span
style={{
fontSize: 12,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '3px 8px',
borderRadius: 5,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
}}
>
{post.signal === 'buy'
? `↑ LONG ${post.target_asset}`
: `↓ SHORT ${post.target_asset}`}
</span>
{post.expected_move_pct != null && (
<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
{`model projection ~${post.expected_move_pct}% · 1h`}
</span>
)}
{post.category && (
<span
style={{
fontSize: 10,
color: 'var(--ink-4)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{post.category.replace(/_/g, ' ')}
</span>
)}
</div>
)}
{/* AI reasoning */}
{post.ai_reasoning && (
<div>
<div className="ai-reasoning-label">
{post.signal === 'buy' || post.signal === 'short'
? 'Why this signal fired'
: 'Why this was filtered out'}
</div>
<div className="ai-reasoning-card">{post.ai_reasoning}</div>
</div>
)}
{/* Price impact — peak move in signal direction per window */}
{impact && (
<div>
<div
className="tiny"
style={{ marginBottom: 8 }}
>{`Price moved · ${impact.asset} · after signal`}</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
{(['m5', 'm15', 'm1h'] as const).map((key) => {
const label = key === 'm5' ? '5m' : key === 'm15' ? '15m' : '1h'
const v = impact[key] // null = window still open
const correct =
impact[`correct_${key}` as 'correct_m5' | 'correct_m15' | 'correct_m1h']
const pending = v == null
return (
<div
key={key}
style={{
padding: 10,
background: 'var(--bg-sunk)',
borderRadius: 'var(--r-sm)',
border: `1px solid ${pending ? 'var(--amber)' : 'var(--line)'}`,
textAlign: 'center',
opacity: pending ? 0.75 : 1,
}}
>
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 4 }}>
{label}
</div>
<div
className={pending ? '' : `delta ${v >= 0 ? 'up' : 'down'}`}
style={{
fontSize: 14,
fontWeight: 600,
color: pending ? 'var(--ink-3)' : undefined,
}}
>
{pending ? '…' : fmtImpactPct(v)}
</div>
{!pending && correct != null && (
<div
style={{
fontSize: 10,
marginTop: 4,
color: correct ? 'var(--up)' : 'var(--down)',
}}
>
{correct ? '✓' : '✗'}
</div>
)}
{pending && (
<div style={{ fontSize: 9, marginTop: 4, color: 'var(--amber)' }}>live</div>
)}
</div>
)
})}
</div>
</div>
)}
</div>
)}
</div>
)
})
export default PostRow
export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime }