Над списком агентов — пиксельный мопс бросает задачу, работающие агенты гоняют её по
трассе (CSS offset-path), свободные ждут на скамейке. Данные — core teamChaseView: трасса
= агенты с живым раннером (≤8, остальные «+N»), скамейка — свободные в команде, счётчик —
задачи в «Готово» видимых проектов; «+1» — только при росте счётчика, «Жмите «Принять»» —
только при задачах на приёмке. Живая область team, LiveRefresh pauseHidden. Подсказки,
касание (первое — подсказка, второе — переход), клавиатура, прокрутка к карточке,
«Скрыть» с запоминанием, уменьшенное движение и экономия батареи, < 420 px — строка значков.
PWA: свой шрифт Press Start 2P (OFL), service worker кэширует оболочку и /team, без сети —
последний состав и «Нет связи — данные на ЧЧ:ММ».
Заодно: listAgents и выбор свободного агента считали занятость по id сессии вместо id агента
(drizzle рендерит ${agents.id} в подзапросе голым "id").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
429 lines
18 KiB
TypeScript
429 lines
18 KiB
TypeScript
"use client";
|
||
|
||
// PEP-179: «Погоня за задачей» above the team list. The pug (the product manager) drops a task,
|
||
// agents at work chase it around the track, free ones wait on the bench. Live data comes from
|
||
// the page (core `teamChaseView`) and is re-read by `LiveRefresh scope="team"`; motion is pure CSS
|
||
// (TeamChase.module.css). A copy of the last data stays in localStorage for the offline app.
|
||
|
||
import { useRouter } from "next/navigation";
|
||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from "react";
|
||
import type { ChaseAgent, TeamChaseView } from "@peppa/core";
|
||
import { intlLocale } from "@peppa/shared/i18n";
|
||
import { setTeamChaseHiddenAction } from "@/app/(app)/team/actions";
|
||
import { useT } from "@/components/I18n";
|
||
import { useWords } from "@/components/Words";
|
||
import s from "./TeamChase.module.css";
|
||
|
||
const CYCLE = 9;
|
||
const TASK_LEAD = 3.6;
|
||
const FIRST_GAP = 0.67;
|
||
const GAP = 0.54;
|
||
const HEIGHT = 410;
|
||
const TOP = 150;
|
||
const BOTTOM = 380;
|
||
const STORE = "peppa.team-chase";
|
||
|
||
/** The rounded track for a stage `w` px wide, starting under the pug (top middle). */
|
||
export function trackPath(w: number): { d: string; left: number; right: number; r: number } {
|
||
const m = Math.max(28, Math.round(w * 0.08));
|
||
const left = m;
|
||
const right = w - m;
|
||
const r = Math.max(30, Math.min(80, (right - left) / 5, (BOTTOM - TOP) / 2));
|
||
const cx = w / 2;
|
||
const d = `M ${cx} ${TOP} H ${right - r} A ${r} ${r} 0 0 1 ${right} ${TOP + r} V ${BOTTOM - r} A ${r} ${r} 0 0 1 ${right - r} ${BOTTOM} H ${left + r} A ${r} ${r} 0 0 1 ${left} ${BOTTOM - r} V ${TOP + r} A ${r} ${r} 0 0 1 ${left + r} ${TOP} Z`;
|
||
return { d, left, right, r };
|
||
}
|
||
|
||
/** How far ahead (s) a runner in `slot` is: a line behind the task, around the loop. */
|
||
const lead = (slot: number) => (((TASK_LEAD - FIRST_GAP - slot * GAP) % CYCLE) + CYCLE) % CYCLE;
|
||
|
||
/** Stable places on the track: an agent keeps its slot while it runs, so nobody jumps. */
|
||
function useSlots(ids: number[]): Map<number, number> {
|
||
const ref = useRef(new Map<number, number>());
|
||
return useMemo(() => {
|
||
const prev = ref.current;
|
||
const next = new Map<number, number>();
|
||
for (const id of ids) if (prev.has(id)) next.set(id, prev.get(id)!);
|
||
for (const id of ids) {
|
||
if (next.has(id)) continue;
|
||
const used = new Set(next.values());
|
||
let slot = 0;
|
||
while (used.has(slot)) slot++;
|
||
next.set(id, slot);
|
||
}
|
||
ref.current = next;
|
||
return next;
|
||
}, [ids.join(",")]); // eslint-disable-line react-hooks/exhaustive-deps
|
||
}
|
||
|
||
// The pixel pug (12×11), coloured after the clay mascot (`PugMascot`). Asleep — eyes closed.
|
||
const PUG_COLORS: Record<string, string> = { D: "#4A3428", F: "#E8B98A", K: "#0B0B0B", W: "#FFFFFF", P: "#FF7DB8" };
|
||
const PUG_AWAKE = ["DD.FFFFFF.DD", "DDFFFFFFFFDD", "DFFFFFFFFFFD", "FFKKFFFFKKFF", "FFKWFFFFKWFF", "FFFFDDDDFFFF", "FFFDDDDDDFFF", "FFFDDKKDDFFF", ".FFDDDDDDFF.", ".FFFDPPDFFF.", "..FFFFFFFF.."];
|
||
const PUG_ASLEEP = [...PUG_AWAKE.slice(0, 3), "FFFFFFFFFFFF", "FKKKFFFFKKKF", ...PUG_AWAKE.slice(5)];
|
||
|
||
function PixelPug({ asleep, label }: { asleep: boolean; label: string }) {
|
||
const rows = asleep ? PUG_ASLEEP : PUG_AWAKE;
|
||
return (
|
||
<svg width="60" height="55" viewBox="0 0 12 11" shapeRendering="crispEdges" role="img" aria-label={label}>
|
||
{rows.flatMap((row, y) => [...row].map((c, x) => (c === "." ? null : <rect key={`${x}-${y}`} x={x} y={y} width="1" height="1" fill={PUG_COLORS[c]} />)))}
|
||
</svg>
|
||
);
|
||
}
|
||
|
||
/** The agent's sign: the first letter of the nickname in a circle of its colour. */
|
||
const initial = (name: string) => [...name.trim()][0]?.toUpperCase() ?? "?";
|
||
|
||
function readStore(): TeamChaseView | null {
|
||
try {
|
||
const v = JSON.parse(localStorage.getItem(STORE) ?? "null");
|
||
return v && Array.isArray(v.runners) && Array.isArray(v.bench) ? (v as TeamChaseView) : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
export function TeamChase({ view, hidden: hiddenAtStart, awaitingKey }: { view: TeamChaseView; hidden: boolean; awaitingKey: string | null }) {
|
||
const t = useT();
|
||
const w = useWords();
|
||
const router = useRouter();
|
||
const [hidden, setHidden] = useState(hiddenAtStart);
|
||
const [data, setData] = useState(view);
|
||
const [offline, setOffline] = useState(false);
|
||
const [paused, setPaused] = useState(false);
|
||
const [lowPower, setLowPower] = useState(false);
|
||
const [open, setOpen] = useState<string | null>(null);
|
||
const [width, setWidth] = useState(720);
|
||
const [plus, setPlus] = useState(0);
|
||
const stage = useRef<HTMLDivElement>(null);
|
||
const touch = useRef(false);
|
||
const accepted = useRef(view.accepted);
|
||
const seen = useRef<Set<string> | null>(null);
|
||
|
||
// Fresh server data: keep it, remember it for the offline app, «+1» when the count grew.
|
||
useEffect(() => {
|
||
setData(view);
|
||
try {
|
||
localStorage.setItem(STORE, JSON.stringify(view));
|
||
} catch {}
|
||
if (view.accepted > accepted.current) setPlus((k) => k + 1);
|
||
accepted.current = view.accepted;
|
||
}, [view]);
|
||
|
||
// Offline: the newest known team (the cached page or the stored copy); back online — re-read.
|
||
// «Offline» is also a network that is there while Peppa is not (the page came from the
|
||
// service worker's cache): a small request to the server tells, repeated while it fails.
|
||
useEffect(() => {
|
||
let off = false;
|
||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||
let stopped = false;
|
||
const set = (next: boolean) => {
|
||
if (next) {
|
||
const stored = readStore();
|
||
if (stored && stored.at > view.at) setData(stored);
|
||
} else if (off) router.refresh();
|
||
off = next;
|
||
setOffline(next);
|
||
};
|
||
const probe = async () => {
|
||
if (timer) clearTimeout(timer);
|
||
timer = null;
|
||
if (stopped || document.visibilityState !== "visible") return;
|
||
let ok = navigator.onLine;
|
||
if (ok) ok = await fetch("/api/health", { cache: "no-store" }).then(() => true, () => false);
|
||
if (stopped) return;
|
||
set(!ok);
|
||
if (!ok) timer = setTimeout(probe, 15_000);
|
||
};
|
||
const onOffline = () => set(true);
|
||
const onVisible = () => document.visibilityState === "visible" && void probe();
|
||
void probe();
|
||
window.addEventListener("online", probe);
|
||
window.addEventListener("offline", onOffline);
|
||
document.addEventListener("visibilitychange", onVisible);
|
||
return () => {
|
||
stopped = true;
|
||
if (timer) clearTimeout(timer);
|
||
window.removeEventListener("online", probe);
|
||
window.removeEventListener("offline", onOffline);
|
||
document.removeEventListener("visibilitychange", onVisible);
|
||
};
|
||
}, [router, view.at]);
|
||
|
||
// A hidden tab or a minimised app: the picture stands still.
|
||
useEffect(() => {
|
||
const onVis = () => setPaused(document.visibilityState !== "visible");
|
||
onVis();
|
||
document.addEventListener("visibilitychange", onVis);
|
||
return () => document.removeEventListener("visibilitychange", onVis);
|
||
}, []);
|
||
|
||
// Battery saver: a discharging battery under 20 % — no motion.
|
||
useEffect(() => {
|
||
const nav = navigator as Navigator & { getBattery?: () => Promise<{ charging: boolean; level: number; addEventListener: (e: string, f: () => void) => void }> };
|
||
nav
|
||
.getBattery?.()
|
||
.then((b) => {
|
||
const check = () => setLowPower(!b.charging && b.level <= 0.2);
|
||
check();
|
||
b.addEventListener("chargingchange", check);
|
||
b.addEventListener("levelchange", check);
|
||
})
|
||
.catch(() => {});
|
||
}, []);
|
||
|
||
// The installed app works offline: shell files and this page are cached by /sw.js.
|
||
useEffect(() => {
|
||
navigator.serviceWorker?.register("/sw.js", { scope: "/" }).catch(() => {});
|
||
}, []);
|
||
|
||
useLayoutEffect(() => {
|
||
const el = stage.current;
|
||
if (!el) return;
|
||
const measure = () => el.clientWidth && setWidth(el.clientWidth);
|
||
measure();
|
||
const ro = new ResizeObserver(measure);
|
||
ro.observe(el);
|
||
return () => ro.disconnect();
|
||
}, [hidden]);
|
||
|
||
// Close an open hint on a tap elsewhere.
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
const close = (e: PointerEvent) => !(e.target as Element).closest?.("[data-chase-key]") && setOpen(null);
|
||
document.addEventListener("pointerdown", close);
|
||
return () => document.removeEventListener("pointerdown", close);
|
||
}, [open]);
|
||
|
||
const slots = useSlots(data.runners.map((a) => a.id));
|
||
// Who just came in (from the bench or new to the team) — they hop in, the rest keep running.
|
||
const fresh = useMemo(() => {
|
||
const keys = [...data.runners.map((a) => `r${a.id}`), ...data.bench.map((a) => `b${a.id}`)];
|
||
const before = seen.current;
|
||
seen.current = new Set(keys);
|
||
return before ? new Set(keys.filter((k) => !before.has(k))) : new Set<string>();
|
||
}, [data]);
|
||
|
||
const toggle = (next: boolean) => {
|
||
setHidden(next);
|
||
void setTeamChaseHiddenAction(next).catch(() => {});
|
||
};
|
||
|
||
/** Touch: the first tap shows the hint, the second acts. Mouse and keyboard act at once. */
|
||
const tap = (key: string, act: () => void) => {
|
||
if (touch.current && open !== key) return setOpen(key);
|
||
setOpen(null);
|
||
act();
|
||
};
|
||
const showCard = (id: number) => {
|
||
const card = document.getElementById(`agent-${id}`);
|
||
if (!card) return;
|
||
const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||
card.scrollIntoView({ behavior: still ? "auto" : "smooth", block: "center" });
|
||
card.setAttribute("data-highlight", "");
|
||
setTimeout(() => card.removeAttribute("data-highlight"), 2500);
|
||
};
|
||
|
||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString(intlLocale(t.locale), { hour: "2-digit", minute: "2-digit" });
|
||
const working = data.runners.length + data.extra;
|
||
const idle = working === 0;
|
||
const { d, left, right, r } = trackPath(width);
|
||
const cx = width / 2;
|
||
const tasksWord = w.Task("genPl");
|
||
|
||
if (hidden)
|
||
return (
|
||
<div className={`${s.chase} ${s.collapsed}`}>
|
||
<span>
|
||
{t("Работают: {n}", { n: working })} · {t("Свободны: {n}", { n: data.bench.length })}
|
||
</span>
|
||
<button type="button" className={s.hide} onClick={() => toggle(false)}>
|
||
{t("Показать")}
|
||
</button>
|
||
</div>
|
||
);
|
||
|
||
const runnerLabel = (a: ChaseAgent) => (a.task ? t("Агент {name}, задача {title}", { name: a.name, title: a.task.title }) : t("Агент {name}, работает", { name: a.name }));
|
||
const goTask = (a: ChaseAgent) => a.task && router.push(`/t/${a.task.key}`);
|
||
const runnerProps = (a: ChaseAgent, key: string) => ({
|
||
type: "button" as const,
|
||
"aria-label": runnerLabel(a),
|
||
"data-chase-key": key,
|
||
"data-open": open === key ? "" : undefined,
|
||
onPointerDown: (e: React.PointerEvent) => (touch.current = e.pointerType !== "mouse"),
|
||
onKeyDown: () => (touch.current = false),
|
||
onClick: () => tap(key, () => goTask(a)),
|
||
});
|
||
const tip = (a: ChaseAgent) => (
|
||
<span className={s.tip} aria-hidden>
|
||
{a.name}
|
||
{" · "}
|
||
{a.task ? `${a.task.key} ${a.task.title}` : t("работает")}
|
||
</span>
|
||
);
|
||
|
||
return (
|
||
<section
|
||
className={[s.chase, paused && s.paused, lowPower && s.still, idle && s.idle].filter(Boolean).join(" ")}
|
||
aria-label={t("Агенты за работой")}
|
||
data-team-chase
|
||
>
|
||
<div className={s.frame}>
|
||
<div className={s.hud}>
|
||
<span className={s.player}>
|
||
{t("Игрок")}: <b>{t("вы")}</b>
|
||
</span>
|
||
<span className={s.title}>Peppa FACTORY</span>
|
||
<span data-chase-counter={data.accepted}>
|
||
{tasksWord}: <b>{String(data.accepted).padStart(6, "0")}</b>
|
||
</span>
|
||
</div>
|
||
{offline && <p className={s.offline} role="status">{t("Нет связи — данные на {time}", { time: hhmm(data.at) })}</p>}
|
||
|
||
<div ref={stage} className={s.stage} style={{ "--path": `path('${d}')` } as CSSProperties}>
|
||
<svg className={s.track} width={width} height={HEIGHT} aria-hidden>
|
||
<path d={d} fill="none" stroke="#00E5FF" strokeWidth="10" strokeOpacity=".12" />
|
||
<path d={d} fill="none" stroke="#00E5FF" strokeWidth="2" strokeDasharray="10 8" />
|
||
</svg>
|
||
{!idle && <div className={s.chute} style={{ left: cx }} />}
|
||
<div className={s.you} style={{ left: cx }}>
|
||
<div className={s.youbox} style={{ position: "relative" }}>
|
||
<div className={s.pug}>
|
||
<PixelPug asleep={idle} label={idle ? t("Мопс Peppa FACTORY спит") : t("Мопс Peppa FACTORY")} />
|
||
</div>
|
||
{idle && (
|
||
<span className={s.zzz} aria-hidden>
|
||
z<small>z</small>
|
||
</span>
|
||
)}
|
||
</div>
|
||
<span className={s.youtag}>
|
||
{t("вы")} · {t("продакт")}
|
||
</span>
|
||
</div>
|
||
{idle ? (
|
||
<div className={s.restingTask} style={{ left: cx + 56 }} aria-hidden />
|
||
) : (
|
||
<>
|
||
<div className={s.say} style={{ left: cx }}>
|
||
{t("Ловите {task}!", { task: w.task("acc") })}
|
||
</div>
|
||
<div className={s.drop} style={{ left: cx }} aria-hidden />
|
||
<div className={s.task} aria-hidden />
|
||
</>
|
||
)}
|
||
{plus > 0 && (
|
||
<span key={plus} className={s.plus} style={{ left: cx }} aria-hidden>
|
||
+1
|
||
</span>
|
||
)}
|
||
{data.runners.map((a) => {
|
||
const key = `r${a.id}`;
|
||
const ahead = lead(slots.get(a.id) ?? 0);
|
||
return (
|
||
<button
|
||
key={key}
|
||
{...runnerProps(a, key)}
|
||
className={`${s.runner} ${fresh.has(key) ? s.enter : ""}`}
|
||
style={{ animationDelay: `-${ahead.toFixed(2)}s`, "--d": `${((ahead / CYCLE) * 100).toFixed(2)}%`, color: a.color } as CSSProperties}
|
||
>
|
||
<span className={s.hop} style={{ animationDelay: `-${((slots.get(a.id) ?? 0) * 0.11).toFixed(2)}s` }}>
|
||
<span className={s.agent} aria-hidden>
|
||
{initial(a.name)}
|
||
</span>
|
||
<span className={s.tag} aria-hidden>
|
||
{a.name}
|
||
</span>
|
||
</span>
|
||
{tip(a)}
|
||
</button>
|
||
);
|
||
})}
|
||
{data.extra > 0 && (
|
||
<span className={s.more} style={{ left: right - r, top: TOP - 34 }}>
|
||
+{data.extra}
|
||
</span>
|
||
)}
|
||
<div className={s.mid} style={{ left: left + r * 0.5 + 16, right: width - right + r * 0.5 + 16, top: TOP + 34, height: BOTTOM - TOP - 68 }}>
|
||
{idle ? (
|
||
<p>{t("Агенты отдыхают")}</p>
|
||
) : (
|
||
<>
|
||
<p>
|
||
{t("Работают: {n}", { n: working })}
|
||
<br />
|
||
{t("Гоняют {task} по кругу, пока не доведут до готового", { task: w.task("acc") })}
|
||
</p>
|
||
<div className={s.legend} aria-hidden>
|
||
{data.runners.map((a) => (
|
||
<span key={a.id} style={{ color: a.color }}>
|
||
■ {a.name}
|
||
</span>
|
||
))}
|
||
</div>
|
||
</>
|
||
)}
|
||
{awaitingKey && (
|
||
<a className={`${s.accept} ${s.blink}`} href={`/t/${awaitingKey}`}>
|
||
{t("Жмите «Принять»")}
|
||
</a>
|
||
)}
|
||
</div>
|
||
<div className={s.row}>
|
||
{data.runners.map((a) => {
|
||
const key = `m${a.id}`;
|
||
return (
|
||
<button key={key} {...runnerProps(a, key)} className={s.mini} style={{ color: a.color }}>
|
||
<span className={s.agent} aria-hidden>
|
||
{initial(a.name)}
|
||
</span>
|
||
{tip(a)}
|
||
</button>
|
||
);
|
||
})}
|
||
{data.extra > 0 && <span className={s.more} style={{ position: "static", alignSelf: "center" }}>+{data.extra}</span>}
|
||
</div>
|
||
</div>
|
||
|
||
{data.bench.length > 0 && (
|
||
<div className={s.bench}>
|
||
<h3>
|
||
{t("Свободны: {n}", { n: data.bench.length })} · {t("наведите, чтобы узнать кличку")}
|
||
</h3>
|
||
<ul className={s.seats}>
|
||
{data.bench.map((a, i) => {
|
||
const key = `b${a.id}`;
|
||
return (
|
||
<li key={key}>
|
||
<button
|
||
type="button"
|
||
className={`${s.seat} ${fresh.has(key) ? s.seatEnter : ""}`}
|
||
style={{ color: a.color }}
|
||
aria-label={t("Агент {name}, свободен", { name: a.name })}
|
||
data-chase-key={key}
|
||
data-open={open === key ? "" : undefined}
|
||
onPointerDown={(e) => (touch.current = e.pointerType !== "mouse")}
|
||
onKeyDown={() => (touch.current = false)}
|
||
onClick={() => tap(key, () => showCard(a.id))}
|
||
>
|
||
<span className={s.seatIcon} style={{ animationDelay: `-${((i * 0.29) % 1.8).toFixed(2)}s` }} aria-hidden>
|
||
{initial(a.name)}
|
||
</span>
|
||
<span className={s.tip} aria-hidden>
|
||
{a.name} · {t("свободен")}
|
||
</span>
|
||
</button>
|
||
</li>
|
||
);
|
||
})}
|
||
</ul>
|
||
</div>
|
||
)}
|
||
<button type="button" className={s.hide} onClick={() => toggle(true)}>
|
||
{t("Скрыть")}
|
||
</button>
|
||
<div className={s.scan} aria-hidden />
|
||
</div>
|
||
</section>
|
||
);
|
||
}
|