SpoolBuddyLayout.tsx 10 KB

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