Files
pwa-homelab-mon/web/src/components/ServiceCard.tsx
T
alexey.bagno b714c00b27
Deploy / deploy (push) Successful in 8s
sorting+modal fix
2026-08-31 23:09:35 +05:00

193 lines
5.7 KiB
TypeScript

import { useState, useRef } from "preact/hooks";
import { createClient } from "@connectrpc/connect";
import { createConnectTransport } from "@connectrpc/connect-web";
import { Container, Server, X } from "lucide-preact";
import type { Service } from "../gen/homelab/v1/homelab_pb";
import {
HomelabService,
ServiceKind,
ServiceOp,
} from "../gen/homelab/v1/homelab_pb";
const client = createClient(
HomelabService,
createConnectTransport({ baseUrl: "" }),
);
/** Бейдж статуса: systemd — active/failed/выключен (not-found = намеренно disabled, не ошибка), docker — агрегат проекта. */
function badge(s: Service) {
if (s.error)
return (
<span class="badge badge-error badge-sm" title={s.error}>
ошибка
</span>
);
if (s.kind === ServiceKind.DOCKER) {
if (s.state === "active")
return (
<span class="badge badge-success badge-sm">работает {s.substate}</span>
);
if (s.state === "partial")
return (
<span class="badge badge-warning badge-sm">частично {s.substate}</span>
);
return <span class="badge badge-ghost badge-sm">остановлен</span>;
}
if (s.loadState === "not-found")
return <span class="badge badge-ghost badge-sm">выключен</span>;
if (s.state === "active")
return (
<span class="badge badge-success badge-sm">
{s.substate || "активен"}
</span>
);
if (s.state === "failed")
return <span class="badge badge-error badge-sm">сбой</span>;
return <span class="badge badge-ghost badge-sm">остановлен</span>;
}
/** Кнопки контроля; вынесены, чтобы переиспользовать на карточке и в модалке. */
function Controls({
s,
onAct,
busy,
}: {
s: Service;
onAct: (op: ServiceOp) => void;
busy: boolean;
}) {
const disabled =
s.kind === ServiceKind.SYSTEMD && s.loadState === "not-found";
const btn = (op: ServiceOp, label: string, title?: string) => (
<button
class="btn btn-xs btn-outline"
disabled={busy || disabled}
title={title}
onClick={(e) => {
e.stopPropagation(); // кнопка не должна открывать info-модалку карточки
onAct(op);
}}
>
{label}
</button>
);
return (
<div class="flex flex-wrap gap-2 items-center">
{btn(ServiceOp.START, "start")}
{btn(
ServiceOp.STOP,
"stop",
"docker stop: контейнер не поднимется при ребуте (unless-stopped)",
)}
{btn(ServiceOp.RESTART, "restart")}
</div>
);
}
/** Карточка сервиса: systemd-юнит или docker-проект, start/stop/restart через ServiceAction, info — статус-вывод в модалке. */
export function ServiceCard({
s,
refresh,
}: {
s: Service;
refresh: () => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [info, setInfo] = useState<string | null>(null);
const [infoBusy, setInfoBusy] = useState(false);
const infoOpen = useRef(false);
const closeInfo = () => {
infoOpen.current = false;
setInfo(null);
};
const act = async (op: ServiceOp) => {
setBusy(true);
setError("");
try {
await client.serviceAction({ name: s.name, kind: s.kind, op });
refresh(); // не ждём 3s поллинга
if (infoOpen.current) {
const r = await client.serviceInfo({ name: s.name, kind: s.kind });
setInfo(r.output);
}
} catch (e) {
setError(String(e).replace(/^.*real error: /, ""));
} finally {
setBusy(false);
}
};
const openInfo = async () => {
setInfoBusy(true);
setError("");
infoOpen.current = true;
try {
setInfo(
(await client.serviceInfo({ name: s.name, kind: s.kind })).output,
);
} catch (e) {
setError(String(e).replace(/^.*real error: /, ""));
} finally {
setInfoBusy(false);
}
};
const kindIcon =
s.kind === ServiceKind.DOCKER ? (
<Container size={14} class="text-info shrink-0" />
) : (
<Server size={14} class="text-primary shrink-0" />
);
return (
<div class="card bg-base-200 shadow">
<div class="card-body p-4 gap-2" onClick={openInfo}>
<div class="flex items-center gap-2">
{kindIcon}
<span class="font-medium text-sm flex-1 truncate">{s.name}</span>
{badge(s)}
</div>
{error && (
<div role="alert" class="alert alert-error text-sm py-2">
{error}
</div>
)}
<div class="flex flex-wrap gap-2 items-center">
<Controls s={s} onAct={act} busy={busy} />
</div>
{s.containers.length > 0 && (
<p class="text-xs text-base-content/50 font-mono break-all">
{s.containers.join(", ")}
</p>
)}
</div>
{info !== null && (
<div class="modal modal-open">
<div class="modal-box max-w-2xl">
<button
class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
onClick={closeInfo}
>
<X size={16} />
</button>
<h3 class="font-bold text-lg flex items-center gap-2">
{kindIcon} {s.name}
</h3>
<div class="mt-3">
<Controls s={s} onAct={act} busy={busy} />
</div>
<pre class="bg-base-300 rounded-box p-3 mt-3 text-xs whitespace-pre-wrap overflow-x-auto">
{infoBusy ? "…" : info}
</pre>
</div>
<div class="modal-backdrop" onClick={closeInfo} />
</div>
)}
</div>
);
}