forked from pinks/eris
1
0
Fork 0
eris/ui/AppHeader.tsx

114 lines
3.1 KiB
TypeScript
Raw Normal View History

2023-10-05 09:00:51 +00:00
import { cx } from "@twind/core";
import React, { ReactNode } from "react";
import { NavLink } from "react-router-dom";
import useSWR from "swr";
2023-10-08 21:23:54 +00:00
import { fetchApi, handleResponse } from "./apiClient.tsx";
2023-10-05 09:00:51 +00:00
function NavTab(props: { to: string; children: ReactNode }) {
return (
<NavLink
className={({ isActive }) => cx("tab", isActive && "tab-active")}
to={props.to}
>
{props.children}
</NavLink>
);
}
export function AppHeader(
props: { className?: string; sessionId?: string; onLogOut: () => void },
) {
const { className, sessionId, onLogOut } = props;
const session = useSWR(
2023-10-08 21:23:54 +00:00
sessionId ? ["sessions/{sessionId}", "GET", { params: { sessionId } }] as const : null,
(args) => fetchApi(...args).then(handleResponse),
2023-10-05 09:00:51 +00:00
{ onError: () => onLogOut() },
);
const user = useSWR(
session.data?.userId
2023-10-08 21:23:54 +00:00
? ["users/{userId}", "GET", { params: { userId: String(session.data.userId) } }] as const
2023-10-05 09:00:51 +00:00
: null,
2023-10-08 21:23:54 +00:00
(args) => fetchApi(...args).then(handleResponse),
2023-10-05 09:00:51 +00:00
);
2023-10-10 16:21:25 +00:00
const userPhoto = useSWR(
session.data?.userId
? ["users/{userId}/photo", "GET", {
params: { userId: String(session.data.userId) },
}] as const
: null,
(args) => fetchApi(...args).then(handleResponse).then((blob) => URL.createObjectURL(blob)),
);
2023-10-05 09:00:51 +00:00
return (
<header
className={cx(
"bg-zinc-50 dark:bg-zinc-800 shadow-md flex items-center gap-2 px-4 py-1",
className,
)}
>
{/* logo */}
<img className="w-12 h-12" src="/favicon.png" alt="logo" />
{/* tabs */}
<nav className="flex-grow self-stretch flex items-stretch justify-center gap-2">
<NavTab to="/">
Stats
</NavTab>
2023-10-13 11:47:57 +00:00
<NavTab to="/workers">
Workers
</NavTab>
2023-10-05 09:00:51 +00:00
<NavTab to="/queue">
Queue
</NavTab>
<NavTab to="/settings">
Settings
</NavTab>
</nav>
{/* loading indicator */}
{session.isLoading || user.isLoading ? <div className="spinner" /> : null}
{/* user avatar */}
{user.data
2023-10-10 16:21:25 +00:00
? userPhoto.data
2023-10-05 09:00:51 +00:00
? (
<img
2023-10-10 16:21:25 +00:00
src={userPhoto.data}
2023-10-05 09:00:51 +00:00
alt="avatar"
className="w-9 h-9 rounded-full"
/>
)
: (
<div className="w-9 h-9 rounded-full bg-zinc-400 dark:bg-zinc-500 flex items-center justify-center text-white text-2xl font-bold select-none">
{user.data.first_name.at(0)?.toUpperCase()}
</div>
)
: null}
{/* login/logout button */}
{!session.isLoading && !user.isLoading && sessionId
? (
user.data
? (
<button className="button-outlined" onClick={() => onLogOut()}>
Logout
</button>
)
: (
<a
className="button-filled"
href={`https://t.me/ErisTheBot?start=${sessionId}`}
target="_blank"
>
Login
</a>
)
)
: null}
</header>
);
}