import React, { ReactNode } from "react"; import { NavLink } from "react-router-dom"; import useSWR from "swr"; import { cx } from "twind/core"; import { 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}", "GET", { params: { sessionId } }] as const : null, (args) => fetchApi(...args).then(handleResponse), { onError: () => onLogOut() }, ); const getUser = useSWR( getSession.data?.userId ? ["users/{userId}", "GET", { params: { userId: String(getSession.data.userId) } }] as const : null, (args) => fetchApi(...args).then(handleResponse), ); const getBot = useSWR( ["bot", "GET", {}] as const, (args) => fetchApi(...args).then(handleResponse), ); const getUserPhoto = useSWR( getSession.data?.userId ? ["users/{userId}/photo", "GET", { params: { userId: String(getSession.data.userId) }, }] as const : null, (args) => fetchApi(...args).then(handleResponse).then((blob) => URL.createObjectURL(blob)), ); 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}
); }