mc-dashboard/components/AdminTabs.tsx
hurkicorgi cf467b26c7 Expanded scheduled tasks + keyboard shortcuts
- scripts/run-task.sh: dispatcher for say / backup / snapshot-prune with
  safe arg handling (message stripped of CR/LF, integer-clamped keep
  count). Logs to ~/logs/mc-dashboard/tasks.log (falls back to /tmp).
- New /api/schedule/tasks GET/POST/DELETE route: stores tasks as
  crontab lines with `# mc-task:<base64(json)>` marker so the UI can
  round-trip them. Strict server-side validation:
    - Cron expression regex (5 fields, * / N / N-N / N,N / */N)
    - say message: 1–120 chars, no newlines/backticks/shell quotes
    - snapshot-prune keep: integer 1–50
    - task id: 16-hex only
  Single-quote-escaped message in the generated shell command.
- ScheduledTasks UI under ServerControls (alongside the existing single
  ScheduledRestart): pick type (Announce / Backup / Prune snapshots),
  preset schedule (daily at HH:MM or every N hours), adds with one
  click. Tasks list shows human-readable schedule + "next in Xh" hint
  computed client-side. Hover-reveal Remove action.
- Admin keyboard shortcuts: when not typing,
    r — refetch the active tab's query keys (toast feedback)
    / — focus the first input/contenteditable in the active panel
    ? — toast the shortcuts cheat sheet
  Chord-free, mirrors existing ⌘K palette and Esc handlers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 05:57:39 -06:00

169 lines
5.3 KiB
TypeScript

"use client";
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ServerControls } from "@/components/ServerControls";
import { Analytics } from "@/components/Analytics";
import { Skeleton } from "@/components/ui/skeleton";
const TabFallback = () => (
<div className="space-y-3">
<Skeleton className="h-24 w-full" />
<Skeleton className="h-48 w-full" />
</div>
);
const PlayerManager = dynamic(
() => import("@/components/PlayerManager").then((m) => ({ default: m.PlayerManager })),
{ loading: TabFallback, ssr: false }
);
const ChatBridge = dynamic(
() => import("@/components/ChatBridge").then((m) => ({ default: m.ChatBridge })),
{ loading: TabFallback, ssr: false }
);
const ModManager = dynamic(
() => import("@/components/ModManager").then((m) => ({ default: m.ModManager })),
{ loading: TabFallback, ssr: false }
);
const BackupManager = dynamic(
() => import("@/components/BackupManager").then((m) => ({ default: m.BackupManager })),
{ loading: TabFallback, ssr: false }
);
const LogViewer = dynamic(
() => import("@/components/LogViewer").then((m) => ({ default: m.LogViewer })),
{ loading: TabFallback, ssr: false }
);
const TABS = [
{ value: "server", label: "Server" },
{ value: "players", label: "Players" },
{ value: "chat", label: "Chat" },
{ value: "mods", label: "Mods" },
{ value: "backups", label: "Backups" },
{ value: "logs", label: "Logs" },
];
const TAB_QUERIES: Record<string, string[]> = {
server: "status analytics schedule schedule-tasks".split(" "),
players: ["players"],
chat: ["chat"],
mods: "mods mod-updates snapshots".split(" "),
backups: ["backups"],
logs: ["logs"],
};
export function AdminTabs() {
const queryClient = useQueryClient();
const [mounted, setMounted] = useState(false);
const [value, setValue] = useState<string>("server");
useEffect(() => {
const isEditable = (el: Element | null) => {
if (!el) return false;
const tag = (el as HTMLElement).tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") return true;
return (el as HTMLElement).isContentEditable;
};
const onKey = (e: KeyboardEvent) => {
if (e.metaKey || e.ctrlKey || e.altKey) return;
if (isEditable(document.activeElement)) return;
if (e.key === "r") {
e.preventDefault();
const keys = TAB_QUERIES[value] || [];
keys.forEach((k) => {
queryClient.refetchQueries({ queryKey: [k] });
});
toast.success(`Refreshing ${value}...`, { duration: 1500 });
} else if (e.key === "/") {
const panel = document.querySelector(
'[data-slot="tabs-content"] input, [data-slot="tabs-content"] [contenteditable="true"]'
) as HTMLElement | null;
if (panel) {
e.preventDefault();
panel.focus();
}
} else if (e.key === "?") {
e.preventDefault();
toast.message("Keyboard shortcuts", {
description:
"⌘K palette · r refresh · / focus search · Esc close · hash links jump tabs",
duration: 5000,
});
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [value, queryClient]);
useEffect(() => {
setMounted(true);
const hash = window.location.hash.replace("#", "");
if (hash && TABS.some((t) => t.value === hash)) {
setValue(hash);
return;
}
const saved = localStorage.getItem("admin-tab");
if (saved && TABS.some((t) => t.value === saved)) setValue(saved);
}, []);
useEffect(() => {
const onHash = () => {
const h = window.location.hash.replace("#", "");
if (h && TABS.some((t) => t.value === h)) setValue(h);
};
window.addEventListener("hashchange", onHash);
return () => window.removeEventListener("hashchange", onHash);
}, []);
useEffect(() => {
if (!mounted) return;
localStorage.setItem("admin-tab", value);
history.replaceState(null, "", `#${value}`);
}, [value, mounted]);
if (!mounted) return null;
return (
<Tabs
value={value}
onValueChange={(v) => setValue(v as string)}
className="w-full"
>
<TabsList
aria-label="Admin sections"
className="flex w-full flex-wrap h-auto sm:h-9 gap-1 p-1 overflow-x-auto justify-start sm:justify-center"
>
{TABS.map((t) => (
<TabsTrigger key={t.value} value={t.value} className="text-xs sm:text-sm">
{t.label}
</TabsTrigger>
))}
</TabsList>
<TabsContent value="server" className="mt-4 space-y-4 sm:space-y-6">
<ServerControls />
<Analytics />
</TabsContent>
<TabsContent value="players" className="mt-4">
<PlayerManager />
</TabsContent>
<TabsContent value="chat" className="mt-4" keepMounted={false}>
<ChatBridge />
</TabsContent>
<TabsContent value="mods" className="mt-4">
<ModManager />
</TabsContent>
<TabsContent value="backups" className="mt-4">
<BackupManager />
</TabsContent>
<TabsContent value="logs" className="mt-4" keepMounted={false}>
<LogViewer />
</TabsContent>
</Tabs>
);
}