CameraWall.tsx 12 KB

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