|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + ReactNode, |
| 4 | + useContext, |
| 5 | + useEffect, |
| 6 | + useState, |
| 7 | +} from "react"; |
| 8 | + |
| 9 | +interface PipelineGraphViewPreferences { |
| 10 | + showNames: boolean; |
| 11 | + setShowNames: (val: boolean) => void; |
| 12 | + showDurations: boolean; |
| 13 | + setShowDurations: (val: boolean) => void; |
| 14 | +} |
| 15 | + |
| 16 | +const defaultPreferences = { |
| 17 | + showNames: false, |
| 18 | + showDurations: false, |
| 19 | +}; |
| 20 | + |
| 21 | +const UserPreferencesContext = createContext< |
| 22 | + PipelineGraphViewPreferences | undefined |
| 23 | +>(undefined); |
| 24 | + |
| 25 | +const makeKey = (setting: string) => `pgv-graph-view.${setting}`; |
| 26 | + |
| 27 | +const loadFromLocalStorage = <T,>(key: string, fallback: T): T => { |
| 28 | + if (typeof window === "undefined") { |
| 29 | + return fallback; |
| 30 | + } |
| 31 | + try { |
| 32 | + const value = window.localStorage.getItem(key); |
| 33 | + if (value !== null) { |
| 34 | + if (typeof fallback === "boolean") { |
| 35 | + return (value === "true") as typeof fallback; |
| 36 | + } |
| 37 | + return value as unknown as T; |
| 38 | + } |
| 39 | + } catch (e) { |
| 40 | + console.error(`Error loading localStorage key "${key}"`, e); |
| 41 | + } |
| 42 | + return fallback; |
| 43 | +}; |
| 44 | + |
| 45 | +export const UserPreferencesProvider = ({ |
| 46 | + children, |
| 47 | +}: { |
| 48 | + children: ReactNode; |
| 49 | +}) => { |
| 50 | + const stageNamesKey = makeKey("stageNames"); |
| 51 | + const stageDurationsKey = makeKey("stageDurations"); |
| 52 | + |
| 53 | + const [showNames, setShowNames] = useState<boolean>( |
| 54 | + loadFromLocalStorage(stageNamesKey, defaultPreferences.showNames), |
| 55 | + ); |
| 56 | + const [showDurations, setShowDurations] = useState<boolean>( |
| 57 | + loadFromLocalStorage(stageDurationsKey, defaultPreferences.showDurations), |
| 58 | + ); |
| 59 | + |
| 60 | + useEffect(() => { |
| 61 | + window.localStorage.setItem(stageNamesKey, String(showNames)); |
| 62 | + }, [showNames]); |
| 63 | + |
| 64 | + useEffect(() => { |
| 65 | + window.localStorage.setItem(stageDurationsKey, String(showDurations)); |
| 66 | + }, [showDurations]); |
| 67 | + |
| 68 | + return ( |
| 69 | + <UserPreferencesContext.Provider |
| 70 | + value={{ |
| 71 | + showNames, |
| 72 | + setShowNames, |
| 73 | + showDurations, |
| 74 | + setShowDurations, |
| 75 | + }} |
| 76 | + > |
| 77 | + {children} |
| 78 | + </UserPreferencesContext.Provider> |
| 79 | + ); |
| 80 | +}; |
| 81 | + |
| 82 | +export const useUserPreferences = (): PipelineGraphViewPreferences => { |
| 83 | + const context = useContext(UserPreferencesContext); |
| 84 | + if (!context) { |
| 85 | + throw new Error( |
| 86 | + "useMonitorPreferences must be used within a UserPreferencesProvider", |
| 87 | + ); |
| 88 | + } |
| 89 | + return context; |
| 90 | +}; |
0 commit comments