railyard/apps/ritgram/web/components/UserHoverCard.tsx
caelum0x aa848c66d0 fix(ritgram): Apple-design unslop pass + Rithub OAuth2 sign-in + critical login-redirect-loop fix
Apple design (plans/gtm/APPLE-DESIGN-RULES-2026-11-17.md): rewrote theme
tokens in globals.css/tailwind.config.js to neutral black/white + one
accent (#0071E3), replacing the GitHub-dark blue+green dual-accent theme;
mechanically swept every raw inline hex/rgba literal across app/components
that bypassed the CSS vars (506 hex + 326 rgb(a) replacements) since most
of the app hardcoded colors rather than using tokens; removed all emoji,
decorative gradients (Tailwind bg-gradient-to-* and raw linear/radial-
gradient() in inline styles), confetti, and glow/blur decorative orbs;
converted Navbar/Navigation to icon-only with aria-label+title. Finished
two stopped agents' in-progress work: deleted the fake AnimatedStats/
LiveActivity/ProjectShowcase/Testimonials auth-panel components and
cleaned up the emoji-laden feature list in (auth)/layout.tsx. Removed
remaining fabricated stats (topics/topics/[slug] posts-per-week/
contributors/followers) per the no-fake-numbers rule.

Rithub sign-in: added "Continue with Rithub" as an icon-only OAuth2
button (RithubMark component) on login/register, hidden "Continue with
GitHub" when GITHUB_CLIENT_ID is unset (confirmed unset in prod). Backend:
authenticateWithGitea in oauthService.ts exchanges the Gitea OAuth2 code,
resolves identity via the existing ForgeConnection table (no schema
migration needed), issues the same JWT/session as GitHub/Google login.
OAuth2 app created live on rithub.dev via its REST API as admin user
caelum0x; client id/secret stored in railyard-box's compose file (env
files don't ship to the runtime image, so the actual wiring lives in
docker-compose.yml, not backend/.env) and in ~/products/.env.

Critical bug found and fixed while verifying: services/api.ts's global
401 interceptor redirected every anonymous visitor to /login a couple
seconds after ANY page load -- including /login and /register themselves
-- because the AuthBootstrap's background GET /auth/me (expected to 401
for signed-out visitors) was treated the same as a real session-expiry
401, triggering a refresh attempt, another 401, and a hard
window.location.href redirect, which re-ran AuthBootstrap and repeated.
Fixed by excluding /auth/me and /auth/refresh from that redirect path.
Verified live with a fresh, cookie-less browser: previously looped
/register -> /login forever; now stable after 6s.

Also fixed: production CORS/API origin mismatch -- the frontend was
built with NEXT_PUBLIC_API_URL pointing at ritgram.ereboslab.com while
served from ritgram.rithub.dev, so every API call (login, register, etc.)
was blocked by CORS; rebuilt with rithub.dev as canonical and CORS_ORIGIN
allowing both domains.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-17 17:33:41 +03:00

173 lines
5.8 KiB
TypeScript

'use client'
import { type ReactElement } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { useQuery } from '@tanstack/react-query'
import { userService } from '@/services/userService'
import { useAuthStore } from '@/store/authStore'
import { Tooltip } from './ui/tooltip'
import { FollowButton } from './FollowButton'
interface HoverProfile {
id: string
username: string
displayName?: string
bio?: string
avatar?: string
followersCount: number
followingCount: number
isFollowing: boolean
githubUsername?: string
}
function normalize(raw: unknown): HoverProfile {
const r = (raw ?? {}) as Record<string, unknown>
return {
id: String(r.id ?? ''),
username: String(r.username ?? ''),
displayName: (r.displayName as string) ?? (r.fullName as string) ?? undefined,
bio: r.bio ? String(r.bio) : undefined,
avatar: (r.avatar as string) ?? (r.avatarUrl as string) ?? undefined,
followersCount: typeof r.followersCount === 'number' ? r.followersCount : 0,
followingCount: typeof r.followingCount === 'number' ? r.followingCount : 0,
isFollowing: Boolean(r.isFollowing),
githubUsername: r.githubUsername ? String(r.githubUsername) : undefined,
}
}
function formatCount(count: number): string {
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`
if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`
return String(count)
}
interface UserHoverCardProps {
/** Username to preview. The card lazily fetches the full profile on hover. */
username: string
/** Trigger element (a link, avatar, etc.). */
children: ReactElement
}
/**
* Wraps a trigger element with a profile-preview hover card showing the user's
* avatar, display name, bio, follower/following counts, and a follow button.
*
* Adapted from the source UserTooltip/UserLinkWithTooltip pair onto the
* gitgram-web stack: data comes from `userService.getProfile` via React Query
* (fetched lazily once on first hover and cached), the popover uses this
* product's `ui/tooltip` primitive, and follow state reuses the existing
* `FollowButton`.
*/
export function UserHoverCard({ username, children }: UserHoverCardProps) {
const { user: currentUser } = useAuthStore()
const { data, status } = useQuery({
queryKey: ['hover-profile', username],
queryFn: async () => normalize(await userService.getProfile(username)),
staleTime: 5 * 60 * 1000,
enabled: Boolean(username),
retry: false,
})
const isSelf = Boolean(currentUser?.username && currentUser.username === username)
const card = (
<span className="block w-72 rounded-xl border border-[var(--border)] bg-[var(--surface)] p-4 shadow-xl">
{status === 'pending' && (
<span className="flex animate-pulse flex-col gap-3" aria-hidden="true">
<span className="flex items-center justify-between">
<span className="h-14 w-14 rounded-full bg-[var(--surface-secondary)]" />
</span>
<span className="h-3 w-1/2 rounded bg-[var(--surface-secondary)]" />
<span className="h-3 w-3/4 rounded bg-[var(--surface-secondary)]" />
</span>
)}
{status === 'error' && (
<span className="block text-sm text-[var(--foreground-secondary)]">
Couldn&apos;t load @{username}
</span>
)}
{status === 'success' && data && (
<span className="flex flex-col gap-3">
<span className="flex items-start justify-between gap-2">
<Link
href={`/${data.username}`}
onClick={(e) => e.stopPropagation()}
aria-label={`View @${data.username}`}
>
{data.avatar ? (
<Image
src={data.avatar}
alt={data.username}
width={56}
height={56}
unoptimized
className="h-14 w-14 rounded-full object-cover"
/>
) : (
<span className="flex h-14 w-14 items-center justify-center rounded-full bg-primary text-lg font-semibold text-white">
{data.username.slice(0, 2).toUpperCase()}
</span>
)}
</Link>
{!isSelf && data.id && (
<FollowButton
userId={data.id}
username={data.username}
initialFollowing={data.isFollowing}
githubUsername={data.githubUsername}
/>
)}
</span>
<Link
href={`/${data.username}`}
onClick={(e) => e.stopPropagation()}
className="block min-w-0"
>
<span className="block truncate text-base font-semibold text-[var(--foreground)] hover:underline">
{data.displayName ?? data.username}
</span>
<span className="block truncate text-sm text-[var(--foreground-secondary)]">
@{data.username}
</span>
</Link>
{data.bio && (
<span className="block whitespace-pre-line text-sm text-[var(--foreground)] [overflow-wrap:anywhere] line-clamp-4">
{data.bio}
</span>
)}
<span className="flex items-center gap-4 text-sm text-[var(--foreground-secondary)]">
<span>
<span className="font-semibold text-[var(--foreground)]">
{formatCount(data.followingCount)}
</span>{' '}
Following
</span>
<span>
<span className="font-semibold text-[var(--foreground)]">
{formatCount(data.followersCount)}
</span>{' '}
Followers
</span>
</span>
</span>
)}
</span>
)
return (
<Tooltip content={card} openDelay={350}>
{children}
</Tooltip>
)
}
export default UserHoverCard