about summary refs log tree commit diff
path: root/src/state/shell/selected-feed.tsx
blob: 08b7ba77c96b53fb2d54ff4f6b5fcfe8eb2105cf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React from 'react'

import {isWeb} from '#/platform/detection'
import * as persisted from '#/state/persisted'
import {FeedDescriptor} from '#/state/queries/post-feed'

type StateContext = FeedDescriptor | null
type SetContext = (v: FeedDescriptor) => void

const stateContext = React.createContext<StateContext>(null)
const setContext = React.createContext<SetContext>((_: string) => {})

function getInitialFeed(): FeedDescriptor | null {
  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 as FeedDescriptor
      }
    }

    const feedFromSession = sessionStorage.getItem('lastSelectedHomeFeed')
    if (feedFromSession) {
      // Fall back to a previously chosen feed for this browser tab.
      return feedFromSession as FeedDescriptor
    }
  }

  const feedFromPersisted = persisted.get('lastSelectedHomeFeed')
  if (feedFromPersisted) {
    // Fall back to the last chosen one across all tabs.
    return feedFromPersisted as FeedDescriptor
  }

  return null
}

export function Provider({children}: React.PropsWithChildren<{}>) {
  const [state, setState] = React.useState(() => getInitialFeed())

  const saveState = React.useCallback((feed: FeedDescriptor) => {
    setState(feed)
    if (isWeb) {
      try {
        sessionStorage.setItem('lastSelectedHomeFeed', feed)
      } catch {}
    }
    persisted.write('lastSelectedHomeFeed', feed)
  }, [])

  return (
    <stateContext.Provider value={state}>
      <setContext.Provider value={saveState}>{children}</setContext.Provider>
    </stateContext.Provider>
  )
}

export function useSelectedFeed() {
  return React.useContext(stateContext)
}

export function useSetSelectedFeed() {
  return React.useContext(setContext)
}