FilamentTrends.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. import { useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. AreaChart,
  5. Area,
  6. XAxis,
  7. YAxis,
  8. CartesianGrid,
  9. Tooltip,
  10. ResponsiveContainer,
  11. PieChart,
  12. Pie,
  13. Cell,
  14. } from 'recharts';
  15. import type { ArchiveSlim } from '../api/client';
  16. import { MetricToggle, type Metric } from './MetricToggle';
  17. import { parseUTCDate } from '../utils/date';
  18. import { formatWeight } from '../utils/weight';
  19. import { splitFilamentTypes } from '../utils/filamentTypes';
  20. interface FilamentTrendsProps {
  21. archives: ArchiveSlim[];
  22. currency?: string;
  23. dateFrom?: string;
  24. dateTo?: string;
  25. }
  26. /** An archive's materials, or 'Unknown' when it has none (#3262). */
  27. function archiveFilamentTypes(filamentType: string | null | undefined): string[] {
  28. const types = splitFilamentTypes(filamentType);
  29. return types.length ? types : ['Unknown'];
  30. }
  31. const COLORS = ['#00ae42', '#3b82f6', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#14b8a6', '#f97316'];
  32. const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  33. const HOUR_SUFFIXES = ['12am', '1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm'];
  34. export function FilamentTrends({ archives, currency = '$', dateFrom, dateTo }: FilamentTrendsProps) {
  35. const { t } = useTranslation();
  36. const [filamentTypeMetric, setFilamentTypeMetric] = useState<Metric>('weight');
  37. const [colorMetric, setColorMetric] = useState<Metric>('weight');
  38. // Calculate daily usage data
  39. const dailyData = useMemo(() => {
  40. const dataMap = new Map<string, { date: string; filament: number; cost: number; energy: number; prints: number }>();
  41. archives.forEach(archive => {
  42. const date = parseUTCDate(archive.completed_at || archive.created_at) || new Date();
  43. // Use local date string for grouping
  44. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  45. const existing = dataMap.get(key) || { date: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  46. existing.filament += archive.filament_used_grams || 0;
  47. existing.cost += archive.cost || 0;
  48. existing.energy += archive.energy_kwh || 0;
  49. existing.prints += archive.quantity ?? 1;
  50. dataMap.set(key, existing);
  51. });
  52. return Array.from(dataMap.values())
  53. .sort((a, b) => a.date.localeCompare(b.date))
  54. .map(d => ({
  55. ...d,
  56. dateLabel: new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
  57. }));
  58. }, [archives]);
  59. // Compute effective span in days from props or archive spread
  60. const spanDays = useMemo(() => {
  61. if (dateFrom && dateTo) {
  62. return Math.max((new Date(dateTo).getTime() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  63. }
  64. if (dateFrom) {
  65. return Math.max((Date.now() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  66. }
  67. if (archives.length < 2) return 0;
  68. const times = archives.map(a => new Date(a.completed_at || a.created_at).getTime());
  69. return (Math.max(...times) - Math.min(...times)) / 86400000;
  70. }, [archives, dateFrom, dateTo]);
  71. // Calculate hourly data for short timeframes (≤ 7 days)
  72. const hourlyData = useMemo(() => {
  73. if (spanDays > 7) return [];
  74. const dataMap = new Map<string, { date: string; filament: number; cost: number; energy: number; prints: number }>();
  75. const multiDay = spanDays > 1;
  76. archives.forEach(archive => {
  77. const date = parseUTCDate(archive.completed_at || archive.created_at) || new Date();
  78. const h = date.getHours();
  79. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}T${String(h).padStart(2, '0')}`;
  80. const existing = dataMap.get(key) || { date: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  81. existing.filament += archive.filament_used_grams || 0;
  82. existing.cost += archive.cost || 0;
  83. existing.energy += archive.energy_kwh || 0;
  84. existing.prints += archive.quantity ?? 1;
  85. dataMap.set(key, existing);
  86. });
  87. return Array.from(dataMap.values())
  88. .sort((a, b) => a.date.localeCompare(b.date))
  89. .map(d => {
  90. const [datePart, hourPart] = d.date.split('T');
  91. const dt = new Date(datePart);
  92. const h = parseInt(hourPart, 10);
  93. const label = multiDay
  94. ? `${DAY_NAMES[dt.getDay()]} ${HOUR_SUFFIXES[h]}`
  95. : HOUR_SUFFIXES[h];
  96. return { ...d, dateLabel: label };
  97. });
  98. }, [archives, spanDays]);
  99. // Calculate weekly aggregated data when there are many daily points
  100. const weeklyData = useMemo(() => {
  101. if (dailyData.length <= 60) return dailyData;
  102. const dataMap = new Map<string, { week: string; filament: number; cost: number; energy: number; prints: number }>();
  103. dailyData.forEach(day => {
  104. const date = new Date(day.date);
  105. const weekStart = new Date(date);
  106. weekStart.setDate(date.getDate() - date.getDay());
  107. const key = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(2, '0')}`;
  108. const existing = dataMap.get(key) || { week: key, filament: 0, cost: 0, energy: 0, prints: 0 };
  109. existing.filament += day.filament;
  110. existing.cost += day.cost;
  111. existing.energy += day.energy;
  112. existing.prints += day.prints;
  113. dataMap.set(key, existing);
  114. });
  115. return Array.from(dataMap.values())
  116. .sort((a, b) => a.week.localeCompare(b.week))
  117. .map(d => ({
  118. date: d.week,
  119. dateLabel: `Week of ${new Date(d.week).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`,
  120. ...d,
  121. }));
  122. }, [dailyData]);
  123. // Usage by filament type
  124. const filamentTypeData = useMemo(() => {
  125. const dataMap = new Map<string, number>();
  126. archives.forEach(archive => {
  127. // Multiple types (e.g. "PLA, PETG" or "PLA Basic,PLA") share the print
  128. const types = archiveFilamentTypes(archive.filament_type);
  129. types.forEach(t => {
  130. const grams = (archive.filament_used_grams || 0) / types.length;
  131. dataMap.set(t, (dataMap.get(t) || 0) + grams);
  132. });
  133. });
  134. return Array.from(dataMap.entries())
  135. .map(([name, value]) => ({ name, value: Math.round(value) }))
  136. .sort((a, b) => b.value - a.value);
  137. }, [archives]);
  138. // Usage by filament type (print count)
  139. const filamentTypePrintData = useMemo(() => {
  140. const dataMap = new Map<string, number>();
  141. archives.forEach(archive => {
  142. const types = archiveFilamentTypes(archive.filament_type);
  143. types.forEach(t => {
  144. dataMap.set(t, (dataMap.get(t) || 0) + 1);
  145. });
  146. });
  147. return Array.from(dataMap.entries())
  148. .map(([name, value]) => ({ name, value }))
  149. .sort((a, b) => b.value - a.value);
  150. }, [archives]);
  151. // Usage by filament type (print time in hours)
  152. const filamentTypeTimeData = useMemo(() => {
  153. const dataMap = new Map<string, number>();
  154. archives.forEach(archive => {
  155. const types = archiveFilamentTypes(archive.filament_type);
  156. const seconds = (archive.actual_time_seconds || archive.print_time_seconds || 0) / types.length;
  157. types.forEach(t => {
  158. dataMap.set(t, (dataMap.get(t) || 0) + seconds);
  159. });
  160. });
  161. return Array.from(dataMap.entries())
  162. .map(([name, seconds]) => ({ name, value: Math.round((seconds / 3600) * 10) / 10 }))
  163. .sort((a, b) => b.value - a.value);
  164. }, [archives]);
  165. // Success rate by filament type
  166. const filamentSuccessData = useMemo(() => {
  167. const map = new Map<string, { completed: number; failed: number }>();
  168. archives.forEach(a => {
  169. if (a.status !== 'completed' && a.status !== 'failed') return;
  170. const types = archiveFilamentTypes(a.filament_type);
  171. types.forEach(type => {
  172. const entry = map.get(type) || { completed: 0, failed: 0 };
  173. if (a.status === 'completed') entry.completed++;
  174. else entry.failed++;
  175. map.set(type, entry);
  176. });
  177. });
  178. return Array.from(map.entries())
  179. .filter(([, v]) => v.completed + v.failed >= 2)
  180. .map(([name, v]) => {
  181. const total = v.completed + v.failed;
  182. const rate = Math.round((v.completed / total) * 100);
  183. return { name, rate, total };
  184. })
  185. .sort((a, b) => b.rate - a.rate);
  186. }, [archives]);
  187. // Color distribution
  188. const colorData = useMemo(() => {
  189. const colorMap = new Map<string, { count: number; weight: number }>();
  190. archives.forEach(a => {
  191. if (!a.filament_color) return;
  192. const colors = a.filament_color.split(',').map(c => c.trim());
  193. const weightPerColor = (a.filament_used_grams || 0) / colors.length;
  194. colors.forEach(hex => {
  195. const entry = colorMap.get(hex) || { count: 0, weight: 0 };
  196. entry.count++;
  197. entry.weight += weightPerColor;
  198. colorMap.set(hex, entry);
  199. });
  200. });
  201. return Array.from(colorMap.entries())
  202. .map(([hex, data]) => ({
  203. hex,
  204. value: colorMetric === 'prints' ? data.count : Math.round(data.weight),
  205. }))
  206. .sort((a, b) => b.value - a.value);
  207. }, [archives, colorMetric]);
  208. const activeFilamentTypeData =
  209. filamentTypeMetric === 'weight' ? filamentTypeData :
  210. filamentTypeMetric === 'prints' ? filamentTypePrintData :
  211. filamentTypeTimeData;
  212. const chartData = spanDays <= 7 && hourlyData.length > 0 ? hourlyData : weeklyData;
  213. const totalFilament = archives.reduce((sum, a) => sum + (a.filament_used_grams || 0), 0);
  214. const totalCost = archives.reduce((sum, a) => sum + (a.cost || 0), 0);
  215. const totalEnergy = archives.reduce((sum, a) => sum + (a.energy_kwh || 0), 0);
  216. const totalEnergyCost = archives.reduce((sum, a) => sum + (a.energy_cost || 0), 0);
  217. // `??`, not `||`: an archive edited down to 0 produced nothing (#3051), and
  218. // `0 || 1` would count the ruined plate as one print here while the project
  219. // page correctly counts none.
  220. const totalPrints = archives.reduce((sum, a) => sum + (a.quantity ?? 1), 0);
  221. const printerCount = new Set(archives.map(a => a.printer_id).filter(Boolean)).size;
  222. return (
  223. <div className="space-y-4">
  224. {/* Summary Cards */}
  225. <div className="grid grid-cols-3 gap-2 max-[640px]:grid-cols-1">
  226. <div className="bg-bambu-dark rounded-lg p-4">
  227. <div className="flex items-center justify-between gap-2">
  228. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodFilament')}</p>
  229. <p className="text-2xl font-bold text-white leading-none">{formatWeight(totalFilament)}</p>
  230. </div>
  231. <p className="text-xs text-bambu-gray">{printerCount} {t('nav.printers').toLowerCase()}</p>
  232. </div>
  233. <div className="bg-bambu-dark rounded-lg p-4">
  234. <div className="flex items-center justify-between gap-2">
  235. <p className="text-sm text-bambu-gray leading-none">{t('stats.periodCost')}</p>
  236. <p className="text-2xl font-bold text-white leading-none">{currency}{totalCost.toFixed(2)}</p>
  237. </div>
  238. <p className="text-xs text-bambu-gray">{totalPrints} {t('common.prints')}</p>
  239. </div>
  240. <div className="bg-bambu-dark rounded-lg p-4">
  241. <div className="flex items-center justify-between gap-2">
  242. <p className="text-sm text-bambu-gray leading-none">{t('stats.avgPerPrint')}</p>
  243. <p className="text-2xl font-bold text-white leading-none">
  244. {totalPrints > 0
  245. ? (totalFilament / totalPrints).toFixed(0)
  246. : 0}g
  247. </p>
  248. </div>
  249. <p className="text-xs text-bambu-gray">
  250. {currency}{totalPrints > 0 ? (totalCost / totalPrints).toFixed(2) : '0.00'} avg
  251. </p>
  252. </div>
  253. </div>
  254. {/* Usage Over Time Chart */}
  255. {chartData.length > 0 ? (
  256. <div className="bg-bambu-dark rounded-lg p-4">
  257. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.usageOverTime')}</h4>
  258. <ResponsiveContainer width="100%" height={250}>
  259. <AreaChart data={chartData}>
  260. <defs>
  261. <linearGradient id="colorFilament" x1="0" y1="0" x2="0" y2="1">
  262. <stop offset="5%" stopColor="#00ae42" stopOpacity={0.3}/>
  263. <stop offset="95%" stopColor="#00ae42" stopOpacity={0}/>
  264. </linearGradient>
  265. </defs>
  266. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  267. <XAxis
  268. dataKey="dateLabel"
  269. stroke="#9ca3af"
  270. tick={{ fontSize: 12 }}
  271. interval="preserveStartEnd"
  272. />
  273. <YAxis
  274. stroke="#9ca3af"
  275. tick={{ fontSize: 12 }}
  276. tickFormatter={(value) => `${value}g`}
  277. />
  278. <Tooltip
  279. contentStyle={{
  280. backgroundColor: '#2d2d2d',
  281. border: '1px solid #3d3d3d',
  282. borderRadius: '8px',
  283. }}
  284. labelStyle={{ color: '#fff' }}
  285. formatter={(value) => [`${Number(value ?? 0).toFixed(0)}g`, 'Filament']}
  286. />
  287. <Area
  288. type="monotone"
  289. dataKey="filament"
  290. stroke="#00ae42"
  291. strokeWidth={2}
  292. fillOpacity={1}
  293. fill="url(#colorFilament)"
  294. />
  295. </AreaChart>
  296. </ResponsiveContainer>
  297. </div>
  298. ) : (
  299. <div className="bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray">
  300. {t('stats.noPrintDataInRange')}
  301. </div>
  302. )}
  303. {/* Energy Over Time Chart (#1432) — only when smart-plug per-print data exists */}
  304. {totalEnergy > 0 && chartData.length > 0 && (
  305. <div className="bg-bambu-dark rounded-lg p-4">
  306. <div className="flex items-center justify-between mb-4">
  307. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.energyOverTime')}</h4>
  308. <span className="text-xs text-bambu-gray">
  309. {totalEnergy.toFixed(3)} kWh · {currency}{totalEnergyCost.toFixed(2)}
  310. </span>
  311. </div>
  312. <ResponsiveContainer width="100%" height={250}>
  313. <AreaChart data={chartData}>
  314. <defs>
  315. <linearGradient id="colorEnergy" x1="0" y1="0" x2="0" y2="1">
  316. <stop offset="5%" stopColor="#f59e0b" stopOpacity={0.3}/>
  317. <stop offset="95%" stopColor="#f59e0b" stopOpacity={0}/>
  318. </linearGradient>
  319. </defs>
  320. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  321. <XAxis
  322. dataKey="dateLabel"
  323. stroke="#9ca3af"
  324. tick={{ fontSize: 12 }}
  325. interval="preserveStartEnd"
  326. />
  327. <YAxis
  328. stroke="#9ca3af"
  329. tick={{ fontSize: 12 }}
  330. tickFormatter={(value) => `${value}kWh`}
  331. />
  332. <Tooltip
  333. contentStyle={{
  334. backgroundColor: '#2d2d2d',
  335. border: '1px solid #3d3d3d',
  336. borderRadius: '8px',
  337. }}
  338. labelStyle={{ color: '#fff' }}
  339. formatter={(value) => [`${Number(value ?? 0).toFixed(3)} kWh`, t('stats.energyUsed')]}
  340. />
  341. <Area
  342. type="monotone"
  343. dataKey="energy"
  344. stroke="#f59e0b"
  345. strokeWidth={2}
  346. fillOpacity={1}
  347. fill="url(#colorEnergy)"
  348. />
  349. </AreaChart>
  350. </ResponsiveContainer>
  351. </div>
  352. )}
  353. {/* Bottom Charts */}
  354. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  355. {/* Filament Type Distribution */}
  356. <div className="bg-bambu-dark rounded-lg p-4">
  357. <div className="flex items-center justify-between mb-4">
  358. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.byMaterial')}</h4>
  359. <MetricToggle value={filamentTypeMetric} onChange={setFilamentTypeMetric} />
  360. </div>
  361. {activeFilamentTypeData.length > 0 ? (
  362. <div className="flex items-center gap-4">
  363. <ResponsiveContainer width={160} height={160}>
  364. <PieChart>
  365. <Pie
  366. data={activeFilamentTypeData}
  367. cx="50%"
  368. cy="50%"
  369. innerRadius={40}
  370. outerRadius={70}
  371. paddingAngle={2}
  372. dataKey="value"
  373. >
  374. {activeFilamentTypeData.map((_, index) => (
  375. <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
  376. ))}
  377. </Pie>
  378. <Tooltip
  379. contentStyle={{
  380. backgroundColor: '#2d2d2d',
  381. border: '1px solid #3d3d3d',
  382. borderRadius: '8px',
  383. }}
  384. formatter={(value) => [
  385. filamentTypeMetric === 'weight' ? formatWeight(Number(value ?? 0)) :
  386. filamentTypeMetric === 'time' ? `${Number(value ?? 0)}h` :
  387. `${value ?? 0}`,
  388. filamentTypeMetric === 'weight' ? 'Usage' : filamentTypeMetric === 'time' ? 'Time' : 'Prints',
  389. ]}
  390. />
  391. </PieChart>
  392. </ResponsiveContainer>
  393. <div className="flex-1 space-y-2 overflow-hidden">
  394. {activeFilamentTypeData.map((entry, index) => {
  395. const total = activeFilamentTypeData.reduce((sum, e) => sum + e.value, 0);
  396. const percent = total > 0 ? ((entry.value / total) * 100).toFixed(0) : 0;
  397. return (
  398. <div key={entry.name} className="flex items-center gap-2 text-sm">
  399. <div
  400. className="w-3 h-3 rounded-sm flex-shrink-0"
  401. style={{ backgroundColor: COLORS[index % COLORS.length] }}
  402. />
  403. <span className="text-white truncate flex-1">{entry.name}</span>
  404. <span className="text-bambu-gray flex-shrink-0">
  405. {filamentTypeMetric === 'weight' ? formatWeight(entry.value) :
  406. filamentTypeMetric === 'time' ? `${entry.value}h` :
  407. entry.value} · {percent}%
  408. </span>
  409. </div>
  410. );
  411. })}
  412. </div>
  413. </div>
  414. ) : (
  415. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  416. {t('stats.noFilamentData')}
  417. </div>
  418. )}
  419. </div>
  420. {/* Success by Material */}
  421. <div className="bg-bambu-dark rounded-lg p-4">
  422. <h4 className="text-sm font-medium text-bambu-gray mb-4">{t('stats.filamentSuccess')}</h4>
  423. {filamentSuccessData.length > 0 ? (
  424. <div className="space-y-1.5">
  425. {filamentSuccessData.map(d => (
  426. <div key={d.name} className="flex items-center gap-2 text-sm">
  427. <span className="text-white truncate w-20 flex-shrink-0">{d.name}</span>
  428. <div className="flex-1 h-1.5 bg-bambu-dark-secondary rounded-full">
  429. <div
  430. className={`h-full rounded-full transition-all ${
  431. d.rate >= 90 ? 'bg-status-ok' : d.rate >= 70 ? 'bg-status-warning' : 'bg-status-error'
  432. }`}
  433. style={{ width: `${d.rate}%` }}
  434. />
  435. </div>
  436. <span className={`font-medium flex-shrink-0 tabular-nums ${
  437. d.rate >= 90 ? 'text-status-ok' : d.rate >= 70 ? 'text-status-warning' : 'text-status-error'
  438. }`}>
  439. {d.rate}%
  440. </span>
  441. <span className="text-bambu-gray flex-shrink-0 text-xs">({d.total})</span>
  442. </div>
  443. ))}
  444. </div>
  445. ) : (
  446. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  447. {t('stats.noArchiveData')}
  448. </div>
  449. )}
  450. </div>
  451. {/* Color Distribution */}
  452. <div className="bg-bambu-dark rounded-lg p-4">
  453. <div className="flex items-center justify-between mb-4">
  454. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.colorDistribution')}</h4>
  455. <MetricToggle value={colorMetric} onChange={setColorMetric} exclude={['time']} />
  456. </div>
  457. {colorData.length > 0 ? (() => {
  458. const colorTotal = colorData.reduce((sum, e) => sum + e.value, 0);
  459. return (
  460. <div>
  461. <div className="relative mx-auto" style={{ width: 160, height: 160 }}>
  462. <ResponsiveContainer width="100%" height="100%">
  463. <PieChart>
  464. <Pie
  465. data={colorData}
  466. cx="50%"
  467. cy="50%"
  468. innerRadius={45}
  469. outerRadius={70}
  470. paddingAngle={2}
  471. dataKey="value"
  472. >
  473. {colorData.map((entry, index) => (
  474. <Cell key={`color-${index}`} fill={entry.hex} stroke="#1a1a1a" strokeWidth={1} />
  475. ))}
  476. </Pie>
  477. <Tooltip
  478. contentStyle={{
  479. backgroundColor: '#2d2d2d',
  480. border: '1px solid #3d3d3d',
  481. borderRadius: '8px',
  482. }}
  483. formatter={(value) => [
  484. colorMetric === 'weight' ? formatWeight(Number(value ?? 0)) : `${value ?? 0}`,
  485. colorMetric === 'weight' ? t('stats.filamentByWeight') : t('stats.filamentByPrints'),
  486. ]}
  487. />
  488. </PieChart>
  489. </ResponsiveContainer>
  490. <div className="absolute inset-0 flex flex-col items-center justify-center">
  491. <span className="text-lg font-bold text-white">
  492. {colorMetric === 'weight' ? formatWeight(colorTotal) : colorTotal}
  493. </span>
  494. <span className="text-[10px] text-bambu-gray">
  495. {colorData.length} {colorData.length === 1 ? 'color' : 'colors'}
  496. </span>
  497. </div>
  498. </div>
  499. <div className="grid grid-cols-2 gap-x-3 gap-y-1 mt-2">
  500. {colorData.slice(0, 8).map((entry) => {
  501. const percent = colorTotal > 0 ? ((entry.value / colorTotal) * 100).toFixed(0) : 0;
  502. return (
  503. <div key={entry.hex} className="flex items-center gap-1.5 text-xs min-w-0">
  504. <div className="w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20"
  505. style={{ backgroundColor: entry.hex }} />
  506. <span className="text-bambu-gray truncate">
  507. {percent}%
  508. </span>
  509. </div>
  510. );
  511. })}
  512. </div>
  513. {colorData.length > 8 && (
  514. <p className="text-[10px] text-bambu-gray mt-1 text-center">+{colorData.length - 8} more</p>
  515. )}
  516. </div>
  517. );
  518. })() : (
  519. <div className="h-[160px] flex items-center justify-center text-bambu-gray">
  520. {t('stats.noColorData')}
  521. </div>
  522. )}
  523. </div>
  524. </div>
  525. </div>
  526. );
  527. }