mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
at ruby-v 66 lines 1.9 kB view raw
1import React from 'react' 2 3import {isWeb} from '#/platform/detection' 4import * as persisted from '#/state/persisted' 5import {FeedDescriptor} from '#/state/queries/post-feed' 6 7type StateContext = FeedDescriptor | null 8type SetContext = (v: FeedDescriptor) => void 9 10const stateContext = React.createContext<StateContext>(null) 11const setContext = React.createContext<SetContext>((_: string) => {}) 12 13function getInitialFeed(): FeedDescriptor | null { 14 if (isWeb) { 15 if (window.location.pathname === '/') { 16 const params = new URLSearchParams(window.location.search) 17 const feedFromUrl = params.get('feed') 18 if (feedFromUrl) { 19 // If explicitly booted from a link like /?feed=..., prefer that. 20 return feedFromUrl as FeedDescriptor 21 } 22 } 23 24 const feedFromSession = sessionStorage.getItem('lastSelectedHomeFeed') 25 if (feedFromSession) { 26 // Fall back to a previously chosen feed for this browser tab. 27 return feedFromSession as FeedDescriptor 28 } 29 } 30 31 const feedFromPersisted = persisted.get('lastSelectedHomeFeed') 32 if (feedFromPersisted) { 33 // Fall back to the last chosen one across all tabs. 34 return feedFromPersisted as FeedDescriptor 35 } 36 37 return null 38} 39 40export function Provider({children}: React.PropsWithChildren<{}>) { 41 const [state, setState] = React.useState(() => getInitialFeed()) 42 43 const saveState = React.useCallback((feed: FeedDescriptor) => { 44 setState(feed) 45 if (isWeb) { 46 try { 47 sessionStorage.setItem('lastSelectedHomeFeed', feed) 48 } catch {} 49 } 50 persisted.write('lastSelectedHomeFeed', feed) 51 }, []) 52 53 return ( 54 <stateContext.Provider value={state}> 55 <setContext.Provider value={saveState}>{children}</setContext.Provider> 56 </stateContext.Provider> 57 ) 58} 59 60export function useSelectedFeed() { 61 return React.useContext(stateContext) 62} 63 64export function useSetSelectedFeed() { 65 return React.useContext(setContext) 66}