import React, { ReactNode } from "react"; import { NavLink } from "react-router-dom"; import useSWR from "swr"; import { cx } from "twind/core"; import { API_URL, fetchApi, handleResponse } from "./apiClient.ts"; function NavTab(props: { to: string; children: ReactNode }) { return ( cx("tab", isActive && "tab-active")} to={props.to} > {props.children} ); } export function AppHeader(props: { className?: string; sessionId: string | null; onLogOut: () => void; }) { const { className, sessionId, onLogOut } = props; const getSession = useSWR( sessionId ? ["/sessions/:sessionId", { method: "GET", params: { sessionId } }] as const : null, (args) => fetchApi(...args).then(handleResponse), { onError: () => onLogOut() }, ); const getUser = useSWR( getSession.data?.userId ? ["/users/:userId", { method: "GET", params: { userId: String(getSession.data.userId) }, }] as const : null, (args) => fetchApi(...args).then(handleResponse), ); const getBot = useSWR( ["/bot", { method: "GET" }] as const, (args) => fetchApi(...args).then(handleResponse), ); const getUserPhoto = useSWR( getSession.data?.userId ? ["/users/:userId/photo", { method: "GET", params: { userId: String(getSession.data.userId) }, }] as const : null, () => // elysia fetch can't download file fetch(`${API_URL}/users/${getSession.data?.userId}/photo`) .then((response) => { if (!response.ok) throw new Error(response.statusText); return response; }) .then((response) => response.blob()) .then((blob) => blob ? URL.createObjectURL(blob) : null), ); return (
{/* logo */} logo {/* tabs */} {/* loading indicator */} {getSession.isLoading || getUser.isLoading ?
: null} {/* user avatar */} {getUser.data ? getUserPhoto.data ? ( avatar ) : (
{getUser.data.first_name.at(0)?.toUpperCase()}
) : null} {/* login/logout button */} {!getSession.isLoading && !getUser.isLoading && getBot.data && sessionId ? ( getUser.data ? ( ) : ( Login ) ) : null}
); }