|
| 1 | +import React, { useState, useCallback, useEffect, type ReactNode } from "react"; |
| 2 | +import { SPLASH_REGISTRY, DISABLE_SPLASH_SCREENS, type SplashConfig } from "./index"; |
| 3 | +import { useAPI } from "@/browser/contexts/API"; |
| 4 | + |
| 5 | +export function SplashScreenProvider({ children }: { children: ReactNode }) { |
| 6 | + const { api } = useAPI(); |
| 7 | + const [queue, setQueue] = useState<SplashConfig[]>([]); |
| 8 | + const [loaded, setLoaded] = useState(false); |
| 9 | + |
| 10 | + // Load viewed splash screens from config on mount |
| 11 | + useEffect(() => { |
| 12 | + // Skip if disabled or API not ready |
| 13 | + if (DISABLE_SPLASH_SCREENS || !api) { |
| 14 | + setLoaded(true); |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + void (async () => { |
| 19 | + try { |
| 20 | + const viewedIds = await api.splashScreens.getViewedSplashScreens(); |
| 21 | + |
| 22 | + // Filter registry to undismissed splashes, sorted by priority (highest number first) |
| 23 | + const activeQueue = SPLASH_REGISTRY.filter((splash) => { |
| 24 | + // Priority 0 = never show |
| 25 | + if (splash.priority === 0) return false; |
| 26 | + |
| 27 | + // Check if this splash has been viewed |
| 28 | + return !viewedIds.includes(splash.id); |
| 29 | + }).sort((a, b) => b.priority - a.priority); // Higher number = higher priority = shown first |
| 30 | + |
| 31 | + setQueue(activeQueue); |
| 32 | + } catch (error) { |
| 33 | + console.error("Failed to load viewed splash screens:", error); |
| 34 | + // On error, don't show any splash screens |
| 35 | + setQueue([]); |
| 36 | + } finally { |
| 37 | + setLoaded(true); |
| 38 | + } |
| 39 | + })(); |
| 40 | + }, [api]); |
| 41 | + |
| 42 | + const currentSplash = queue[0] ?? null; |
| 43 | + |
| 44 | + const dismiss = useCallback(async () => { |
| 45 | + if (!currentSplash || !api) return; |
| 46 | + |
| 47 | + // Mark as viewed in config |
| 48 | + try { |
| 49 | + await api.splashScreens.markSplashScreenViewed({ splashId: currentSplash.id }); |
| 50 | + } catch (error) { |
| 51 | + console.error("Failed to mark splash screen as viewed:", error); |
| 52 | + } |
| 53 | + |
| 54 | + // Remove from queue, next one shows automatically |
| 55 | + setQueue((q) => q.slice(1)); |
| 56 | + }, [currentSplash, api]); |
| 57 | + |
| 58 | + // Don't render splash until we've loaded the viewed state |
| 59 | + if (!loaded) { |
| 60 | + return <>{children}</>; |
| 61 | + } |
| 62 | + |
| 63 | + return ( |
| 64 | + <> |
| 65 | + {children} |
| 66 | + {currentSplash && <currentSplash.component onDismiss={() => void dismiss()} />} |
| 67 | + </> |
| 68 | + ); |
| 69 | +} |
0 commit comments