HeaterHistoryModal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { useState, useEffect } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { X, Flame, Square, Box, TrendingUp, TrendingDown, Minus } from 'lucide-react';
  4. import {
  5. LineChart,
  6. Line,
  7. XAxis,
  8. YAxis,
  9. CartesianGrid,
  10. Tooltip,
  11. ResponsiveContainer,
  12. Legend,
  13. } from 'recharts';
  14. import { api, type HeaterSensorKind, type PrinterSensorHistoryResponse } from '../api/client';
  15. import { parseUTCDate, applyTimeFormat, type TimeFormat } from '../utils/date';
  16. import { useTranslation } from 'react-i18next';
  17. import { useUiSettings } from '../hooks/useUiSettings';
  18. interface HeaterHistoryModalProps {
  19. isOpen: boolean;
  20. onClose: () => void;
  21. printerId: number;
  22. printerName: string;
  23. initialKind?: HeaterSensorKind;
  24. availableKinds?: HeaterSensorKind[];
  25. }
  26. type TimeRange = '6h' | '24h' | '48h' | '7d';
  27. const TIME_RANGES: { value: TimeRange; label: string; hours: number }[] = [
  28. { value: '6h', label: '6h', hours: 6 },
  29. { value: '24h', label: '24h', hours: 24 },
  30. { value: '48h', label: '48h', hours: 48 },
  31. { value: '7d', label: '7d', hours: 168 },
  32. ];
  33. const KIND_COLORS: Record<HeaterSensorKind, string> = {
  34. nozzle: '#fb923c',
  35. nozzle_2: '#f97316',
  36. bed: '#60a5fa',
  37. chamber: '#34d399',
  38. };
  39. const KIND_TARGET_COLORS: Record<HeaterSensorKind, string> = {
  40. nozzle: '#fed7aa',
  41. nozzle_2: '#fdba74',
  42. bed: '#bfdbfe',
  43. chamber: '#a7f3d0',
  44. };
  45. export function HeaterHistoryModal({
  46. isOpen,
  47. onClose,
  48. printerId,
  49. printerName,
  50. initialKind = 'nozzle',
  51. availableKinds = ['nozzle', 'bed', 'chamber'],
  52. }: HeaterHistoryModalProps) {
  53. const { t } = useTranslation();
  54. const [timeRange, setTimeRange] = useState<TimeRange>('24h');
  55. const [kind, setKind] = useState<HeaterSensorKind>(initialKind);
  56. useEffect(() => {
  57. setKind(initialKind);
  58. }, [initialKind]);
  59. const { data: settings } = useUiSettings();
  60. const timeFormat: TimeFormat = settings?.time_format || 'system';
  61. useEffect(() => {
  62. if (!isOpen) return;
  63. const handleKeyDown = (e: KeyboardEvent) => {
  64. if (e.key === 'Escape') onClose();
  65. };
  66. window.addEventListener('keydown', handleKeyDown);
  67. return () => window.removeEventListener('keydown', handleKeyDown);
  68. }, [isOpen, onClose]);
  69. const hours = TIME_RANGES.find(r => r.value === timeRange)?.hours || 24;
  70. const { data, isLoading, error } = useQuery<PrinterSensorHistoryResponse>({
  71. queryKey: ['printer-sensor-history', printerId, hours, availableKinds.join(',')],
  72. queryFn: () => api.getPrinterSensorHistory(printerId, hours, availableKinds),
  73. enabled: isOpen,
  74. refetchInterval: 60000,
  75. });
  76. if (!isOpen) return null;
  77. const series = data?.series.find(s => s.sensor_kind === kind);
  78. const rawPoints = (series?.data || []).map(p => {
  79. const date = parseUTCDate(p.recorded_at) || new Date();
  80. return {
  81. time: date.getTime(),
  82. value: p.value,
  83. target: p.target,
  84. };
  85. });
  86. const domainStart = Date.now() - hours * 60 * 60 * 1000;
  87. const domainEnd = Date.now();
  88. const chartData = [...rawPoints];
  89. if (chartData.length > 0) {
  90. const first = chartData[0];
  91. if (first.time > domainStart) {
  92. chartData.unshift({ ...first, time: domainStart });
  93. }
  94. const last = chartData[chartData.length - 1];
  95. if (last.time < domainEnd) {
  96. chartData.push({ ...last, time: domainEnd });
  97. }
  98. }
  99. const lastPoint = chartData[chartData.length - 1];
  100. const currentValue = lastPoint?.value;
  101. const currentTarget = lastPoint?.target;
  102. const getTrend = (values: (number | null)[]) => {
  103. const filtered = values.filter((v): v is number => v != null);
  104. if (filtered.length < 4) return 'stable';
  105. const firstQuarter = filtered.slice(0, Math.floor(filtered.length / 4));
  106. const lastQuarter = filtered.slice(-Math.floor(filtered.length / 4));
  107. const firstAvg = firstQuarter.reduce((a, b) => a + b, 0) / firstQuarter.length;
  108. const lastAvg = lastQuarter.reduce((a, b) => a + b, 0) / lastQuarter.length;
  109. const diff = lastAvg - firstAvg;
  110. if (Math.abs(diff) < 2) return 'stable';
  111. return diff > 0 ? 'up' : 'down';
  112. };
  113. const trend = getTrend(chartData.map(d => d.value));
  114. const TrendIcon = ({ trend }: { trend: string }) => {
  115. if (trend === 'up') return <TrendingUp className="w-4 h-4 text-red-600 dark:text-red-400" />;
  116. if (trend === 'down') return <TrendingDown className="w-4 h-4 text-green-600 dark:text-green-400" />;
  117. return <Minus className="w-4 h-4 text-gray-400 dark:text-bambu-gray" />;
  118. };
  119. const modalBg = 'var(--bg-secondary)';
  120. const cardBg = 'var(--bg-primary)';
  121. const borderColor = 'var(--border-color)';
  122. const textPrimary = 'var(--text-primary)';
  123. const textSecondary = 'var(--text-secondary)';
  124. const axisColor = 'var(--text-muted)';
  125. const kindLabel = (k: HeaterSensorKind) => {
  126. switch (k) {
  127. case 'nozzle':
  128. return t('printers.heaterHistory.nozzle', 'Nozzle');
  129. case 'nozzle_2':
  130. return t('printers.heaterHistory.nozzle2', 'Nozzle 2');
  131. case 'bed':
  132. return t('printers.heaterHistory.bed', 'Bed');
  133. case 'chamber':
  134. return t('printers.heaterHistory.chamber', 'Chamber');
  135. }
  136. };
  137. const KindIcon = ({ k }: { k: HeaterSensorKind }) => {
  138. if (k === 'nozzle' || k === 'nozzle_2') return <Flame className="w-4 h-4" />;
  139. if (k === 'bed') return <Square className="w-4 h-4" />;
  140. return <Box className="w-4 h-4" />;
  141. };
  142. return (
  143. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
  144. <div
  145. className="rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl"
  146. style={{ backgroundColor: modalBg }}
  147. onClick={e => e.stopPropagation()}
  148. >
  149. <div className="flex items-center justify-between px-6 py-4 border-b" style={{ borderColor }}>
  150. <div>
  151. <h2 className="text-lg font-semibold" style={{ color: textPrimary }}>
  152. {t('printers.heaterHistory.title', 'Heater History')}
  153. </h2>
  154. <p className="text-sm" style={{ color: textSecondary }}>{printerName}</p>
  155. </div>
  156. <button
  157. onClick={onClose}
  158. className="p-2 rounded-lg transition-colors"
  159. style={{ color: textSecondary }}
  160. aria-label={t('common.close', 'Close')}
  161. >
  162. <X className="w-5 h-5" />
  163. </button>
  164. </div>
  165. <div className="p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]">
  166. <div className="flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-3">
  167. <div className="inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit" style={{ backgroundColor: cardBg }}>
  168. {availableKinds.map(k => (
  169. <button
  170. key={k}
  171. onClick={() => setKind(k)}
  172. className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${
  173. kind === k ? 'text-white' : ''
  174. }`}
  175. style={kind === k ? { backgroundColor: KIND_COLORS[k] } : { color: textSecondary }}
  176. >
  177. <KindIcon k={k} />
  178. {kindLabel(k)}
  179. </button>
  180. ))}
  181. </div>
  182. <div className="inline-flex gap-1 rounded-lg p-1 max-w-full flex-wrap w-fit" style={{ backgroundColor: cardBg }}>
  183. {TIME_RANGES.map(range => (
  184. <button
  185. key={range.value}
  186. onClick={() => setTimeRange(range.value)}
  187. className={`px-3 py-1 text-sm rounded-md transition-colors ${
  188. timeRange === range.value ? 'bg-bambu-green text-white' : ''
  189. }`}
  190. style={timeRange !== range.value ? { color: textSecondary } : undefined}
  191. >
  192. {range.label}
  193. </button>
  194. ))}
  195. </div>
  196. </div>
  197. <div className="grid grid-cols-4 gap-4 max-[550px]:grid-cols-2">
  198. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  199. <p className="text-xs" style={{ color: textSecondary }}>{t('common.current', 'Current')}</p>
  200. <div className="flex items-center gap-2">
  201. <p className="text-2xl font-bold" style={{ color: KIND_COLORS[kind] }}>
  202. {currentValue != null ? `${Math.round(currentValue)}°C` : '—'}
  203. </p>
  204. <TrendIcon trend={trend} />
  205. </div>
  206. {currentTarget != null && currentTarget > 0 && (
  207. <p className="text-xs mt-1" style={{ color: textSecondary }}>
  208. {t('common.target', 'Target')}: {Math.round(currentTarget)}°C
  209. </p>
  210. )}
  211. </div>
  212. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  213. <p className="text-xs" style={{ color: textSecondary }}>{t('common.average', 'Average')}</p>
  214. <p className="text-2xl font-bold" style={{ color: textPrimary }}>
  215. {series?.avg_value != null ? `${series.avg_value}°C` : '—'}
  216. </p>
  217. </div>
  218. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  219. <p className="text-xs" style={{ color: textSecondary }}>{t('common.min', 'Min')}</p>
  220. <p className="text-2xl font-bold" style={{ color: textPrimary }}>
  221. {series?.min_value != null ? `${Math.round(series.min_value)}°C` : '—'}
  222. </p>
  223. </div>
  224. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  225. <p className="text-xs" style={{ color: textSecondary }}>{t('common.max', 'Max')}</p>
  226. <p className="text-2xl font-bold" style={{ color: textPrimary }}>
  227. {series?.max_value != null ? `${Math.round(series.max_value)}°C` : '—'}
  228. </p>
  229. </div>
  230. </div>
  231. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  232. {isLoading ? (
  233. <div className="h-64 flex items-center justify-center" style={{ color: textSecondary }}>
  234. {t('common.loading', 'Loading...')}
  235. </div>
  236. ) : error ? (
  237. <div className="h-64 flex items-center justify-center text-red-700 dark:text-red-400">
  238. {t('printers.heaterHistory.error', 'Failed to load history')}
  239. </div>
  240. ) : chartData.length === 0 ? (
  241. <div className="h-64 flex items-center justify-center" style={{ color: textSecondary }}>
  242. {t('printers.heaterHistory.empty', 'No data recorded yet')}
  243. </div>
  244. ) : (
  245. <ResponsiveContainer width="100%" height={300}>
  246. <LineChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
  247. <CartesianGrid strokeDasharray="3 3" stroke={borderColor} />
  248. <XAxis
  249. dataKey="time"
  250. type="number"
  251. domain={[domainStart, domainEnd]}
  252. tickFormatter={ts =>
  253. new Date(ts).toLocaleTimeString(
  254. [],
  255. applyTimeFormat({ hour: '2-digit', minute: '2-digit' }, timeFormat),
  256. )
  257. }
  258. stroke={axisColor}
  259. fontSize={11}
  260. />
  261. <YAxis
  262. stroke={axisColor}
  263. fontSize={11}
  264. domain={[0, 'auto']}
  265. tickFormatter={v => `${Math.round(v)}°`}
  266. />
  267. <Tooltip
  268. contentStyle={{
  269. backgroundColor: modalBg,
  270. border: `1px solid ${borderColor}`,
  271. borderRadius: 6,
  272. color: textPrimary,
  273. }}
  274. labelFormatter={(ts) =>
  275. new Date(ts as number).toLocaleString(
  276. undefined,
  277. applyTimeFormat(
  278. { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' },
  279. timeFormat,
  280. ),
  281. )
  282. }
  283. formatter={(value) => (value != null ? `${Math.round(Number(value))}°C` : '—')}
  284. />
  285. <Legend />
  286. <Line
  287. type="monotone"
  288. dataKey="value"
  289. name={t('common.current', 'Current')}
  290. stroke={KIND_COLORS[kind]}
  291. strokeWidth={2}
  292. dot={false}
  293. isAnimationActive={false}
  294. />
  295. <Line
  296. type="stepAfter"
  297. dataKey="target"
  298. name={t('common.target', 'Target')}
  299. stroke={KIND_TARGET_COLORS[kind]}
  300. strokeDasharray="4 4"
  301. strokeWidth={1.5}
  302. dot={false}
  303. isAnimationActive={false}
  304. />
  305. </LineChart>
  306. </ResponsiveContainer>
  307. )}
  308. </div>
  309. </div>
  310. </div>
  311. </div>
  312. );
  313. }