SpoolBuddyLayout.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. import { Suspense, useState, useEffect, useRef, useCallback, useMemo } from 'react';
  2. import { Outlet, useNavigate, useLocation } from 'react-router-dom';
  3. import { useQuery, useQueries } from '@tanstack/react-query';
  4. import { useTranslation } from 'react-i18next';
  5. import { SpoolBuddyTopBar } from './SpoolBuddyTopBar';
  6. import { SpoolBuddyBottomNav } from './SpoolBuddyBottomNav';
  7. import { SpoolBuddyStatusBar } from './SpoolBuddyStatusBar';
  8. import { SpoolBuddyQuickMenu } from './SpoolBuddyQuickMenu';
  9. import { useSpoolBuddyState } from '../../hooks/useSpoolBuddyState';
  10. import { useColorCatalogVersion } from '../../hooks/useColorCatalogVersion';
  11. import { api, spoolbuddyApi, type Printer, type PrinterStatus } from '../../api/client';
  12. import { VirtualKeyboard } from '../VirtualKeyboard';
  13. import { PageLoading } from '../PageLoading';
  14. import { useToast } from '../../contexts/ToastContext';
  15. import { useUiSettings } from '../../hooks/useUiSettings';
  16. export function SpoolBuddyLayout() {
  17. // Cascade a re-render into all SpoolBuddy pages when the color catalog
  18. // loads, for the same reason as the main Layout — SpoolBuddyInventoryPage
  19. // renders spool color names on mount. See #857.
  20. useColorCatalogVersion();
  21. const [selectedPrinterId, setSelectedPrinterId] = useState<number | null>(null);
  22. const [alert, setAlert] = useState<{ type: 'warning' | 'error' | 'info'; message: string } | null>(null);
  23. const [displayBrightness, setDisplayBrightness] = useState(100);
  24. const { t, i18n } = useTranslation();
  25. const navigate = useNavigate();
  26. const location = useLocation();
  27. const sbState = useSpoolBuddyState();
  28. // Hide the global toast viewport on the kiosk display. Restore on unmount so
  29. // navigating back to the main app sees its toasts again.
  30. const { setViewportSuppressed } = useToast();
  31. useEffect(() => {
  32. setViewportSuppressed(true);
  33. return () => setViewportSuppressed(false);
  34. }, [setViewportSuppressed]);
  35. // Sync language from backend settings (kiosk has its own browser with empty localStorage)
  36. const { data: appSettings } = useUiSettings();
  37. useEffect(() => {
  38. if (appSettings?.language && appSettings.language !== i18n.language) {
  39. i18n.changeLanguage(appSettings.language);
  40. }
  41. }, [appSettings?.language, i18n]);
  42. // Query device data to initialize display settings on any page
  43. const { data: devices = [] } = useQuery({
  44. queryKey: ['spoolbuddy-devices'],
  45. queryFn: () => spoolbuddyApi.getDevices(),
  46. refetchInterval: 30000,
  47. });
  48. const device = devices[0];
  49. const effectiveDeviceOnline = sbState.deviceOnline || Boolean(device?.online);
  50. const sbStateForUi = useMemo(
  51. () => ({ ...sbState, deviceOnline: effectiveDeviceOnline }),
  52. [sbState, effectiveDeviceOnline]
  53. );
  54. // Sync display settings from device on initial load
  55. const initializedRef = useRef(false);
  56. useEffect(() => {
  57. if (device && !initializedRef.current) {
  58. setDisplayBrightness(device.display_brightness);
  59. initializedRef.current = true;
  60. }
  61. }, [device]);
  62. // Force dark theme on mount, restore on unmount
  63. useEffect(() => {
  64. const root = document.documentElement;
  65. const hadDark = root.classList.contains('dark');
  66. root.classList.add('dark');
  67. return () => {
  68. if (!hadDark) root.classList.remove('dark');
  69. };
  70. }, []);
  71. // Auto-check for SpoolBuddy daemon updates
  72. const { data: updateCheck } = useQuery({
  73. queryKey: ['spoolbuddy-update-check', device?.device_id],
  74. queryFn: () => device ? spoolbuddyApi.checkDaemonUpdate(device.device_id) : Promise.resolve(null),
  75. enabled: !!device,
  76. refetchInterval: 5 * 60 * 1000, // re-check every 5 minutes
  77. staleTime: 0,
  78. });
  79. // Update alert based on device state and available updates.
  80. // Only clear alerts that the layout itself set (not alerts from child pages).
  81. const layoutAlertRef = useRef<string | null>(null);
  82. useEffect(() => {
  83. if (!effectiveDeviceOnline) {
  84. const msg = 'SpoolBuddy device disconnected';
  85. setAlert({ type: 'warning', message: msg });
  86. layoutAlertRef.current = msg;
  87. } else if (updateCheck?.update_available && updateCheck.latest_version) {
  88. const msg = `Update available: v${updateCheck.latest_version}`;
  89. setAlert({ type: 'info', message: msg });
  90. layoutAlertRef.current = msg;
  91. } else if (layoutAlertRef.current) {
  92. setAlert(null);
  93. layoutAlertRef.current = null;
  94. }
  95. }, [effectiveDeviceOnline, updateCheck?.update_available, updateCheck?.latest_version]);
  96. // A scanned tag that could not be looked up at all, which otherwise looks
  97. // like nothing happened. Its own slot above the page and layout alerts, so
  98. // it neither replaces them nor is cleared by them, and it clears itself.
  99. const [scanNotice, setScanNotice] = useState<{ type: 'error'; message: string } | null>(null);
  100. const tRef = useRef(t);
  101. tRef.current = t;
  102. useEffect(() => {
  103. let clearTimer: ReturnType<typeof setTimeout> | undefined;
  104. const show = (key: string) => () => {
  105. setScanNotice({ type: 'error', message: tRef.current(key) });
  106. clearTimeout(clearTimer);
  107. clearTimer = setTimeout(() => setScanNotice(null), 10000);
  108. };
  109. const onUnavailable = show('spoolbuddy.status.spoolmanUnavailable');
  110. const onLookupError = show('spoolbuddy.status.lookupFailed');
  111. window.addEventListener('spoolman-unavailable', onUnavailable);
  112. window.addEventListener('spoolbuddy-lookup-error', onLookupError);
  113. return () => {
  114. clearTimeout(clearTimer);
  115. window.removeEventListener('spoolman-unavailable', onUnavailable);
  116. window.removeEventListener('spoolbuddy-lookup-error', onLookupError);
  117. };
  118. }, []);
  119. // Auto-navigate to dashboard when a NEW tag is detected (transition from no-tag to tag).
  120. // Blanking itself is handled by swayidle/wlopm at the OS level on the kiosk device —
  121. // when the HDMI output powers off and the user taps the screen, labwc delivers the
  122. // input event to swayidle's `resume` command which re-powers HDMI. See issue #937.
  123. const tagDetected = Boolean(sbState.matchedSpool || sbState.unknownTagUid || sbState.unknownTrayUuid);
  124. const prevTagDetected = useRef(false);
  125. useEffect(() => {
  126. if (tagDetected && !prevTagDetected.current) {
  127. if (location.pathname !== '/spoolbuddy') {
  128. navigate('/spoolbuddy');
  129. }
  130. }
  131. prevTagDetected.current = tagDetected;
  132. }, [tagDetected, location.pathname, navigate]);
  133. // Online printers list for swipe-to-switch
  134. const { data: printers = [] } = useQuery({
  135. queryKey: ['printers'],
  136. queryFn: () => api.getPrinters(),
  137. });
  138. const statusQueries = useQueries({
  139. queries: printers.map((printer: Printer) => ({
  140. queryKey: ['printerStatus', printer.id],
  141. queryFn: () => api.getPrinterStatus(printer.id),
  142. refetchInterval: 10000,
  143. select: (data: PrinterStatus) => ({ connected: data?.connected }),
  144. })),
  145. });
  146. const onlinePrinters = useMemo(() => {
  147. return printers.filter((_: Printer, i: number) => statusQueries[i]?.data?.connected);
  148. }, [printers, statusQueries]);
  149. // Swipe left/right to cycle through online printers
  150. const touchStartRef = useRef<{ x: number; y: number } | null>(null);
  151. const swipeLockedRef = useRef(false);
  152. const SWIPE_THRESHOLD = 50;
  153. const rootRef = useRef<HTMLDivElement>(null);
  154. const handleTouchStart = useCallback((e: React.TouchEvent) => {
  155. touchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
  156. swipeLockedRef.current = false;
  157. }, []);
  158. const handleTouchEnd = useCallback((e: React.TouchEvent) => {
  159. if (!touchStartRef.current) return;
  160. const dx = e.changedTouches[0].clientX - touchStartRef.current.x;
  161. const dy = e.changedTouches[0].clientY - touchStartRef.current.y;
  162. const startY = touchStartRef.current.y;
  163. touchStartRef.current = null;
  164. swipeLockedRef.current = false;
  165. // Vertical swipe down from top area → open quick menu
  166. // Top bar is 48px; allow starting swipe up to 120px from top to account for finger size
  167. if (dy >= SWIPE_THRESHOLD && Math.abs(dy) > Math.abs(dx) && startY < 120) {
  168. setQuickMenuOpen(true);
  169. return;
  170. }
  171. // Horizontal swipe: cycle printers
  172. if (onlinePrinters.length < 2) return;
  173. if (Math.abs(dx) < SWIPE_THRESHOLD || Math.abs(dy) > Math.abs(dx)) return;
  174. const currentIdx = onlinePrinters.findIndex((p: Printer) => p.id === selectedPrinterId);
  175. const nextIdx = dx < 0
  176. ? (currentIdx + 1) % onlinePrinters.length // swipe left → next
  177. : (currentIdx - 1 + onlinePrinters.length) % onlinePrinters.length; // swipe right → prev
  178. setSelectedPrinterId(onlinePrinters[nextIdx].id);
  179. }, [onlinePrinters, selectedPrinterId, setSelectedPrinterId]);
  180. // Block browser back/forward swipe gesture with non-passive touchmove listener
  181. useEffect(() => {
  182. const el = rootRef.current;
  183. if (!el) return;
  184. const onTouchMove = (e: TouchEvent) => {
  185. if (!touchStartRef.current) return;
  186. const dx = Math.abs(e.touches[0].clientX - touchStartRef.current.x);
  187. const dy = Math.abs(e.touches[0].clientY - touchStartRef.current.y);
  188. // Once locked as horizontal, prevent default for the rest of this gesture
  189. if (swipeLockedRef.current) { e.preventDefault(); return; }
  190. if (dx > 10 && dx > dy) { swipeLockedRef.current = true; e.preventDefault(); }
  191. };
  192. el.addEventListener('touchmove', onTouchMove, { passive: false });
  193. return () => el.removeEventListener('touchmove', onTouchMove);
  194. }, []);
  195. // Track virtual keyboard visibility to hide bottom bars
  196. const [keyboardVisible, setKeyboardVisible] = useState(false);
  197. // Quick menu (swipe down to open)
  198. const [quickMenuOpen, setQuickMenuOpen] = useState(false);
  199. // CSS brightness filter (software dimming)
  200. const brightnessStyle = displayBrightness < 100
  201. ? { filter: `brightness(${displayBrightness / 100})` } as const
  202. : undefined;
  203. return (
  204. <>
  205. <div
  206. ref={rootRef}
  207. data-spoolbuddy-kiosk
  208. className="w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden"
  209. style={{ ...brightnessStyle, overscrollBehaviorX: 'none' }}
  210. onTouchStart={handleTouchStart}
  211. onTouchEnd={handleTouchEnd}
  212. >
  213. {/* Pull-down handle — tap or swipe to open quick menu */}
  214. <button
  215. onClick={() => setQuickMenuOpen(true)}
  216. className="w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none"
  217. aria-label="Open quick menu"
  218. >
  219. <div className="w-8 h-0.5 rounded-full bg-zinc-600" />
  220. </button>
  221. <SpoolBuddyTopBar
  222. selectedPrinterId={selectedPrinterId}
  223. onPrinterChange={setSelectedPrinterId}
  224. deviceOnline={effectiveDeviceOnline}
  225. />
  226. <main className="flex-1 overflow-y-auto">
  227. <Suspense fallback={<PageLoading />}>
  228. <Outlet context={{
  229. selectedPrinterId, setSelectedPrinterId, sbState: sbStateForUi, setAlert,
  230. displayBrightness, setDisplayBrightness,
  231. }} />
  232. </Suspense>
  233. </main>
  234. {!keyboardVisible && <SpoolBuddyStatusBar alert={scanNotice ?? alert} />}
  235. {!keyboardVisible && <SpoolBuddyBottomNav />}
  236. <VirtualKeyboard onVisibilityChange={setKeyboardVisible} />
  237. </div>
  238. {/* Quick menu (swipe down from top) */}
  239. <SpoolBuddyQuickMenu
  240. isOpen={quickMenuOpen}
  241. onClose={() => setQuickMenuOpen(false)}
  242. deviceId={device?.device_id ?? null}
  243. deviceOnline={effectiveDeviceOnline}
  244. />
  245. </>
  246. );
  247. }
  248. // Hook for child pages to access shared context
  249. export interface SpoolBuddyOutletContext {
  250. selectedPrinterId: number | null;
  251. setSelectedPrinterId: (id: number) => void;
  252. sbState: ReturnType<typeof useSpoolBuddyState>;
  253. setAlert: (alert: { type: 'warning' | 'error' | 'info'; message: string } | null) => void;
  254. displayBrightness: number;
  255. setDisplayBrightness: (brightness: number) => void;
  256. }