refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router

This commit is contained in:
2026-11-03 20:42:30 +08:00
parent de1a903462
commit 1791dbb557
188 changed files with 52461 additions and 2 deletions
+45
View File
@@ -0,0 +1,45 @@
'use client'
/**
* AnimatedNumber — flashes green/red when its value changes, the way a live
* trading terminal ticks. Pure presentational: it renders `display` (already
* formatted) but watches `value` (the raw number) to decide flash direction.
*
* The flash is a CSS class toggled for ~600ms via a keyframe (`tick-flash-up` /
* `tick-flash-down` in globals.css). Respects prefers-reduced-motion (the CSS
* keyframes are disabled there, so this degrades to a plain number).
*/
import { useEffect, useRef, useState } from 'react'
interface Props {
/** Raw numeric value — drives the flash direction when it changes. */
value: number | null | undefined
/** Pre-formatted string to actually show (e.g. "$72,140"). */
display: string
/** Extra className(s) for the wrapper. */
className?: string
style?: React.CSSProperties
}
export default function AnimatedNumber({ value, display, className = '', style }: Props) {
const prev = useRef<number | null | undefined>(value)
const [dir, setDir] = useState<'up' | 'down' | null>(null)
useEffect(() => {
const p = prev.current
if (value != null && p != null && value !== p) {
setDir(value > p ? 'up' : 'down')
const id = setTimeout(() => setDir(null), 600)
prev.current = value
return () => clearTimeout(id)
}
prev.current = value
}, [value])
return (
<span className={`tick-num ${dir ? `tick-flash-${dir}` : ''} ${className}`} style={style}>
{display}
</span>
)
}
+89
View File
@@ -0,0 +1,89 @@
'use client'
/**
* Inline "?"" hint icon with a hover tooltip.
*
* Use this for any UI element whose meaning isn't obvious from its label —
* stat boxes, tab names, jargon-y settings. Goal is the same as the (i)
* dots in Linear / Hyperliquid / Coinglass: small, ignorable, one hover
* away from a one-line plain-English explanation.
*
* Design rules:
* * `text` MUST be one short sentence — never paste long docs in here.
* If you need a paragraph, you're explaining the wrong thing.
* * The icon is intentionally subtle (12 px circle, ink-4 colour). It
* should disappear visually until the user actively scans for help.
* * The tooltip uses CSS hover positioning — no portals. The only JS is
* an on-reveal measurement that clamps the bubble inside the viewport
* (a centred bubble on an icon near the screen edge used to hang
* off-screen, worst on phones). Trade-off: it's still clipped by the
* nearest `overflow:hidden` ancestor. Pages that need tooltips inside
* a `<table>` cell should add `overflow: visible` to that row/td.
*
* Usage:
* <span>Latest cycle <InfoTip text="The single most recent funding payment, in %." /></span>
*
* <InfoTip
* text="Last 24h of cycles, averaged. Smooths the noise of one print."
* placement="bottom" // default 'top'
* />
*/
import { useRef } from 'react'
import type { CSSProperties } from 'react'
type Placement = 'top' | 'bottom' | 'left' | 'right'
interface Props {
text: string
placement?: Placement
/** Tip max-width in px. Default 240 — fits ~2 short lines. */
width?: number
/** Tweak the icon's vertical alignment for fussy contexts. */
iconStyle?: CSSProperties
}
export default function InfoTip({ text, placement = 'top', width = 240, iconStyle }: Props) {
const rootRef = useRef<HTMLSpanElement>(null)
// Clamp the bubble inside the viewport when it's revealed. The bubble is
// CSS-centred on the icon, so near a screen edge it overflowed off-screen.
// Measured at shift=0, then the needed horizontal offset is written to the
// --tip-shift var consumed by the .infotip-top/-bottom transforms.
function clampIntoViewport() {
const bubble = rootRef.current?.querySelector<HTMLElement>('.infotip-bubble')
if (!bubble) return
bubble.style.setProperty('--tip-shift', '0px')
const r = bubble.getBoundingClientRect()
const vw = document.documentElement.clientWidth
const margin = 8
let shift = 0
if (r.left < margin) shift = margin - r.left
else if (r.right > vw - margin) shift = vw - margin - r.right
if (shift !== 0) bubble.style.setProperty('--tip-shift', `${shift}px`)
}
return (
<span
ref={rootRef}
className={`infotip infotip-${placement}`}
// role=button is a slight overstatement but it lets screen-reader users
// know there's a thing to tab to. The actual content is in data-tip and
// also as a regular <span> child for non-CSS-tooltip fallback.
role="button"
tabIndex={0}
aria-label={text}
style={{ ['--tip-w' as string]: `${width}px`, ...iconStyle }}
onMouseEnter={clampIntoViewport}
onFocus={clampIntoViewport}
onTouchStart={clampIntoViewport}
>
<span aria-hidden="true" className="infotip-icon">
?
</span>
<span className="infotip-bubble" role="tooltip">
{text}
</span>
</span>
)
}
+27
View File
@@ -0,0 +1,27 @@
/**
* One-line "what is this page" tagline that sits right under the page title.
*
* Replaces ad-hoc <p className="page-sub"> spots that ended up as ghost-gray
* unreadable status lines ("Macro cycle bottom · 2 signals"). The new contract:
*
* * ALWAYS one short sentence — game-tutorial style. Tells the user the
* "what" in plain English, not the "how" (the how lives in InfoTip's).
* * Slightly bigger + higher contrast than page-sub. Meant to be read,
* not glanced past.
* * Optional `count` slot for the dim stat ("2 signals", "30 posts").
* Renders muted after a separator so the tagline itself stays clean.
*/
export default function PageHint({
children,
count,
}: {
children: React.ReactNode
count?: string
}) {
return (
<p className="page-hint">
{children}
{count && <span className="page-hint-count">{count}</span>}
</p>
)
}
+233
View File
@@ -0,0 +1,233 @@
'use client'
import React from 'react'
interface PaginationProps {
page: number
total: number // total pages
count: number // total items
pageSize: number
onChange: (page: number) => void
/** Scroll to top on page change. Default true. */
scrollTop?: boolean
}
/**
* Shared pagination control used across all list pages.
*
* Visual design:
* ‹ 1 2 … 5 [6] 7 … 12 › Showing 151–180 of 340
*
* Active page uses brand orange. Ellipsis collapses distant pages.
* Prev/Next disabled at boundaries (dimmed, not hidden).
*/
export default function Pagination({
page,
total,
count,
pageSize,
onChange,
scrollTop = true,
}: PaginationProps) {
if (total <= 1) return null
const from = (page - 1) * pageSize + 1
const to = Math.min(page * pageSize, count)
function go(p: number) {
if (p < 1 || p > total || p === page) return
onChange(p)
if (scrollTop) window.scrollTo({ top: 0, behavior: 'smooth' })
}
/** Page number list with ellipsis compression. */
function pages(): (number | '…')[] {
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
const out: (number | '…')[] = []
const push = (n: number | '…') => {
if (out[out.length - 1] !== n) out.push(n)
}
push(1)
if (page > 3) push('…')
for (let i = Math.max(2, page - 1); i <= Math.min(total - 1, page + 1); i++) push(i)
if (page < total - 2) push('…')
push(total)
return out
}
return (
<div style={wrapStyle}>
{/* ← Prev */}
<NavBtn onClick={() => go(page - 1)} disabled={page === 1} label="Previous page">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path
d="M9 11L5 7l4-4"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<span>Prev</span>
</NavBtn>
{/* Page numbers */}
<div style={numsStyle}>
{pages().map((n, i) =>
n === '…' ? (
<span key={`e${i}`} style={ellipsisStyle}>
…
</span>
) : (
<PageBtn key={n} num={n as number} active={n === page} onClick={go} />
),
)}
</div>
{/* Next → */}
<NavBtn onClick={() => go(page + 1)} disabled={page === total} label="Next page">
<span>Next</span>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path
d="M5 3l4 4-4 4"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</NavBtn>
{/* Count */}
<span style={countStyle}>
{from}–{to} <span style={{ opacity: 0.5 }}>of</span> {count.toLocaleString()}
</span>
</div>
)
}
// ── Sub-components ────────────────────────────────────────────────────────────
function PageBtn({
num,
active,
onClick,
}: {
num: number
active: boolean
onClick: (n: number) => void
}) {
const [hover, setHover] = React.useState(false)
const bg = active ? 'var(--amber)' : hover ? 'var(--bg-sunk)' : 'transparent'
const color = active ? '#fff' : hover ? 'var(--ink)' : 'var(--ink-2)'
const border = active ? '1.5px solid var(--amber)' : '1.5px solid var(--line)'
return (
<button
onClick={() => onClick(num)}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
aria-current={active ? 'page' : undefined}
style={{
width: 34,
height: 34,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
border,
background: bg,
color,
fontSize: 13,
fontWeight: active ? 700 : 400,
cursor: 'pointer',
transition: 'background 0.12s, color 0.12s, border-color 0.12s',
boxShadow: active ? '0 1px 4px rgba(245,165,36,0.25)' : 'none',
flexShrink: 0,
}}
>
{num}
</button>
)
}
function NavBtn({
onClick,
disabled,
label,
children,
}: {
onClick: () => void
disabled: boolean
label: string
children: React.ReactNode
}) {
const [hover, setHover] = React.useState(false)
return (
<button
onClick={onClick}
disabled={disabled}
aria-label={label}
onMouseEnter={() => !disabled && setHover(true)}
onMouseLeave={() => setHover(false)}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 5,
height: 34,
padding: '0 12px',
borderRadius: 8,
border: '1.5px solid var(--line)',
background: hover && !disabled ? 'var(--bg-sunk)' : 'transparent',
color: disabled ? 'var(--ink-4)' : hover ? 'var(--ink)' : 'var(--ink-2)',
fontSize: 12,
fontWeight: 500,
cursor: disabled ? 'not-allowed' : 'pointer',
transition: 'background 0.12s, color 0.12s',
flexShrink: 0,
}}
>
{children}
</button>
)
}
// ── Styles ────────────────────────────────────────────────────────────────────
const wrapStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
padding: '28px 0 8px',
flexWrap: 'wrap',
}
const numsStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
gap: 4,
flexWrap: 'wrap',
justifyContent: 'center',
}
const ellipsisStyle: React.CSSProperties = {
width: 28,
textAlign: 'center',
fontSize: 13,
color: 'var(--ink-4)',
userSelect: 'none',
flexShrink: 0,
}
const countStyle: React.CSSProperties = {
fontSize: 11,
color: 'var(--ink-3)',
fontVariantNumeric: 'tabular-nums',
marginLeft: 6,
whiteSpace: 'nowrap',
}
+202
View File
@@ -0,0 +1,202 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useAccount } from 'wagmi'
import { useWsSubscribe } from '@/lib/wsContext'
interface TradeAlert {
id: number
event:
| 'execution_failed'
| 'insufficient_balance'
| 'budget_reached'
| 'reconcile_drift'
| 'circuit_breaker_tripped'
asset?: string
reason?: string
balance_usd?: number
required_usd?: number
spent_usd?: number
cap_usd?: number
// reconcile_drift fields (from reconciler.py broadcast)
// orphan_hl is a list of {asset, trade_id} dicts, NOT a number
orphan_hl?: unknown[]
marked_closed?: number
ghost_positions?: unknown[]
// circuit_breaker_tripped fields (from circuit_breaker.py broadcast)
system?: string
cb_reason?: string
unlock_at?: string
}
// How long each alert stays visible before auto-dismissing.
const AUTO_DISMISS_MS = 10_000
function alertMessage(alert: TradeAlert): string {
switch (alert.event) {
case 'execution_failed':
return `Auto-trade failed${alert.asset ? ` on ${alert.asset}` : ''}${alert.reason ? `: ${alert.reason}` : ''}. Check your HL API key and account status.`
case 'insufficient_balance':
return `Insufficient balance to open${alert.asset ? ` ${alert.asset}` : ''}: account has $${alert.balance_usd?.toFixed(2) ?? '?'}, trade requires $${alert.required_usd?.toFixed(2) ?? '?'}. Top up your Hyperliquid account.`
case 'budget_reached':
return `Daily budget reached${alert.asset ? ` (${alert.asset})` : ''}: $${alert.spent_usd?.toFixed(0) ?? '?'} spent of $${alert.cap_usd?.toFixed(0) ?? '?'} cap. No more trades today.`
// B47: reconciler detects DB ↔ HL mismatch (ghost/orphan position)
case 'reconcile_drift': {
const parts = []
const orphanCount = (alert.orphan_hl as unknown[])?.length ?? 0
if (orphanCount > 0) parts.push(`${orphanCount} orphan(s) on HL`)
if (alert.marked_closed) parts.push(`${alert.marked_closed} auto-closed`)
if ((alert.ghost_positions as unknown[])?.length)
parts.push(`${(alert.ghost_positions as unknown[]).length} ghost(s)`)
return `Position drift detected: ${parts.join(', ') || 'mismatch between DB and HL'}. Check your Hyperliquid account.`
}
// B53: circuit breaker fired — Auto-Trade suspended
case 'circuit_breaker_tripped':
return `Circuit breaker tripped${alert.system ? ` (${alert.system})` : ''}${alert.cb_reason ? `: ${alert.cb_reason}` : ''}. Auto-Trade suspended — turn it back ON on the Trump page to acknowledge and resume.`
default:
return 'Auto-trade event — check your account.'
}
}
let _seq = 0
export default function TradeAlertBanner() {
const { address } = useAccount()
const [alerts, setAlerts] = useState<TradeAlert[]>([])
const dismiss = useCallback((id: number) => {
setAlerts((prev) => prev.filter((a) => a.id !== id))
}, [])
// Auto-dismiss each alert after AUTO_DISMISS_MS.
// Effect re-runs whenever the alert list changes. For each alert we schedule
// a timeout; cleanup cancels all pending timers when the list updates or
// the component unmounts — prevents a dismissed-then-re-added alert from
// triggering a ghost dismiss.
useEffect(() => {
if (alerts.length === 0) return
const timers = alerts.map((a) => window.setTimeout(() => dismiss(a.id), AUTO_DISMISS_MS))
return () => timers.forEach(clearTimeout)
}, [alerts, dismiss])
useWsSubscribe(
'trade_alert',
useCallback(
(raw) => {
const msg = raw as { wallet?: string; event?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
const alert = { id: ++_seq, ...msg } as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
// B47: reconcile_drift — DB↔HL position mismatch flagged by the reconciler.
useWsSubscribe(
'reconcile_drift',
useCallback(
(raw) => {
const msg = raw as { wallet?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
const alert = { id: ++_seq, event: 'reconcile_drift' as const, ...msg } as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
// B53: circuit_breaker_tripped — Auto-Trade suspended by the CB.
useWsSubscribe(
'circuit_breaker_tripped',
useCallback(
(raw) => {
const msg = raw as { wallet?: string; reason?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
// Rename 'reason' → 'cb_reason' to avoid collision with the trade_alert 'reason' field.
const { reason: cb_reason, ...rest } = msg
const alert = {
id: ++_seq,
event: 'circuit_breaker_tripped' as const,
cb_reason,
...rest,
} as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
if (alerts.length === 0) return null
return (
<>
<style>{`
@keyframes tradeAlertIn {
from { opacity: 0; transform: translateX(-50%) translateY(-8px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes tradeAlertOut {
from { opacity: 1; }
to { opacity: 0; }
}
`}</style>
<div
style={{
position: 'fixed',
top: 60,
left: '50%',
transform: 'translateX(-50%)',
zIndex: 9999,
display: 'flex',
flexDirection: 'column',
gap: 8,
width: 'min(480px, calc(100vw - 32px))',
pointerEvents: 'none',
animation: 'tradeAlertIn 0.2s ease',
}}
>
{alerts.map((alert) => (
<div
key={alert.id}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: 10,
padding: '12px 14px',
borderRadius: 10,
background: 'var(--bg)',
border: '1px solid var(--down)',
boxShadow: '0 4px 20px rgba(0,0,0,.3)',
pointerEvents: 'auto',
}}
>
<span style={{ fontSize: 16, flexShrink: 0, marginTop: 1 }}>⚠️</span>
<div style={{ flex: 1, fontSize: 12, lineHeight: 1.5, color: 'var(--ink)' }}>
<strong style={{ color: 'var(--down)', display: 'block', marginBottom: 2 }}>
Auto-trade blocked
</strong>
{alertMessage(alert)}
</div>
<button
onClick={() => dismiss(alert.id)}
style={{
flexShrink: 0,
padding: 0,
border: 'none',
background: 'transparent',
cursor: 'pointer',
color: 'var(--ink-4)',
fontSize: 16,
lineHeight: 1,
}}
aria-label="Dismiss"
>
×
</button>
</div>
))}
</div>
</>
)
}