"use client"; // PEP-179: «Погоня за задачей» — the picture above the team list. Working agents chase the task // round the track (CSS offset-path), free ones wait on the bench, a pug product owner throws the // task. Data comes from the server (`teamChaseView`) and is re-read by . import { useRouter } from "next/navigation"; import { useEffect, useRef, useState, useTransition } from "react"; import { useT } from "@/components/I18n"; import type { TeamChaseView } from "@peppa/core"; import { setTeamChaseHiddenAction } from "@/app/(app)/team/actions"; import css from "./TeamChase.module.css"; const SNAPSHOT_KEY = "peppa.team-chase.snapshot"; const initial = (name: string) => [...name][0]?.toUpperCase() ?? "?"; /** A rounded rectangle through the stage as an offset-path (the stage width is measured). */ export function trackPath(w: number, top = 176, bottom = 372, r = 40): string { const l = 28; const rt = Math.max(l + 2 * r, w - 28); return `path("M ${l + r} ${top} H ${rt - r} Q ${rt} ${top} ${rt} ${top + r} V ${bottom - r} Q ${rt} ${bottom} ${rt - r} ${bottom} H ${l + r} Q ${l} ${bottom} ${l} ${bottom - r} V ${top + r} Q ${l} ${top} ${l + r} ${top} Z")`; } /** Pixel pug (inline SVG: nothing to download, works offline). */ function Pug({ sleeping }: { sleeping: boolean }) { const px = (x: number, y: number, w: number, h: number, f: string) => ; return ( {px(1, 0, 3, 3, "#6b4a2b")} {px(8, 0, 3, 3, "#6b4a2b")} {px(2, 2, 8, 7, "#e8c48a")} {px(3, 4, 6, 4, "#3a2a1a")} {sleeping ? <>{px(3, 3, 2, 1, "#000")}{px(7, 3, 2, 1, "#000")} : <>{px(3, 3, 2, 2, "#fff")}{px(7, 3, 2, 2, "#fff")}{px(4, 4, 1, 1, "#000")}{px(8, 4, 1, 1, "#000")}} {px(5, 6, 2, 1, "#000")} ); } export function TeamChase({ view, acceptKeys, hidden: hiddenInitial }: { view: TeamChaseView; acceptKeys: string[]; hidden: boolean }) { const t = useT(); const router = useRouter(); const [hidden, setHidden] = useState(hiddenInitial); const [, start] = useTransition(); const stage = useRef(null); const [width, setWidth] = useState(720); const [visible, setVisible] = useState(true); const [still, setStill] = useState(false); const [online, setOnline] = useState(true); const [data, setData] = useState(view); const [plus, setPlus] = useState(0); const [open, setOpen] = useState(null); const prevAccepted = useRef(null); const known = useRef(new Set()); const [fresh, setFresh] = useState>(new Set()); // Fresh server data → the shown state; remember it for offline starts. useEffect(() => { setData(view); try { localStorage.setItem(SNAPSHOT_KEY, JSON.stringify(view)); } catch {} if (prevAccepted.current != null && view.accepted > prevAccepted.current) setPlus((n) => n + 1); prevAccepted.current = view.accepted; const names = [...view.runners, ...view.bench].map((a) => `${a.id}`); if (known.current.size) setFresh(new Set(names.filter((n) => !known.current.has(n)))); known.current = new Set(names); }, [view]); // Offline start: the page came from cache (or failed) — show the last snapshot we kept. useEffect(() => { const sync = () => setOnline(navigator.onLine); sync(); window.addEventListener("online", sync); window.addEventListener("offline", sync); if (!navigator.onLine) { try { const raw = localStorage.getItem(SNAPSHOT_KEY); if (raw) { const snap = JSON.parse(raw) as TeamChaseView; if (snap.at > view.at) setData(snap); } } catch {} } return () => { window.removeEventListener("online", sync); window.removeEventListener("offline", sync); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { const el = stage.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth)); ro.observe(el); setWidth(el.clientWidth); return () => ro.disconnect(); }, [hidden]); // Hidden tab → animations pause; battery saver → they stop (agents keep their places). useEffect(() => { const vis = () => setVisible(document.visibilityState === "visible"); document.addEventListener("visibilitychange", vis); let off = () => {}; type Battery = EventTarget & { level: number; charging: boolean }; (navigator as Navigator & { getBattery?: () => Promise }).getBattery?.().then((b) => { const upd = () => setStill(!b.charging && b.level <= 0.2); upd(); b.addEventListener("levelchange", upd); b.addEventListener("chargingchange", upd); off = () => { b.removeEventListener("levelchange", upd); b.removeEventListener("chargingchange", upd); }; }).catch(() => {}); if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {}); return () => { document.removeEventListener("visibilitychange", vis); off(); }; }, []); useEffect(() => { if (!plus) return; const id = setTimeout(() => setPlus(0), 1500); return () => clearTimeout(id); }, [plus]); const toggle = (h: boolean) => { setHidden(h); start(() => void setTeamChaseHiddenAction(h)); }; const at = new Date(data.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); const n = data.runners.length; const idle = n === 0; const path = trackPath(width); const awaiting = acceptKeys.length; const mid = width / 2; const go = (e: React.MouseEvent | React.KeyboardEvent, id: string, action: () => void) => { // Touch: the first tap shows the hint, the second goes. A mouse goes at once. const touch = "pointerType" in e.nativeEvent && (e.nativeEvent as PointerEvent).pointerType === "touch"; if (touch && open !== id) return setOpen(id); setOpen(null); action(); }; const toCard = (id: number) => { const el = document.getElementById(`agent-${id}`); if (!el) return; el.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "center" }); el.animate([{ outline: "2px solid #00e5ff" }, { outline: "2px solid transparent" }], { duration: 1600 }); }; if (hidden) return (
{t("Погоня за задачей")}
); return (
e.target === e.currentTarget && setOpen(null)}>
{t("Погоня за задачей")} {t("Принято")}: {data.accepted}
{!online &&
{t("Нет связи — данные на {time}", { time: at })}
}
{idle && z z}
{t("мопс-продакт")} {plus > 0 && +1}
{!idle && <>
} {!idle &&
{t("Новая задача!")}
} {idle ? (

{t("Агенты отдыхают")}

) : ( <>
{data.runners.map((a, i) => { const label = a.task ? t("агент {name} · {title}", { name: a.name, title: a.task.title }) : t("агент {name} работает", { name: a.name }); const key = `r${a.id}`; return ( ); })} {data.extra > 0 && {t("ещё {n}", { n: data.extra })}} )}
{data.runners.map((a) => ( ))}
{awaiting > 0 && ( {t("Жмите «Принять»")} )}

{data.bench.length ? t("Свободны — ждут задачу") : t("Все заняты")}

    {data.bench.map((a) => (
  • ))}
); }