Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homepage: Build avatar and profile banner into user dashboard #6117

Merged
merged 8 commits into from
Jun 7, 2024
2 changes: 1 addition & 1 deletion packages/app-root/src/components/HomePageContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default function HomePageContainer({
</Box>
) : (
<Box height={{ min: '100vh' }}>
{user?.login ? <UserHome authUser={user}/> : <DefaultHome />}
{user?.login ? <UserHome authUser={user} /> : <DefaultHome />}
</Box>
)}
<CommunityContainer
Expand Down
10 changes: 6 additions & 4 deletions packages/lib-user/dev/components/App/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
Contributors,
GroupStats,
MyGroups,
UserHome,
UserStats
} from '@components'

Expand All @@ -31,7 +32,7 @@ function App({
useEffect(() => {
async function checkUserSession() {
setLoading(true)

try {
const user = await auth.checkCurrent()
setUser(user)
Expand All @@ -41,7 +42,7 @@ function App({
setLoading(false)
}
}

auth.listen('change', checkUserSession)

return function () {
Expand Down Expand Up @@ -93,13 +94,14 @@ function App({
</li>
</ul>
</ul>
{user?.id ? <UserHome authUser={user} /> : null}
</div>
)

if (groups) {
const subpaths = groups.split('/')
const groupId = subpaths[0] || ''

if (subpaths[0] === '[user_group_id]') {
content = <p>In the url query param <code>?groups=</code>, please replace <code>[user_group_id]</code> with a user group id.</p>
} else if (subpaths[1] === 'contributors') {
Expand Down Expand Up @@ -185,7 +187,7 @@ function App({
/>
</div>
</header>
{loading ?
{loading ?
<p>Loading...</p> : (
<div>
{content}
Expand Down
2 changes: 2 additions & 0 deletions packages/lib-user/src/components/UserHome/UserHome.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { shape, string } from 'prop-types'

import { Layout } from '@components/shared'
import DashboardContainer from './components/Dashboard/DashboardContainer.js'
import RecentSubjectsContainer from './components/RecentSubjects/RecentSubjectsContainer.js'

function UserHome({ authUser }) {
return (
<Layout>
<DashboardContainer authUser={authUser}/>
<RecentSubjectsContainer authUser={authUser} />
</Layout>
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Box, Image, ResponsiveContext } from 'grommet'
import styled from 'styled-components'
import { bool, shape, string } from 'prop-types'
import { useContext } from 'react'

const Relative = styled(Box)`
position: relative;
`

const StyledAvatar = styled(Image)`
width: 128px;
height: 128px;
mcbouslog marked this conversation as resolved.
Show resolved Hide resolved
object-fit: cover;
border-radius: 50%;
border: solid white 6px;
position: absolute;
top: 203px;

// For Grommet breakpoint small
@media (width < 769px) {
width: 80px;
height: 80px;
top: 137px;
}
`

export default function Dashboard({ isLoading = false, user }) {
const size = useContext(ResponsiveContext)

return (
<Relative
fill
align='center'
height={
size !== 'small'
? { min: '270px', max: '270px' }
: { min: '180px', max: '180px' }
}
background={
isLoading || !user?.profile_header
? 'brand'
: { image: `url(${user.profile_header})` }
}
round={size !== 'small' ? { size: '16px', corner: 'top' } : false}
>
<StyledAvatar
alt='User avatar'
src={
!user?.avatar_src || isLoading
? 'https://www.zooniverse.org/assets/simple-avatar.png'
: user.avatar_src
}
/>
</Relative>
)
}

Dashboard.propTypes = {
isLoading: bool,
user: shape({
avatar_src: string,
id: string.isRequired,
profile_header: string
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Dashboard from './Dashboard.js'

export default {
title: 'Components / UserHome / Dashboard',
component: Dashboard
}

const USER = {
admin: false,
avatar_src: 'https://panoptes-uploads-staging.zooniverse.org/user_avatar/e638f5a3-7ffb-4d23-bb08-f296377a2e74.jpeg',
display_name: 'Test User 1',
id: '12345',
login: 'TestUser',
profile_header: 'https://panoptes-uploads.zooniverse.org/user_profile_header/9da9fd16-46c1-4d84-a272-83ac19fb32c3.jpeg'
}

const USER_NO_IMAGES = {
admin: false,
avatar_src: '',
display_name: 'Zootester 123',
id: '847637',
login: 'zootester123',
profile_header: ''
}

export const Default = {
args: {
user: USER
}
}

export const NoAvatarOrBanner = {
args: {
user: USER_NO_IMAGES
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { panoptes } from '@zooniverse/panoptes-js'
import auth from 'panoptes-client/lib/auth'
import useSWR from 'swr'

import Dashboard from './Dashboard'

const SWROptions = {
revalidateIfStale: true,
revalidateOnMount: true,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshInterval: 0
}

/* This is a similar pattern to usePanoptesUser hook, but includes the profile_header */
const fetchProfileBanner = async ({ authUser }) => {
const token = await auth.checkBearerToken()
const authorization = `Bearer ${token}`
const query = { include: 'profile_header', user_id: authUser.id }

try {
const { body } = await panoptes.get('/users', query, { authorization })
const user = body.users?.[0]
Copy link
Contributor

@eatyourgreens eatyourgreens Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API request runs a search across the Users table, returning all users that match query. If the user ID is undefined, it will return the first 20 users from the Users table.

When you want a single, specific resource by ID, the form of the URL to use is GET /api/users/1234?include=profile_header.

You don't need an Authorization header here either, since users are public resources.

When you add Authorization headers to a request, the browser generally won't cache the response, because auth'ed requests are seen as private and not cacheable, so you might end up generating unnecessary network traffic. That can become an important consideration when you're building a busy page with a lot of users, like the Zooniverse home page.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to know! Thanks, I'll refactor this fetch.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm understanding correctly I think this means we can delete auth (lines 17 and 18), remove user_id from the query, and refactor line 22 to const { body } = await panoptes.get(/users/${authUser.id}, query)?

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. A unique cache key for this URL is:

const key = {
  endpoint: `/users/{authUser.id}`,
  query: { include: 'profile_header' }
}

With that key, the client request becomes:

panoptes.get(key.endpoint, key.query)

Alternatively, you could set the key as the full URL:

const key = `/users/{authUser.id}?include=profile_header`

panoptes.get(key)

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, one other thing. panoptes.get uses an old version of SuperAgent (I think it’s still on version 8? Version 9 came out recently, along with a couple of patches), which means that these requests aren’t using fetch.

The app router in Next.js is built on top of fetch so code like this won’t be able to take advantage of Next’s built-in data-caching. Not a big deal right now, when you’re testing with just a single visitor, but something to have in mind when you roll out and need to run the home page under load.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does Next.js's built-in data-caching play with SWR? This request is using SWR in a client component, which is in contrast to using fetch directly in a page.js in app-root:

async function fetchBlogFeed(url) {
try {
const response = await fetch(url)

(Linking the existing superagent Issue to this comment: #317)

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the app router, with Next.js 13.5 and higher, Vercel replace native fetch with their own global fetch that caches the return value.

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-fetch

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 8, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SWR can be used with fetch, like react-query, but will work with any function that returns a Promise-like object.

This page has notes on using it with the app router.
https://swr.vercel.app/docs/with-nextjs

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here’s some documentation on data caching with libraries that don’t use fetch, such as panoptes-js.
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-third-party-libraries

Here’s documentation for the app router data cache, which you’ll need to manage across app instances and deployments, since Zooniverse Next.js is self-hosted on Node.
https://nextjs.org/docs/app/building-your-application/caching#data-cache

I haven’t played around with app router caching, but I believe you can also cache rendered HTML across requests, similar to how the current pages router setup serves pages via a CDN, so that HTML can be served immediately, without waiting for a page build to run.

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here’s a couple of old issues and PRs about slow page build times, for context. Worth bearing in mind for both the new home page and the user stats pages.


if (body.linked?.profile_headers?.length) {
user.profile_header = body.linked.profile_headers[0].src
}
return user
} catch (error) {
console.error(error)
return null
}
}

export default function DashboardContainer({ authUser }) {
const key = { authUser }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If authUser is empty or null, you should set the key to null. That tells SWR to skip the request.

Otherwise, your code here might inadvertently run the SWR hook when it shouldn't, and cache an unexpected value for this key in the SWR cache.

When you pass a key to useSWR, it looks up that key in its global cache and immediately returns the stored result (which is why keys must be unique.) If the stored result is stale, it revalidates the cache by fetching a new result from the remote source. Hence 'stale while revalidate.'

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also a warning that if you've used { authUser } as the key for any other queries, elsewhere in your code, useSWR(key, fetcher, options) will returned the cached values for those queries. That can lead to some weird bugs.

You could avoid that here by passing the query object as the key. I think that's unique to this specific API request. I think that when I was writing SWR hooks for translations, I used the API endpoint and query as the key for each request, but I don't remember the details. That was where I learnt that reusing a key leads to bugs!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DashboardContainer is in UserHome, and UserHome only renders if authUser.login exists. I don't expect authUser to ever be null in this component.

UserHome is conditionally rendered in app-root here. Do you suggest handling the homepage differently?

{user?.login ? <UserHome authUser={user}/> : <DefaultHome />}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you know that authuser will always be defined, then this should be fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good. Good catch with the need for a unique key too, so I'll definitely address that here!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that unique key caught me out here, which is why I added the endpoint.

const defaultKey = {
user: storedUser,
endpoint: '/me'
}

Copy link
Contributor

@eatyourgreens eatyourgreens Jun 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not related to this specific API request, but it can also be a good idea to invalidate the cache when an auth token is refreshed, like this example for user project preferences, which includes authorization in the key:

const key = { endpoint, projectID, userID, authorization }

I think there might be some discussion of that in the SWR docs for query keys. The idea is that you don't want to accidentally show stale private data to another user, eg. on a shared browser, so always clear the cache when the auth header expires and is refreshed.

https://swr.vercel.app/docs/arguments#multiple-arguments

const { data: user, isLoading } = useSWR(key, fetchProfileBanner, SWROptions)

return <Dashboard user={user} isLoading={isLoading} />
}
2 changes: 1 addition & 1 deletion packages/lib-user/src/components/UserHome/index.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { default } from './UserHome'
export { default } from './UserHome.js'