aboutsummaryrefslogtreecommitdiff
path: root/vnext/src/ui/Feeds.js
blob: 086a910e5424d04483516dff48e9c5ab671d03ce (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { useState, useEffect } from 'react'
import { Link, useLocation, useParams, Navigate, useSearchParams } from 'react-router-dom'

import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
dayjs.extend(utc)

import Message from './Message'
import Spinner from './Spinner'

import UserInfo from './UserInfo'

import { getMessages } from '../api'
import { useVisitor } from './VisitorContext'
import { Helmet } from 'react-helmet'

/**
 * @typedef {object} Query
 * @property {string} baseUrl
 * @property {object=} search
 * @property {string} pageParam
 */

/**
 * @typedef {object} PageProps
 * @property {string=} search
 * @property {import('../api').Message[]=} msgs
 */

function RequireAuth({ children }) {
  let location = useLocation()
  let [visitor] = useVisitor()
  if (!visitor.hash) {
    // Redirect them to the /login page, but save the current location they were
    // trying to go to when they were redirected. This allows us to send them
    // along to that page after they login, which is a nicer user experience
    // than dropping them off on the home page.
    return <Navigate to="/login" state={{ from: location }} />
  }

  return children
}

/**
 *
 */
export function Discover() {
  const [search] = useSearchParams()
  const query = {
    baseUrl: '/api/messages',
    search: search,
    pageParam: search.search ? 'page' : 'before_mid'
  }
  return (
    <>
      <Helmet>
        <title>Discover</title>
      </Helmet>
      <Feed query={query} />
    </>
  )
}

/**
 *
 */
export function Discussions() {
  const query = {
    baseUrl: '/api/messages/discussions',
    pageParam: 'to'
  }
  return (
    <>
      <Helmet>
        <title>Discussions</title>
      </Helmet>
      <Feed query={query} />
    </>
  )
}

/**
 *
 */
export function Blog() {
  const { user } = useParams()
  const [params] = useSearchParams()
  const search = {
    ...params,
    uname: user
  }
  const query = {
    baseUrl: '/api/messages',
    search: search,
    pageParam: search.search ? 'page' : 'before_mid'
  }
  const blogTitle = `${user} blog`
  const pageTitle = search.tag ? `${blogTitle}: #${search.tag}` : blogTitle
  return (
    <>
      <Helmet>
        <title>{pageTitle}</title>
      </Helmet>
      <div className="msg-cont">
        <UserInfo uname={user} />
      </div>
      <Feed query={query} />
    </>
  )
}

/**
 * 
 */
export function Tag() {
  const params = useParams()
  const { tag } = params
  const query = {
    baseUrl: '/api/messages',
    search: {
      tag: tag
    },
    pageParam: 'before_mid'
  }
  return (
    <>
      <Helmet>
        <title>#{tag}</title>
      </Helmet>
      <Feed query={query} />
    </>
  )
}

/**
 *
 */
export function Home() {
  const query = {
    baseUrl: '/api/home',
    pageParam: 'before_mid'
  }
  return (
    <RequireAuth>
      <Feed query={query} />
    </RequireAuth>
  )
}

/**
 * @typedef {object} FeedState
 * @property { import('../api').Message[]= } msgs
 * @property { Query} query
 */

/**
 * @param {FeedState} props
 */
function Feed({ query }) {
  const location = useLocation()
  const [visitor] = useVisitor()
  const [state, setState] = useState({
    hash: visitor.hash,
    msgs: [],
    nextpage: null,
    error: false,
    tag: ''
  })
  const [loading, setLoading] = useState(true)
  const [filter] = useSearchParams()
  useEffect(() => {
    setLoading(true)
    let getPageParam = (pageParam, lastMessage, /** @type { URLSearchParams } */ filterParams) => {
      const pageValue = pageParam === 'before_mid' ? lastMessage.mid : pageParam === 'page' ? (Number(filterParams.page) || 0) + 1 : dayjs.utc(lastMessage.updated).valueOf()
      filterParams.append(pageParam, pageValue)
      return `?${filterParams.toString()}`
    }
    let params = { ...Object.fromEntries(filter), ...query.search }
    let url = query.baseUrl
    getMessages(url, params)
      .then(response => {
        const { data } = response
        const { pageParam } = query
        const lastMessage = data.slice(-1)[0] || {}
        const nextpage = getPageParam(pageParam, lastMessage, new URLSearchParams(params))
        document.body.scrollTop = 0
        document.documentElement.scrollTop = 0
        setState((prevState) => {
          return {
            ...prevState,
            msgs: data,
            nextpage: nextpage,
            tag: filter['tag'] || ''
          }
        })
        setLoading(false)
      }).catch(() => {
        setState((prevState) => {
          return {
            ...prevState,
            error: true
          }
        })
      })
  }, [query, filter])
  return (state.msgs.length > 0 ? (
    <div className="msgs">
      {
        state.tag && (
          <p className="page">
            <Link to={{ pathname: `/tag/${state.tag}` }}>
              <span> All posts with tag&nbsp;</span><b>{state.tag}</b>
            </Link>
          </p>
        )
      }
      {
        state.msgs.map(msg =>
          <Message key={msg.mid} data={msg} visitor={visitor} />)
      }
      {
        state.msgs.length >= 20 && (
          <p className="page">
            <Link to={{ pathname: location.pathname, search: state.nextpage }} rel="prev">Next </Link>
          </p>
        )
      }
    </div>
  ) : state.error ? <div>error</div> : loading ? <div className="msgs"><Spinner /><Spinner /><Spinner /><Spinner /></div> : <div>No more messages</div>
  )
}