SpoolBuddyLayout.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 { 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. // Auto-navigate to dashboard when a NEW tag is detected (transition from no-tag to tag).
  97. // Blanking itself is handled by swayidle/wlopm at the OS level on the kiosk device —
  98. // when the HDMI output powers off and the user taps the screen, labwc delivers the
  99. // input event to swayidle's `resume` command which re-powers HDMI. See issue #937.
  100. const tagDetected = Boolean(sbState.matchedSpool || sbState.unknownTagUid || sbState.unknownTrayUuid);
  101. const prevTagDetected = useRef(false);
  102. useEffect(() => {
  103. if (tagDetected && !prevTagDetected.current) {
  104. if (location.pathname !== '/spoolbuddy') {
  105. navigate('/spoolbuddy');
  106. }
  107. }
  108. prevTagDetected.current = tagDetected;
  109. }, [tagDetected, location.pathname, navigate]);
  110. // Online printers list for swipe-to-switch
  111. const { data: printers = [] } = useQuery({
  112. queryKey: ['printers'],
  113. queryFn: () => api.getPrinters(),
  114. });
  115. const statusQueries = useQueries({
  116. queries: printers.map((printer: Printer) => ({
  117. queryKey: ['printerStatus', printer.id],
  118. queryFn: () => api.getPrinterStatus(printer.id),
  119. refetchInterval: 10000,
  120. select: (data: PrinterStatus) => ({ connected: data?.connected }),
  121. })),
  122. });
  123. const onlinePrinters = useMemo(() => {
  124. return printers.filter((_: Printer, i: number) => statusQueries[i]?.data?.connected);
  125. }, [printers, statusQueries]);
  126. // Swipe left/right to cycle through online printers
  127. const touchStartRef = useRef<{ x: number; y: number } | null>(null);
  128. const swipeLockedRef = useRef(false);
  129. const SWIPE_THRESHOLD = 50;
  130. const rootRef = useRef<HTMLDivElement>(null);
  131. const handleTouchStart = useCallback((e: React.TouchEvent) => {
  132. touchStartRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
  133. swipeLockedRef.current = false;
  134. }, []);
  135. const handleTouchEnd = useCallback((e: React.TouchEvent) => {
  136. if (!touchStartRef.current) return;
  137. const dx = e.changedTouches[0].clientX - touchStartRef.current.x;
  138. const dy = e.changedTouches[0].clientY - touchStartRef.current.y;
  139. const startY = touchStartRef.current.y;
  140. touchStartRef.current = null;
  141. swipeLockedRef.current = false;
  142. // Vertical swipe down from top area → open quick menu
  143. // Top bar is 48px; allow starting swipe up to 120px from top to account for finger size
  144. if (dy >= SWIPE_THRESHOLD && Math.abs(dy) > Math.abs(dx) && startY < 120) {
  145. setQuickMenuOpen(true);
  146. return;
  147. }
  148. // Horizontal swipe: cycle printers
  149. if (onlinePrinters.length < 2) return;
  150. if (Math.abs(dx) < SWIPE_THRESHOLD || Math.abs(dy) > Math.abs(dx)) return;
  151. const currentIdx = onlinePrinters.findIndex((p: Printer) => p.id === selectedPrinterId);
  152. const nextIdx = dx < 0
  153. ? (currentIdx + 1) % onlinePrinters.length // swipe left → next
  154. : (currentIdx - 1 + onlinePrinters.length) % onlinePrinters.length; // swipe right → prev
  155. setSelectedPrinterId(onlinePrinters[nextIdx].id);
  156. }, [onlinePrinters, selectedPrinterId, setSelectedPrinterId]);
  157. // Block browser back/forward swipe gesture with non-passive touchmove listener
  158. useEffect(() => {
  159. const el = rootRef.current;
  160. if (!el) return;
  161. const onTouchMove = (e: TouchEvent) => {
  162. if (!touchStartRef.current) return;
  163. const dx = Math.abs(e.touches[0].clientX - touchStartRef.current.x);
  164. const dy = Math.abs(e.touches[0].clientY - touchStartRef.current.y);
  165. // Once locked as horizontal, prevent default for the rest of this gesture
  166. if (swipeLockedRef.current) { e.preventDefault(); return; }
  167. if (dx > 10 && dx > dy) { swipeLockedRef.current = true; e.preventDefault(); }
  168. };
  169. el.addEventListener('touchmove', onTouchMove, { passive: false });
  170. return () => el.removeEventListener('touchmove', onTouchMove);
  171. }, []);
  172. // Track virtual keyboard visibility to hide bottom bars
  173. const [keyboardVisible, setKeyboardVisible] = useState(false);
  174. // Quick menu (swipe down to open)
  175. const [quickMenuOpen, setQuickMenuOpen] = useState(false);
  176. // CSS brightness filter (software dimming)
  177. const brightnessStyle = displayBrightness < 100
  178. ? { filter: `brightness(${displayBrightness / 100})` } as const
  179. : undefined;
  180. return (
  181. <>
  182. <div
  183. ref={rootRef}
  184. data-spoolbuddy-kiosk
  185. className="w-screen h-screen bg-bambu-dark text-white flex flex-col overflow-hidden"
  186. style={{ ...brightnessStyle, overscrollBehaviorX: 'none' }}
  187. onTouchStart={handleTouchStart}
  188. onTouchEnd={handleTouchEnd}
  189. >
  190. {/* Pull-down handle — tap or swipe to open quick menu */}
  191. <button
  192. onClick={() => setQuickMenuOpen(true)}
  193. className="w-full h-1.5 bg-bambu-dark-secondary flex justify-center items-center shrink-0 touch-none"
  194. aria-label="Open quick menu"
  195. >
  196. <div className="w-8 h-0.5 rounded-full bg-zinc-600" />
  197. </button>
  198. <SpoolBuddyTopBar
  199. selectedPrinterId={selectedPrinterId}
  200. onPrinterChange={setSelectedPrinterId}
  201. deviceOnline={effectiveDeviceOnline}
  202. />
  203. <main className="flex-1 overflow-y-auto">
  204. <Suspense fallback={<PageLoading />}>
  205. <Outlet context={{
  206. selectedPrinterId, setSelectedPrinterId, sbState: sbStateForUi, setAlert,
  207. displayBrightness, setDisplayBrightness,
  208. }} />
  209. </Suspense>
  210. </main>
  211. {!keyboardVisible && <SpoolBuddyStatusBar alert={alert} />}
  212. {!keyboardVisible && <SpoolBuddyBottomNav />}
  213. <VirtualKeyboard onVisibilityChange={setKeyboardVisible} />
  214. </div>
  215. {/* Quick menu (swipe down from top) */}
  216. <SpoolBuddyQuickMenu
  217. isOpen={quickMenuOpen}
  218. onClose={() => setQuickMenuOpen(false)}
  219. deviceId={device?.device_id ?? null}
  220. deviceOnline={effectiveDeviceOnline}
  221. />
  222. </>
  223. );
  224. }
  225. // Hook for child pages to access shared context
  226. export interface SpoolBuddyOutletContext {
  227. selectedPrinterId: number | null;
  228. setSelectedPrinterId: (id: number) => void;
  229. sbState: ReturnType<typeof useSpoolBuddyState>;
  230. setAlert: (alert: { type: 'warning' | 'error' | 'info'; message: string } | null) => void;
  231. displayBrightness: number;
  232. setDisplayBrightness: (brightness: number) => void;
  233. }