import React from 'react' import * as persisted from '#/state/persisted' import {isWeb} from '#/platform/detection' type StateContext = string type SetContext = (v: string) => void const stateContext = React.createContext('home') const setContext = React.createContext((_: string) => {}) function getInitialFeed() { if (isWeb) { if (window.location.pathname === '/') { const params = new URLSearchParams(window.location.search) const feedFromUrl = params.get('feed') if (feedFromUrl) { // If explicitly booted from a link like /?feed=..., prefer that. return feedFromUrl } } const feedFromSession = sessionStorage.getItem('lastSelectedHomeFeed') if (feedFromSession) { // Fall back to a previously chosen feed for this browser tab. return feedFromSession } } const feedFromPersisted = persisted.get('lastSelectedHomeFeed') if (feedFromPersisted) { // Fall back to the last chosen one across all tabs. return feedFromPersisted } return 'home' } export function Provider({children}: React.PropsWithChildren<{}>) { const [state, setState] = React.useState(getInitialFeed) const saveState = React.useCallback((feed: string) => { setState(feed) if (isWeb) { try { sessionStorage.setItem('lastSelectedHomeFeed', feed) } catch {} } persisted.write('lastSelectedHomeFeed', feed) }, []) return ( {children} ) } export function useSelectedFeed() { return React.useContext(stateContext) } export function useSetSelectedFeed() { return React.useContext(setContext) }