peppa/apps/web/components/TeamChase.tsx

250 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"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 <LiveRefresh scope="team">.
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) => <rect key={`${x}-${y}-${f}`} x={x} y={y} width={w} height={h} fill={f} />;
return (
<svg width="48" height="40" viewBox="0 0 12 10" shapeRendering="crispEdges" aria-hidden className={css.pug}>
{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")}
</svg>
);
}
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<HTMLDivElement>(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<string | null>(null);
const prevAccepted = useRef<number | null>(null);
const known = useRef(new Set<string>());
const [fresh, setFresh] = useState<Set<string>>(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<Battery> }).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 (
<div className={`${css.chase} ${css.collapsed}`}>
<span>{t("Погоня за задачей")}</span>
<button type="button" className={css.hide} onClick={() => toggle(false)}>{t("Показать")}</button>
</div>
);
return (
<section className={`${css.chase} ${!visible ? css.paused : ""} ${still ? css.still : ""}`} aria-label={t("Погоня за задачей")} onClick={(e) => e.target === e.currentTarget && setOpen(null)}>
<div className={css.frame}>
<div className={css.scan} aria-hidden />
<div className={css.hud}>
<span className={css.title}>{t("Погоня за задачей")}</span>
<span aria-live="polite">{t("Принято")}: <b>{data.accepted}</b></span>
</div>
{!online && <div className={css.offline} role="status">{t("Нет связи — данные на {time}", { time: at })}</div>}
<div ref={stage} className={`${css.stage} ${idle ? css.idle : ""}`} style={{ ["--path" as string]: path }}>
<div className={css.you} style={{ left: mid }}>
<div className={css.youbox}>
<Pug sleeping={idle} />
{idle && <span className={css.zzz} aria-hidden>z z</span>}
</div>
<span className={css.youtag}>{t("мопс-продакт")}</span>
{plus > 0 && <span key={plus} className={css.plus} aria-hidden>+1</span>}
</div>
{!idle && <><div className={css.chute} style={{ left: mid }} aria-hidden /><div className={css.drop} style={{ left: mid }} aria-hidden /></>}
{!idle && <div className={css.say} style={{ left: mid }} aria-hidden>{t("Новая задача!")}</div>}
{idle ? (
<div className={css.mid} style={{ left: 0, right: 0, top: 200 }}>
<div className={css.restingTask} aria-hidden />
<p>{t("Агенты отдыхают")}</p>
</div>
) : (
<>
<div className={css.track} aria-hidden />
<div className={css.task} aria-hidden />
{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 (
<button
key={a.id}
type="button"
className={`${css.runner} ${fresh.has(`${a.id}`) ? css.enter : ""}`}
style={{ ["--d" as string]: `${Math.round((i / n) * 100)}%`, color: a.color, animationDelay: `${-(i / n) * 9}s` }}
data-open={open === key ? "" : undefined}
aria-label={label}
onClick={(e) => go(e, key, () => (a.task ? router.push(`/t/${a.task.key}`) : toCard(a.id)))}
>
<span className={css.hop}>
<span className={css.agent}>{initial(a.name)}</span>
<span className={css.tag}>{a.name}</span>
</span>
<span className={css.tip}>{label}</span>
</button>
);
})}
{data.extra > 0 && <span className={css.more} style={{ right: 36, top: 150 }}>{t("ещё {n}", { n: data.extra })}</span>}
</>
)}
<div className={css.row}>
{data.runners.map((a) => (
<button key={a.id} type="button" className={css.mini} style={{ color: a.color }} aria-label={a.task ? t("агент {name} · {title}", { name: a.name, title: a.task.title }) : a.name} onClick={(e) => go(e, `m${a.id}`, () => (a.task ? router.push(`/t/${a.task.key}`) : toCard(a.id)))} data-open={open === `m${a.id}` ? "" : undefined}>
<span className={css.agent}>{initial(a.name)}</span>
</button>
))}
</div>
</div>
{awaiting > 0 && (
<a className={`${css.accept} ${css.blink}`} style={{ textAlign: "center" }} href={`/t/${acceptKeys[0]}`}>{t("Жмите «Принять»")}</a>
)}
<div className={css.bench}>
<h3>{data.bench.length ? t("Свободны — ждут задачу") : t("Все заняты")}</h3>
<ul className={css.seats}>
{data.bench.map((a) => (
<li key={a.id}>
<button type="button" className={css.seat} style={{ color: a.color }} aria-label={t("агент {name} свободен", { name: a.name })} data-open={open === `s${a.id}` ? "" : undefined} onClick={(e) => go(e, `s${a.id}`, () => toCard(a.id))}>
<span className={`${css.seatIcon} ${fresh.has(`${a.id}`) ? css.seatEnter : ""}`}>{initial(a.name)}</span>
<span className={css.tip}>{t("агент {name} свободен", { name: a.name })}</span>
</button>
</li>
))}
</ul>
</div>
<button type="button" className={css.hide} onClick={() => toggle(true)}>{t("Скрыть")}</button>
</div>
</section>
);
}