| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- import type { PointerEvent } from 'react';
- import { useEffect, useId, useRef, useState } from 'react';
- import {
- prefersReducedMotion,
- ringgit,
- shortRinggit,
- } from '@/components/overview/format';
- import type { OverviewStats } from '@/types';
-
- const LEFT = 56;
- const RIGHT = 12;
- const TOP = 14;
- const BOTTOM = 30;
-
- /** A round step for the side labels, so they read RM 0, 200, 400… */
- function niceStep(max: number): number {
- const raw = Math.max(max, 1) / 4;
- const power = 10 ** Math.floor(Math.log10(raw));
-
- return (
- [1, 2, 2.5, 5, 10].map((f) => f * power).find((s) => s >= raw) ?? raw
- );
- }
-
- /**
- * Sales over the chosen range, with the period before as a dashed line. Drawn at the real pixel
- * width of its box, so the labels stay readable on a phone. Point at it to see each day.
- */
- export default function SalesChart({ stats }: { stats: OverviewStats }) {
- const box = useRef<HTMLDivElement>(null);
- const line = useRef<SVGPathElement>(null);
- const gradient = useId();
- const [width, setWidth] = useState(640);
- const [hover, setHover] = useState<number | null>(null);
-
- useEffect(() => {
- const element = box.current;
-
- if (!element) {
- return;
- }
-
- const observer = new ResizeObserver(([entry]) =>
- setWidth(Math.max(280, Math.round(entry.contentRect.width))),
- );
- observer.observe(element);
-
- return () => observer.disconnect();
- }, []);
-
- const points = stats.series;
- const count = points.length;
- const height = width < 500 ? 210 : 260;
-
- // The line draws itself when the data changes.
- useEffect(() => {
- const path = line.current;
-
- if (!path || prefersReducedMotion()) {
- return;
- }
-
- const length = path.getTotalLength();
- path.style.transition = 'none';
- path.style.strokeDasharray = `${length}`;
- path.style.strokeDashoffset = `${length}`;
- path.getBoundingClientRect();
- path.style.transition =
- 'stroke-dashoffset 1.1s cubic-bezier(.2,.8,.2,1)';
- path.style.strokeDashoffset = '0';
- }, [stats.range, stats.sales, count]);
-
- const top = Math.max(
- ...points.map((p) => Math.max(p.sales, p.previous)),
- 0,
- );
- const step = niceStep(top);
- const yMax = step * 4;
- const x = (i: number) =>
- LEFT + (count <= 1 ? 0 : (i / (count - 1)) * (width - LEFT - RIGHT));
- const y = (value: number) =>
- TOP + (1 - value / yMax) * (height - TOP - BOTTOM);
- const path = (key: 'sales' | 'previous') =>
- points
- .map(
- (p, i) =>
- `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[key]).toFixed(1)}`,
- )
- .join('');
-
- // Side labels must not crowd: keep about 72px between bottom labels.
- const pxPer = (width - LEFT - RIGHT) / Math.max(1, count - 1);
- const every = Math.max(1, Math.ceil(72 / pxPer));
- const last = count - 1;
-
- const onMove = (event: PointerEvent<SVGRectElement>) => {
- const rect =
- event.currentTarget.ownerSVGElement!.getBoundingClientRect();
- const sx = ((event.clientX - rect.left) / rect.width) * width;
- setHover(
- Math.max(
- 0,
- Math.min(
- last,
- Math.round(((sx - LEFT) / (width - LEFT - RIGHT)) * last),
- ),
- ),
- );
- };
-
- const hovered = hover !== null ? points[hover] : null;
-
- return (
- <div ref={box} className="relative">
- <svg
- viewBox={`0 0 ${width} ${height}`}
- className="block h-auto w-full overflow-visible"
- role="img"
- aria-label={`Sales ${stats.label.toLowerCase()}: ${ringgit(stats.sales)} in total`}
- >
- <defs>
- <linearGradient id={gradient} x1="0" x2="0" y1="0" y2="1">
- <stop
- offset="0"
- stopColor="var(--ov-pandan)"
- stopOpacity="0.22"
- />
- <stop
- offset="1"
- stopColor="var(--ov-pandan)"
- stopOpacity="0"
- />
- </linearGradient>
- </defs>
-
- {[0, 1, 2, 3, 4].map((k) => (
- <g key={k}>
- <line
- x1={LEFT}
- x2={width - RIGHT}
- y1={y(step * k)}
- y2={y(step * k)}
- stroke="var(--ov-line)"
- />
- <text
- x={LEFT - 8}
- y={y(step * k) + 4}
- textAnchor="end"
- className="fill-(--ov-muted) text-[11px] tabular-nums"
- >
- {shortRinggit(step * k)}
- </text>
- </g>
- ))}
-
- {points.map((p, i) =>
- (i % every === 0 && (last - i) * pxPer >= 72) ||
- i === last ? (
- <text
- key={i}
- x={x(i)}
- y={height - 8}
- textAnchor={
- i === 0
- ? 'start'
- : i === last
- ? 'end'
- : 'middle'
- }
- className="fill-(--ov-muted) text-[11px]"
- >
- {p.label}
- </text>
- ) : null,
- )}
-
- <path
- d={path('previous')}
- fill="none"
- stroke="var(--ov-prev)"
- strokeWidth="2"
- strokeDasharray="5 5"
- />
- <path
- d={`${path('sales')}L${x(last).toFixed(1)},${y(0)}L${x(0)},${y(0)}Z`}
- fill={`url(#${gradient})`}
- />
- <path
- ref={line}
- d={path('sales')}
- fill="none"
- stroke="var(--ov-pandan)"
- strokeWidth="3"
- strokeLinejoin="round"
- strokeLinecap="round"
- />
- <circle
- cx={x(last)}
- cy={y(points[last]?.sales ?? 0)}
- r="5"
- fill="var(--ov-pandan)"
- stroke="var(--ov-card)"
- strokeWidth="2.5"
- />
-
- {hovered && hover !== null && (
- <>
- <line
- x1={x(hover)}
- x2={x(hover)}
- y1={TOP}
- y2={height - BOTTOM}
- stroke="var(--ov-muted)"
- strokeOpacity="0.5"
- />
- <circle
- cx={x(hover)}
- cy={y(hovered.sales)}
- r="4.5"
- fill="var(--ov-pandan)"
- stroke="var(--ov-card)"
- strokeWidth="2"
- />
- </>
- )}
-
- <rect
- x={LEFT}
- y={TOP}
- width={width - LEFT - RIGHT}
- height={height - TOP - BOTTOM}
- fill="transparent"
- onPointerMove={onMove}
- onPointerLeave={() => setHover(null)}
- />
- </svg>
-
- {hovered && hover !== null && (
- <div
- className="pointer-events-none absolute rounded-lg bg-(--ov-ink) px-2.5 py-2 text-xs whitespace-nowrap text-(--ov-paper)"
- style={{
- left: Math.max(70, Math.min(width - 70, x(hover))),
- top: y(hovered.sales) - 8,
- transform: 'translate(-50%, -100%)',
- }}
- >
- {hovered.label}
- <br />
- <b className="text-sm tabular-nums">
- {ringgit(hovered.sales, hovered.sales % 1 !== 0)}
- </b>{' '}
- <span className="opacity-70">
- before:{' '}
- {ringgit(hovered.previous, hovered.previous % 1 !== 0)}
- </span>
- </div>
- )}
- </div>
- );
- }
|