SpoolBuddySettingsPage.tsx 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. import { useState, useCallback, useRef, useEffect } from 'react';
  2. import { useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { useOutletContext } from 'react-router-dom';
  4. import { useTranslation } from 'react-i18next';
  5. import type { SpoolBuddyOutletContext } from '../../components/spoolbuddy/SpoolBuddyLayout';
  6. import { spoolbuddyApi, type SpoolBuddyDevice } from '../../api/client';
  7. import { DiagnosticModal } from '../../components/spoolbuddy/DiagnosticModal';
  8. import { FileText, Wand2, Zap } from 'lucide-react';
  9. import { parseUTCDate } from '../../utils/date';
  10. import { useKioskDevice } from '../../hooks/useKioskDevice';
  11. function formatUptime(seconds: number): string {
  12. if (seconds < 60) return `${seconds}s`;
  13. if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
  14. const h = Math.floor(seconds / 3600);
  15. const m = Math.floor((seconds % 3600) / 60);
  16. return `${h}h ${m}m`;
  17. }
  18. function formatDateTime(iso: string | null): string {
  19. if (!iso) return '-';
  20. const d = parseUTCDate(iso);
  21. if (!d) return '-';
  22. return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ' ' +
  23. d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
  24. }
  25. const BLANK_OPTIONS = [
  26. { label: 'Off', value: 0 },
  27. { label: '1m', value: 60 },
  28. { label: '2m', value: 120 },
  29. { label: '5m', value: 300 },
  30. { label: '10m', value: 600 },
  31. { label: '30m', value: 1800 },
  32. ];
  33. // --- Device Tab ---
  34. function DeviceTab({ device }: { device: SpoolBuddyDevice }) {
  35. const { t } = useTranslation();
  36. const queryClient = useQueryClient();
  37. const [diagnosticOpen, setDiagnosticOpen] = useState<'nfc' | 'scale' | 'read_tag' | null>(null);
  38. const [backendUrl, setBackendUrl] = useState('');
  39. const [apiToken, setApiToken] = useState('');
  40. const [systemBusy, setSystemBusy] = useState(false);
  41. const [systemMsg, setSystemMsg] = useState<{ type: 'ok' | 'error'; text: string } | null>(null);
  42. // The daemon writes a saved config to its .env file and keeps running on
  43. // the old values until it restarts.
  44. const [restartOffered, setRestartOffered] = useState(false);
  45. // One command slot per device: a restart queued before the daemon took the
  46. // config would replace it.
  47. const configPending = device.pending_command === 'apply_system_config';
  48. useEffect(() => {
  49. if (!backendUrl && device.backend_url) {
  50. setBackendUrl(device.backend_url);
  51. }
  52. }, [device.backend_url, backendUrl]);
  53. const saveConfig = async () => {
  54. if (!backendUrl.trim()) {
  55. setSystemMsg({ type: 'error', text: t('spoolbuddy.settings.systemFieldsRequired', 'Backend URL is required.') });
  56. return;
  57. }
  58. setSystemBusy(true);
  59. setSystemMsg(null);
  60. try {
  61. await spoolbuddyApi.updateSystemConfig(
  62. device.device_id,
  63. backendUrl.trim(),
  64. apiToken.trim() || undefined
  65. );
  66. // Offered only once the device data shows the queued config, so the
  67. // button cannot be pressed on state from before the save.
  68. await queryClient.refetchQueries({ queryKey: ['spoolbuddy-devices'] });
  69. setSystemMsg({ type: 'ok', text: t('spoolbuddy.settings.systemSavedRestart', 'Saved. Restart the daemon to apply it.') });
  70. setRestartOffered(true);
  71. } catch (e) {
  72. setSystemMsg({ type: 'error', text: e instanceof Error ? e.message : t('common.error', 'Error') });
  73. } finally {
  74. setSystemBusy(false);
  75. }
  76. };
  77. const restartDaemon = async () => {
  78. setSystemBusy(true);
  79. try {
  80. await spoolbuddyApi.systemCommand(device.device_id, 'restart_daemon');
  81. setRestartOffered(false);
  82. setSystemMsg({ type: 'ok', text: t('spoolbuddy.settings.systemRestarting', 'Restarting the daemon...') });
  83. } catch (e) {
  84. setSystemMsg({ type: 'error', text: e instanceof Error ? e.message : t('common.error', 'Error') });
  85. } finally {
  86. setSystemBusy(false);
  87. }
  88. };
  89. return (
  90. <div className="space-y-2">
  91. {/* NFC Reader + Device Info side by side */}
  92. <div className="grid grid-cols-2 gap-2">
  93. {/* NFC Reader */}
  94. <div className="bg-zinc-800 rounded-lg p-3">
  95. <h3 className="text-sm font-semibold text-zinc-300 mb-2">
  96. {t('spoolbuddy.settings.nfcReader', 'NFC Reader')}
  97. </h3>
  98. <div className="space-y-1.5 text-xs">
  99. <div className="flex justify-between">
  100. <span className="text-zinc-500">{t('spoolbuddy.settings.type', 'Type')}</span>
  101. <span className="text-zinc-300 font-mono">
  102. {device.nfc_reader_type || 'N/A'}
  103. </span>
  104. </div>
  105. <div className="flex justify-between">
  106. <span className="text-zinc-500">{t('spoolbuddy.settings.connection', 'Connection')}</span>
  107. <span className="text-zinc-300 font-mono">
  108. {device.nfc_connection || 'N/A'}
  109. </span>
  110. </div>
  111. <div className="flex justify-between items-center">
  112. <span className="text-zinc-500">{t('spoolbuddy.status.status', 'Status')}</span>
  113. <div className="flex items-center gap-1.5">
  114. <div className={`w-2 h-2 rounded-full ${
  115. device.nfc_ok ? 'bg-green-500' : device.nfc_reader_type ? 'bg-red-500' : 'bg-zinc-600'
  116. }`} />
  117. <span className={
  118. device.nfc_ok ? 'text-green-400' : device.nfc_reader_type ? 'text-red-400' : 'text-zinc-500'
  119. }>
  120. {device.nfc_ok
  121. ? t('spoolbuddy.status.nfcReady', 'Ready')
  122. : device.nfc_reader_type
  123. ? t('common.error', 'Error')
  124. : t('spoolbuddy.settings.notConnected', 'N/A')}
  125. </span>
  126. </div>
  127. </div>
  128. </div>
  129. </div>
  130. {/* Device Info */}
  131. <div className="bg-zinc-800 rounded-lg p-3">
  132. <h3 className="text-sm font-semibold text-zinc-300 mb-2">
  133. {t('spoolbuddy.settings.deviceInfo', 'Device Info')}
  134. </h3>
  135. <div className="space-y-1.5 text-xs">
  136. <div className="flex justify-between">
  137. <span className="text-zinc-500">{t('spoolbuddy.settings.hostname', 'Host')}</span>
  138. <span className="text-zinc-300 truncate ml-2">{device.hostname}</span>
  139. </div>
  140. <div className="flex justify-between">
  141. <span className="text-zinc-500">IP</span>
  142. <span className="text-zinc-300">{device.ip_address}</span>
  143. </div>
  144. <div className="flex justify-between">
  145. <span className="text-zinc-500">{t('spoolbuddy.settings.uptime', 'Uptime')}</span>
  146. <span className="text-zinc-300">{formatUptime(device.uptime_s)}</span>
  147. </div>
  148. <div className="flex justify-between">
  149. <span className="text-zinc-500">ID</span>
  150. <span className="text-zinc-400 font-mono truncate ml-2">{device.device_id}</span>
  151. </div>
  152. </div>
  153. </div>
  154. </div>
  155. {/* Backend/Auth + Diagnostics side by side */}
  156. <div className="grid grid-cols-2 gap-2">
  157. {/* Backend/Auth Config */}
  158. <div className="bg-zinc-800 rounded-lg p-3 space-y-2">
  159. <h3 className="text-sm font-semibold text-zinc-300">
  160. {t('spoolbuddy.settings.systemConfig', 'Backend & Auth')}
  161. </h3>
  162. <input
  163. value={backendUrl}
  164. onChange={(e) => setBackendUrl(e.target.value)}
  165. placeholder="http://192.168.1.100:5000"
  166. className="w-full px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"
  167. />
  168. <div className="flex gap-2">
  169. <input
  170. type="password"
  171. value={apiToken}
  172. onChange={(e) => setApiToken(e.target.value)}
  173. placeholder={t('spoolbuddy.settings.apiTokenPlaceholder', 'API token')}
  174. className="flex-1 px-2 py-1.5 rounded bg-zinc-900 border border-zinc-700 text-zinc-100 text-xs"
  175. />
  176. <button
  177. onClick={saveConfig}
  178. disabled={systemBusy}
  179. className="px-3 py-1.5 rounded bg-green-700 hover:bg-green-600 disabled:bg-zinc-700 text-xs font-medium text-zinc-100"
  180. >
  181. {t('spoolbuddy.settings.saveConfig', 'Save')}
  182. </button>
  183. </div>
  184. {systemMsg && (
  185. <div className={`text-xs ${systemMsg.type === 'ok' ? 'text-green-400' : 'text-red-400'}`}>
  186. {systemMsg.text}
  187. </div>
  188. )}
  189. {restartOffered && (
  190. <div className="flex items-center gap-2">
  191. <button
  192. onClick={restartDaemon}
  193. disabled={systemBusy || configPending}
  194. className="px-3 py-1.5 rounded bg-zinc-700 hover:bg-zinc-600 disabled:opacity-50 text-xs font-medium text-zinc-100"
  195. >
  196. {t('spoolbuddy.quickMenu.restartDaemon', 'Restart Daemon')}
  197. </button>
  198. {configPending && (
  199. <span className="text-xs text-zinc-500">
  200. {t('spoolbuddy.settings.systemApplying', 'Waiting for the device to take the config...')}
  201. </span>
  202. )}
  203. </div>
  204. )}
  205. </div>
  206. {/* Diagnostic Buttons */}
  207. <div className="bg-zinc-800 rounded-lg p-3 flex flex-col gap-2">
  208. <button
  209. onClick={() => setDiagnosticOpen('nfc')}
  210. className="flex-1 bg-blue-700 hover:bg-blue-600 transition-colors rounded-lg p-2 flex items-center gap-2"
  211. >
  212. <Wand2 className="w-4 h-4 text-blue-300 shrink-0" />
  213. <span className="text-xs font-medium text-blue-100">
  214. {t('spoolbuddy.settings.nfcDiagnostic', 'NFC Diagnostic')}
  215. </span>
  216. </button>
  217. <button
  218. onClick={() => setDiagnosticOpen('scale')}
  219. className="flex-1 bg-yellow-700 hover:bg-yellow-600 transition-colors rounded-lg p-2 flex items-center gap-2"
  220. >
  221. <Zap className="w-4 h-4 text-yellow-300 shrink-0" />
  222. <span className="text-xs font-medium text-yellow-100">
  223. {t('spoolbuddy.settings.scaleDiagnostic', 'Scale Diagnostic')}
  224. </span>
  225. </button>
  226. <button
  227. onClick={() => setDiagnosticOpen('read_tag')}
  228. className="flex-1 bg-emerald-700 hover:bg-emerald-600 transition-colors rounded-lg p-2 flex items-center gap-2"
  229. >
  230. <FileText className="w-4 h-4 text-emerald-300 shrink-0" />
  231. <span className="text-xs font-medium text-emerald-100">
  232. {t('spoolbuddy.settings.readTagDiagnostic', 'Read Tag')}
  233. </span>
  234. </button>
  235. </div>
  236. </div>
  237. {/* Diagnostic Modal */}
  238. {diagnosticOpen && device && (
  239. <DiagnosticModal
  240. type={diagnosticOpen}
  241. deviceId={device.device_id}
  242. onClose={() => setDiagnosticOpen(null)}
  243. />
  244. )}
  245. </div>
  246. );
  247. }
  248. // --- Display Tab ---
  249. function DisplayTab({ device, onBrightnessChange }: {
  250. device: SpoolBuddyDevice;
  251. onBrightnessChange: (value: number) => void;
  252. }) {
  253. const { t } = useTranslation();
  254. const [brightness, setBrightness] = useState(device.display_brightness);
  255. const [blankTimeout, setBlankTimeout] = useState(device.display_blank_timeout);
  256. const [saved, setSaved] = useState(false);
  257. const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  258. const savedTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
  259. // Sync local state when device data updates from server
  260. useEffect(() => {
  261. setBrightness(device.display_brightness);
  262. setBlankTimeout(device.display_blank_timeout);
  263. }, [device.display_brightness, device.display_blank_timeout]);
  264. const showSaved = useCallback(() => {
  265. setSaved(true);
  266. if (savedTimerRef.current) clearTimeout(savedTimerRef.current);
  267. savedTimerRef.current = setTimeout(() => setSaved(false), 1500);
  268. }, []);
  269. const sendDisplayUpdate = useCallback((b: number, bt: number) => {
  270. if (debounceRef.current) clearTimeout(debounceRef.current);
  271. debounceRef.current = setTimeout(() => {
  272. spoolbuddyApi.updateDisplay(device.device_id, b, bt)
  273. .then(() => showSaved())
  274. .catch((e) => console.error('Failed to update display:', e));
  275. }, 300);
  276. }, [device.device_id, showSaved]);
  277. const handleBrightnessChange = (value: number) => {
  278. setBrightness(value);
  279. onBrightnessChange(value); // Instant layout update
  280. sendDisplayUpdate(value, blankTimeout);
  281. };
  282. const handleBlankTimeoutChange = (value: number) => {
  283. setBlankTimeout(value);
  284. sendDisplayUpdate(brightness, value);
  285. };
  286. return (
  287. <div className="space-y-4">
  288. {/* Brightness */}
  289. <div className="bg-zinc-800 rounded-lg p-4">
  290. <div className="flex items-center justify-between mb-3">
  291. <h3 className="text-sm font-semibold text-zinc-300">
  292. {t('spoolbuddy.settings.brightness', 'Brightness')}
  293. </h3>
  294. {saved && (
  295. <span className="text-xs text-green-400 flex items-center gap-1 animate-pulse">
  296. <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
  297. <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
  298. </svg>
  299. {t('spoolbuddy.settings.saved', 'Saved')}
  300. </span>
  301. )}
  302. </div>
  303. <div className="flex items-center gap-3">
  304. <svg className="w-4 h-4 text-zinc-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
  305. <path strokeLinecap="round" strokeLinejoin="round" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
  306. </svg>
  307. <input
  308. type="range"
  309. min={0}
  310. max={100}
  311. value={brightness}
  312. onChange={(e) => handleBrightnessChange(parseInt(e.target.value))}
  313. className="flex-1 h-2 bg-zinc-700 rounded-lg appearance-none cursor-pointer accent-green-500"
  314. />
  315. <span className="text-sm font-mono text-zinc-400 w-10 text-right">{brightness}%</span>
  316. </div>
  317. {!device.has_backlight && (
  318. <p className="text-xs text-zinc-600 mt-2">
  319. {t('spoolbuddy.settings.noBacklight', 'No DSI backlight detected. Brightness control requires a DSI display.')}
  320. </p>
  321. )}
  322. </div>
  323. {/* Screen blank timeout */}
  324. <div className="bg-zinc-800 rounded-lg p-4">
  325. <h3 className="text-sm font-semibold text-zinc-300 mb-1">
  326. {t('spoolbuddy.settings.screenBlank', 'Screen Blank Timeout')}
  327. </h3>
  328. <p className="text-xs text-zinc-500 mb-3">
  329. {t('spoolbuddy.settings.screenBlankDesc', 'Screen turns off after inactivity. Touch to wake.')}
  330. </p>
  331. <div className="grid grid-cols-3 gap-2">
  332. {BLANK_OPTIONS.map((opt) => (
  333. <button
  334. key={opt.value}
  335. onClick={() => handleBlankTimeoutChange(opt.value)}
  336. className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors min-h-[40px] ${
  337. blankTimeout === opt.value
  338. ? 'bg-green-600 text-white'
  339. : 'bg-zinc-700 text-zinc-300 hover:bg-zinc-600'
  340. }`}
  341. >
  342. {opt.label}
  343. </button>
  344. ))}
  345. </div>
  346. </div>
  347. <p className="text-xs text-zinc-600 text-center">
  348. {t('spoolbuddy.settings.displayNote', 'Brightness is applied as a software filter.')}
  349. </p>
  350. </div>
  351. );
  352. }
  353. // --- Scale Tab ---
  354. function StepIndicator({ step, labels }: { step: 'tare' | 'weight'; labels: { tare: string; weight: string } }) {
  355. return (
  356. <div className="flex flex-col items-center w-16 shrink-0 pt-1">
  357. {/* Step 1 circle */}
  358. <div className={`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${
  359. step === 'tare'
  360. ? 'bg-green-600 text-white'
  361. : 'bg-green-600/20 text-green-400'
  362. }`}>
  363. {step === 'weight' ? (
  364. <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
  365. <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
  366. </svg>
  367. ) : '1'}
  368. </div>
  369. <span className={`text-[10px] mt-0.5 ${step === 'tare' ? 'text-green-400 font-medium' : 'text-green-400/60'}`}>
  370. {labels.tare}
  371. </span>
  372. {/* Connector line */}
  373. <div className={`w-px h-5 my-1 ${step === 'weight' ? 'bg-green-600/40' : 'bg-zinc-700'}`} />
  374. {/* Step 2 circle */}
  375. <div className={`flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold ${
  376. step === 'weight'
  377. ? 'bg-green-600 text-white'
  378. : 'bg-zinc-700 text-zinc-500'
  379. }`}>
  380. 2
  381. </div>
  382. <span className={`text-[10px] mt-0.5 ${step === 'weight' ? 'text-green-400 font-medium' : 'text-zinc-600'}`}>
  383. {labels.weight}
  384. </span>
  385. </div>
  386. );
  387. }
  388. function ScaleTab({ device, weight, weightStable, rawAdc }: {
  389. device: SpoolBuddyDevice;
  390. weight: number | null;
  391. weightStable: boolean;
  392. rawAdc: number | null;
  393. }) {
  394. const { t } = useTranslation();
  395. const queryClient = useQueryClient();
  396. const [calStep, setCalStep] = useState<'idle' | 'tare' | 'weight'>('idle');
  397. const [knownWeight, setKnownWeight] = useState('500');
  398. const [tareRawAdc, setTareRawAdc] = useState<number | null>(null);
  399. const [busy, setBusy] = useState(false);
  400. const [status, setStatus] = useState<{ type: 'ok' | 'error'; msg: string } | null>(null);
  401. // Snapshot of device.last_calibrated_at taken when a tare is dispatched.
  402. // The completion watcher below polls the device list and flips the banner
  403. // to "Tare complete!" (or "Tare timed out") once the daemon writes back
  404. // a new last_calibrated_at. Without this watcher the banner just sat at
  405. // "Waiting for device..." forever (#1536).
  406. const [awaitingTareSince, setAwaitingTareSince] = useState<{ snapshot: string | null; startedAtMs: number } | null>(null);
  407. const dismissTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  408. // Clear any pending auto-dismiss when status changes manually or on unmount.
  409. useEffect(() => {
  410. return () => {
  411. if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
  412. };
  413. }, []);
  414. const scheduleStatusDismiss = useCallback((ms: number) => {
  415. if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
  416. dismissTimerRef.current = setTimeout(() => setStatus(null), ms);
  417. }, []);
  418. // Tare-completion watcher: aggressively re-fetch device data while waiting,
  419. // detect when last_calibrated_at advances past the snapshot, then settle
  420. // the banner. Fails open on a 15s timeout so a dead daemon doesn't leave
  421. // the user staring at "Waiting for device..." indefinitely.
  422. useEffect(() => {
  423. if (!awaitingTareSince) return;
  424. const TARE_TIMEOUT_MS = 15000;
  425. const POLL_INTERVAL_MS = 1000;
  426. const elapsed = () => Date.now() - awaitingTareSince.startedAtMs;
  427. const pollHandle = setInterval(() => {
  428. queryClient.invalidateQueries({ queryKey: ['spoolbuddy-devices'] });
  429. }, POLL_INTERVAL_MS);
  430. const timeoutHandle = setTimeout(() => {
  431. setAwaitingTareSince(null);
  432. setStatus({
  433. type: 'error',
  434. msg: t('spoolbuddy.settings.tareTimedOut', 'Tare timed out — is the SpoolBuddy daemon running?'),
  435. });
  436. scheduleStatusDismiss(5000);
  437. }, Math.max(0, TARE_TIMEOUT_MS - elapsed()));
  438. return () => {
  439. clearInterval(pollHandle);
  440. clearTimeout(timeoutHandle);
  441. };
  442. }, [awaitingTareSince, queryClient, t, scheduleStatusDismiss]);
  443. // When fresh device data arrives, check whether last_calibrated_at moved.
  444. useEffect(() => {
  445. if (!awaitingTareSince) return;
  446. const current = device?.last_calibrated_at ?? null;
  447. if (current !== awaitingTareSince.snapshot) {
  448. setAwaitingTareSince(null);
  449. setStatus({ type: 'ok', msg: t('spoolbuddy.settings.tareComplete', 'Tare complete!') });
  450. scheduleStatusDismiss(3000);
  451. }
  452. }, [device?.last_calibrated_at, awaitingTareSince, t, scheduleStatusDismiss]);
  453. const numpadPress = (key: string) => {
  454. if (key === 'backspace') {
  455. setKnownWeight((v) => v.slice(0, -1) || '');
  456. } else if (key === '.' && !knownWeight.includes('.')) {
  457. setKnownWeight((v) => v + '.');
  458. } else if (key >= '0' && key <= '9') {
  459. setKnownWeight((v) => (v === '0' ? key : v + key));
  460. }
  461. };
  462. const handleTare = async () => {
  463. setBusy(true);
  464. setStatus(null);
  465. if (dismissTimerRef.current) {
  466. clearTimeout(dismissTimerRef.current);
  467. dismissTimerRef.current = null;
  468. }
  469. const snapshot = device?.last_calibrated_at ?? null;
  470. try {
  471. await spoolbuddyApi.tare(device.device_id);
  472. setStatus({ type: 'ok', msg: t('spoolbuddy.settings.tareSet', 'Tare command sent. Waiting for device...') });
  473. setAwaitingTareSince({ snapshot, startedAtMs: Date.now() });
  474. } catch {
  475. setStatus({ type: 'error', msg: t('spoolbuddy.settings.tareFailed', 'Failed to send tare command') });
  476. scheduleStatusDismiss(5000);
  477. } finally {
  478. setBusy(false);
  479. }
  480. };
  481. const handleCalStep = async () => {
  482. if (calStep === 'tare') {
  483. setBusy(true);
  484. setStatus(null);
  485. try {
  486. setTareRawAdc(rawAdc);
  487. await spoolbuddyApi.tare(device.device_id);
  488. setStatus({ type: 'ok', msg: t('spoolbuddy.settings.zeroSet', 'Zero point set. Place known weight on scale.') });
  489. setCalStep('weight');
  490. } catch {
  491. setStatus({ type: 'error', msg: t('spoolbuddy.settings.tareFailed', 'Failed to send tare command') });
  492. } finally {
  493. setBusy(false);
  494. }
  495. } else if (calStep === 'weight') {
  496. const weightNum = parseFloat(knownWeight);
  497. if (rawAdc === null || !weightNum || weightNum <= 0) return;
  498. setBusy(true);
  499. setStatus(null);
  500. try {
  501. await spoolbuddyApi.setCalibrationFactor(device.device_id, weightNum, rawAdc, tareRawAdc ?? undefined);
  502. setStatus({ type: 'ok', msg: t('spoolbuddy.settings.calibrationDone', 'Calibration complete!') });
  503. scheduleStatusDismiss(3000);
  504. setCalStep('idle');
  505. } catch {
  506. setStatus({ type: 'error', msg: t('spoolbuddy.settings.calibrationFailed', 'Calibration failed') });
  507. scheduleStatusDismiss(5000);
  508. } finally {
  509. setBusy(false);
  510. }
  511. }
  512. };
  513. // --- Idle state: weight card + buttons ---
  514. if (calStep === 'idle') {
  515. return (
  516. <div className="flex flex-col h-full">
  517. {/* Weight + info card */}
  518. <div className="bg-zinc-800 rounded-lg p-3 mb-3">
  519. <div className="flex items-center justify-between">
  520. <div className="flex items-center gap-2">
  521. <div className={`w-2 h-2 rounded-full ${weightStable ? 'bg-green-500' : 'bg-amber-500 animate-pulse'}`} />
  522. <span className="text-lg font-mono text-zinc-200">
  523. {weight !== null ? `${weight.toFixed(1)} g` : '-- g'}
  524. </span>
  525. </div>
  526. <div className="text-xs text-zinc-500 text-right">
  527. <span>{t('spoolbuddy.settings.tareOffset', 'Tare')}: {device.tare_offset}</span>
  528. <span className="mx-1.5">&middot;</span>
  529. <span>{t('spoolbuddy.settings.calFactor', 'Factor')}: {device.calibration_factor.toFixed(2)}</span>
  530. </div>
  531. </div>
  532. {device.last_calibrated_at && (
  533. <div className="text-xs text-zinc-600 mt-1">
  534. {t('spoolbuddy.settings.lastCalibrated', 'Last calibrated')}: {formatDateTime(device.last_calibrated_at)}
  535. </div>
  536. )}
  537. </div>
  538. {/* Status message */}
  539. {status && (
  540. <div className={`rounded-lg px-3 py-2 mb-3 text-sm ${
  541. status.type === 'ok' ? 'bg-green-900/30 text-green-300 border border-green-800' : 'bg-red-900/30 text-red-300 border border-red-800'
  542. }`}>
  543. {status.msg}
  544. </div>
  545. )}
  546. {/* Action buttons */}
  547. <div className="flex gap-2">
  548. <button
  549. onClick={handleTare}
  550. disabled={busy}
  551. className="flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px] flex items-center justify-center gap-2"
  552. >
  553. {busy && (
  554. <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
  555. <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
  556. <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
  557. </svg>
  558. )}
  559. {t('spoolbuddy.weight.tare', 'Tare')}
  560. </button>
  561. <button
  562. onClick={() => { setCalStep('tare'); setStatus(null); }}
  563. className="flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]"
  564. >
  565. {t('spoolbuddy.weight.calibrate', 'Calibrate')}
  566. </button>
  567. </div>
  568. </div>
  569. );
  570. }
  571. // --- Calibration wizard: step indicator left + content right ---
  572. return (
  573. <div className="flex gap-3">
  574. {/* Left: step indicator */}
  575. <StepIndicator step={calStep} labels={{ tare: t('spoolbuddy.weight.tare', 'Tare'), weight: t('spoolbuddy.settings.knownWeight', 'Known weight') }} />
  576. {/* Right: content */}
  577. <div className="flex-1 min-w-0">
  578. {/* Live weight bar */}
  579. <div className="flex items-center gap-2 bg-zinc-800 rounded-lg px-3 py-1.5 mb-1.5">
  580. <div className={`w-2 h-2 rounded-full shrink-0 ${weightStable ? 'bg-green-500' : 'bg-amber-500 animate-pulse'}`} />
  581. <span className="text-sm font-mono text-zinc-200">
  582. {weight !== null ? `${weight.toFixed(1)} g` : '-- g'}
  583. </span>
  584. <span className={`text-xs ml-auto ${weightStable ? 'text-green-400' : 'text-amber-400'}`}>
  585. {weightStable ? t('spoolbuddy.settings.stable', 'Stable') : t('spoolbuddy.settings.settling', 'Settling...')}
  586. </span>
  587. </div>
  588. {/* Status message */}
  589. {status && (
  590. <div className={`rounded-lg px-3 py-1.5 mb-1.5 text-xs ${
  591. status.type === 'ok' ? 'bg-green-900/30 text-green-300 border border-green-800' : 'bg-red-900/30 text-red-300 border border-red-800'
  592. }`}>
  593. {status.msg}
  594. </div>
  595. )}
  596. {/* Step content */}
  597. {calStep === 'tare' ? (
  598. <p className="text-sm text-zinc-300 mb-3">
  599. {t('spoolbuddy.settings.calStep1', 'Remove all items from the scale and press Set Zero.')}
  600. </p>
  601. ) : (
  602. <>
  603. <div className="flex items-center gap-2 mb-1.5">
  604. <span className="text-xs text-zinc-400 shrink-0">{t('spoolbuddy.settings.knownWeight', 'Known weight')}</span>
  605. <div className="flex-1 bg-zinc-900 border border-zinc-600 rounded px-3 py-1 text-right text-lg font-mono text-zinc-100">
  606. {knownWeight || '0'}<span className="text-zinc-500 ml-1">g</span>
  607. </div>
  608. </div>
  609. <div className="grid grid-cols-4 gap-1 mb-1.5">
  610. {['7','8','9','backspace','4','5','6','.','1','2','3','0'].map((key) => (
  611. <button
  612. key={key}
  613. onClick={() => numpadPress(key)}
  614. className={`rounded text-lg font-medium transition-colors h-[48px] active:scale-95 ${
  615. key === 'backspace'
  616. ? 'bg-zinc-700 text-zinc-300 hover:bg-zinc-600'
  617. : 'bg-zinc-800 text-zinc-100 hover:bg-zinc-700 border border-zinc-700'
  618. }`}
  619. >
  620. {key === 'backspace' ? '\u232B' : key}
  621. </button>
  622. ))}
  623. </div>
  624. </>
  625. )}
  626. {/* Action buttons */}
  627. <div className="flex gap-2">
  628. <button
  629. onClick={() => { setCalStep('idle'); setStatus(null); }}
  630. className="flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors h-[40px]"
  631. >
  632. {t('common.cancel', 'Cancel')}
  633. </button>
  634. <button
  635. onClick={handleCalStep}
  636. disabled={busy}
  637. className="flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors h-[40px] flex items-center justify-center gap-2"
  638. >
  639. {busy && (
  640. <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
  641. <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
  642. <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
  643. </svg>
  644. )}
  645. {calStep === 'tare' ? t('spoolbuddy.settings.setZero', 'Set Zero') : t('spoolbuddy.settings.calibrateNow', 'Calibrate')}
  646. </button>
  647. </div>
  648. </div>
  649. </div>
  650. );
  651. }
  652. // --- Updates Tab ---
  653. function UpdatesTab({ device }: { device: SpoolBuddyDevice }) {
  654. const { t } = useTranslation();
  655. const [busy, setBusy] = useState<'checking' | 'applying' | null>(null);
  656. const [error, setError] = useState<string | null>(null);
  657. const [sshExpanded, setSSHExpanded] = useState(false);
  658. const [copied, setCopied] = useState(false);
  659. const isUpdating = device.update_status === 'pending' || device.update_status === 'updating';
  660. // When applying succeeds and device picks up the update, keep showing busy
  661. useEffect(() => {
  662. if (isUpdating && busy === 'applying') {
  663. setBusy(null); // device has picked it up, isUpdating takes over the UI
  664. }
  665. }, [isUpdating, busy]);
  666. // Reload the page when daemon comes back online after an update
  667. useEffect(() => {
  668. const handleOnline = () => {
  669. if (isUpdating) {
  670. // Daemon re-registered — reload to get fresh version + state
  671. setTimeout(() => window.location.reload(), 1000);
  672. }
  673. };
  674. window.addEventListener('spoolbuddy-online', handleOnline);
  675. return () => window.removeEventListener('spoolbuddy-online', handleOnline);
  676. }, [isUpdating]);
  677. const { data: updateResult, refetch } = useQuery({
  678. queryKey: ['spoolbuddy-update-check', device.device_id],
  679. queryFn: () => spoolbuddyApi.checkDaemonUpdate(device.device_id),
  680. staleTime: 0,
  681. });
  682. const { data: sshKeyData } = useQuery({
  683. queryKey: ['spoolbuddy-ssh-key'],
  684. queryFn: () => spoolbuddyApi.getSSHPublicKey(),
  685. enabled: sshExpanded,
  686. staleTime: Infinity,
  687. });
  688. const checkForUpdates = async () => {
  689. setBusy('checking');
  690. setError(null);
  691. try {
  692. await refetch();
  693. } finally {
  694. setBusy(null);
  695. }
  696. };
  697. const applyUpdate = async () => {
  698. setBusy('applying');
  699. setError(null);
  700. try {
  701. await spoolbuddyApi.triggerUpdate(device.device_id);
  702. // Don't clear busy — keep showing spinner until isUpdating takes over or timeout
  703. } catch (e) {
  704. setError(e instanceof Error ? e.message : 'Failed to trigger update');
  705. setBusy(null);
  706. }
  707. };
  708. const showSpinner = busy != null || isUpdating;
  709. const copyKey = () => {
  710. if (sshKeyData?.public_key) {
  711. navigator.clipboard.writeText(sshKeyData.public_key);
  712. setCopied(true);
  713. setTimeout(() => setCopied(false), 2000);
  714. }
  715. };
  716. const displayVersion = device.firmware_version
  717. || (updateResult?.current_version && updateResult.current_version !== '0.0.0' ? updateResult.current_version : null);
  718. return (
  719. <div className="space-y-3">
  720. {/* Version + Update status + Check — single card */}
  721. <div className="bg-zinc-800 rounded-lg p-3 space-y-3">
  722. {/* Version row */}
  723. <div className="flex justify-between items-center text-sm">
  724. <span className="text-zinc-500">{t('spoolbuddy.settings.currentVersion', 'Current Version')}</span>
  725. <span className="text-zinc-200 font-mono">
  726. {displayVersion || (
  727. <span className="text-zinc-500 italic text-xs">{t('spoolbuddy.settings.versionPending', 'Waiting for daemon...')}</span>
  728. )}
  729. </span>
  730. </div>
  731. {/* Status / progress row */}
  732. {showSpinner ? (
  733. <div className="flex items-center gap-2">
  734. <svg className="w-4 h-4 animate-spin text-green-400 flex-shrink-0" viewBox="0 0 24 24" fill="none">
  735. <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
  736. <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
  737. </svg>
  738. <span className="text-green-300 text-xs">
  739. {busy === 'checking' ? t('spoolbuddy.settings.checking', 'Checking for updates...')
  740. : device.update_message || t('spoolbuddy.settings.updateWaiting', 'Updating...')}
  741. </span>
  742. </div>
  743. ) : device.update_status === 'error' ? (
  744. <p className="text-xs text-red-300">{device.update_message || t('spoolbuddy.settings.updateFailed', 'Update failed')}</p>
  745. ) : error ? (
  746. <p className="text-xs text-red-300">{error}</p>
  747. ) : updateResult?.update_available ? (
  748. <p className="text-xs text-green-300">
  749. {t('spoolbuddy.settings.updateAvailable', 'Update available')}: {displayVersion} → {updateResult.latest_version}
  750. </p>
  751. ) : null}
  752. {/* Action buttons */}
  753. {!showSpinner && (
  754. updateResult?.update_available ? (
  755. <button
  756. onClick={applyUpdate}
  757. disabled={!device.online}
  758. className="w-full px-3 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors"
  759. >
  760. {!device.online
  761. ? t('spoolbuddy.settings.deviceOffline', 'Device Offline')
  762. : t('spoolbuddy.settings.applyUpdate', 'Apply Update')}
  763. </button>
  764. ) : (
  765. <div className="flex gap-2">
  766. <button
  767. onClick={checkForUpdates}
  768. className="flex-1 px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors"
  769. >
  770. {t('spoolbuddy.settings.checkUpdates', 'Check for Updates')}
  771. </button>
  772. <button
  773. onClick={applyUpdate}
  774. disabled={!device.online}
  775. className="px-3 py-2 rounded-lg text-xs font-medium bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-zinc-200 disabled:opacity-40 transition-colors"
  776. >
  777. {t('spoolbuddy.settings.forceUpdate', 'Force Update')}
  778. </button>
  779. </div>
  780. )
  781. )}
  782. </div>
  783. {/* SSH Setup — collapsible */}
  784. <div className="bg-zinc-800 rounded-lg p-3">
  785. <button
  786. onClick={() => setSSHExpanded(!sshExpanded)}
  787. className="w-full flex justify-between items-center text-xs"
  788. >
  789. <span className="font-medium text-zinc-400">
  790. {t('spoolbuddy.settings.sshSetup', 'SSH Setup')}
  791. </span>
  792. <svg
  793. className={`w-3 h-3 text-zinc-500 transition-transform ${sshExpanded ? 'rotate-180' : ''}`}
  794. fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}
  795. >
  796. <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
  797. </svg>
  798. </button>
  799. {sshExpanded && (
  800. <div className="mt-2 space-y-2">
  801. <p className="text-xs text-zinc-500">
  802. {t('spoolbuddy.settings.sshDescription', 'SSH key is deployed automatically. For manual setup, add this key to ~/.ssh/authorized_keys on the device.')}
  803. </p>
  804. {sshKeyData?.public_key ? (
  805. <div className="relative">
  806. <pre className="bg-zinc-900 rounded p-2 text-[10px] text-zinc-400 font-mono break-all whitespace-pre-wrap">
  807. {sshKeyData.public_key}
  808. </pre>
  809. <button
  810. onClick={copyKey}
  811. className="absolute top-1 right-1 px-1.5 py-0.5 rounded text-[10px] bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors"
  812. >
  813. {copied ? t('common.copied', 'Copied!') : t('common.copy', 'Copy')}
  814. </button>
  815. </div>
  816. ) : (
  817. <span className="text-[10px] text-zinc-500 italic">
  818. {t('spoolbuddy.settings.sshKeyLoading', 'Loading...')}
  819. </span>
  820. )}
  821. </div>
  822. )}
  823. </div>
  824. </div>
  825. );
  826. }
  827. // --- System Tab ---
  828. function UsageBar({ percent, color }: { percent: number; color: string }) {
  829. return (
  830. <div className="w-full h-2 bg-zinc-700 rounded-full overflow-hidden">
  831. <div
  832. className={`h-full rounded-full transition-all ${color}`}
  833. style={{ width: `${Math.min(100, Math.max(0, percent))}%` }}
  834. />
  835. </div>
  836. );
  837. }
  838. function formatSystemUptime(seconds: number): string {
  839. const d = Math.floor(seconds / 86400);
  840. const h = Math.floor((seconds % 86400) / 3600);
  841. const m = Math.floor((seconds % 3600) / 60);
  842. if (d > 0) return `${d}d ${h}h ${m}m`;
  843. if (h > 0) return `${h}h ${m}m`;
  844. return `${m}m`;
  845. }
  846. function SystemTab({ device }: { device: SpoolBuddyDevice }) {
  847. const { t } = useTranslation();
  848. const stats = device.system_stats;
  849. if (!stats) {
  850. return (
  851. <div className="flex items-center justify-center h-32">
  852. <p className="text-sm text-zinc-500">
  853. {t('spoolbuddy.settings.systemStatsWaiting', 'Waiting for system stats...')}
  854. </p>
  855. </div>
  856. );
  857. }
  858. const mem = stats.memory;
  859. const disk = stats.disk;
  860. const tempColor = (stats.cpu_temp_c ?? 0) >= 80 ? 'text-red-400' : (stats.cpu_temp_c ?? 0) >= 65 ? 'text-amber-400' : 'text-green-400';
  861. const memColor = (mem?.percent ?? 0) >= 90 ? 'bg-red-500' : (mem?.percent ?? 0) >= 70 ? 'bg-amber-500' : 'bg-green-500';
  862. const diskColor = (disk?.percent ?? 0) >= 90 ? 'bg-red-500' : (disk?.percent ?? 0) >= 70 ? 'bg-amber-500' : 'bg-green-500';
  863. return (
  864. <div className="space-y-2">
  865. {/* CPU + Memory side by side */}
  866. <div className="grid grid-cols-2 gap-2">
  867. <div className="bg-zinc-800 rounded-lg p-3">
  868. <h3 className="text-sm font-semibold text-zinc-300 mb-2">CPU</h3>
  869. <div className="space-y-1.5 text-xs">
  870. <div className="flex justify-between">
  871. <span className="text-zinc-500">{t('spoolbuddy.settings.cores', 'Cores')}</span>
  872. <span className="text-zinc-300 font-mono">{stats.cpu_count ?? '-'}</span>
  873. </div>
  874. <div className="flex justify-between">
  875. <span className="text-zinc-500">{t('spoolbuddy.settings.loadAvg', 'Load Avg')}</span>
  876. <span className="text-zinc-300 font-mono">
  877. {stats.load_avg ? stats.load_avg.join(' / ') : '-'}
  878. </span>
  879. </div>
  880. <div className="flex justify-between">
  881. <span className="text-zinc-500">{t('spoolbuddy.settings.temp', 'Temp')}</span>
  882. <span className={`font-mono font-medium ${tempColor}`}>
  883. {stats.cpu_temp_c != null ? `${stats.cpu_temp_c}\u00B0C` : '-'}
  884. </span>
  885. </div>
  886. </div>
  887. </div>
  888. {/* Memory */}
  889. <div className="bg-zinc-800 rounded-lg p-3">
  890. <h3 className="text-sm font-semibold text-zinc-300 mb-2">
  891. {t('spoolbuddy.settings.memory', 'Memory')}
  892. </h3>
  893. {mem ? (
  894. <div className="space-y-1.5">
  895. <UsageBar percent={mem.percent ?? 0} color={memColor} />
  896. <div className="space-y-1 text-xs">
  897. <div className="flex justify-between">
  898. <span className="text-zinc-500">{t('spoolbuddy.settings.used', 'Used')}</span>
  899. <span className="text-zinc-300 font-mono">{mem.used_mb} / {mem.total_mb} MB</span>
  900. </div>
  901. <div className="flex justify-between">
  902. <span className="text-zinc-500">{t('spoolbuddy.settings.available', 'Free')}</span>
  903. <span className="text-zinc-300 font-mono">{mem.available_mb} MB</span>
  904. </div>
  905. </div>
  906. </div>
  907. ) : (
  908. <span className="text-xs text-zinc-500">-</span>
  909. )}
  910. </div>
  911. </div>
  912. {/* Disk — compact single row */}
  913. <div className="bg-zinc-800 rounded-lg px-3 py-2">
  914. <div className="flex items-center gap-3">
  915. <h3 className="text-sm font-semibold text-zinc-300 shrink-0">
  916. {t('spoolbuddy.settings.disk', 'Disk')}
  917. </h3>
  918. {disk ? (
  919. <>
  920. <div className="flex-1"><UsageBar percent={disk.percent ?? 0} color={diskColor} /></div>
  921. <span className="text-xs text-zinc-300 font-mono shrink-0">{disk.used_gb} / {disk.total_gb} GB</span>
  922. </>
  923. ) : (
  924. <span className="text-xs text-zinc-500">-</span>
  925. )}
  926. </div>
  927. </div>
  928. {/* OS + Runtime side by side */}
  929. <div className="grid grid-cols-2 gap-2">
  930. <div className="bg-zinc-800 rounded-lg p-3">
  931. <h3 className="text-sm font-semibold text-zinc-300 mb-1.5">
  932. {t('spoolbuddy.settings.osInfo', 'OS')}
  933. </h3>
  934. <div className="space-y-1 text-xs">
  935. {stats.os?.os && (
  936. <div className="flex justify-between">
  937. <span className="text-zinc-500">{t('spoolbuddy.settings.distro', 'Distro')}</span>
  938. <span className="text-zinc-300 truncate ml-2">{stats.os.os}</span>
  939. </div>
  940. )}
  941. {stats.os?.kernel && (
  942. <div className="flex justify-between">
  943. <span className="text-zinc-500">{t('spoolbuddy.settings.kernel', 'Kernel')}</span>
  944. <span className="text-zinc-300 font-mono truncate ml-2">{stats.os.kernel}</span>
  945. </div>
  946. )}
  947. {stats.os?.arch && (
  948. <div className="flex justify-between">
  949. <span className="text-zinc-500">{t('spoolbuddy.settings.arch', 'Arch')}</span>
  950. <span className="text-zinc-300 font-mono">{stats.os.arch}</span>
  951. </div>
  952. )}
  953. </div>
  954. </div>
  955. <div className="bg-zinc-800 rounded-lg p-3">
  956. <h3 className="text-sm font-semibold text-zinc-300 mb-1.5">
  957. {t('spoolbuddy.settings.runtime', 'Runtime')}
  958. </h3>
  959. <div className="space-y-1 text-xs">
  960. {stats.os?.python && (
  961. <div className="flex justify-between">
  962. <span className="text-zinc-500">Python</span>
  963. <span className="text-zinc-300 font-mono">{stats.os.python}</span>
  964. </div>
  965. )}
  966. {stats.system_uptime_s != null && (
  967. <div className="flex justify-between">
  968. <span className="text-zinc-500">{t('spoolbuddy.settings.systemUptime', 'Uptime')}</span>
  969. <span className="text-zinc-300">{formatSystemUptime(stats.system_uptime_s)}</span>
  970. </div>
  971. )}
  972. </div>
  973. </div>
  974. </div>
  975. </div>
  976. );
  977. }
  978. // --- Main Settings Page ---
  979. type SettingsTab = 'device' | 'display' | 'scale' | 'updates' | 'system';
  980. export function SpoolBuddySettingsPage() {
  981. const { sbState, setDisplayBrightness } = useOutletContext<SpoolBuddyOutletContext>();
  982. const { t } = useTranslation();
  983. const [activeTab, setActiveTab] = useState<SettingsTab>('device');
  984. // This kiosk's device, not the one the last WebSocket event came from:
  985. // every device's weight updates reach every kiosk (#3504).
  986. const { device } = useKioskDevice(10000);
  987. const tabs: { id: SettingsTab; label: string }[] = [
  988. { id: 'device', label: t('spoolbuddy.settings.tabDevice', 'Device') },
  989. { id: 'display', label: t('spoolbuddy.settings.tabDisplay', 'Display') },
  990. { id: 'scale', label: t('spoolbuddy.settings.tabScale', 'Scale') },
  991. { id: 'updates', label: t('spoolbuddy.settings.tabUpdates', 'Updates') },
  992. { id: 'system', label: t('spoolbuddy.settings.tabSystem', 'System') },
  993. ];
  994. return (
  995. <div className="h-full flex flex-col p-4">
  996. <h1 className="text-xl font-semibold text-zinc-100 mb-3">
  997. {t('spoolbuddy.nav.settings', 'Settings')}
  998. </h1>
  999. {/* Tab bar */}
  1000. <div className="flex gap-1 bg-zinc-800/50 rounded-lg p-1 mb-4">
  1001. {tabs.map((tab) => (
  1002. <button
  1003. key={tab.id}
  1004. onClick={() => setActiveTab(tab.id)}
  1005. className={`flex-1 px-2 py-2 rounded-md text-sm font-medium transition-colors min-h-[36px] ${
  1006. activeTab === tab.id
  1007. ? 'bg-zinc-700 text-zinc-100'
  1008. : 'text-zinc-500 hover:text-zinc-300'
  1009. }`}
  1010. >
  1011. {tab.label}
  1012. </button>
  1013. ))}
  1014. </div>
  1015. {/* Content */}
  1016. <div className="flex-1 min-h-0 overflow-y-auto">
  1017. {!device ? (
  1018. <div className="flex items-center justify-center h-32">
  1019. <div className="text-center text-zinc-500">
  1020. <p className="text-sm">{t('spoolbuddy.settings.noDevice', 'No SpoolBuddy device found')}</p>
  1021. </div>
  1022. </div>
  1023. ) : (
  1024. <>
  1025. {activeTab === 'device' && <DeviceTab device={device} />}
  1026. {activeTab === 'display' && (
  1027. <DisplayTab
  1028. device={device}
  1029. onBrightnessChange={setDisplayBrightness}
  1030. />
  1031. )}
  1032. {activeTab === 'scale' && (
  1033. <ScaleTab
  1034. device={device}
  1035. weight={sbState.weight}
  1036. weightStable={sbState.weightStable}
  1037. rawAdc={sbState.rawAdc}
  1038. />
  1039. )}
  1040. {activeTab === 'updates' && <UpdatesTab device={device} />}
  1041. {activeTab === 'system' && <SystemTab device={device} />}
  1042. </>
  1043. )}
  1044. </div>
  1045. </div>
  1046. );
  1047. }