StreamOverlayPage.tsx 24 KB

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