StreamOverlayPage.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import { useEffect, useMemo } from 'react';
  2. import { useParams, useSearchParams } from 'react-router-dom';
  3. import { useQuery, useQueryClient } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import { Layers, Clock, Timer, Printer, Flame, Square, Box } from 'lucide-react';
  6. import { useOverlayLogo } from '../hooks/useOverlayLogo';
  7. import { overlayGradient, overlayProgressTextStyle } from '../utils/overlayBranding';
  8. import { OverlayFrame } from '../components/OverlayFrame';
  9. import { OVERLAY_DIMENSIONS, type OverlayLayout } from '../utils/overlayLayout';
  10. import './StreamOverlayPage.css';
  11. import { UpdatedStreamOverlay } from '../components/UpdatedStreamOverlay';
  12. import { api, ApiError, withStreamToken } from '../api/client';
  13. import { formatDuration, formatETA, type TimeFormat } from '../utils/date';
  14. import { mapModelCode } from '../utils/printerModel';
  15. import { useOverlayCameraRecovery } from '../hooks/useOverlayCameraRecovery';
  16. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  17. type OverlaySize = 'small' | 'medium' | 'large';
  18. interface OverlayConfig {
  19. layout: OverlayLayout | null;
  20. size: OverlaySize;
  21. updatedArtwork: boolean;
  22. backgroundTransparency: number;
  23. fps: number;
  24. showCamera: boolean;
  25. showProgress: boolean;
  26. showLayers: boolean;
  27. showEta: boolean;
  28. showFilename: boolean;
  29. showStatus: boolean;
  30. showPrinter: boolean;
  31. showModel: boolean;
  32. showNozzle: boolean;
  33. showBed: boolean;
  34. showChamber: boolean;
  35. }
  36. function formatPrintName(name: string | null, gcodeFile: string | null | undefined, t: (key: string, fallback: string, opts?: Record<string, unknown>) => string): string {
  37. if (!name) return '';
  38. if (!gcodeFile) return name;
  39. const match = gcodeFile.match(/plate_(\d+)\.gcode/);
  40. if (match && parseInt(match[1], 10) > 1) {
  41. return `${name} — ${t('printers.plateNumber', 'Plate {{number}}', { number: match[1] })}`;
  42. }
  43. return name;
  44. }
  45. function parseConfig(params: URLSearchParams): OverlayConfig {
  46. // The default set is deliberately unchanged by #1422: temperatures are opt-in,
  47. // so every overlay URL already pasted into an OBS scene keeps looking the same
  48. // after upgrading.
  49. const show = params.get('show')?.split(',') || ['progress', 'layers', 'eta', 'filename', 'status'];
  50. // Parse FPS (default 15, max 30, min 1)
  51. const fpsParam = parseInt(params.get('fps') || '15', 10);
  52. const fps = Math.min(Math.max(isNaN(fpsParam) ? 15 : fpsParam, 1), 30);
  53. // Parse camera toggle (default true, set camera=false to hide)
  54. const cameraParam = params.get('camera');
  55. const showCamera = cameraParam !== 'false' && cameraParam !== '0';
  56. const transparencyParam = Number(params.get('backgroundTransparency'));
  57. const backgroundTransparency = Number.isFinite(transparencyParam)
  58. ? Math.min(100, Math.max(0, transparencyParam))
  59. : 0;
  60. const layout = params.get('layout');
  61. return {
  62. layout: layout === 'portrait' || layout === 'landscape' ? layout : null,
  63. backgroundTransparency,
  64. size: (params.get('size') as OverlaySize) || 'medium',
  65. fps,
  66. updatedArtwork: params.get('artwork') === '2',
  67. showCamera,
  68. showProgress: show.includes('progress'),
  69. showLayers: show.includes('layers'),
  70. showEta: show.includes('eta'),
  71. showFilename: show.includes('filename'),
  72. showStatus: show.includes('status'),
  73. showPrinter: show.includes('printer'),
  74. showModel: show.includes('model'),
  75. showNozzle: show.includes('nozzle'),
  76. showBed: show.includes('bed'),
  77. showChamber: show.includes('chamber'),
  78. };
  79. }
  80. // Accepts the minimal shape shared by PrinterStatus (logged-in path) and the
  81. // token-authed OverlayStatus (kiosk path) — both carry state + stg_cur_name.
  82. function getStatusText(status: { state: string | null; stg_cur_name?: string | null }, t: TFunction): string {
  83. if (status.stg_cur_name) return status.stg_cur_name;
  84. switch (status.state) {
  85. case 'RUNNING': return t('streamOverlay.status.printing');
  86. case 'PAUSE': return t('streamOverlay.status.paused');
  87. case 'FINISH': return t('streamOverlay.status.finished');
  88. case 'FAILED': return t('streamOverlay.status.failed');
  89. case 'IDLE': return t('streamOverlay.status.idle');
  90. default: return status.state || t('streamOverlay.status.unknown');
  91. }
  92. }
  93. // Reads one reading out of either status shape. The kiosk feed types
  94. // temperatures as Record<string, number>; the logged-in PrinterStatus types it
  95. // as a named object that also carries `*_heating` booleans. Narrowing here lets
  96. // one render path serve both without casting.
  97. function readTemp(temps: Record<string, unknown>, key: string): number | null {
  98. const value = temps[key];
  99. return typeof value === 'number' ? value : null;
  100. }
  101. interface TempReadingProps {
  102. icon: React.ReactNode;
  103. label: string;
  104. current: number;
  105. target: number | null;
  106. sizes: ReturnType<typeof getSizeClasses>;
  107. }
  108. // One "Nozzle 220°C" reading. The target is appended only while it is set and
  109. // still differs from the current value, so a hotend that has reached
  110. // temperature reads "220°C" for the rest of the print instead of the noisier
  111. // "220 / 220°C".
  112. function TempReading({ icon, label, current, target, sizes }: TempReadingProps) {
  113. const heating = target != null && target > 0 && Math.round(target) !== Math.round(current);
  114. return (
  115. <div className={`flex items-center ${sizes.gap} text-white/70`}>
  116. {icon}
  117. <span className={`classic-overlay__text ${sizes.text}`}>
  118. <span className="mr-1">{label}</span>
  119. <span className="text-white">{Math.round(current)}°C</span>
  120. {heating && (
  121. <>
  122. <span className="mx-1">/</span>
  123. <span>{Math.round(target)}°C</span>
  124. </>
  125. )}
  126. </span>
  127. </div>
  128. );
  129. }
  130. function getSizeClasses(size: OverlaySize) {
  131. switch (size) {
  132. case 'small':
  133. return {
  134. container: 'p-3',
  135. text: 'text-sm',
  136. textLarge: 'text-lg',
  137. progressHeight: 'h-2',
  138. icon: 'w-3 h-3',
  139. gap: 'gap-2',
  140. logoHeight: 'h-12',
  141. };
  142. case 'large':
  143. return {
  144. container: 'p-6',
  145. text: 'text-xl',
  146. textLarge: 'text-3xl',
  147. progressHeight: 'h-4',
  148. icon: 'w-6 h-6',
  149. gap: 'gap-4',
  150. logoHeight: 'h-24',
  151. };
  152. case 'medium':
  153. default:
  154. return {
  155. container: 'p-4',
  156. text: 'text-base',
  157. textLarge: 'text-xl',
  158. progressHeight: 'h-3',
  159. icon: 'w-4 h-4',
  160. gap: 'gap-3',
  161. logoHeight: 'h-16',
  162. };
  163. }
  164. }
  165. export function StreamOverlayPage() {
  166. const { printerId } = useParams<{ printerId: string }>();
  167. const [searchParams] = useSearchParams();
  168. const { t } = useTranslation();
  169. const queryClient = useQueryClient();
  170. const id = parseInt(printerId || '0', 10);
  171. const config = useMemo(() => parseConfig(searchParams), [searchParams]);
  172. const sizes = getSizeClasses(config.size);
  173. // Kiosk mode (#2613): OBS and other embeds have no login session, so they
  174. // pass an `overlay`-scoped token in the URL. When present, every data call
  175. // (status + camera stream) is authenticated by that token instead of a JWT.
  176. const token = searchParams.get('token');
  177. const kiosk = token != null && token !== '';
  178. const logo = useOverlayLogo(searchParams.get('logo') === '1', token);
  179. const progressBackground = overlayGradient(searchParams.get('progressFrom'), searchParams.get('progressTo'));
  180. const progressTextStyle = overlayProgressTextStyle(progressBackground);
  181. const customLogo = logo ? (
  182. <img
  183. src={logo}
  184. alt={t('streamOverlay.branding.logo')}
  185. className="mb-2 object-contain"
  186. style={{
  187. maxHeight: config.layout ? OVERLAY_DIMENSIONS[config.layout].height * 0.14 : '14vh',
  188. maxWidth: config.layout ? OVERLAY_DIMENSIONS[config.layout].width * 0.2 : '20vw',
  189. }}
  190. />
  191. ) : null;
  192. // Kiosk path: one token-authenticated call for name + live status + the one
  193. // setting the overlay reads. No JWT, so this is the only feed available.
  194. const { data: overlay } = useQuery({
  195. queryKey: ['overlayStatus', id, token],
  196. queryFn: () => api.getOverlayStatus(id, token ?? undefined),
  197. enabled: id > 0 && kiosk,
  198. refetchInterval: 2000,
  199. });
  200. // Logged-in path: the ordinary JWT-authenticated queries, unchanged. Disabled
  201. // in kiosk mode so an unauthenticated OBS browser never fires a doomed 401.
  202. const { data: printerData } = useQuery({
  203. queryKey: ['printer', id],
  204. queryFn: () => api.getPrinter(id),
  205. enabled: id > 0 && !kiosk,
  206. });
  207. const { data: statusData } = useQuery({
  208. queryKey: ['printerStatus', id],
  209. queryFn: () => api.getPrinterStatus(id),
  210. enabled: id > 0 && !kiosk,
  211. refetchInterval: 2000,
  212. });
  213. const { data: settings } = useQuery({
  214. queryKey: ['settings'],
  215. queryFn: api.getSettings,
  216. enabled: !kiosk,
  217. });
  218. // Normalize the two sources into the shape the render below reads. Memoized
  219. // because the title effect depends on `printer` — a fresh object literal each
  220. // render would re-run it (and reset document.title) on every poll tick.
  221. const printer = useMemo(
  222. () =>
  223. kiosk
  224. ? overlay && { name: overlay.name, model: overlay.model, camera_rotation: overlay.camera_rotation }
  225. : printerData,
  226. [kiosk, overlay, printerData],
  227. );
  228. const printerIdentity = [
  229. config.showPrinter ? printer?.name : null,
  230. config.showModel ? mapModelCode(printer?.model ?? null) : null,
  231. ].filter(Boolean).join(' · ');
  232. const status = kiosk ? overlay : statusData;
  233. const { imageKey, closing, imgRef, handleStreamError } = useOverlayCameraRecovery(id > 0 && config.showCamera && status != null);
  234. const timeFormat: TimeFormat = (kiosk ? overlay?.time_format : settings?.time_format) || 'system';
  235. // WebSocket for real-time updates (JWT-authenticated; skipped in kiosk mode,
  236. // where the token can't mint a ws-token — the 2s poll above is the feed).
  237. useEffect(() => {
  238. if (!id || kiosk) return;
  239. let ws: WebSocket | null = null;
  240. let cancelled = false;
  241. // GHSA-r2qv follow-up: mint a ws-token before connecting. Uses
  242. // api.getWebSocketToken so the JWT Authorization header rides along
  243. // (raw fetch+credentials:'include' would miss it — Bambuddy uses
  244. // Bearer tokens, not cookies, for JWT auth). Auth-disabled deployments
  245. // succeed even without a token.
  246. (async () => {
  247. let wsToken: string | undefined;
  248. try {
  249. const resp = await api.getWebSocketToken();
  250. wsToken = resp.token;
  251. } catch (err) {
  252. // A 401 (JWT expired) / 403 (no WEBSOCKET_CONNECT permission) is an
  253. // auth decision — a tokenless socket would just be closed 4401, so
  254. // skip opening one and let the REST polling fallback keep the overlay
  255. // fresh. There's no reconnect loop on this page, so this is purely
  256. // avoiding one doomed socket per mount. A network/5xx error is not
  257. // auth: fall through and try anyway (auth-disabled deployments land
  258. // here with no token and connect fine).
  259. const status = err instanceof ApiError ? err.status : 0;
  260. if (status === 401 || status === 403) return;
  261. }
  262. if (cancelled) return;
  263. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  264. const tokenParam = wsToken ? `?token=${encodeURIComponent(wsToken)}` : '';
  265. const wsUrl = `${protocol}//${window.location.host}/api/v1/ws${tokenParam}`;
  266. ws = new WebSocket(wsUrl);
  267. ws.onmessage = (event) => {
  268. try {
  269. const data = JSON.parse(event.data);
  270. if (data.type === 'printer_status' && data.printer_id === id) {
  271. // The update is the status itself, under `data`; merge it, as the
  272. // app's own socket does, in case it carries only some fields.
  273. queryClient.setQueryData(['printerStatus', id], (old: Record<string, unknown> | undefined) =>
  274. old ? { ...old, ...data.data } : data.data,
  275. );
  276. }
  277. } catch {
  278. // Ignore parse errors
  279. }
  280. };
  281. ws.onerror = () => {
  282. // WebSocket error - polling will continue as fallback
  283. };
  284. })();
  285. return () => {
  286. cancelled = true;
  287. if (ws) ws.close();
  288. };
  289. }, [id, kiosk, queryClient]);
  290. // Update document title
  291. useEffect(() => {
  292. document.title = printer ? `${printer.name} - ${t('streamOverlay.title')}` : t('streamOverlay.title');
  293. return () => {
  294. document.title = 'Bambuddy';
  295. };
  296. }, [printer, t]);
  297. if (!id) {
  298. return (
  299. <div className="min-h-screen bg-black flex items-center justify-center">
  300. <p className="text-white">{t('streamOverlay.invalidPrinterId')}</p>
  301. </div>
  302. );
  303. }
  304. if (!status) {
  305. return (
  306. <div className="min-h-screen bg-black flex items-center justify-center">
  307. <p className="text-gray-400">{t('common.loading')}</p>
  308. </div>
  309. );
  310. }
  311. const isPrinting = status.connected && (status.state === 'RUNNING' || status.state === 'PAUSE');
  312. const progress = status.progress || 0;
  313. // Temperature readings the URL asked for, in a fixed order, skipping any the
  314. // printer doesn't report. Labels reuse printers.heaterHistory.* so the naming
  315. // matches the heater chart rather than inventing a second vocabulary.
  316. const temps: Record<string, unknown> = status.temperatures ?? {};
  317. const tempReadings: {
  318. key: string;
  319. icon: React.ReactNode;
  320. label: string;
  321. current: number;
  322. target: number | null;
  323. }[] = [];
  324. if (config.showNozzle) {
  325. const nozzle = readTemp(temps, 'nozzle');
  326. const nozzle2 = readTemp(temps, 'nozzle_2');
  327. if (nozzle != null) {
  328. tempReadings.push({
  329. key: 'nozzle',
  330. icon: <Flame className={`classic-overlay__icon ${sizes.icon}`} />,
  331. label: t('printers.heaterHistory.nozzle', 'Nozzle'),
  332. current: nozzle,
  333. target: readTemp(temps, 'nozzle_target'),
  334. });
  335. }
  336. if (nozzle2 != null) {
  337. tempReadings.push({
  338. key: 'nozzle_2',
  339. icon: <Flame className={`classic-overlay__icon ${sizes.icon}`} />,
  340. label: t('printers.heaterHistory.nozzle2', 'Nozzle 2'),
  341. current: nozzle2,
  342. target: readTemp(temps, 'nozzle_2_target'),
  343. });
  344. }
  345. }
  346. if (config.showBed) {
  347. const bed = readTemp(temps, 'bed');
  348. if (bed != null) {
  349. tempReadings.push({
  350. key: 'bed',
  351. icon: <Square className={`classic-overlay__icon ${sizes.icon}`} />,
  352. label: t('printers.heaterHistory.bed', 'Bed'),
  353. current: bed,
  354. target: readTemp(temps, 'bed_target'),
  355. });
  356. }
  357. }
  358. if (config.showChamber) {
  359. const chamber = readTemp(temps, 'chamber');
  360. if (chamber != null) {
  361. tempReadings.push({
  362. key: 'chamber',
  363. icon: <Box className={`classic-overlay__icon ${sizes.icon}`} />,
  364. label: t('printers.heaterHistory.chamber', 'Chamber'),
  365. current: chamber,
  366. target: readTemp(temps, 'chamber_target'),
  367. });
  368. }
  369. }
  370. // Append the kiosk token directly rather than leaning on withStreamToken's
  371. // module cache — the cache is populated by an effect and would miss the first
  372. // render (a 401 flash before the retry). The logged-in path keeps the cache.
  373. const camPath = `/api/v1/printers/${id}/camera/stream?fps=${config.fps}&t=${imageKey}`;
  374. const streamUrl = kiosk && token
  375. ? `${camPath}&token=${encodeURIComponent(token)}`
  376. : withStreamToken(camPath);
  377. if (config.updatedArtwork) {
  378. const active = status.connected && isPrinting;
  379. const remainingTime = status.remaining_time;
  380. const hasRemaining = active && config.showEta && remainingTime != null && remainingTime > 0;
  381. const artwork = <UpdatedStreamOverlay
  382. layout={config.layout ?? undefined}
  383. backgroundTransparency={config.backgroundTransparency}
  384. customLogo={customLogo}
  385. progressBackground={progressBackground}
  386. size={config.size}
  387. camera={config.showCamera ? { url: closing ? undefined : streamUrl, rotation: printer?.camera_rotation ?? 0, onError: handleStreamError, imgRef } : null}
  388. name={config.showPrinter ? printer?.name ?? null : null}
  389. model={config.showModel ? mapModelCode(printer?.model ?? null) || null : null}
  390. filename={config.showFilename && status.current_print ? formatPrintName(status.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i, ''), status.gcode_file, t) : null}
  391. status={config.showStatus ? (status.connected ? getStatusText(status, t) : t('streamOverlay.printerOffline')) : null}
  392. state={status.connected ? status.state : null}
  393. progress={active && config.showProgress ? Math.min(100, Math.max(0, Number.isFinite(progress) ? progress : 0)) : null}
  394. layers={active && config.showLayers && status.layer_num != null && status.total_layers != null && status.total_layers > 0 ? `${status.layer_num} / ${status.total_layers}` : null}
  395. remaining={hasRemaining ? formatDuration(remainingTime * 60) : null}
  396. eta={hasRemaining ? formatETA(remainingTime, timeFormat, t) : null}
  397. temperatures={status.connected ? tempReadings : []}
  398. />;
  399. return config.layout ? <OverlayFrame layout={config.layout}>{artwork}</OverlayFrame> : artwork;
  400. }
  401. const dimensions = config.layout ? OVERLAY_DIMENSIONS[config.layout] : null;
  402. const rotation = printer?.camera_rotation ?? 0;
  403. const sideways = Math.abs(rotation % 180) === 90;
  404. const artwork = (
  405. <div className="classic-overlay min-h-screen bg-black relative overflow-hidden" data-layout={config.layout ?? undefined} data-size={config.size}>
  406. {/* Camera feed - fullscreen background (optional) */}
  407. {config.showCamera && (
  408. <img
  409. ref={imgRef}
  410. key={imageKey}
  411. src={closing ? undefined : streamUrl}
  412. alt={t('streamOverlay.cameraStream')}
  413. className="absolute inset-0 w-full h-full object-contain"
  414. style={dimensions ? {
  415. left: '50%', top: '50%', maxWidth: 'none',
  416. width: sideways ? dimensions.height : dimensions.width,
  417. height: sideways ? dimensions.width : dimensions.height,
  418. transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
  419. } : rotation ? { transform: `rotate(${rotation}deg)` } : undefined}
  420. onError={handleStreamError}
  421. />
  422. )}
  423. {/* Channel branding above the Bambuddy mark. */}
  424. <div className="absolute top-4 right-4 z-10 flex flex-col items-end">
  425. {customLogo}
  426. <a
  427. href="https://github.com/maziggy/bambuddy"
  428. target="_blank"
  429. rel="noopener noreferrer"
  430. >
  431. <img
  432. src="/img/bambuddy_logo_dark_transparent.png"
  433. alt="Bambuddy"
  434. className={`classic-overlay__logo ${sizes.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`}
  435. />
  436. </a>
  437. </div>
  438. {/* Status overlay - bottom */}
  439. <div className="absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent">
  440. <div className={`classic-overlay__panel ${sizes.container}`}>
  441. {/* Printer name and model can each be selected independently. */}
  442. {printerIdentity && (
  443. <div className={`flex items-center ${sizes.gap} mb-2`}>
  444. <Printer className={`classic-overlay__icon ${sizes.icon} shrink-0 text-white/70`} />
  445. <span className={`classic-overlay__text ${sizes.text} min-w-0 truncate text-white font-medium`}>{printerIdentity}</span>
  446. </div>
  447. )}
  448. {/* Filename */}
  449. {config.showFilename && status.current_print && (
  450. <div className={`classic-overlay__filename ${sizes.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`}>
  451. {formatPrintName(status.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i, ''), status.gcode_file, t)}
  452. </div>
  453. )}
  454. {/* Status text */}
  455. {config.showStatus && (
  456. <div className={`classic-overlay__text ${sizes.text} text-white/70 mb-2`}>
  457. {!status.connected ? t('streamOverlay.printerOffline') : getStatusText(status, t)}
  458. </div>
  459. )}
  460. {/* Progress bar */}
  461. {config.showProgress && isPrinting && (
  462. <div className="mb-3">
  463. <div className={`flex items-center justify-between mb-1 classic-overlay__text ${sizes.text}`}>
  464. <span className="text-white/70" style={progressTextStyle}>{t('streamOverlay.progress')}</span>
  465. <span className="text-white font-bold" style={progressTextStyle}>{Math.round(progress)}%</span>
  466. </div>
  467. <div className={`w-full bg-white/20 rounded-full ${sizes.progressHeight}`}>
  468. <div
  469. className={`bg-bambu-green ${sizes.progressHeight} rounded-full transition-all duration-500`}
  470. style={{ width: `${progress}%`, background: progressBackground }}
  471. />
  472. </div>
  473. </div>
  474. )}
  475. {/* Stats row */}
  476. {isPrinting && (config.showLayers || config.showEta) && (
  477. <div className={`flex items-center ${sizes.gap} flex-wrap`}>
  478. {/* Layers */}
  479. {config.showLayers && status.layer_num != null && status.total_layers != null && status.total_layers > 0 && (
  480. <div className={`flex items-center ${sizes.gap} text-white/70`}>
  481. <Layers className={`classic-overlay__icon ${sizes.icon}`} />
  482. <span className={`classic-overlay__text ${sizes.text}`}>
  483. <span className="text-white">{status.layer_num}</span>
  484. <span className="mx-1">/</span>
  485. <span>{status.total_layers}</span>
  486. </span>
  487. </div>
  488. )}
  489. {/* Remaining time */}
  490. {config.showEta && status.remaining_time != null && status.remaining_time > 0 && (
  491. <>
  492. <div className={`flex items-center ${sizes.gap} text-white/70`}>
  493. <Timer className={`classic-overlay__icon ${sizes.icon}`} />
  494. <span className={`classic-overlay__text ${sizes.text} text-white`}>
  495. {formatDuration(status.remaining_time * 60)}
  496. </span>
  497. </div>
  498. <div className={`flex items-center ${sizes.gap} text-white/70`}>
  499. <Clock className={`classic-overlay__icon ${sizes.icon}`} />
  500. <span className={`classic-overlay__text ${sizes.text} text-white`}>
  501. {t('streamOverlay.eta')} {formatETA(status.remaining_time, timeFormat, t)}
  502. </span>
  503. </div>
  504. </>
  505. )}
  506. </div>
  507. )}
  508. {/* Temperatures (#1422). Rendered whether or not a print is running —
  509. a preheating or cooling printer is exactly when these are worth
  510. watching. Each reading appears only when the printer reports it,
  511. so a single-nozzle machine shows one nozzle and a model without a
  512. chamber sensor shows no chamber row even if `chamber` is in
  513. ?show= (the backend omits the reading entirely for those). */}
  514. {tempReadings.length > 0 && status.connected && (
  515. <div className={`flex items-center ${sizes.gap} flex-wrap mt-2`}>
  516. {tempReadings.map((reading) => (
  517. <TempReading
  518. key={reading.key}
  519. icon={reading.icon}
  520. label={reading.label}
  521. current={reading.current}
  522. target={reading.target}
  523. sizes={sizes}
  524. />
  525. ))}
  526. </div>
  527. )}
  528. </div>
  529. </div>
  530. </div>
  531. );
  532. return config.layout ? <OverlayFrame layout={config.layout}>{artwork}</OverlayFrame> : artwork;
  533. }