CameraWall.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import { useEffect, useMemo, useRef, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQueries } from '@tanstack/react-query';
  4. import { Settings as SettingsIcon } from 'lucide-react';
  5. import { DEFAULT_CAM_WALL_TILE_SIZE, camWallGridClasses } from './camWallTileSize';
  6. import { CameraTile, type CameraTileMode, type CameraTileStatusMode } from './CameraTile';
  7. import { filterKnownHMSErrors } from './HMSErrorModal';
  8. import { api, type PrinterStatus } from '../api/client';
  9. // The wall only ever reads these three fields off a printer, so it asks for no
  10. // more than that. Printer[] satisfies this structurally, and so does the
  11. // smaller payload the token-authenticated kiosk feed returns (#2531) — which
  12. // deliberately carries neither serial number nor IP.
  13. export interface CameraWallPrinter {
  14. id: number;
  15. name: string;
  16. camera_rotation?: number;
  17. }
  18. // What a tile draws from a printer's status. PrinterStatus satisfies it; so
  19. // does CamWallPrinter, which is how the kiosk page feeds the same component
  20. // without the JWT-gated per-printer status endpoint.
  21. export interface CameraWallStatus {
  22. connected?: boolean;
  23. state?: string | null;
  24. progress?: number | null;
  25. remaining_time?: number | null;
  26. layer_num?: number | null;
  27. total_layers?: number | null;
  28. subtask_name?: string | null;
  29. gcode_file?: string | null;
  30. hms_errors?: PrinterStatus['hms_errors'];
  31. }
  32. interface CameraWallProps {
  33. printers: CameraWallPrinter[];
  34. maxLive: number;
  35. snapshotIntervalSec: number;
  36. statusMode: CameraTileStatusMode;
  37. onChangeMaxLive: (next: number) => void;
  38. onChangeSnapshotIntervalSec: (next: number) => void;
  39. onChangeStatusMode: (next: CameraTileStatusMode) => void;
  40. // Omitted on a kiosk wall: a TV has no pointer, and click-through would open
  41. // a page the wall's token cannot authenticate. Tiles render inert instead.
  42. onTileClick?: (printerId: number, printerName: string) => void;
  43. // Supplied by the kiosk page, which polls one feed for the whole wall. When
  44. // absent the component fetches per-printer status itself, reusing the
  45. // ['printerStatus', id] cache the printer cards already populate.
  46. statuses?: Map<number, CameraWallStatus | undefined>;
  47. // Kiosk walls hide the settings popover — the knobs come from the URL, and
  48. // there is nobody standing at the screen to turn them.
  49. showSettings?: boolean;
  50. // 1=S, 2=M, 3=L, 4=XL, the same scale as the printer cards (#2735). Sets how
  51. // many tiles share a row; the tiles stay 16:9.
  52. tileSize?: number;
  53. }
  54. const MIN_MAX_LIVE = 1;
  55. const MAX_MAX_LIVE = 16;
  56. const MIN_SNAPSHOT_SEC = 2;
  57. const MAX_SNAPSHOT_SEC = 60;
  58. const STATUS_MODES: CameraTileStatusMode[] = ['off', 'compact', 'full'];
  59. export function CameraWall({
  60. printers,
  61. maxLive,
  62. snapshotIntervalSec,
  63. statusMode,
  64. onTileClick,
  65. onChangeMaxLive,
  66. onChangeSnapshotIntervalSec,
  67. onChangeStatusMode,
  68. statuses,
  69. showSettings: settingsEnabled = true,
  70. tileSize = DEFAULT_CAM_WALL_TILE_SIZE,
  71. }: CameraWallProps) {
  72. const { t } = useTranslation();
  73. const tileRefs = useRef<Map<number, HTMLDivElement | null>>(new Map());
  74. // Reuses the same ['printerStatus', id] cache that each PrinterCard
  75. // populates, so flipping between Cards and Cam Wall is instant. Skipped
  76. // entirely when the caller already has the statuses — the kiosk page polls
  77. // one feed for the whole wall, and its token cannot reach this endpoint.
  78. const ownQueries = statuses ? [] : printers;
  79. const statusQueries = useQueries({
  80. queries: ownQueries.map((p) => ({
  81. queryKey: ['printerStatus', p.id],
  82. queryFn: () => api.getPrinterStatus(p.id),
  83. staleTime: 5000,
  84. })),
  85. });
  86. const fetchedStatuses = useMemo(() => {
  87. const map = new Map<number, CameraWallStatus | undefined>();
  88. ownQueries.forEach((p, i) => {
  89. map.set(p.id, statusQueries[i]?.data);
  90. });
  91. return map;
  92. // eslint-disable-next-line react-hooks/exhaustive-deps
  93. }, [printers, statusQueries, statuses]);
  94. const statusByPrinter = statuses ?? fetchedStatuses;
  95. const [visibleIds, setVisibleIds] = useState<Set<number>>(() => new Set());
  96. const [showSettings, setShowSettings] = useState(false);
  97. const settingsRef = useRef<HTMLDivElement | null>(null);
  98. useEffect(() => {
  99. if (!showSettings) return;
  100. const handler = (e: MouseEvent) => {
  101. if (settingsRef.current && !settingsRef.current.contains(e.target as Node)) {
  102. setShowSettings(false);
  103. }
  104. };
  105. document.addEventListener('mousedown', handler);
  106. return () => document.removeEventListener('mousedown', handler);
  107. }, [showSettings]);
  108. // IntersectionObserver: a tile is "visible" when ≥40% of it is on-screen.
  109. // 40% (not 0%) avoids flicker at scroll boundaries where a tile is fractionally
  110. // visible — we don't want to spin up a live stream for a 5-pixel sliver.
  111. useEffect(() => {
  112. const observer = new IntersectionObserver(
  113. (entries) => {
  114. setVisibleIds((prev) => {
  115. const next = new Set(prev);
  116. for (const entry of entries) {
  117. const id = Number((entry.target as HTMLElement).dataset.printerId);
  118. if (!Number.isFinite(id)) continue;
  119. if (entry.isIntersecting) next.add(id);
  120. else next.delete(id);
  121. }
  122. return next;
  123. });
  124. },
  125. { threshold: 0.4 },
  126. );
  127. for (const [, el] of tileRefs.current) {
  128. if (el) observer.observe(el);
  129. }
  130. return () => observer.disconnect();
  131. }, [printers]);
  132. // Live slot allocation: visible tiles get live up to `maxLive`, in printer
  133. // list order so the assignment is stable. Visible-but-over-cap fall back to
  134. // snapshot polling. Off-screen tiles render paused (no network). Disconnected
  135. // printers also render paused regardless of visibility — there's nothing to
  136. // stream and burning a live-budget slot on them would starve a working tile.
  137. const modeByPrinter = useMemo(() => {
  138. const map = new Map<number, CameraTileMode>();
  139. let liveBudget = Math.max(0, maxLive);
  140. for (const p of printers) {
  141. const connected = statusByPrinter.get(p.id)?.connected ?? false;
  142. if (!visibleIds.has(p.id) || !connected) {
  143. map.set(p.id, 'paused');
  144. continue;
  145. }
  146. if (liveBudget > 0) {
  147. map.set(p.id, 'live');
  148. liveBudget -= 1;
  149. } else {
  150. map.set(p.id, 'snapshot');
  151. }
  152. }
  153. return map;
  154. }, [printers, visibleIds, maxLive, statusByPrinter]);
  155. if (printers.length === 0) {
  156. return (
  157. <div className="rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-6 text-center text-bambu-gray">
  158. {t('printers.camWall.noPrinters')}
  159. </div>
  160. );
  161. }
  162. return (
  163. <div className="space-y-3">
  164. <div className="flex items-center justify-between text-xs text-bambu-gray">
  165. <span>
  166. {t('printers.camWall.summary', {
  167. live: Array.from(modeByPrinter.values()).filter((m) => m === 'live').length,
  168. snap: Array.from(modeByPrinter.values()).filter((m) => m === 'snapshot').length,
  169. total: printers.length,
  170. })}
  171. </span>
  172. {/* Not merely hidden — a kiosk wall must not carry a focusable control
  173. it cannot act on. CSS-hiding would leave it tabbable. */}
  174. {settingsEnabled && (
  175. <div className="relative" ref={settingsRef}>
  176. <button
  177. type="button"
  178. onClick={() => setShowSettings((v) => !v)}
  179. className="flex h-7 items-center gap-1 rounded-md border border-bambu-dark-tertiary bg-bambu-dark px-2 text-white hover:bg-bambu-dark-tertiary"
  180. title={t('printers.camWall.settings.title')}
  181. >
  182. <SettingsIcon className="h-3.5 w-3.5" />
  183. <span>{t('printers.camWall.settings.title')}</span>
  184. </button>
  185. {showSettings && (
  186. <div className="absolute right-0 top-9 z-30 w-72 space-y-3 rounded-lg border border-bambu-dark-tertiary bg-bambu-dark-secondary p-3 shadow-xl">
  187. <label className="block space-y-1">
  188. <span className="text-xs font-medium text-white">
  189. {t('printers.camWall.settings.maxLive')}
  190. </span>
  191. <input
  192. type="number"
  193. min={MIN_MAX_LIVE}
  194. max={MAX_MAX_LIVE}
  195. value={maxLive}
  196. onChange={(e) => {
  197. const n = Math.min(
  198. MAX_MAX_LIVE,
  199. Math.max(MIN_MAX_LIVE, Number(e.target.value) || MIN_MAX_LIVE),
  200. );
  201. onChangeMaxLive(n);
  202. }}
  203. className="w-full rounded-md border border-bambu-dark-tertiary bg-bambu-dark px-2 py-1 text-sm text-white"
  204. />
  205. <span className="block text-[11px] text-bambu-gray">
  206. {t('printers.camWall.settings.maxLiveHint')}
  207. </span>
  208. </label>
  209. <label className="block space-y-1">
  210. <span className="text-xs font-medium text-white">
  211. {t('printers.camWall.settings.snapshotInterval')}
  212. </span>
  213. <input
  214. type="number"
  215. min={MIN_SNAPSHOT_SEC}
  216. max={MAX_SNAPSHOT_SEC}
  217. value={snapshotIntervalSec}
  218. onChange={(e) => {
  219. const n = Math.min(
  220. MAX_SNAPSHOT_SEC,
  221. Math.max(MIN_SNAPSHOT_SEC, Number(e.target.value) || MIN_SNAPSHOT_SEC),
  222. );
  223. onChangeSnapshotIntervalSec(n);
  224. }}
  225. className="w-full rounded-md border border-bambu-dark-tertiary bg-bambu-dark px-2 py-1 text-sm text-white"
  226. />
  227. <span className="block text-[11px] text-bambu-gray">
  228. {t('printers.camWall.settings.snapshotIntervalHint')}
  229. </span>
  230. </label>
  231. <div className="space-y-1">
  232. <span className="block text-xs font-medium text-white">
  233. {t('printers.camWall.settings.statusOverlay')}
  234. </span>
  235. <div
  236. role="radiogroup"
  237. aria-label={t('printers.camWall.settings.statusOverlay')}
  238. className="flex overflow-hidden rounded-md border border-bambu-dark-tertiary"
  239. >
  240. {STATUS_MODES.map((m) => (
  241. <button
  242. key={m}
  243. type="button"
  244. role="radio"
  245. aria-checked={statusMode === m}
  246. onClick={() => onChangeStatusMode(m)}
  247. className={`flex-1 px-2 py-1 text-xs ${
  248. statusMode === m
  249. ? 'bg-bambu-green text-black font-semibold'
  250. : 'bg-bambu-dark text-white hover:bg-bambu-dark-tertiary'
  251. }`}
  252. >
  253. {t(`printers.camWall.statusMode.${m}`)}
  254. </button>
  255. ))}
  256. </div>
  257. <span className="block text-[11px] text-bambu-gray">
  258. {t('printers.camWall.settings.statusOverlayHint')}
  259. </span>
  260. </div>
  261. </div>
  262. )}
  263. </div>
  264. )}
  265. </div>
  266. <div className={`grid gap-3 ${camWallGridClasses(tileSize)}`} data-testid="camwall-grid">
  267. {printers.map((p) => {
  268. const mode = modeByPrinter.get(p.id) ?? 'paused';
  269. return (
  270. <div
  271. key={p.id}
  272. ref={(el) => {
  273. tileRefs.current.set(p.id, el);
  274. }}
  275. data-printer-id={p.id}
  276. >
  277. <CameraTile
  278. printerId={p.id}
  279. printerName={p.name}
  280. cameraRotation={p.camera_rotation}
  281. mode={mode}
  282. snapshotIntervalMs={snapshotIntervalSec * 1000}
  283. connected={statusByPrinter.get(p.id)?.connected ?? false}
  284. statusMode={statusMode}
  285. printerState={statusByPrinter.get(p.id)?.state ?? null}
  286. progress={statusByPrinter.get(p.id)?.progress ?? null}
  287. remainingMin={statusByPrinter.get(p.id)?.remaining_time ?? null}
  288. layerNum={statusByPrinter.get(p.id)?.layer_num ?? null}
  289. totalLayers={statusByPrinter.get(p.id)?.total_layers ?? null}
  290. printName={
  291. statusByPrinter.get(p.id)?.subtask_name ??
  292. statusByPrinter.get(p.id)?.gcode_file ??
  293. null
  294. }
  295. hmsErrorCount={
  296. filterKnownHMSErrors(statusByPrinter.get(p.id)?.hms_errors ?? []).length
  297. }
  298. onClick={onTileClick ? () => onTileClick(p.id, p.name) : undefined}
  299. />
  300. </div>
  301. );
  302. })}
  303. </div>
  304. </div>
  305. );
  306. }