1import { A, useLocation, useMatch } from "@solidjs/router";
2import ArrowUpRight from "lucide-solid/icons/arrow-up-right";
3import Boxes from "lucide-solid/icons/boxes";
4import ChevronRight from "lucide-solid/icons/chevron-right";
5import ChevronsUpDown from "lucide-solid/icons/chevrons-up-down";
6import Clapperboard from "lucide-solid/icons/clapperboard";
7import Eye from "lucide-solid/icons/eye";
8import HardDrive from "lucide-solid/icons/hard-drive";
9import House from "lucide-solid/icons/house";
10import LogOut from "lucide-solid/icons/log-out";
11import Monitor from "lucide-solid/icons/monitor";
12import Rocket from "lucide-solid/icons/rocket";
13import Server from "lucide-solid/icons/server";
14import SquarePlay from "lucide-solid/icons/square-play";
15import UserRound from "lucide-solid/icons/user-round";
16import Plug from "lucide-solid/icons/plug";
17import Users from "lucide-solid/icons/users";
18import FolderHeart from "lucide-solid/icons/folder-heart";
19import { createSignal, For, type JSX, onCleanup, Show } from "solid-js";
20import { type Health, type Me, type Section, VIEW_AS } from "../types/model.ts";
21import { queries } from "../api.ts";
22import snowflake from "../snowflake.svg";
23import { bytes, cores, plural } from "../format.ts";
24import { signOut } from "../auth.ts";
25import { account, Avatar, displayName } from "../pages/Account.tsx";
26import { status } from "../pages/Overview.tsx";
27import { TABS as STORAGE_TABS } from "../pages/Storage.tsx";
28import { TABS as YOUTUBE_TABS } from "../pages/YouTube.tsx";
29import { stream } from "../live.ts";
30import { AppIcon } from "./AppIcon.tsx";
31import { lastGood, Loaded } from "./Loaded.tsx";
32import { PaperCloverMark } from "./PaperCloverMark.tsx";
33import { PirateFlag } from "./PirateFlag.tsx";
34import { Spark } from "./Spark.tsx";
35import { Status, StatusLabel } from "./Status.tsx";
36
37type Icon = (props: { class: string }) => JSX.Element;
38
39interface Page {
40 href: string;
41 label: string;
42 icon: Icon;
43 section: Section;
44 /** `?tab=` values, labels and icons, the page's default first. */
45 tabs?: readonly (readonly [string, string, Icon])[];
46}
47
48const BEFORE: Page[] = [{ href: "/", label: "overview", icon: House, section: "launcher" }];
49
50const AFTER: Page[] = [
51 { href: "/mcp", label: "ai / mcp", icon: Plug, section: "ai" },
52 {
53 href: "/storage", label: "storage", icon: HardDrive, section: "admin",
54 tabs: STORAGE_TABS,
55 },
56 { href: "/media", label: "media", icon: Clapperboard, section: "media" },
57 { href: "/seedbox", label: "seedbox", icon: PirateFlag, section: "media" },
58 {
59 href: "/youtube", label: "youtube", icon: SquarePlay, section: "media",
60 tabs: YOUTUBE_TABS,
61 },
62 { href: "/paper-clover", label: "paper clover", icon: PaperCloverMark, section: "admin" },
63 { href: "/users", label: "users", icon: Users, section: "admin" },
64 { href: "/shares", label: "shares", icon: FolderHeart, section: "admin" },
65 { href: "/deploys", label: "deploys", icon: Rocket, section: "admin" },
66 { href: "/vms", label: "vms", icon: Monitor, section: "vms" },
67];
68
69/** Every page and the section that opens it; admins also get the Services group between the two halves. */
70export const PAGES = [...BEFORE, ...AFTER];
71
72/** Groups an admin can preview the dashboard as. */
73const PREVIEW_GROUPS = ["media", "media-manage", "metrics", "vm", "ai"];
74
75/** How many apps need a look, on the overview's link, so it shows from every page. */
76function IssueCount() {
77 const issues = () => status.latest()?.issues ?? [];
78 return (
79 <Show when={issues().length}>
80 <span class="badge">
81 <span class="tally" data-tip={issues().map((issue) =>
82 `${issue.service.name} ${issue.health}`).join(", ")}>
83 <StatusLabel health={issues().some((issue) => issue.health === "down") ? "down" : "degraded"}>{issues().length}</StatusLabel>
84 <span class="sr-only">need a look</span>
85 </span>
86 </span>
87 </Show>
88 );
89}
90
91/** A group's open state, remembered across visits. */
92function remembered(key: string, initial: boolean) {
93 const [open, setOpen] = createSignal((localStorage.getItem(key) ?? (initial ? "open" : "closed")) === "open");
94 const toggle = () => {
95 setOpen(!open());
96 localStorage.setItem(key, open() ? "open" : "closed");
97 };
98 return [open, toggle] as const;
99}
100
101function NavLink(props: { page: Page; children?: JSX.Element }) {
102 const link = (
103 <A href={props.page.href} end class="nav-item" activeClass="active">
104 <props.page.icon class="icon" />
105 <span class="label">{props.page.label}</span>
106 {props.children}
107 </A>
108 );
109 return (
110 <Show when={props.page.tabs} fallback={link}>
111 {(tabs) => {
112 const [open, toggle] = remembered(`sidebar.${props.page.label}`, false);
113 const location = useLocation();
114 const current = (tab: string) => location.pathname === props.page.href
115 && (new URLSearchParams(location.search).get("tab") ?? tabs()[0]![0]) === tab;
116 return (
117 <>
118 <div class="nav-row">
119 {link}
120 <button class="nav-toggle" aria-expanded={open()} aria-label={`${props.page.label} tabs`} onClick={toggle}>
121 <ChevronRight class={`chevron ${open() ? "open" : ""}`} />
122 </button>
123 </div>
124 <div class="nav-group" classList={{ open: open() }} inert={!open()}>
125 <div>
126 <For each={tabs()}>
127 {([tab, label, Icon]) => (
128 <a href={tab ? `${props.page.href}?tab=${tab}` : props.page.href} class="nav-sub"
129 aria-current={current(tab) ? "page" : undefined}>
130 <Icon class="icon" />{label}
131 </a>
132 )}
133 </For>
134 </div>
135 </div>
136 </>
137 );
138 }}
139 </Show>
140 );
141}
142
143function VMNav() {
144 const location = useLocation();
145 const [open, toggle] = remembered("sidebar.vms", true);
146 const [data, { refetch }] = queries.vms.use(() => open() || location.pathname === "/vms" ? undefined : false);
147 const loaded = lastGood(data);
148 const timer = setInterval(() => open() && !data.loading && refetch(), 15_000);
149 onCleanup(() => clearInterval(timer));
150 const selected = () => location.pathname === "/vms" ? new URLSearchParams(location.search).get("vm") : null;
151 return <>
152 <div class="nav-row">
153 <a href="/vms" class="nav-item" aria-current={location.pathname === "/vms" && !selected() ? "page" : undefined} classList={{ active: location.pathname === "/vms" && !selected() }}>
154 <Monitor class="icon" /><span class="label">vms</span>
155 </a>
156 <button class="nav-toggle" aria-expanded={open()} aria-label="Virtual machines" onClick={toggle}>
157 <ChevronRight class={`chevron ${open() ? "open" : ""}`} />
158 </button>
159 </div>
160 <div class="nav-group" classList={{ open: open() }} inert={!open()}><div>
161 <For each={loaded()?.domains}>{(vm) => <a href={`/vms?vm=${encodeURIComponent(vm.name)}`} class="nav-sub"
162 aria-current={selected() === vm.name ? "page" : undefined}>
163 <Monitor class="icon" /><span class="label">{vm.name}</span><Status health={vm.setup === "failed" || vm.state === "crashed" ? "down" : vm.state === "running" ? vm.setup && vm.setup !== "ready" ? "starting" : "healthy" : "stopped"} />
164 </a>}</For>
165 <Show when={data.error && !loaded()}><span class="nav-sub muted">VMs unavailable</span></Show>
166 </div></div>
167 </>;
168}
169
170/** Health states counted together in the collapsed group's summary, in order. */
171const TALLY: [Health, Health[], string][] = [
172 ["healthy", ["healthy"], "up"],
173 ["down", ["down"], "down"],
174 ["degraded", ["degraded"], "degraded"],
175 ["deploying", ["deploying", "restarting", "starting"], "changing"],
176 ["stopped", ["stopped"], "stopped"],
177];
178
179function Services() {
180 const [open, toggle] = remembered("sidebar.services", true);
181 const [services, { refetch }] = queries.services.use();
182 stream.start();
183
184 const health = (id: string, fallback: Health) => stream.latest()?.services[id]?.health ?? fallback;
185 const loaded = lastGood(services);
186 const tally = () => TALLY.map(([shape, states, word]) => {
187 const names = (loaded() ?? []).filter((service) => states.includes(health(service.id, service.health))).map((s) => s.name);
188 return { shape, word, names };
189 }).filter((group) => group.names.length);
190
191 return (
192 <>
193 <button class="nav-item" onClick={toggle} aria-expanded={open()}>
194 <Boxes class="icon" />
195 <span class="label">services</span>
196 <span class="badge">
197 <For each={tally()}>
198 {(group) => (
199 <span class="tally" data-tip={group.shape === "healthy" ? undefined : group.names.join(", ")}>
200 <StatusLabel health={group.shape}>
201 {group.names.length}<Show when={group.shape === "healthy"}> {group.word}</Show>
202 </StatusLabel>
203 <Show when={group.shape !== "healthy"}><span class="sr-only">{group.word}</span></Show>
204 </span>
205 )}
206 </For>
207 </span>
208 <ChevronRight class={`chevron ${open() ? "open" : ""}`} />
209 </button>
210 <div class="nav-group" classList={{ open: open(), stale: !stream.live() }} inert={!open()}>
211 <div>
212 <Loaded data={services} what="services" retry={refetch} skeleton={
213 <For each={Array(8)}>{() => <div class="service-row"><span /><span class="skeleton" /><span class="skeleton" /></div>}</For>
214 }>
215 {(all) => (
216 <For each={all()}>
217 {(service) => {
218 const trail = () => stream.trails()[service.id];
219 const sample = () => stream.latest()?.services[service.id];
220 const cpu = () => sample()?.cpu ?? service.cpu;
221 const memory = () => sample()?.memory ?? service.memory;
222 return (
223 <A href={`/services/${service.id}`} class="service-row" activeClass="active">
224 <Status health={health(service.id, service.health)} />
225 <AppIcon id={service.id} name={service.name} icon={service.icon} />
226 <span class="name">{service.name}</span>
227 <Spark values={trail()?.cpu ?? []} count={stream.count()} max={service.cpuLimit / 10} color="var(--series-1)"
228 label={`cpu ${cpu() === null ? "not measured" : cores(cpu()!)} of ${plural(service.cpuLimit, "core")}`} />
229 <Spark values={trail()?.memory ?? []} count={stream.count()} max={service.memoryLimit} color="var(--series-2)"
230 label={`memory ${memory() === null ? "not measured" : bytes(memory()!)} of ${bytes(service.memoryLimit)}`} />
231 <Show when={service.url} fallback={<span />}>
232 {(url) => (
233 <a class="row-icon" href={url()} target="_blank" rel="noreferrer" aria-label={`Open ${service.name}`}
234 data-tip={new URL(url()).host} onClick={(event) => event.stopPropagation()}>
235 <ArrowUpRight size={13} />
236 </a>
237 )}
238 </Show>
239 </A>
240 );
241 }}
242 </For>
243 )}
244 </Loaded>
245 </div>
246 </div>
247 </>
248 );
249}
250
251function VpsServices() {
252 const [open, toggle] = remembered("sidebar.vps", true);
253 const [services, { refetch }] = queries.vps.use();
254 const timer = setInterval(() => !services.loading && refetch(), 15_000);
255 onCleanup(() => clearInterval(timer));
256 const loaded = lastGood(services);
257 const down = () => (loaded() ?? []).filter((service) => service.health !== "healthy").map((service) => service.name);
258 return (
259 <>
260 <button class="nav-item" onClick={toggle} aria-expanded={open()}>
261 <Server class="icon" />
262 <span class="label">vps services</span>
263 <span class="badge">
264 <Show when={down().length}>
265 <span class="tally" data-tip={down().join(", ")}><StatusLabel health="down">{down().length}</StatusLabel></span>
266 </Show>
267 </span>
268 <ChevronRight class={`chevron ${open() ? "open" : ""}`} />
269 </button>
270 <div class="nav-group" classList={{ open: open() }} inert={!open()}><div>
271 <For each={loaded()}>{(service) => (
272 <A href={`/vps/${service.name}`} class="nav-sub" activeClass="active">
273 <Status health={service.health} /><span class="label">{service.name}</span>
274 </A>
275 )}</For>
276 <Show when={services.error && !loaded()}><span class="nav-sub muted">VPS unavailable</span></Show>
277 </div></div>
278 </>
279 );
280}
281
282/** Previews the dashboard as someone in fewer groups; the server only honors it for admins. */
283export function viewAs(groups: string[] | null) {
284 document.cookie = groups ? `${VIEW_AS}=${encodeURIComponent(groups.join(","))}; path=/; samesite=strict` : `${VIEW_AS}=; path=/; max-age=0`;
285 location.reload();
286}
287
288function Whoami(props: { me: Me }) {
289 const user = lastGood(account);
290 const name = () => {
291 const known = user();
292 return known ? displayName(known) : account.error ? props.me.name : "";
293 };
294 const here = useMatch(() => "/account");
295 const [picked, setPicked] = createSignal(props.me.viewing ? props.me.groups : []);
296 let menu!: HTMLDivElement;
297 return (
298 <div class="whoami">
299 <button class="whoami-button" classList={{ active: !!here() }} popovertarget="account-menu">
300 <Avatar picture={user()?.picture ?? null} name={name()} />
301 <span class="name"><Show when={user()} fallback={account.error ? name() : <span class="skeleton" style={{ width: "100px" }} />}>
302 {(profile) => displayName(profile())}
303 </Show></span>
304 <ChevronsUpDown size={14} class="icon" />
305 </button>
306 <div ref={menu} id="account-menu" popover class="account-menu">
307 <A href="/account" class="nav-item" onClick={() => menu.hidePopover()}><UserRound class="icon" /><span class="label">profile</span></A>
308 <button class="nav-item" onClick={signOut}><LogOut class="icon" /><span class="label">sign out</span></button>
309 <Show when={props.me.viewing || props.me.sections.includes("admin")}>
310 <form class="view-as" onSubmit={(event) => {
311 event.preventDefault();
312 viewAs(picked());
313 }}>
314 <span class="muted">view as someone in</span>
315 <div class="chips">
316 <For each={PREVIEW_GROUPS}>
317 {(group) => (
318 <button type="button" class="chip" aria-pressed={picked().includes(group)}
319 onClick={() => setPicked(picked().includes(group) ? picked().filter((g) => g !== group) : [...picked(), group])}>
320 {group}
321 </button>
322 )}
323 </For>
324 </div>
325 <button class="button small"><Eye size={14} />{picked().length ? "preview" : "preview as friend"}</button>
326 </form>
327 </Show>
328 </div>
329 </div>
330 );
331}
332
333export function Sidebar(props: { me: Me }) {
334 const allowed = (page: Page) => props.me.sections.includes(page.section);
335 return (
336 <nav class="sidebar" aria-label="Main">
337 <div class="brand">
338 <img src={snowflake} alt="" />
339 the snow globe
340 </div>
341 <div class="nav">
342 <For each={BEFORE.filter(allowed)}>{(page) => <NavLink page={page}><IssueCount /></NavLink>}</For>
343 <Show when={props.me.sections.includes("admin")}>
344 <Services />
345 <VpsServices />
346 </Show>
347 <For each={AFTER.filter(allowed)}>{(page) => page.section === "vms" ? <VMNav /> : <NavLink page={page} />}</For>
348 </div>
349 <Whoami me={props.me} />
350 </nav>
351 );
352}