feat: enhance project structure with server and workflow management

- Introduced a new server package with Fastify for handling API requests and workflows.
- Implemented user authentication and authorization with JWT and cookie management.
- Added endpoints for managing workflows, runs, and user accounts.
- Established a dashboard for monitoring workflow status and statistics.
- Included a script sandbox for executing user-defined scripts securely.
- Updated README with setup instructions and API documentation.
- Configured database migrations for user management.
- Enhanced logging capabilities for better traceability.
This commit is contained in:
2026-08-14 14:25:37 +07:00
parent 5574d6f723
commit 023cf83cfa
48 changed files with 6127 additions and 359 deletions
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>scrunner</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
{
"name": "@scrunner/web",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@monaco-editor/react": "^4.7.0",
"@tanstack/react-query": "^5.84.0",
"axios": "^1.11.0",
"mermaid": "^11.9.0",
"react": "^19.1.1",
"react-dom": "^19.1.1",
"react-icons": "^5.5.0",
"react-router-dom": "^7.8.0",
"yaml": "^2.8.1"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.11",
"@vitejs/plugin-react": "^5.0.0",
"daisyui": "^5.0.50",
"tailwindcss": "^4.1.11",
"vite": "^7.1.2"
}
}
+60
View File
@@ -0,0 +1,60 @@
import { useEffect } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { useBootstrap, useMe } from "./api/hooks.js";
import { Layout } from "./components/Layout.jsx";
import { AuthPage } from "./pages/AuthPage.jsx";
import { HomePage } from "./pages/HomePage.jsx";
import { ScriptsPage } from "./pages/ScriptsPage.jsx";
import { WorkflowsPage } from "./pages/WorkflowsPage.jsx";
import { EventsPage } from "./pages/EventsPage.jsx";
import { EventDetailPage } from "./pages/EventDetailPage.jsx";
import { UsersPage } from "./pages/UsersPage.jsx";
export function App() {
const qc = useQueryClient();
const bootstrap = useBootstrap();
const me = useMe();
useEffect(() => {
function onUnauthorized() {
qc.setQueryData(["me"], null);
}
window.addEventListener("scrunner:unauthorized", onUnauthorized);
return () => window.removeEventListener("scrunner:unauthorized", onUnauthorized);
}, [qc]);
const user = me.data?.user;
const loading =
bootstrap.isLoading || (me.isLoading && !me.isError && me.data === undefined);
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<span className="loading loading-spinner loading-lg" />
</div>
);
}
if (!user) {
return <AuthPage needsSetup={Boolean(bootstrap.data?.needsSetup)} />;
}
return (
<Layout user={user}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/scripts" element={<ScriptsPage />} />
<Route path="/workflows" element={<WorkflowsPage />} />
<Route path="/events" element={<EventsPage />} />
<Route path="/events/:id" element={<EventDetailPage />} />
{user.role === "admin" ? (
<Route path="/users" element={<UsersPage />} />
) : (
<Route path="/users" element={<Navigate to="/" replace />} />
)}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Layout>
);
}
+22
View File
@@ -0,0 +1,22 @@
import axios from "axios";
export const api = axios.create({
baseURL: "/api",
withCredentials: true,
});
api.interceptors.response.use(
(res) => res,
(err) => {
const url = err.config?.url ?? "";
const isAuthCall = url.includes("/auth/login") || url.includes("/auth/register") || url.includes("/auth/me") || url.includes("/auth/bootstrap");
if (err.response?.status === 401 && !isAuthCall) {
window.dispatchEvent(new Event("scrunner:unauthorized"));
}
return Promise.reject(err);
},
);
export function errorMessage(err, fallback = "request failed") {
return err?.response?.data?.error ?? err?.message ?? fallback;
}
+256
View File
@@ -0,0 +1,256 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "./client.js";
export function useBootstrap() {
return useQuery({
queryKey: ["bootstrap"],
queryFn: async () => (await api.get("/auth/bootstrap")).data,
});
}
export function useMe() {
return useQuery({
queryKey: ["me"],
queryFn: async () => {
try {
return (await api.get("/auth/me")).data;
} catch (err) {
if (err.response?.status === 401) return { user: null };
throw err;
}
},
retry: false,
});
}
export function useLogin() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/auth/login", body)).data,
onSuccess: (data) => {
qc.setQueryData(["me"], data);
qc.invalidateQueries({ queryKey: ["bootstrap"] });
},
});
}
export function useRegister() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/auth/register", body)).data,
onSuccess: (data) => {
qc.setQueryData(["me"], data);
qc.invalidateQueries({ queryKey: ["bootstrap"] });
},
});
}
export function useLogout() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await api.post("/auth/logout")).data,
onSuccess: () => {
qc.setQueryData(["me"], null);
qc.clear();
},
});
}
export function useDashboard() {
return useQuery({
queryKey: ["dashboard"],
queryFn: async () => (await api.get("/dashboard")).data,
refetchInterval: (query) =>
query.state.data?.running?.length ? 4000 : 15000,
});
}
export function useScripts() {
return useQuery({
queryKey: ["scripts"],
queryFn: async () => (await api.get("/scripts")).data.scripts,
});
}
export function useScript(name, enabled = true) {
return useQuery({
queryKey: ["scripts", name],
queryFn: async () => (await api.get(`/scripts/${encodeURIComponent(name)}`)).data,
enabled: Boolean(name) && enabled,
});
}
export function useSaveScript() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ name, content }) =>
(await api.put(`/scripts/${encodeURIComponent(name)}`, { content })).data,
onSuccess: (_data, vars) => {
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["scripts", vars.name] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useDeleteScript() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (name) =>
(await api.delete(`/scripts/${encodeURIComponent(name)}`)).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useWorkflows(owner) {
return useQuery({
queryKey: ["workflows", owner ?? "all"],
queryFn: async () => {
const params = owner ? { owner } : {};
return (await api.get("/workflows", { params })).data.workflows;
},
});
}
export function useWorkflow(owner, file, enabled = true) {
return useQuery({
queryKey: ["workflows", owner, file],
queryFn: async () =>
(await api.get(`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`))
.data,
enabled: Boolean(owner && file) && enabled,
});
}
export function useOwners() {
return useQuery({
queryKey: ["owners"],
queryFn: async () => (await api.get("/owners")).data.owners,
});
}
export function useSaveWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, content }) =>
(
await api.put(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`,
{ content },
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useDeleteWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file }) =>
(
await api.delete(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}`,
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useRunWorkflow() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ owner, file, data }) =>
(
await api.post(
`/workflows/${encodeURIComponent(owner)}/${encodeURIComponent(file)}/run`,
data !== undefined ? { data } : {},
)
).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["runs"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useReregisterWorkflows() {
const qc = useQueryClient();
return useMutation({
mutationFn: async () => (await api.post("/workflows/reregister")).data,
onSuccess: () => {
qc.invalidateQueries({ queryKey: ["workflows"] });
qc.invalidateQueries({ queryKey: ["scripts"] });
qc.invalidateQueries({ queryKey: ["owners"] });
qc.invalidateQueries({ queryKey: ["dashboard"] });
},
});
}
export function useRuns(filters = {}) {
const { owner, workflow, status, limit } = filters;
return useQuery({
queryKey: ["runs", { owner, workflow, status, limit }],
queryFn: async () => {
const params = {};
if (owner) params.owner = owner;
if (workflow) params.workflow = workflow;
if (status) params.status = status;
if (limit) params.limit = limit;
return (await api.get("/runs", { params })).data.runs;
},
});
}
export function useRun(id) {
return useQuery({
queryKey: ["runs", id],
queryFn: async () => (await api.get(`/runs/${encodeURIComponent(id)}`)).data,
enabled: Boolean(id),
refetchInterval: (query) =>
query.state.data?.status === "running" ? 2000 : false,
});
}
export function useUsers() {
return useQuery({
queryKey: ["users"],
queryFn: async () => (await api.get("/users")).data.users,
});
}
export function useCreateUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (body) => (await api.post("/users", body)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
export function useUpdateUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async ({ id, ...body }) =>
(await api.patch(`/users/${encodeURIComponent(id)}`, body)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
export function useDeleteUser() {
const qc = useQueryClient();
return useMutation({
mutationFn: async (id) =>
(await api.delete(`/users/${encodeURIComponent(id)}`)).data,
onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
});
}
@@ -0,0 +1,30 @@
import Editor from "@monaco-editor/react";
import { useTheme } from "../theme.jsx";
export function CodeEditor({ language, value, onChange, height = "50vh" }) {
const { theme } = useTheme();
const isMobile = typeof window !== "undefined" && window.innerWidth < 768;
return (
<div className="overflow-hidden rounded-box border border-base-300">
<Editor
height={height}
language={language}
value={value}
onChange={(v) => onChange(v ?? "")}
theme={theme === "dark" ? "vs-dark" : "light"}
options={{
minimap: { enabled: !isMobile },
lineNumbers: "on",
tabSize: 2,
insertSpaces: true,
autoIndent: "full",
automaticLayout: true,
wordWrap: "on",
scrollBeyondLastLine: false,
fontSize: 13,
}}
/>
</div>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { NavLink, useNavigate } from "react-router-dom";
import {
LuActivity,
LuCode,
LuGitBranch,
LuHouse,
LuLogOut,
LuMenu,
LuMoon,
LuSun,
LuUsers,
} from "react-icons/lu";
import { useLogout } from "../api/hooks.js";
import { useTheme } from "../theme.jsx";
const links = [
{ to: "/", label: "Home", icon: LuHouse, end: true },
{ to: "/scripts", label: "Scripts", icon: LuCode },
{ to: "/workflows", label: "Workflows", icon: LuGitBranch },
{ to: "/events", label: "Events", icon: LuActivity },
];
export function Layout({ user, children }) {
const { theme, toggle } = useTheme();
const logout = useLogout();
const navigate = useNavigate();
const navItems = [
...links,
...(user.role === "admin"
? [{ to: "/users", label: "Users", icon: LuUsers }]
: []),
];
function closeDrawer() {
const el = document.getElementById("nav-drawer");
if (el) el.checked = false;
}
return (
<div className="drawer lg:drawer-open">
<input id="nav-drawer" type="checkbox" className="drawer-toggle" />
<div className="drawer-content flex min-h-screen flex-col">
<div className="navbar bg-base-100 border-base-300 sticky top-0 z-10 border-b">
<div className="flex-none lg:hidden">
<label htmlFor="nav-drawer" className="btn btn-square btn-ghost" aria-label="Open menu">
<LuMenu className="size-5" />
</label>
</div>
<div className="flex-1 px-2 text-lg font-semibold">scrunner</div>
<div className="flex items-center gap-1">
<button
type="button"
className="btn btn-ghost btn-square"
onClick={toggle}
title={theme === "dark" ? "Light" : "Dark"}
aria-label="Toggle theme"
>
{theme === "dark" ? <LuSun className="size-5" /> : <LuMoon className="size-5" />}
</button>
<span className="hidden sm:inline text-sm opacity-70 px-2">{user.username}</span>
<button
type="button"
className="btn btn-ghost btn-square"
title="Log out"
aria-label="Log out"
onClick={() =>
logout.mutate(undefined, { onSuccess: () => navigate("/") })
}
>
<LuLogOut className="size-5" />
</button>
</div>
</div>
<main className="flex-1 p-4">{children}</main>
</div>
<div className="drawer-side z-20">
<label htmlFor="nav-drawer" aria-label="Close menu" className="drawer-overlay" />
<ul className="menu bg-base-200 min-h-full w-64 p-4">
<li className="menu-title">scrunner</li>
{navItems.map(({ to, label, icon: Icon, end }) => (
<li key={to}>
<NavLink to={to} end={end} onClick={closeDrawer}>
<Icon className="size-4" />
{label}
</NavLink>
</li>
))}
</ul>
</div>
</div>
);
}
@@ -0,0 +1,75 @@
import { useEffect, useId, useRef } from "react";
import { useNavigate } from "react-router-dom";
import mermaid from "mermaid";
import { useTheme } from "../theme.jsx";
function findNode(root, id) {
return (
root.querySelector(`#${CSS.escape(id)}`) ||
root.querySelector(`[id="${CSS.escape(id)}"]`) ||
root.querySelector(`[id*="${CSS.escape(id)}"]`)
);
}
export function MermaidDiagram({ chart, scriptIds = {} }) {
const { theme } = useTheme();
const navigate = useNavigate();
const ref = useRef(null);
const reactId = useId().replace(/:/g, "");
const scriptKey = JSON.stringify(scriptIds);
useEffect(() => {
if (!chart || !ref.current) {
if (ref.current) ref.current.innerHTML = "";
return;
}
let cancelled = false;
mermaid.initialize({
startOnLoad: false,
securityLevel: "loose",
suppressErrorRendering: true,
theme: theme === "dark" ? "dark" : "default",
});
const ids = JSON.parse(scriptKey);
const renderId = `mmd-${reactId}-${Date.now()}`;
mermaid
.render(renderId, chart)
.then(({ svg }) => {
if (cancelled || !ref.current) return;
ref.current.innerHTML = svg;
for (const [nodeId, script] of Object.entries(ids)) {
const el = findNode(ref.current, nodeId);
if (!el) continue;
el.style.cursor = "pointer";
el.setAttribute("title", script);
el.addEventListener("click", () => {
navigate(`/scripts?edit=${encodeURIComponent(script)}`);
});
}
})
.catch((err) => {
if (cancelled || !ref.current) return;
ref.current.innerHTML = "";
const p = document.createElement("p");
p.className = "text-error text-sm";
p.textContent = "Could not render diagram";
ref.current.appendChild(p);
});
return () => {
cancelled = true;
};
}, [chart, scriptKey, theme, navigate, reactId]);
if (!chart) return null;
return (
<div
ref={ref}
className="mermaid-clickable overflow-x-auto rounded-box border border-base-300 bg-base-200 p-3"
/>
);
}
+14
View File
@@ -0,0 +1,14 @@
@import "tailwindcss";
@plugin "daisyui" {
themes: light --default, dark --prefersdark;
}
html,
body,
#root {
min-height: 100%;
}
.mermaid-clickable [id^="s"] {
cursor: pointer;
}
+51
View File
@@ -0,0 +1,51 @@
export function formatTime(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "—";
return d.toLocaleString();
}
export function StatusBadge({ status }) {
const cls =
status === "success"
? "badge-success"
: status === "failed"
? "badge-error"
: status === "running"
? "badge-warning"
: "badge-ghost";
return <span className={`badge badge-sm ${cls}`}>{status ?? "—"}</span>;
}
/** Config load + last-run health for the workflows list. */
export function WorkflowStatusBadge({ workflow }) {
if (workflow.loadError) {
return (
<span className="badge badge-error badge-sm" title={workflow.loadError}>
broken
</span>
);
}
if (!workflow.enabled) {
return <span className="badge badge-ghost badge-sm">disabled</span>;
}
if (workflow.lastStatus === "failed") {
return <span className="badge badge-error badge-sm">failed</span>;
}
if (workflow.lastStatus === "running") {
return <span className="badge badge-warning badge-sm">running</span>;
}
if (workflow.lastStatus === "success") {
return <span className="badge badge-success badge-sm">working</span>;
}
return <span className="badge badge-ghost badge-sm">never run</span>;
}
export function levelName(level) {
if (level <= 10) return "trace";
if (level <= 20) return "debug";
if (level <= 30) return "info";
if (level <= 40) return "warn";
if (level <= 50) return "error";
return "fatal";
}
+67
View File
@@ -0,0 +1,67 @@
function sanitize(label) {
const cleaned = String(label ?? "")
.replace(/[^A-Za-z0-9]+/g, "_")
.replace(/_+/g, "_")
.replace(/^_|_$/g, "")
.slice(0, 48);
return cleaned || "node";
}
function parseStep(step) {
if (typeof step === "string") return step;
if (step?.script) return step.script;
return null;
}
export function workflowToArchitecture(parsed) {
/** @type {Record<string, string>} */
const scriptIds = {};
if (!parsed || typeof parsed !== "object") {
return { chart: "", scriptIds };
}
const groupId = "wf";
const name = sanitize(parsed.name || "workflow");
const lines = ["architecture-beta", ` group ${groupId}[${name}]`];
const triggerIds = [];
const triggers = Array.isArray(parsed.triggers) ? parsed.triggers : [];
triggers.forEach((t, i) => {
const id = `t${i}`;
const icon = t?.type === "cron" ? "cloud" : "internet";
const label =
t?.type === "cron"
? `cron ${t.schedule ?? ""}`
: `${t?.method ?? "POST"} ${t?.path ?? ""}`;
lines.push(` service ${id}(${icon})[${sanitize(label)}] in ${groupId}`);
triggerIds.push(id);
});
const scripts = Array.isArray(parsed.scripts) ? parsed.scripts : [];
let prev = null;
let firstScript = null;
scripts.forEach((step, i) => {
const script = parseStep(step);
if (!script) return;
const id = `s${i}`;
scriptIds[id] = script;
lines.push(` service ${id}(server)[${sanitize(script)}] in ${groupId}`);
if (!firstScript) firstScript = id;
if (prev) lines.push(` ${prev}:R -- L:${id}`);
prev = id;
});
// All triggers point at the first script (not chained to each other).
if (firstScript) {
for (const tid of triggerIds) {
lines.push(` ${tid}:R -- L:${firstScript}`);
}
}
// Keep multiple triggers in one column so they don't overlap.
if (triggerIds.length >= 2) {
lines.push(` align column ${triggerIds.join(" ")}`);
}
return { chart: lines.join("\n"), scriptIds };
}
+28
View File
@@ -0,0 +1,28 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "./theme.jsx";
import { App } from "./App.jsx";
import "./index.css";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 10_000,
refetchOnWindowFocus: false,
},
},
});
createRoot(document.getElementById("root")).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>
</QueryClientProvider>
</StrictMode>,
);
+64
View File
@@ -0,0 +1,64 @@
import { useState } from "react";
import { LuLogIn, LuUserPlus } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import { useLogin, useRegister } from "../api/hooks.js";
export function AuthPage({ needsSetup }) {
const login = useLogin();
const register = useRegister();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const mutation = needsSetup ? register : login;
const error = mutation.isError ? errorMessage(mutation.error) : null;
function onSubmit(e) {
e.preventDefault();
mutation.mutate({ username, password });
}
return (
<div className="min-h-screen flex items-center justify-center p-4 bg-base-200">
<form
onSubmit={onSubmit}
className="fieldset bg-base-100 border-base-300 rounded-box w-full max-w-sm border p-6 gap-3"
>
<legend className="fieldset-legend text-lg">
{needsSetup ? "Create admin" : "Sign in"}
</legend>
<label className="label" htmlFor="username">
Username
</label>
<input
id="username"
className="input w-full"
autoComplete="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
<label className="label" htmlFor="password">
Password
</label>
<input
id="password"
type="password"
className="input w-full"
autoComplete={needsSetup ? "new-password" : "current-password"}
value={password}
onChange={(e) => setPassword(e.target.value)}
required
minLength={8}
/>
{error ? <p className="text-error text-sm">{error}</p> : null}
<button
type="submit"
className="btn btn-primary mt-2"
disabled={mutation.isPending}
>
{needsSetup ? <LuUserPlus className="size-4" /> : <LuLogIn className="size-4" />}
{needsSetup ? "Create" : "Sign in"}
</button>
</form>
</div>
);
}
+129
View File
@@ -0,0 +1,129 @@
import { useState } from "react";
import { Link, useParams } from "react-router-dom";
import { LuArrowLeft } from "react-icons/lu";
import { useRun } from "../api/hooks.js";
import { formatTime, levelName, StatusBadge } from "../lib/format.jsx";
export function EventDetailPage() {
const { id } = useParams();
const { data: run, isLoading, error } = useRun(id);
const [wordWrap, setWordWrap] = useState(true);
if (isLoading) return <span className="loading loading-spinner loading-lg" />;
if (error || !run) return <p className="text-error">Event not found</p>;
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Link to="/events" className="btn btn-ghost btn-sm btn-square" aria-label="Back">
<LuArrowLeft className="size-4" />
</Link>
<h1 className="text-xl font-semibold truncate">{run.workflow_name || run.workflow}</h1>
<StatusBadge status={run.status} />
</div>
<dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1 text-sm">
<div>
<dt className="opacity-60">Started</dt>
<dd>{formatTime(run.started_at)}</dd>
</div>
<div>
<dt className="opacity-60">Finished</dt>
<dd>{formatTime(run.finished_at)}</dd>
</div>
<div>
<dt className="opacity-60">Trigger</dt>
<dd>
{run.trigger_type}
{run.trigger_detail ? ` · ${run.trigger_detail}` : ""}
</dd>
</div>
<div>
<dt className="opacity-60">Duration</dt>
<dd>{run.duration_ms != null ? `${run.duration_ms}ms` : "—"}</dd>
</div>
</dl>
{run.error ? (
<div role="alert" className="alert alert-error text-sm">
{run.error}
</div>
) : null}
<section>
<h2 className="font-semibold mb-2">Steps</h2>
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>#</th>
<th>Script</th>
<th>Status</th>
<th>Duration</th>
<th>Error</th>
</tr>
</thead>
<tbody>
{(run.steps ?? []).map((s) => (
<tr key={s.id}>
<td>{s.step_index}</td>
<td className="font-mono">
<Link className="link" to={`/scripts?edit=${encodeURIComponent(s.script)}`}>
{s.script}
</Link>
</td>
<td>
<StatusBadge status={s.status} />
</td>
<td>{s.duration_ms != null ? `${s.duration_ms}ms` : "—"}</td>
<td className="text-error text-xs">{s.error || ""}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
<section>
<div className="mb-2 flex items-center justify-between gap-2">
<h2 className="font-semibold">Logs</h2>
<label className="label cursor-pointer gap-2 py-0">
<span className="label-text text-sm">Word wrap</span>
<input
type="checkbox"
className="checkbox checkbox-sm"
checked={wordWrap}
onChange={(e) => setWordWrap(e.target.checked)}
/>
</label>
</div>
<div className="mockup-code text-xs max-h-[50vh] overflow-auto">
{(run.logs ?? []).length === 0 ? (
<div className="flex gap-3 px-5 py-0.5 font-mono opacity-50">
<span className="w-12 shrink-0 text-right">—</span>
<span>no logs</span>
</div>
) : (
run.logs.map((l) => (
<div key={l.id} className="flex gap-3 px-5 py-0.5 font-mono">
<span className="w-12 shrink-0 text-right opacity-50">
{levelName(l.level)}
</span>
<span
className={
wordWrap
? "min-w-0 flex-1 whitespace-pre-wrap break-words"
: "whitespace-pre"
}
>
{l.ts} {l.msg ?? ""}
{l.payload ? ` ${JSON.stringify(l.payload)}` : ""}
</span>
</div>
))
)}
</div>
</section>
</div>
);
}
+82
View File
@@ -0,0 +1,82 @@
import { Link, useSearchParams } from "react-router-dom";
import { useRuns } from "../api/hooks.js";
import { formatTime, StatusBadge } from "../lib/format.jsx";
export function EventsPage() {
const [params, setParams] = useSearchParams();
const workflow = params.get("workflow") || "";
const status = params.get("status") || "";
const { data: runs = [], isLoading } = useRuns({
workflow: workflow || undefined,
status: status || undefined,
limit: 100,
});
function update(key, value) {
const next = new URLSearchParams(params);
if (value) next.set(key, value);
else next.delete(key);
setParams(next);
}
return (
<div className="space-y-4">
<h1 className="text-xl font-semibold">Events</h1>
<div className="flex flex-col sm:flex-row gap-2">
<input
className="input input-sm w-full sm:max-w-sm"
placeholder="workflow key"
value={workflow}
onChange={(e) => update("workflow", e.target.value)}
/>
<select
className="select select-sm w-full sm:max-w-xs"
value={status}
onChange={(e) => update("status", e.target.value)}
>
<option value="">all statuses</option>
<option value="running">running</option>
<option value="success">success</option>
<option value="failed">failed</option>
</select>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Status</th>
<th>Workflow</th>
<th>Trigger</th>
<th>Started</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
{runs.map((r) => (
<tr key={r.id} className="hover">
<td>
<StatusBadge status={r.status} />
</td>
<td>
<Link className="link" to={`/events/${r.id}`}>
{r.workflow_name || r.workflow}
</Link>
</td>
<td className="text-xs">
{r.trigger_type}
{r.trigger_detail ? ` · ${r.trigger_detail}` : ""}
</td>
<td className="whitespace-nowrap">{formatTime(r.started_at)}</td>
<td>{r.duration_ms != null ? `${r.duration_ms}ms` : "—"}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
+124
View File
@@ -0,0 +1,124 @@
import { Link } from "react-router-dom";
import {
LuActivity,
LuCode,
LuGitBranch,
LuTriangleAlert,
} from "react-icons/lu";
import { useDashboard } from "../api/hooks.js";
import { formatTime, StatusBadge } from "../lib/format.jsx";
export function HomePage() {
const { data, isLoading, error } = useDashboard();
if (isLoading) {
return <span className="loading loading-spinner loading-lg" />;
}
if (error) {
return <p className="text-error">Failed to load dashboard</p>;
}
const failed = data.needsAttention?.failed ?? [];
const broken = data.needsAttention?.brokenWorkflows ?? [];
return (
<div className="space-y-6">
<div className="stats stats-vertical sm:stats-horizontal shadow w-full bg-base-100">
<div className="stat">
<div className="stat-figure text-primary">
<LuGitBranch className="size-7" />
</div>
<div className="stat-title">Workflows</div>
<div className="stat-value text-2xl">{data.workflowCount}</div>
<div className="stat-desc">{data.enabledCount} enabled</div>
</div>
<div className="stat">
<div className="stat-figure text-secondary">
<LuCode className="size-7" />
</div>
<div className="stat-title">Scripts</div>
<div className="stat-value text-2xl">{data.scriptCount}</div>
</div>
<div className="stat">
<div className="stat-figure text-warning">
<LuActivity className="size-7" />
</div>
<div className="stat-title">Running</div>
<div className="stat-value text-2xl">{data.running?.length ?? 0}</div>
</div>
<div className="stat">
<div className="stat-figure text-error">
<LuTriangleAlert className="size-7" />
</div>
<div className="stat-title">Attention</div>
<div className="stat-value text-2xl">
{failed.length + broken.length}
</div>
</div>
</div>
<section>
<h2 className="text-lg font-semibold mb-2">Running</h2>
<RunList runs={data.running} empty="None" />
</section>
<section>
<h2 className="text-lg font-semibold mb-2">Needs attention</h2>
{broken.length > 0 ? (
<ul className="mb-3 space-y-1">
{broken.map((w) => (
<li key={w.key}>
<Link
className="link link-error"
to={`/workflows?edit=${encodeURIComponent(w.owner)}/${encodeURIComponent(w.file)}`}
>
{w.key}: {w.loadError}
</Link>
</li>
))}
</ul>
) : null}
<RunList runs={failed} empty={broken.length ? "" : "None"} />
</section>
<section>
<h2 className="text-lg font-semibold mb-2">Recent</h2>
<RunList runs={data.recent} empty="None" />
</section>
</div>
);
}
function RunList({ runs, empty }) {
if (!runs?.length) {
return empty ? <p className="opacity-60 text-sm">{empty}</p> : null;
}
return (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Status</th>
<th>Workflow</th>
<th>Started</th>
</tr>
</thead>
<tbody>
{runs.map((r) => (
<tr key={r.id} className="hover">
<td>
<StatusBadge status={r.status} />
</td>
<td>
<Link className="link" to={`/events/${r.id}`}>
{r.workflow_name || r.workflow}
</Link>
</td>
<td className="whitespace-nowrap">{formatTime(r.started_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { LuPencil, LuPlus, LuSave, LuTrash2, LuX } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteScript,
useSaveScript,
useScript,
useScripts,
} from "../api/hooks.js";
import { CodeEditor } from "../components/CodeEditor.jsx";
const NEW_TEMPLATE = `export default async function main(ctx) {
return ctx;
}
`;
export function ScriptsPage() {
const [params, setParams] = useSearchParams();
const editName = params.get("edit");
const { data: scripts = [], isLoading } = useScripts();
const [mode, setMode] = useState(null);
const [name, setName] = useState("");
const [content, setContent] = useState("");
const [confirmDelete, setConfirmDelete] = useState(null);
const existing = useScript(mode === "edit" ? name : null, mode === "edit");
const save = useSaveScript();
const del = useDeleteScript();
useEffect(() => {
if (editName) {
setMode("edit");
setName(editName);
}
}, [editName]);
useEffect(() => {
if (mode === "edit" && existing.data?.content != null) {
setContent(existing.data.content);
}
}, [mode, existing.data]);
function openAdd() {
setMode("add");
setName("");
setContent(NEW_TEMPLATE);
setParams({});
}
function openEdit(script) {
setMode("edit");
setName(script);
setParams({ edit: script });
}
function closeForm() {
setMode(null);
setName("");
setContent("");
setParams({});
}
function onSave(e) {
e.preventDefault();
const file = name.endsWith(".js") ? name : `${name}.js`;
save.mutate(
{ name: file, content },
{
onSuccess: () => {
setMode("edit");
setName(file);
setParams({ edit: file });
},
},
);
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Scripts</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Name</th>
<th className="w-24" />
</tr>
</thead>
<tbody>
{scripts.map((s) => (
<tr key={s} className="hover">
<td className="font-mono">{s}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(s)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(s)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSave} className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-semibold">{mode === "add" ? "New script" : name}</h2>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<input
className="input input-sm w-full max-w-md"
placeholder="name.js"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
) : null}
{mode === "edit" && existing.isLoading ? (
<span className="loading loading-spinner" />
) : (
<CodeEditor language="javascript" value={content} onChange={setContent} />
)}
{save.isError ? (
<p className="text-error text-sm">{errorMessage(save.error)}</p>
) : null}
<button type="submit" className="btn btn-primary btn-sm" disabled={save.isPending}>
<LuSave className="size-4" />
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(confirmDelete, {
onSuccess: () => {
if (name === confirmDelete) closeForm();
setConfirmDelete(null);
},
})
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+194
View File
@@ -0,0 +1,194 @@
import { useState } from "react";
import { LuPencil, LuPlus, LuTrash2, LuX } from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useCreateUser,
useDeleteUser,
useUpdateUser,
useUsers,
} from "../api/hooks.js";
export function UsersPage() {
const { data: users = [], isLoading } = useUsers();
const create = useCreateUser();
const update = useUpdateUser();
const del = useDeleteUser();
const [mode, setMode] = useState(null);
const [form, setForm] = useState({
username: "",
password: "",
role: "operator",
id: null,
});
const [confirmDelete, setConfirmDelete] = useState(null);
function openAdd() {
setMode("add");
setForm({ username: "", password: "", role: "operator", id: null });
}
function openEdit(u) {
setMode("edit");
setForm({ username: u.username, password: "", role: u.role, id: u.id });
}
function closeForm() {
setMode(null);
}
function onSubmit(e) {
e.preventDefault();
if (mode === "add") {
create.mutate(
{
username: form.username,
password: form.password,
role: form.role,
},
{ onSuccess: closeForm },
);
} else {
const body = { id: form.id, role: form.role };
if (form.password) body.password = form.password;
update.mutate(body, { onSuccess: closeForm });
}
}
const mutation = mode === "add" ? create : update;
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Users</h1>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th />
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id} className="hover">
<td>{u.username}</td>
<td>
<span className="badge badge-sm">{u.role}</span>
</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(u)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(u)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSubmit} className="fieldset bg-base-100 border-base-300 rounded-box max-w-md border p-4">
<div className="flex items-center justify-between">
<legend className="fieldset-legend">
{mode === "add" ? "New user" : form.username}
</legend>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<>
<label className="label">Username</label>
<input
className="input w-full"
value={form.username}
onChange={(e) => setForm({ ...form, username: e.target.value })}
required
/>
</>
) : null}
<label className="label">{mode === "add" ? "Password" : "New password"}</label>
<input
type="password"
className="input w-full"
value={form.password}
onChange={(e) => setForm({ ...form, password: e.target.value })}
required={mode === "add"}
minLength={mode === "add" ? 8 : undefined}
placeholder={mode === "edit" ? "leave blank to keep" : ""}
/>
<label className="label">Role</label>
<select
className="select w-full"
value={form.role}
onChange={(e) => setForm({ ...form, role: e.target.value })}
>
<option value="operator">operator</option>
<option value="admin">admin</option>
</select>
{mutation.isError ? (
<p className="text-error text-sm">{errorMessage(mutation.error)}</p>
) : null}
<button type="submit" className="btn btn-primary mt-2" disabled={mutation.isPending}>
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete.username}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(confirmDelete.id, { onSuccess: () => setConfirmDelete(null) })
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
+384
View File
@@ -0,0 +1,384 @@
import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import { parse as parseYaml } from "yaml";
import {
LuActivity,
LuPencil,
LuPlay,
LuPlus,
LuRefreshCw,
LuSave,
LuTrash2,
LuX,
} from "react-icons/lu";
import { errorMessage } from "../api/client.js";
import {
useDeleteWorkflow,
useOwners,
useReregisterWorkflows,
useRunWorkflow,
useSaveWorkflow,
useWorkflow,
useWorkflows,
} from "../api/hooks.js";
import { CodeEditor } from "../components/CodeEditor.jsx";
import { MermaidDiagram } from "../components/MermaidDiagram.jsx";
import { formatTime, WorkflowStatusBadge } from "../lib/format.jsx";
import { workflowToArchitecture } from "../lib/workflow-mermaid.js";
const NEW_YAML = `name: new workflow
scripts:
- get-current-time.js
triggers:
- type: HTTP
method: POST
path: /new
`;
export function WorkflowsPage() {
const navigate = useNavigate();
const [params, setParams] = useSearchParams();
const editParam = params.get("edit");
const { data: workflows = [], isLoading } = useWorkflows();
const { data: owners = [] } = useOwners();
const [mode, setMode] = useState(null);
const [owner, setOwner] = useState("default");
const [file, setFile] = useState("");
const [content, setContent] = useState("");
const [confirmDelete, setConfirmDelete] = useState(null);
const [runError, setRunError] = useState(null);
const existing = useWorkflow(
mode === "edit" ? owner : null,
mode === "edit" ? file : null,
mode === "edit",
);
const save = useSaveWorkflow();
const del = useDeleteWorkflow();
const run = useRunWorkflow();
const reregister = useReregisterWorkflows();
useEffect(() => {
if (!editParam) return;
const slash = editParam.indexOf("/");
if (slash === -1) return;
setMode("edit");
setOwner(editParam.slice(0, slash));
setFile(editParam.slice(slash + 1));
}, [editParam]);
useEffect(() => {
if (mode === "edit" && existing.data?.content != null) {
setContent(existing.data.content);
}
}, [mode, existing.data]);
const { parsed, parseError, mermaid } = useMemo(() => {
try {
const parsedYaml = parseYaml(content);
const arch = workflowToArchitecture(parsedYaml);
return { parsed: parsedYaml, parseError: null, mermaid: arch };
} catch (err) {
return {
parsed: null,
parseError: err instanceof Error ? err.message : String(err),
mermaid: { chart: "", scriptIds: {} },
};
}
}, [content]);
function openAdd() {
setMode("add");
setOwner(owners[0] || "default");
setFile("");
setContent(NEW_YAML);
setParams({});
}
function openEdit(w) {
setMode("edit");
setOwner(w.owner);
setFile(w.file);
setParams({ edit: `${w.owner}/${w.file}` });
}
function closeForm() {
setMode(null);
setFile("");
setContent("");
setParams({});
}
function onSave(e) {
e.preventDefault();
const yamlFile = file.endsWith(".yaml") || file.endsWith(".yml") ? file : `${file}.yaml`;
save.mutate(
{ owner, file: yamlFile, content },
{
onSuccess: () => {
setMode("edit");
setFile(yamlFile);
setParams({ edit: `${owner}/${yamlFile}` });
},
},
);
}
function onRun(w) {
setRunError(null);
run.mutate(
{ owner: w.owner, file: w.file },
{
onSuccess: (data) => {
if (data?.runId) navigate(`/events/${data.runId}`);
},
onError: (err) => {
const runId = err?.response?.data?.runId;
if (runId) {
navigate(`/events/${runId}`);
return;
}
setRunError(`${w.key}: ${errorMessage(err)}`);
},
},
);
}
const runningKey =
run.isPending && run.variables
? `${run.variables.owner}/${run.variables.file}`
: null;
return (
<div className="space-y-4">
<div className="flex items-center justify-between gap-2">
<h1 className="text-xl font-semibold">Workflows</h1>
<div className="flex items-center gap-2">
<button
type="button"
className="btn btn-ghost btn-sm"
title="Reregister workflows"
disabled={reregister.isPending}
onClick={() => reregister.mutate()}
>
{reregister.isPending ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuRefreshCw className="size-4" />
)}
Reregister
</button>
<button type="button" className="btn btn-primary btn-sm" onClick={openAdd}>
<LuPlus className="size-4" />
Add
</button>
</div>
</div>
{reregister.isError ? (
<p className="text-error text-sm">{errorMessage(reregister.error)}</p>
) : null}
{runError ? <p className="text-error text-sm">{runError}</p> : null}
{isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="overflow-x-auto">
<table className="table table-sm">
<thead>
<tr>
<th>Name</th>
<th>Owner</th>
<th>Status</th>
<th>Triggers</th>
<th>Last run</th>
<th>Runs</th>
<th />
</tr>
</thead>
<tbody>
{workflows.map((w) => (
<tr key={w.key} className="hover">
<td>{w.name}</td>
<td className="font-mono text-xs">{w.owner}</td>
<td>
<WorkflowStatusBadge workflow={w} />
</td>
<td>
<TriggerList triggers={w.triggers} />
</td>
<td className="whitespace-nowrap">{formatTime(w.lastInvokedAt)}</td>
<td>{w.invocationCount}</td>
<td className="text-right whitespace-nowrap">
<button
type="button"
className="btn btn-ghost btn-xs"
title="Run"
disabled={Boolean(w.loadError) || runningKey === w.key}
onClick={() => onRun(w)}
>
{runningKey === w.key ? (
<span className="loading loading-spinner loading-xs" />
) : (
<LuPlay className="size-4" />
)}
</button>
<Link
className="btn btn-ghost btn-xs"
title="Events"
to={`/events?workflow=${encodeURIComponent(w.key)}`}
>
<LuActivity className="size-4" />
</Link>
<button
type="button"
className="btn btn-ghost btn-xs"
title="Edit"
onClick={() => openEdit(w)}
>
<LuPencil className="size-4" />
</button>
<button
type="button"
className="btn btn-ghost btn-xs text-error"
title="Delete"
onClick={() => setConfirmDelete(w)}
>
<LuTrash2 className="size-4" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{mode ? (
<form onSubmit={onSave} className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-semibold">
{mode === "add" ? "New workflow" : `${owner}/${file}`}
</h2>
<button type="button" className="btn btn-ghost btn-sm btn-square" onClick={closeForm} aria-label="Close">
<LuX className="size-4" />
</button>
</div>
{mode === "add" ? (
<div className="flex flex-col sm:flex-row gap-2">
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="owner"
value={owner}
onChange={(e) => setOwner(e.target.value)}
required
/>
<input
className="input input-sm w-full sm:max-w-xs"
placeholder="file.yaml"
value={file}
onChange={(e) => setFile(e.target.value)}
required
/>
</div>
) : null}
{mode === "edit" && existing.isLoading ? (
<span className="loading loading-spinner" />
) : (
<div className="grid gap-3 lg:grid-cols-2">
<CodeEditor language="yaml" value={content} onChange={setContent} />
<div>
{parseError ? (
<p className="text-error text-sm">{parseError}</p>
) : (
<MermaidDiagram
chart={mermaid.chart}
scriptIds={mermaid.scriptIds}
/>
)}
{parsed?.name ? (
<p className="text-sm opacity-70 mt-2">{parsed.name}</p>
) : null}
</div>
</div>
)}
{save.isError ? (
<p className="text-error text-sm">{errorMessage(save.error)}</p>
) : null}
<button type="submit" className="btn btn-primary btn-sm" disabled={save.isPending}>
<LuSave className="size-4" />
Save
</button>
</form>
) : null}
{confirmDelete ? (
<dialog className="modal modal-open">
<div className="modal-box">
<h3 className="font-bold">Delete {confirmDelete.key}?</h3>
{del.isError ? (
<p className="text-error text-sm mt-2">{errorMessage(del.error)}</p>
) : null}
<div className="modal-action">
<button type="button" className="btn btn-ghost" onClick={() => setConfirmDelete(null)}>
Cancel
</button>
<button
type="button"
className="btn btn-error"
disabled={del.isPending}
onClick={() =>
del.mutate(
{ owner: confirmDelete.owner, file: confirmDelete.file },
{
onSuccess: () => {
if (owner === confirmDelete.owner && file === confirmDelete.file) {
closeForm();
}
setConfirmDelete(null);
},
},
)
}
>
Delete
</button>
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button type="button" onClick={() => setConfirmDelete(null)}>
close
</button>
</form>
</dialog>
) : null}
</div>
);
}
function triggerLabel(t) {
const type = String(t?.type ?? "").toLowerCase();
if (type === "cron") return t.schedule || "cron";
if (type === "http") return t.path || "/";
return t?.type ?? "—";
}
function triggerKind(t) {
const type = String(t?.type ?? "").toLowerCase();
if (type === "http") return t.method || "POST";
return t?.type ?? "—";
}
function TriggerList({ triggers }) {
if (!triggers?.length) return <span className="opacity-50">—</span>;
return (
<ul className="space-y-0.5">
{triggers.map((t, i) => (
<li key={i} className="font-mono text-xs whitespace-nowrap">
<span className="opacity-60">{triggerKind(t)}</span> {triggerLabel(t)}
</li>
))}
</ul>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { createContext, useContext, useEffect, useState } from "react";
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(() => {
if (typeof localStorage === "undefined") return "light";
return localStorage.getItem("theme") || "light";
});
useEffect(() => {
document.documentElement.setAttribute("data-theme", theme);
localStorage.setItem("theme", theme);
}, [theme]);
const toggle = () => setTheme((t) => (t === "dark" ? "light" : "dark"));
return (
<ThemeContext.Provider value={{ theme, setTheme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
return useContext(ThemeContext);
}
+14
View File
@@ -0,0 +1,14 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5173,
proxy: {
"/api": { target: "http://127.0.0.1:9000", changeOrigin: true },
"/admin": { target: "http://127.0.0.1:9000", changeOrigin: true },
},
},
});