|
| 1 | +// Context to keep track of a call to action (e.g. popover introducing a new feature) |
| 2 | +// The state of the CTA will be stored in local storage, so it will persist across page reloads |
| 3 | +// If `dismiss` is called, the CTA will not be shown again |
| 4 | +import { |
| 5 | + createContext, |
| 6 | + useCallback, |
| 7 | + useContext, |
| 8 | + useEffect, |
| 9 | + useState, |
| 10 | + PropsWithChildren, |
| 11 | +} from 'react' |
| 12 | + |
| 13 | +type CTAPopoverState = { |
| 14 | + isOpen: boolean |
| 15 | + initializeCTA: () => void // Call to "open" the CTA if it's not already been dismissed by the user |
| 16 | + dismiss: () => void // Call to "close" the CTA and store the dismissal in local storage |
| 17 | +} |
| 18 | + |
| 19 | +type StoredValue = { dismissed: true } |
| 20 | + |
| 21 | +const CTAPopoverContext = createContext<CTAPopoverState | undefined>(undefined) |
| 22 | + |
| 23 | +const STORAGE_KEY = 'ctaPopoverDismissed' |
| 24 | + |
| 25 | +const isDismissed = (): boolean => { |
| 26 | + if (typeof window === 'undefined') return false // SSR guard |
| 27 | + try { |
| 28 | + const raw = localStorage.getItem(STORAGE_KEY) |
| 29 | + if (!raw) return false |
| 30 | + const parsed = JSON.parse(raw) as StoredValue |
| 31 | + return parsed?.dismissed |
| 32 | + } catch { |
| 33 | + return false // corruption / quota / disabled storage |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +export function CTAPopoverProvider({ children }: PropsWithChildren) { |
| 38 | + // We start closed because we might only want to "turn on" the CTA if an experiment is active |
| 39 | + const [isOpen, setIsOpen] = useState(false) |
| 40 | + |
| 41 | + const persistDismissal = useCallback(() => { |
| 42 | + setIsOpen(false) |
| 43 | + try { |
| 44 | + const obj: StoredValue = { dismissed: true } |
| 45 | + localStorage.setItem(STORAGE_KEY, JSON.stringify(obj)) |
| 46 | + } catch { |
| 47 | + /* ignore */ |
| 48 | + } |
| 49 | + }, []) |
| 50 | + |
| 51 | + const dismiss = useCallback(() => persistDismissal(), [persistDismissal]) |
| 52 | + const initializeCTA = useCallback(() => { |
| 53 | + const dismissed = isDismissed() |
| 54 | + if (dismissed) { |
| 55 | + setIsOpen(false) |
| 56 | + } else { |
| 57 | + setIsOpen(true) |
| 58 | + } |
| 59 | + }, [isDismissed]) |
| 60 | + |
| 61 | + // Wrap in a useEffect to avoid a hydration mismatch (SSR guard) |
| 62 | + useEffect(() => { |
| 63 | + const stored = isDismissed() |
| 64 | + setIsOpen(!stored) |
| 65 | + }, []) |
| 66 | + |
| 67 | + return ( |
| 68 | + <CTAPopoverContext.Provider value={{ isOpen, initializeCTA, dismiss }}> |
| 69 | + {children} |
| 70 | + </CTAPopoverContext.Provider> |
| 71 | + ) |
| 72 | +} |
| 73 | + |
| 74 | +export const useCTAPopoverContext = () => { |
| 75 | + const ctx = useContext(CTAPopoverContext) |
| 76 | + if (!ctx) throw new Error('useCTAPopoverContext must be used inside <CTAPopoverProvider>') |
| 77 | + return ctx |
| 78 | +} |
0 commit comments