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

Fixes #1078: Banner Images Reload twice #1162

Merged
merged 4 commits into from
Oct 7, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/frontend/src/components/Banner/Banner.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { makeStyles } from '@material-ui/core/styles';
import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown';
import { Fab, Grid, Typography, Link } from '@material-ui/core';
import useSiteMetadata from '../../hooks/use-site-metadata';
import DynamicBackgroundContainer from '../DynamicBackgroundContainer';
import DynamicBackgroundContainer from '../DynamicBackgroundContainer.jsx';
Copy link
Contributor

Choose a reason for hiding this comment

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

We don't need .jsx in imports. Let's remove in this case.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Line 7, linter was yelling about this. 🤷‍♂️.


const useStyles = makeStyles((theme) => ({
h1: {
Expand Down Expand Up @@ -89,9 +89,9 @@ const useStyles = makeStyles((theme) => ({
position: 'relative',
bottom: theme.spacing(20),
zIndex: 300,
margin: '0 auto',
[theme.breakpoints.between('xs', 'sm')]: {
left: '55%',
right: theme.spacing(4),
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 we missed a rebase commit here where you should have accepted remote 😄 d2b2e08, this would undo the commit that was previously done.

left: '80%',
bottom: theme.spacing(18),
},
},
Expand Down Expand Up @@ -219,7 +219,7 @@ export default function Banner() {
<Grid
container
spacing={0}
direction="row"
direction="column"
Copy link
Contributor

Choose a reason for hiding this comment

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

Same comment as above, this undoes recent commit d2b2e08.

alignItems="center"
justify="center"
className={classes.container}
Expand Down
220 changes: 200 additions & 20 deletions src/frontend/src/components/Posts/Posts.jsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,217 @@
import React from 'react';
import React, { useState, useEffect, useCallback, useRef } from 'react';
import PropTypes from 'prop-types';
import { Container } from '@material-ui/core';
import { Container, Button, Grid } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';

import parse from 'parse-link-header';
import useSiteMetaData from '../../hooks/use-site-metadata';
import Post from '../Post/Post.jsx';
import CustomizedSnackBar from '../SnackBar/SnackBar.jsx';
import Spinner from '../Spinner/Spinner.jsx';

const useStyles = makeStyles({
const useStyles = makeStyles((theme) => ({
root: {
padding: 0,
maxWidth: '785px',
},
});
content: {
'& > *': {
/**
* We, the implementors of this CSS realize how morally wrong it is
* to use !important in any case. That does not excuse the hour long
* Fight while finding other ways
*/
color: `${theme.palette.secondary.light} !important`,
borderColor: `${theme.palette.secondary.light} !important`,
padding: theme.spacing(2),
bottom: theme.spacing(4),
fontSize: '2rem',
transition: 'all linear 250ms',

[theme.breakpoints.between('xs', 'sm')]: {
bottom: theme.spacing(8),
},
},
},
activeCircle: {
borderRadius: '4rem',
transition: 'all linear 250ms',
color: theme.palette.primary.light,
},
}));

const Posts = ({ posts }) => {
const Posts = () => {
const classes = useStyles();
const savedCallback = useRef();
const [initNumPosts, setInitNumPosts] = useState(0);
const [currentNumPosts, setCurrentNumPosts] = useState(0);
const [shouldCheckForNewPosts, setShouldCheckForNewPosts] = useState(false);
const [alert, setAlert] = useState(false);
const [loading, setLoading] = useState(false);
const { telescopeUrl } = useSiteMetaData();
const [posts, setPosts] = useState([]);
const [numPages, setNumPages] = useState(1);
const [endOfPosts, setEndOfPosts] = useState(false);
const snackbarMessage = 'There is new content available!';

// Pagination
const [nextPageLink, setNextPageLink] = useState(`/posts?page=${numPages}`);

useEffect(() => {
async function getPosts() {
try {
setLoading(true);
const res = await fetch(`${telescopeUrl}${nextPageLink}`);

if (!res.ok) {
throw new Error(res.statusText);
}

const postUrls = await res.json();
const links = parse(res.headers.get('Link'));
const postsData = await Promise.all(
postUrls.map(({ url }) => fetch(`${telescopeUrl}${url}`).then((resp) => resp.json()))
);

setPosts([...posts, ...postsData]);
setNextPageLink(links.next.url);

// When we reach the end, disable the next-button UI
setEndOfPosts(links.next.url === links.last.url);
} catch (error) {
console.log('Something went wrong when fetching data', error);
} finally {
setLoading(false);
}
}

getPosts();
// Disabling the eslint check as nextPageLink and posts will cause the page to not render properly
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [telescopeUrl, numPages]);

function getNewPosts() {
setLoading(true);
setNumPages(numPages + 1);
}

const getPostsCount = useCallback(async () => {
if (!shouldCheckForNewPosts) {
return null;
}
try {
const res = await fetch(`${telescopeUrl}/posts`, { method: 'HEAD' });
if (!res.ok) {
throw new Error(res.statusText);
}
return res.headers.get('x-total-count');
} catch (error) {
console.log(error);
} finally {
setShouldCheckForNewPosts(false);
}
return null;
}, [telescopeUrl, shouldCheckForNewPosts]);

const callback = useCallback(async () => {
setCurrentNumPosts(await getPostsCount());
}, [getPostsCount]);

useEffect(() => {
savedCallback.current = callback;
});

useEffect(() => {
async function setPostsInfo() {
try {
setInitNumPosts(await getPostsCount());
} catch (error) {
console.log({ error });
}
}
setPostsInfo();
}, [getPostsCount, currentNumPosts]);

useEffect(() => {
function getCurrentNumPosts() {
setShouldCheckForNewPosts(true);
savedCallback.current();
}
savedCallback.current = callback;
// Polls every 5 minutes
const interval = setInterval(() => {
getCurrentNumPosts();
}, 5 * 60 * 1000);
return () => clearInterval(interval);
}, [callback]);

useEffect(() => {
function getCurrentNumPosts() {
setShouldCheckForNewPosts(true);
savedCallback.current();
}
savedCallback.current = callback;
// Polls every 5 minutes
const interval = setInterval(getCurrentNumPosts, 5 * 60 * 1000);
return () => clearInterval(interval);
}, [callback]);

useEffect(() => {
// Prevents alert from appearing upon page loading.
// Also checks whether there are new posts available
if (!loading && currentNumPosts !== initNumPosts && currentNumPosts !== 0) {
setAlert(true);
} else {
setAlert(false);
}
}, [currentNumPosts, initNumPosts, loading]);

function GenerateLoadButtonContent() {
if (endOfPosts) {
return 'No more posts. Your turn! Add your feed...';
}
return 'Load More Posts';
}

return posts.length > 0 ? (
<Container className={classes.root}>
{posts.map(({ id, feed, html, title, url, updated }) => (
<Post
key={id}
id={id}
author={feed.author}
url={url}
html={html}
title={title}
date={updated}
link={feed.link}
/>
))}
<Container>
<Container className={classes.root}>
{posts.map(({ id, feed, html, title, url, updated }) => (
<Post
key={id}
id={id}
author={feed.author}
url={url}
html={html}
title={title}
date={updated}
link={feed.link}
/>
))}
</Container>
<Container>
<Grid container spacing={0} direction="column" alignItems="center" justify="center">
<Grid item xs={12} className={classes.content}>
<Button
color="primary"
disabled={endOfPosts}
variant="outlined"
className={`${loading ? classes.activeCircle : ''}`}
onClick={() => getNewPosts()}
>
<GenerateLoadButtonContent />
</Button>
</Grid>
</Grid>

{alert ? <CustomizedSnackBar posts={currentNumPosts} message={snackbarMessage} /> : null}
</Container>
</Container>
) : (
<></>
<>
<Grid container spacing={0} direction="column" alignItems="center" justify="center">
<Spinner className={classes.activeCircle} />
</Grid>
</>
);
};

Expand Down
Loading