AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sales-chart.tsx 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import type { PointerEvent } from 'react';
  2. import { useEffect, useId, useRef, useState } from 'react';
  3. import {
  4. prefersReducedMotion,
  5. ringgit,
  6. shortRinggit,
  7. } from '@/components/overview/format';
  8. import type { OverviewStats } from '@/types';
  9. const LEFT = 56;
  10. const RIGHT = 12;
  11. const TOP = 14;
  12. const BOTTOM = 30;
  13. /** A round step for the side labels, so they read RM 0, 200, 400… */
  14. function niceStep(max: number): number {
  15. const raw = Math.max(max, 1) / 4;
  16. const power = 10 ** Math.floor(Math.log10(raw));
  17. return (
  18. [1, 2, 2.5, 5, 10].map((f) => f * power).find((s) => s >= raw) ?? raw
  19. );
  20. }
  21. /**
  22. * Sales over the chosen range, with the period before as a dashed line. Drawn at the real pixel
  23. * width of its box, so the labels stay readable on a phone. Point at it to see each day.
  24. */
  25. export default function SalesChart({ stats }: { stats: OverviewStats }) {
  26. const box = useRef<HTMLDivElement>(null);
  27. const line = useRef<SVGPathElement>(null);
  28. const gradient = useId();
  29. const [width, setWidth] = useState(640);
  30. const [hover, setHover] = useState<number | null>(null);
  31. useEffect(() => {
  32. const element = box.current;
  33. if (!element) {
  34. return;
  35. }
  36. const observer = new ResizeObserver(([entry]) =>
  37. setWidth(Math.max(280, Math.round(entry.contentRect.width))),
  38. );
  39. observer.observe(element);
  40. return () => observer.disconnect();
  41. }, []);
  42. const points = stats.series;
  43. const count = points.length;
  44. const height = width < 500 ? 210 : 260;
  45. // The line draws itself when the data changes.
  46. useEffect(() => {
  47. const path = line.current;
  48. if (!path || prefersReducedMotion()) {
  49. return;
  50. }
  51. const length = path.getTotalLength();
  52. path.style.transition = 'none';
  53. path.style.strokeDasharray = `${length}`;
  54. path.style.strokeDashoffset = `${length}`;
  55. path.getBoundingClientRect();
  56. path.style.transition =
  57. 'stroke-dashoffset 1.1s cubic-bezier(.2,.8,.2,1)';
  58. path.style.strokeDashoffset = '0';
  59. }, [stats.range, stats.sales, count]);
  60. const top = Math.max(
  61. ...points.map((p) => Math.max(p.sales, p.previous)),
  62. 0,
  63. );
  64. const step = niceStep(top);
  65. const yMax = step * 4;
  66. const x = (i: number) =>
  67. LEFT + (count <= 1 ? 0 : (i / (count - 1)) * (width - LEFT - RIGHT));
  68. const y = (value: number) =>
  69. TOP + (1 - value / yMax) * (height - TOP - BOTTOM);
  70. const path = (key: 'sales' | 'previous') =>
  71. points
  72. .map(
  73. (p, i) =>
  74. `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(p[key]).toFixed(1)}`,
  75. )
  76. .join('');
  77. // Side labels must not crowd: keep about 72px between bottom labels.
  78. const pxPer = (width - LEFT - RIGHT) / Math.max(1, count - 1);
  79. const every = Math.max(1, Math.ceil(72 / pxPer));
  80. const last = count - 1;
  81. const onMove = (event: PointerEvent<SVGRectElement>) => {
  82. const rect =
  83. event.currentTarget.ownerSVGElement!.getBoundingClientRect();
  84. const sx = ((event.clientX - rect.left) / rect.width) * width;
  85. setHover(
  86. Math.max(
  87. 0,
  88. Math.min(
  89. last,
  90. Math.round(((sx - LEFT) / (width - LEFT - RIGHT)) * last),
  91. ),
  92. ),
  93. );
  94. };
  95. const hovered = hover !== null ? points[hover] : null;
  96. return (
  97. <div ref={box} className="relative">
  98. <svg
  99. viewBox={`0 0 ${width} ${height}`}
  100. className="block h-auto w-full overflow-visible"
  101. role="img"
  102. aria-label={`Sales ${stats.label.toLowerCase()}: ${ringgit(stats.sales)} in total`}
  103. >
  104. <defs>
  105. <linearGradient id={gradient} x1="0" x2="0" y1="0" y2="1">
  106. <stop
  107. offset="0"
  108. stopColor="var(--ov-pandan)"
  109. stopOpacity="0.22"
  110. />
  111. <stop
  112. offset="1"
  113. stopColor="var(--ov-pandan)"
  114. stopOpacity="0"
  115. />
  116. </linearGradient>
  117. </defs>
  118. {[0, 1, 2, 3, 4].map((k) => (
  119. <g key={k}>
  120. <line
  121. x1={LEFT}
  122. x2={width - RIGHT}
  123. y1={y(step * k)}
  124. y2={y(step * k)}
  125. stroke="var(--ov-line)"
  126. />
  127. <text
  128. x={LEFT - 8}
  129. y={y(step * k) + 4}
  130. textAnchor="end"
  131. className="fill-(--ov-muted) text-[11px] tabular-nums"
  132. >
  133. {shortRinggit(step * k)}
  134. </text>
  135. </g>
  136. ))}
  137. {points.map((p, i) =>
  138. (i % every === 0 && (last - i) * pxPer >= 72) ||
  139. i === last ? (
  140. <text
  141. key={i}
  142. x={x(i)}
  143. y={height - 8}
  144. textAnchor={
  145. i === 0
  146. ? 'start'
  147. : i === last
  148. ? 'end'
  149. : 'middle'
  150. }
  151. className="fill-(--ov-muted) text-[11px]"
  152. >
  153. {p.label}
  154. </text>
  155. ) : null,
  156. )}
  157. <path
  158. d={path('previous')}
  159. fill="none"
  160. stroke="var(--ov-prev)"
  161. strokeWidth="2"
  162. strokeDasharray="5 5"
  163. />
  164. <path
  165. d={`${path('sales')}L${x(last).toFixed(1)},${y(0)}L${x(0)},${y(0)}Z`}
  166. fill={`url(#${gradient})`}
  167. />
  168. <path
  169. ref={line}
  170. d={path('sales')}
  171. fill="none"
  172. stroke="var(--ov-pandan)"
  173. strokeWidth="3"
  174. strokeLinejoin="round"
  175. strokeLinecap="round"
  176. />
  177. <circle
  178. cx={x(last)}
  179. cy={y(points[last]?.sales ?? 0)}
  180. r="5"
  181. fill="var(--ov-pandan)"
  182. stroke="var(--ov-card)"
  183. strokeWidth="2.5"
  184. />
  185. {hovered && hover !== null && (
  186. <>
  187. <line
  188. x1={x(hover)}
  189. x2={x(hover)}
  190. y1={TOP}
  191. y2={height - BOTTOM}
  192. stroke="var(--ov-muted)"
  193. strokeOpacity="0.5"
  194. />
  195. <circle
  196. cx={x(hover)}
  197. cy={y(hovered.sales)}
  198. r="4.5"
  199. fill="var(--ov-pandan)"
  200. stroke="var(--ov-card)"
  201. strokeWidth="2"
  202. />
  203. </>
  204. )}
  205. <rect
  206. x={LEFT}
  207. y={TOP}
  208. width={width - LEFT - RIGHT}
  209. height={height - TOP - BOTTOM}
  210. fill="transparent"
  211. onPointerMove={onMove}
  212. onPointerLeave={() => setHover(null)}
  213. />
  214. </svg>
  215. {hovered && hover !== null && (
  216. <div
  217. className="pointer-events-none absolute rounded-lg bg-(--ov-ink) px-2.5 py-2 text-xs whitespace-nowrap text-(--ov-paper)"
  218. style={{
  219. left: Math.max(70, Math.min(width - 70, x(hover))),
  220. top: y(hovered.sales) - 8,
  221. transform: 'translate(-50%, -100%)',
  222. }}
  223. >
  224. {hovered.label}
  225. <br />
  226. <b className="text-sm tabular-nums">
  227. {ringgit(hovered.sales, hovered.sales % 1 !== 0)}
  228. </b>{' '}
  229. <span className="opacity-70">
  230. before:{' '}
  231. {ringgit(hovered.previous, hovered.previous % 1 !== 0)}
  232. </span>
  233. </div>
  234. )}
  235. </div>
  236. );
  237. }