furhter bug fixes and updates
This commit is contained in:
@@ -29,7 +29,9 @@ const PAD_RIGHT = 8;
|
||||
const PAD_TOP = 8;
|
||||
const PAD_BOTTOM = 30;
|
||||
const Y_MAX = 64; // game's hard player cap
|
||||
const MIN_ZOOM_SPAN_MS = 5 * 60_000; // don't let scroll-zoom go tighter than 5 minutes
|
||||
const MIN_ZOOM_SPAN_MS = 5 * 60_000; // don't zoom in tighter than 5 minutes
|
||||
const HARD_FLOOR_EPOCH = Date.UTC(2015, 6, 16); // won't pan back further than July 16, 2015
|
||||
const FETCH_DEBOUNCE_MS = 400;
|
||||
|
||||
function toLocalInputValue(d: Date): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
@@ -38,6 +40,7 @@ function toLocalInputValue(d: Date): string {
|
||||
|
||||
export default function PopulationChart() {
|
||||
const { ref: containerRef, width } = useContainerWidth<HTMLDivElement>();
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const now = new Date();
|
||||
const dayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
|
||||
@@ -46,19 +49,28 @@ export default function PopulationChart() {
|
||||
const [points, setPoints] = useState<Point[]>([]);
|
||||
const [mapBoundaries, setMapBoundaries] = useState<MapBoundary[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [fetchingMore, setFetchingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Full bounds of whatever's currently fetched (via the calendar Start/End)
|
||||
// Bounds of everything currently loaded (grows as panning/zooming reaches
|
||||
// beyond it and triggers a new fetch — see ensureCoverage below).
|
||||
const [dataMinEpoch, setDataMinEpoch] = useState(0);
|
||||
const [dataMaxEpoch, setDataMaxEpoch] = useState(0);
|
||||
|
||||
// Currently VISIBLE window — what scroll-to-zoom / drag-to-pan adjusts.
|
||||
// Starts equal to the full fetched range and narrows/shifts from there.
|
||||
// The "home" range to return to on Reset — whatever was last explicitly
|
||||
// requested via the calendar Start/End + Update, as opposed to wherever
|
||||
// panning/zooming has since wandered off to.
|
||||
const [homeStart, setHomeStart] = useState(0);
|
||||
const [homeEnd, setHomeEnd] = useState(0);
|
||||
|
||||
// Currently VISIBLE window.
|
||||
const [viewStart, setViewStart] = useState(0);
|
||||
const [viewEnd, setViewEnd] = useState(0);
|
||||
|
||||
const dragStartRef = useRef<{ x: number; viewStart: number; viewEnd: number } | null>(null);
|
||||
const dragMovedRef = useRef(false);
|
||||
const fetchInFlightRef = useRef(false);
|
||||
const wheelDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const [hoverPoint, setHoverPoint] = useState<Point | null>(null);
|
||||
const [hoverX, setHoverX] = useState<number | null>(null);
|
||||
@@ -70,24 +82,44 @@ export default function PopulationChart() {
|
||||
const [currentUpdatedAt, setCurrentUpdatedAt] = useState<number | null>(null);
|
||||
const [secondsAgo, setSecondsAgo] = useState(0);
|
||||
|
||||
// A specific HISTORICAL point clicked on the chart.
|
||||
// A specific HISTORICAL point clicked (or auto-selected as the latest) on the chart.
|
||||
const [selectedPoint, setSelectedPoint] = useState<Point | null>(null);
|
||||
const [selectedPlayers, setSelectedPlayers] = useState<PlayerChip[]>([]);
|
||||
const [loadingSelected, setLoadingSelected] = useState(false);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
async function loadPlayersAt(point: Point) {
|
||||
setSelectedPoint(point);
|
||||
setLoadingSelected(true);
|
||||
try {
|
||||
const res = await fetch(`/api/population/players?at=${encodeURIComponent(point.t)}`);
|
||||
const data = await res.json();
|
||||
setSelectedPlayers(data.players ?? []);
|
||||
} catch {
|
||||
setSelectedPlayers([]);
|
||||
} finally {
|
||||
setLoadingSelected(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRange(
|
||||
rangeStartMs: number,
|
||||
rangeEndMs: number,
|
||||
opts: { preserveView?: boolean; selectLatest?: boolean } = {},
|
||||
) {
|
||||
const { preserveView = false, selectLatest = false } = opts;
|
||||
if (preserveView) setFetchingMore(true);
|
||||
else setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
start: new Date(start).toISOString(),
|
||||
end: new Date(end).toISOString(),
|
||||
start: new Date(rangeStartMs).toISOString(),
|
||||
end: new Date(rangeEndMs).toISOString(),
|
||||
});
|
||||
const res = await fetch(`/api/population?${params.toString()}`);
|
||||
if (!res.ok) throw new Error((await res.json()).error ?? 'failed to load');
|
||||
const data = await res.json();
|
||||
const pts: Point[] = (data.points as any[]).map((p) => ({ ...p, tEpoch: new Date(p.t).getTime() }));
|
||||
const bounds: MapBoundary[] = (data.mapBoundaries as any[]).map((b) => ({ ...b, tEpoch: new Date(b.t).getTime() }));
|
||||
const pts: Point[] = (data.points as any[]).map((p: any) => ({ ...p, tEpoch: new Date(p.t).getTime() }));
|
||||
const bounds: MapBoundary[] = (data.mapBoundaries as any[]).map((b: any) => ({ ...b, tEpoch: new Date(b.t).getTime() }));
|
||||
setPoints(pts);
|
||||
setMapBoundaries(bounds);
|
||||
if (pts.length > 0) {
|
||||
@@ -95,13 +127,25 @@ export default function PopulationChart() {
|
||||
const maxE = pts[pts.length - 1].tEpoch;
|
||||
setDataMinEpoch(minE);
|
||||
setDataMaxEpoch(maxE);
|
||||
setViewStart(minE);
|
||||
setViewEnd(maxE);
|
||||
// Deliberately NOT syncing the start/end calendar fields to minE/maxE
|
||||
// here — those are bucket-boundary timestamps (up to one bucket
|
||||
// width earlier than what was actually requested), not the real
|
||||
// request range. Overwriting the inputs with them caused Update to
|
||||
// silently shrink the End field by one bucket width on every click.
|
||||
// The calendar fields should only ever reflect what was typed.
|
||||
if (!preserveView) {
|
||||
setViewStart(minE);
|
||||
setViewEnd(maxE);
|
||||
setHomeStart(minE);
|
||||
setHomeEnd(maxE);
|
||||
}
|
||||
if (selectLatest) loadPlayersAt(pts[pts.length - 1]);
|
||||
}
|
||||
} catch (e: any) {
|
||||
setError(e.message ?? 'something went wrong');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setFetchingMore(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,7 +166,7 @@ export default function PopulationChart() {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
fetchRange(dayAgo.getTime(), now.getTime(), { selectLatest: true });
|
||||
loadCurrentPlayers();
|
||||
const poll = setInterval(loadCurrentPlayers, 30_000);
|
||||
return () => clearInterval(poll);
|
||||
@@ -136,18 +180,18 @@ export default function PopulationChart() {
|
||||
return () => clearInterval(tick);
|
||||
}, [currentUpdatedAt]);
|
||||
|
||||
async function loadPlayersAt(point: Point) {
|
||||
setSelectedPoint(point);
|
||||
setLoadingSelected(true);
|
||||
try {
|
||||
const res = await fetch(`/api/population/players?at=${encodeURIComponent(point.t)}`);
|
||||
const data = await res.json();
|
||||
setSelectedPlayers(data.players ?? []);
|
||||
} catch {
|
||||
setSelectedPlayers([]);
|
||||
} finally {
|
||||
setLoadingSelected(false);
|
||||
}
|
||||
// If the visible window extends beyond what's loaded, fetch more —
|
||||
// fires after a drag ends or a short pause after scroll-zooming, not on
|
||||
// every intermediate frame.
|
||||
function ensureCoverage(neededStart: number, neededEnd: number) {
|
||||
if (fetchInFlightRef.current) return;
|
||||
if (neededStart >= dataMinEpoch && neededEnd <= dataMaxEpoch) return;
|
||||
fetchInFlightRef.current = true;
|
||||
const fetchStart = Math.min(neededStart, dataMinEpoch);
|
||||
const fetchEnd = Math.max(neededEnd, dataMaxEpoch);
|
||||
fetchRange(fetchStart, fetchEnd, { preserveView: true }).finally(() => {
|
||||
fetchInFlightRef.current = false;
|
||||
});
|
||||
}
|
||||
|
||||
const plotWidth = Math.max(0, width - PAD_LEFT - PAD_RIGHT);
|
||||
@@ -165,8 +209,6 @@ export default function PopulationChart() {
|
||||
return viewStart + ((x - PAD_LEFT) / plotWidth) * (viewEnd - viewStart);
|
||||
}
|
||||
|
||||
// Render a couple of points beyond each edge of the visible window too,
|
||||
// so the line doesn't visibly truncate right at the viewport boundary.
|
||||
let firstIdx = points.findIndex((p) => p.tEpoch >= viewStart);
|
||||
if (firstIdx === -1) firstIdx = points.length - 1;
|
||||
let lastIdx = -1;
|
||||
@@ -184,6 +226,12 @@ export default function PopulationChart() {
|
||||
.map((p, i) => `${i === 0 ? 'M' : 'L'} ${xForEpoch(p.tEpoch).toFixed(1)} ${yForValue(p.players).toFixed(1)}`)
|
||||
.join(' ');
|
||||
|
||||
const baselineY = PAD_TOP + plotHeight;
|
||||
const areaPath =
|
||||
renderPoints.length > 0
|
||||
? `${linePath} L ${xForEpoch(renderPoints[renderPoints.length - 1].tEpoch).toFixed(1)} ${baselineY} L ${xForEpoch(renderPoints[0].tEpoch).toFixed(1)} ${baselineY} Z`
|
||||
: '';
|
||||
|
||||
const visibleBoundaries = mapBoundaries.filter((b) => b.tEpoch >= viewStart && b.tEpoch <= viewEnd);
|
||||
|
||||
function findNearestPoint(x: number): Point | null {
|
||||
@@ -221,12 +269,14 @@ export default function PopulationChart() {
|
||||
const epochDelta = -(dx / plotWidth) * span;
|
||||
let newStart = dragStartRef.current.viewStart + epochDelta;
|
||||
let newEnd = dragStartRef.current.viewEnd + epochDelta;
|
||||
if (newStart < dataMinEpoch) {
|
||||
newStart = dataMinEpoch;
|
||||
|
||||
if (newStart < HARD_FLOOR_EPOCH) {
|
||||
newStart = HARD_FLOOR_EPOCH;
|
||||
newEnd = newStart + span;
|
||||
}
|
||||
if (newEnd > dataMaxEpoch) {
|
||||
newEnd = dataMaxEpoch;
|
||||
const rightLimit = Date.now();
|
||||
if (newEnd > rightLimit) {
|
||||
newEnd = rightLimit;
|
||||
newStart = newEnd - span;
|
||||
}
|
||||
setViewStart(newStart);
|
||||
@@ -236,6 +286,9 @@ export default function PopulationChart() {
|
||||
}
|
||||
|
||||
function handleMouseUp() {
|
||||
if (dragMovedRef.current) {
|
||||
ensureCoverage(viewStart, viewEnd);
|
||||
}
|
||||
dragStartRef.current = null;
|
||||
}
|
||||
|
||||
@@ -255,41 +308,58 @@ export default function PopulationChart() {
|
||||
if (p) loadPlayersAt(p);
|
||||
}
|
||||
|
||||
function handleWheel(e: React.WheelEvent<SVGSVGElement>) {
|
||||
e.preventDefault();
|
||||
if (plotWidth === 0) return;
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const anchorEpoch = epochForX(x);
|
||||
const zoomFactor = e.deltaY > 0 ? 1.15 : 1 / 1.15; // scroll down = zoom out, up = zoom in
|
||||
// Native (non-passive) wheel listener — React's onWheel is passive by
|
||||
// default, so e.preventDefault() silently does nothing there and the
|
||||
// page scrolls along with the zoom. This is the only way to actually
|
||||
// stop that.
|
||||
useEffect(() => {
|
||||
const svg = svgRef.current;
|
||||
if (!svg) return;
|
||||
|
||||
const fullSpan = dataMaxEpoch - dataMinEpoch || 1;
|
||||
let newSpan = (viewEnd - viewStart) * zoomFactor;
|
||||
newSpan = Math.min(newSpan, fullSpan);
|
||||
newSpan = Math.max(newSpan, MIN_ZOOM_SPAN_MS);
|
||||
function onWheel(e: WheelEvent) {
|
||||
e.preventDefault();
|
||||
if (plotWidth === 0) return;
|
||||
const rect = svg!.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const anchorEpoch = epochForX(x);
|
||||
const zoomFactor = e.deltaY > 0 ? 1.15 : 1 / 1.15;
|
||||
|
||||
const ratio = (anchorEpoch - viewStart) / ((viewEnd - viewStart) || 1);
|
||||
let newStart = anchorEpoch - ratio * newSpan;
|
||||
let newEnd = newStart + newSpan;
|
||||
const fullSpan = Date.now() - HARD_FLOOR_EPOCH;
|
||||
let newSpan = (viewEnd - viewStart) * zoomFactor;
|
||||
newSpan = Math.min(newSpan, fullSpan);
|
||||
newSpan = Math.max(newSpan, MIN_ZOOM_SPAN_MS);
|
||||
|
||||
if (newStart < dataMinEpoch) {
|
||||
newStart = dataMinEpoch;
|
||||
newEnd = newStart + newSpan;
|
||||
const ratio = (anchorEpoch - viewStart) / ((viewEnd - viewStart) || 1);
|
||||
let newStart = anchorEpoch - ratio * newSpan;
|
||||
let newEnd = newStart + newSpan;
|
||||
|
||||
if (newStart < HARD_FLOOR_EPOCH) {
|
||||
newStart = HARD_FLOOR_EPOCH;
|
||||
newEnd = newStart + newSpan;
|
||||
}
|
||||
const rightLimit = Date.now();
|
||||
if (newEnd > rightLimit) {
|
||||
newEnd = rightLimit;
|
||||
newStart = newEnd - newSpan;
|
||||
}
|
||||
setViewStart(newStart);
|
||||
setViewEnd(newEnd);
|
||||
|
||||
if (wheelDebounceRef.current) clearTimeout(wheelDebounceRef.current);
|
||||
wheelDebounceRef.current = setTimeout(() => ensureCoverage(newStart, newEnd), FETCH_DEBOUNCE_MS);
|
||||
}
|
||||
if (newEnd > dataMaxEpoch) {
|
||||
newEnd = dataMaxEpoch;
|
||||
newStart = newEnd - newSpan;
|
||||
}
|
||||
setViewStart(newStart);
|
||||
setViewEnd(newEnd);
|
||||
}
|
||||
|
||||
svg.addEventListener('wheel', onWheel, { passive: false });
|
||||
return () => svg.removeEventListener('wheel', onWheel);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [viewStart, viewEnd, plotWidth, dataMinEpoch, dataMaxEpoch]);
|
||||
|
||||
function resetZoom() {
|
||||
setViewStart(dataMinEpoch);
|
||||
setViewEnd(dataMaxEpoch);
|
||||
setViewStart(homeStart);
|
||||
setViewEnd(homeEnd);
|
||||
}
|
||||
|
||||
const isZoomed = viewStart > dataMinEpoch + 1000 || viewEnd < dataMaxEpoch - 1000;
|
||||
const isZoomed = viewStart > homeStart + 1000 || viewEnd < homeEnd - 1000;
|
||||
const yTicks = [0, 16, 32, 48, 64];
|
||||
const xTickCount = 5;
|
||||
const xTicks =
|
||||
@@ -303,7 +373,10 @@ export default function PopulationChart() {
|
||||
<div className="mb-6 pb-6 border-b border-base-border">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="w-2 h-2 rounded-full bg-accent shadow-[0_0_6px_theme(colors.accent.DEFAULT)]" />
|
||||
<span className="relative flex w-2 h-2">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-accent opacity-60" />
|
||||
<span className="relative inline-flex rounded-full w-2 h-2 bg-accent shadow-[0_0_6px_theme(colors.accent.DEFAULT)]" />
|
||||
</span>
|
||||
<div className="stat-label">
|
||||
Currently online{currentCount != null ? ` — ${currentCount} player${currentCount === 1 ? '' : 's'}` : ''}
|
||||
</div>
|
||||
@@ -322,7 +395,7 @@ export default function PopulationChart() {
|
||||
className="flex flex-wrap items-center gap-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
load();
|
||||
fetchRange(new Date(start).getTime(), new Date(end).getTime(), { selectLatest: true });
|
||||
}}
|
||||
>
|
||||
<label className="flex flex-col text-xs text-ink-muted gap-1">
|
||||
@@ -360,7 +433,8 @@ export default function PopulationChart() {
|
||||
<path d="M9 9l6 6M9 15l6-6" strokeLinecap="round" />
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
</svg>
|
||||
Scroll to zoom, drag to pan, click a point for who was online
|
||||
Scroll to zoom, drag to pan (all the way back to 2015), click a point for who was online
|
||||
{fetchingMore && <span className="text-ink-faint">— loading more…</span>}
|
||||
</div>
|
||||
{isZoomed && (
|
||||
<button onClick={resetZoom} className="text-xs text-ink-muted hover:text-accent transition-colors underline">
|
||||
@@ -376,6 +450,7 @@ export default function PopulationChart() {
|
||||
<div className="h-full flex items-center justify-center text-ink-muted text-sm">No data in this range.</div>
|
||||
) : (
|
||||
<svg
|
||||
ref={svgRef}
|
||||
width={width}
|
||||
height={HEIGHT}
|
||||
style={{ cursor: 'crosshair', touchAction: 'none' }}
|
||||
@@ -384,8 +459,14 @@ export default function PopulationChart() {
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onClick={handleClick}
|
||||
onWheel={handleWheel}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="popAreaGradient" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="#3FD37A" stopOpacity="0.28" />
|
||||
<stop offset="100%" stopColor="#3FD37A" stopOpacity="0" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
{yTicks.map((v) => {
|
||||
const y = yForValue(v);
|
||||
return (
|
||||
@@ -418,17 +499,34 @@ export default function PopulationChart() {
|
||||
|
||||
<line x1={PAD_LEFT} y1={PAD_TOP + plotHeight} x2={width - PAD_RIGHT} y2={PAD_TOP + plotHeight} stroke="#4C5652" />
|
||||
|
||||
<path d={linePath} fill="none" stroke="#3FD37A" strokeWidth={2} />
|
||||
<path d={areaPath} fill="url(#popAreaGradient)" stroke="none" />
|
||||
<path
|
||||
d={linePath}
|
||||
fill="none"
|
||||
stroke="#3FD37A"
|
||||
strokeWidth={2}
|
||||
strokeLinejoin="round"
|
||||
style={{ filter: 'drop-shadow(0 0 5px rgba(63, 211, 122, 0.45))' }}
|
||||
/>
|
||||
|
||||
{hoverPoint && (
|
||||
<circle
|
||||
cx={xForEpoch(hoverPoint.tEpoch)}
|
||||
cy={yForValue(hoverPoint.players)}
|
||||
r={4}
|
||||
fill="#3FD37A"
|
||||
stroke="#0B0F0E"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
<g>
|
||||
<circle
|
||||
cx={xForEpoch(hoverPoint.tEpoch)}
|
||||
cy={yForValue(hoverPoint.players)}
|
||||
r={9}
|
||||
fill="#3FD37A"
|
||||
fillOpacity={0.15}
|
||||
/>
|
||||
<circle
|
||||
cx={xForEpoch(hoverPoint.tEpoch)}
|
||||
cy={yForValue(hoverPoint.players)}
|
||||
r={4}
|
||||
fill="#3FD37A"
|
||||
stroke="#0B0F0E"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user