refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router
This commit is contained in:
@@ -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>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user