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
@@ -0,0 +1,76 @@
'use client'
import { useMemo } from 'react'
import Link from 'next/link'
import { usePathname, useSearchParams } from '@/lib/navigation'
import { defaultLocale, locales, type Locale } from '@/i18n'
function replaceLocale(pathname: string, nextLocale: Locale) {
const segments = pathname.split('/').filter(Boolean)
const current = segments[0]
if (locales.includes(current as Locale)) {
segments[0] = nextLocale
} else {
segments.unshift(nextLocale)
}
return '/' + segments.join('/')
}
export default function LanguageSwitch() {
const pathname = usePathname()
const searchParams = useSearchParams()
const options: Array<{ locale: Locale; label: string }> = [{ locale: 'en', label: 'EN' }]
const activeLocale = useMemo<Locale>(() => {
const seg = pathname.split('/').filter(Boolean)[0]
return locales.includes(seg as Locale) ? (seg as Locale) : defaultLocale
}, [pathname])
return (
<div
aria-label="Language switch"
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
padding: 4,
borderRadius: 999,
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
flexShrink: 0,
}}
>
{options.map(({ locale, label }) => {
const active = activeLocale === locale
const nextPath = replaceLocale(pathname || `/${defaultLocale}`, locale)
const qs = searchParams.toString()
const href = qs ? `${nextPath}?${qs}` : nextPath
return (
<Link
key={locale}
href={href}
aria-pressed={active}
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
minWidth: 40,
padding: '6px 10px',
borderRadius: 999,
border: 'none',
background: active ? 'var(--ink)' : 'transparent',
color: active ? 'var(--bg)' : 'var(--ink-3)',
fontSize: 12,
fontWeight: 700,
lineHeight: 1,
cursor: 'pointer',
textDecoration: 'none',
}}
>
{label}
</Link>
)
})}
</div>
)
}
+256
View File
@@ -0,0 +1,256 @@
'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from '@/lib/navigation'
import { useAccount, useConnect, useDisconnect } from 'wagmi'
import { useTranslations } from 'next-intl'
import { getFirstReadyConnector, walletConnectErrorLabel } from '@/lib/walletConnect'
import { needsMobileWallet } from '@/lib/mobileWallet'
import MobileWalletSheet from '@/components/wallet/MobileWalletSheet'
// i18n shelved — LanguageSwitch hidden but kept on disk for future revival.
// import LanguageSwitch from './LanguageSwitch'
function BrandMark() {
return <span className="brand-mark">α</span>
}
function ThemeToggle() {
const [theme, setTheme] = useState<'light' | 'dark'>('light')
useEffect(() => {
const stored = localStorage.getItem('theme') as 'light' | 'dark' | null
const t = stored || 'light'
setTheme(t)
document.documentElement.dataset.theme = t
}, [])
function toggle() {
const next = theme === 'dark' ? 'light' : 'dark'
setTheme(next)
localStorage.setItem('theme', next)
document.documentElement.dataset.theme = next
}
return (
<button
className="icon-btn theme-toggle"
onClick={toggle}
aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
title={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
>
{theme === 'dark' ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="2" />
<path
d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<path
d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
</svg>
)}
</button>
)
}
export default function Navbar() {
const t = useTranslations('nav')
const pathname = usePathname()
const { address, isConnected } = useAccount()
const { connectAsync, connectors } = useConnect()
const { disconnect } = useDisconnect()
const [mounted, setMounted] = useState(false)
const [walletMenuOpen, setWalletMenuOpen] = useState(false)
const [copied, setCopied] = useState(false)
const [connectError, setConnectError] = useState('')
const [mobileSheetOpen, setMobileSheetOpen] = useState(false)
async function copyAddress(addr: string) {
let ok = false
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(addr)
ok = true
} else {
// Fallback for non-secure contexts where the Clipboard API is absent.
const ta = document.createElement('textarea')
ta.value = addr
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
ok = document.execCommand('copy')
document.body.removeChild(ta)
}
} catch {
ok = false
}
setCopied(ok)
setTimeout(() => setCopied(false), 1500)
}
useEffect(() => {
setMounted(true)
}, [])
useEffect(() => {
setWalletMenuOpen(false)
}, [pathname, address])
useEffect(() => {
if (isConnected) setConnectError('')
}, [isConnected])
const locale = pathname.split('/')[1] || 'en'
const path = '/' + pathname.split('/').slice(2).join('/')
async function handleConnectWallet() {
setConnectError('')
// On mobile without an injected provider, show the wallet deep-link sheet
// instead of throwing "No wallet found". This lets users open the dApp
// inside MetaMask / Trust / Coinbase without a confusing error.
if (needsMobileWallet()) {
setMobileSheetOpen(true)
return
}
try {
const connector = await getFirstReadyConnector(connectors)
if (!connector) {
// Desktop with no extension — give a helpful hint instead of raw error.
setConnectError('No wallet extension found. Install MetaMask or another browser wallet.')
return
}
await connectAsync({ connector })
} catch (err: unknown) {
setConnectError(walletConnectErrorLabel(err))
}
}
// Two independent trading systems get their own top-level tabs — no
// intermediate "Signals" hub. Trump = event scalp; BTC = reversal.
const tabs = [
{ key: '/', label: t('tabs.overview') },
{ key: '/trump', label: t('tabs.trump') },
{ key: '/macro', label: t('tabs.vibes') },
{ key: '/kol', label: t('tabs.kol') },
{ key: '/trades', label: t('tabs.trades') },
{ key: '/analytics', label: t('tabs.analytics') },
{ key: '/settings', label: t('tabs.settings') },
]
function isActive(key: string) {
if (key === '/') return path === '/' || path === '//'
// /posts (legacy hub) still resolves but isn't a tab; treat it + /archive
// as part of the Trump section so a tab stays highlighted there.
if (key === '/trump')
return path.startsWith('/trump') || path.startsWith('/posts') || path.startsWith('/archive')
return path.startsWith(key)
}
const shortAddr = address ? `${address.slice(0, 6)}…${address.slice(-4)}` : null
return (
<>
<MobileWalletSheet open={mobileSheetOpen} onClose={() => setMobileSheetOpen(false)} />
<nav className="nav">
<Link
href={`/${locale}`}
className="brand"
style={{ textDecoration: 'none', color: 'inherit' }}
>
<BrandMark />
<span>{t('brand')}</span>
</Link>
<div className="nav-tabs">
{tabs.map((tab) => (
<Link
key={tab.key}
href={`/${locale}${tab.key === '/' ? '' : tab.key}`}
className={`nav-tab ${isActive(tab.key) ? 'active' : ''}`}
prefetch
>
{tab.label}
</Link>
))}
</div>
<div className="nav-spacer" />
<div className="nav-right">
{/* <LanguageSwitch /> — shelved until i18n coverage is complete */}
<ThemeToggle />
<div className="wallet-anchor">
{!mounted ? (
<button className="connect-btn lg" suppressHydrationWarning>
{t('actions.connectWallet')}
</button>
) : isConnected && shortAddr ? (
<div className="wallet-menu-wrap" style={{ position: 'relative' }}>
<button
className="wallet-chip"
onClick={() => setWalletMenuOpen((open) => !open)}
onBlur={(e) => {
if (!e.currentTarget.parentElement?.contains(e.relatedTarget as Node | null)) {
setWalletMenuOpen(false)
}
}}
aria-expanded={walletMenuOpen}
aria-haspopup="menu"
>
<span className="ava" />
<span className="mono">{shortAddr}</span>
</button>
<div className={`wallet-menu ${walletMenuOpen ? 'open' : ''}`} role="menu">
<button
role="menuitem"
onMouseDown={(e) => {
e.preventDefault()
if (address) copyAddress(address)
}}
>
{copied ? t('actions.copied') : t('actions.copyAddress')}
</button>
<button
role="menuitem"
className="danger"
onMouseDown={(e) => {
e.preventDefault()
disconnect()
setWalletMenuOpen(false)
}}
>
{t('actions.disconnect')}
</button>
</div>
</div>
) : (
<button
className="connect-btn lg"
onClick={() => {
void handleConnectWallet()
}}
>
{t('actions.connectWallet')}
</button>
)}
{!isConnected && connectError ? (
<p className="wallet-connect-error" role="alert">
{connectError}
</p>
) : null}
</div>
</div>
</nav>
</>
)
}
+89
View File
@@ -0,0 +1,89 @@
'use client'
/**
* Ticker — horizontal scrolling price tape under the navbar, the way a crypto
* terminal shows a running market strip. Driven by the shared WebSocket price
* feed (no new socket). Each asset cell flashes green/red on a price change and
* shows the live last price.
*
* Behaviour notes:
* - The strip is duplicated once and translated -50% in a CSS marquee so the
* loop is seamless (`ticker-marquee` keyframe in globals.css).
* - prefers-reduced-motion disables the scroll (CSS), so the tape becomes a
* static, readable row instead of moving.
* - The animation is paused on hover so a user can read a specific price.
* - Assets with no tick yet render "—" rather than a stale zero.
*/
import { useRef, useState } from 'react'
import { useWsSubscribe } from '@/lib/wsContext'
// Assets the backend streams (see binance ASSET_MAP + hl_price_feed). Order is
// the display order in the tape.
const ASSETS = ['BTC', 'ETH', 'SOL', 'BNB', 'DOGE', 'LINK', 'AAVE', 'TRUMP', 'HYPE'] as const
interface Cell {
price: number | null
dir: 'up' | 'down' | null
}
function fmtPrice(p: number): string {
if (p >= 1000) return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 0 })
if (p >= 1) return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 2 })
return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 4 })
}
export default function Ticker() {
const [cells, setCells] = useState<Record<string, Cell>>({})
// Per-asset flash-clear timers so a fast stream doesn't leak setTimeouts.
const timers = useRef<Record<string, ReturnType<typeof setTimeout>>>({})
useWsSubscribe('price', (msg) => {
const m = msg as { asset?: string; price?: number }
if (!m.asset || typeof m.price !== 'number') return
const asset = m.asset.toUpperCase()
if (!ASSETS.includes(asset as (typeof ASSETS)[number])) return
setCells((prev) => {
const old = prev[asset]
const dir: Cell['dir'] =
old?.price != null && m.price !== old.price
? m.price! > old.price
? 'up'
: 'down'
: (old?.dir ?? null)
return { ...prev, [asset]: { price: m.price!, dir } }
})
// Clear the flash after 600ms.
clearTimeout(timers.current[asset])
timers.current[asset] = setTimeout(() => {
setCells((prev) => (prev[asset] ? { ...prev, [asset]: { ...prev[asset], dir: null } } : prev))
}, 600)
})
const strip = ASSETS.map((a) => {
const c = cells[a]
return (
<span key={a} className={`ticker-cell ${c?.dir ? `tick-flash-${c.dir}` : ''}`}>
<span className="ticker-sym">{a}</span>
<span className="ticker-px">{c?.price != null ? fmtPrice(c.price) : '—'}</span>
<span className={`ticker-arrow ${c?.dir ?? ''}`} aria-hidden>
{c?.dir === 'up' ? '▲' : c?.dir === 'down' ? '▼' : ''}
</span>
</span>
)
})
return (
<div className="ticker" role="region" aria-label="Live market prices">
<div className="ticker-track">
{strip}
{/* duplicate for seamless loop */}
<span aria-hidden style={{ display: 'contents' }}>
{strip}
</span>
</div>
</div>
)
}