docbrown/app/javascript/articles/Feed.jsx
Nick Taylor f6e99dec8b
Nickytonline/homepage main feed component (#6164) [deploy]
* wip

* Removed reference to cached_tag_list as the feed enpoint only returns tag_list now.

* Removed reference to cached_properties.

* Updated <CommentsCount /> and <TagList /> to support additinal className

* wip

* wip

* Undid init scrolling for Algolia articles

* Converted homePageFeed.jsx to an ERB template to access Sprockets.

* Now the homePageFeed.jsx files is an ERB so it can load Sprockets assets.

* wip

* Removed accidental commit of debugger statement in ERB.

* Now different feed time frames are loaded based on the homepage feed tab clicked.

* Prevent default Algolia paging when on the homepage.

* Added a tiny comment about feed time frame.

* Now feed loads properly for each time frame on home page.

* prop name refactor.

* Reneabled default Algolia scrolling.

* On the homepage, we no longer overwrite article HTML with Algolia data for initial articles.

* Assumption is the proper URL for main_image of featured article will be sent in the feed.

* Fixed Google Analytics for featured article.

* No longer need the new-feed ID for checking if we're on the homepage.

* Trying to make codeclimate happy.

* wip

* Removed reference to cached_tag_list as the feed enpoint only returns tag_list now.

* Removed reference to cached_properties.

* Updated <CommentsCount /> and <TagList /> to support additinal className

* wip

* wip

* Undid init scrolling for Algolia articles

* Converted homePageFeed.jsx to an ERB template to access Sprockets.

* Now the homePageFeed.jsx files is an ERB so it can load Sprockets assets.

* wip

* Removed accidental commit of debugger statement in ERB.

* Now different feed time frames are loaded based on the homepage feed tab clicked.

* Prevent default Algolia paging when on the homepage.

* Added a tiny comment about feed time frame.

* Now feed loads properly for each time frame on home page.

* prop name refactor.

* Reneabled default Algolia scrolling.

* On the homepage, we no longer overwrite article HTML with Algolia data for initial articles.

* Assumption is the proper URL for main_image of featured article will be sent in the feed.

* Fixed Google Analytics for featured article.

* No longer need the new-feed ID for checking if we're on the homepage.

* Added postcst episodes to <Feed /> state.

* Breaking up Article.jsx to make codeclimate happy.

* wip

* Created the <TodaysPodcastEpisodes /> and <PodcastEpisode /> components.

* Fixed issues with some components that were updated for the <FeaturedArticle />

* Added tests for <FeaturedArticle />

* Barreled up <FeaturedArticle />

* Added Storybook stories for <FeaturedArticle />

* Featured articles don't display org, so removed that test.

* Added proper today's podcasts components to feed.

* Converted some leftover ERB + removed pro checkmark as it doesn't exist yet.

* Now logic is same as master for feed timeframe.

* Updated <FeaturedArticle /> snapshots.

* On frontpage, bookmark button state is managed by Preact components now.

* bookmarkedFeedItems is now a prop on <Feed />.

* Fixed logic check for initializing reading list icons.

* Now <Article /> and <FeaturedArticle /> receive a bookmarkClick prop.

* Removed beginnings of scroll handler in <Feed /> as we're using what's there already for now.

* Removed logic to not show main image on other time frame feeds as it was not correct.

* Fixed issue with 0 rendering when no podcast episodes in feed.

* Converted <SaveButton /> to a stateful component.

* wip - <Feed /> render prop now passes bookmarked feed item ID set and a click event.

* Moved FEED_ICONS to an export so it's easier to use JSX/JS in <Feed />

* Moved <Feed /> into article components.

* Now reading list save buttons work properly in Preact components.

* Fixed issue with Save buttons in Algolia paging/<Feed />

* Updated snapshots.

* Took <Feed /> out of articles barrel file as jest was trying to import FEED_ICONs which is an ERB template.

* Now the Preact feed is dynamically imported.

* Now the Preact <Feed /> only loads for a logged on user.

* Fixed <FeaturedArticle /> so that the save button behaves properly now.

* Updated article stories for Storybook.

* Putting this back to the order it was because I've removed my code changes for this block.

* Fixed when renderFeed is imported for a logged on user.

* Add podcasts to feed and render home from server

* Add padding to feature laoding div

* Update tests

* Add more loading articles

* Fix conflicts

* Add readinglist javascript to initscrolling

* Ensure first article is one with image

* Organize feed items outside of feed instead of in it

Co-authored-by: Ben Halpern <bendhalpern@gmail.com>
Co-authored-by: Josh Puetz <josh@grorichpuetz.com>
2020-02-28 14:14:47 -05:00

162 lines
4.5 KiB
JavaScript

import { h, Component } from 'preact';
import PropTypes from 'prop-types';
import { FEED_ICONS } from '../packs/feedIcons.js.erb';
/* global userData sendHapticMessage showModal buttonFormData renderNewSidebarCount */
export class Feed extends Component {
componentDidMount() {
const { timeFrame } = this.props;
const { reading_list_ids = [] } = userData(); // eslint-disable-line camelcase
this.setState({ bookmarkedFeedItems: new Set(reading_list_ids) });
Feed.getFeedItems(timeFrame).then(feedItems => {
// Ensure first article is one with a main_image
const featuredStory = feedItems.find(story => story.main_image !== null);
// Remove that first one from the array.
const index = feedItems.indexOf(featuredStory);
feedItems.splice(index, 1);
const subStories = feedItems;
const organizedFeedItems = [featuredStory, subStories].flat();
console.log(organizedFeedItems);
this.setState({feedItems: organizedFeedItems, podcastEpisodes: Feed.getPodcastEpisodes() });
});
}
componentDidUpdate(prevProps) {
const { timeFrame } = this.props;
if (prevProps.timeFrame !== timeFrame) {
// The feed timeframe has changed. Get new feed data.
Feed.getFeedItems(timeFrame).then(feedItems => {
this.setState(_prevState => ({ feedItems }));
});
}
}
/**
* Retrieves feed data.
*
* @param {number} [page=1] Page of feed data to retrieve
*
* @returns {Promise} A promise containing the JSON response for the feed data.
*/
static getFeedItems(timeFrame = '', page = 1) {
return fetch(`/stories/feed/${timeFrame}?page=${page}`, {
method: 'GET',
headers: {
Accept: 'application/json',
'X-CSRF-Token': window.csrfToken,
'Content-Type': 'application/json',
},
credentials: 'same-origin',
}).then(response => response.json());
}
static getPodcastEpisodes() {
const el = document.getElementById('followed-podcasts');
const user = userData(); // Global
const episodes = []
if (user && user.followed_podcast_ids && user.followed_podcast_ids.length > 0) {
let data = JSON.parse(el.dataset.episodes);
data.forEach(function(ep) {
if (user.followed_podcast_ids.indexOf(ep.podcast.id) > -1) {
episodes.push(ep)
}
});
}
return episodes;
}
/**
* Dispatches a click event to bookmark/unbook,ard an article.
*
* @param {Event} event
*/
bookmarkClick = event => {
// The assumption is that the user is logged on at this point.
const { userStatus } = document.body;
event.preventDefault();
sendHapticMessage('medium');
if (userStatus === 'logged-out') {
showModal('add-to-readinglist-from-index');
return;
}
const { currentTarget: button } = event;
const data = buttonFormData(button);
getCsrfToken()
.then(sendFetch('reaction-creation', data))
// eslint-disable-next-line consistent-return
.then(response => {
if (response.status === 200) {
return response.json().then(json => {
const articleId = Number(button.dataset.reactableId);
this.setState(previousState => {
const { bookmarkedFeedItems } = previousState;
const { result } = json;
const updatedBookmarkedFeedItems = new Set([
...bookmarkedFeedItems.values(),
]);
if (result === 'create') {
updatedBookmarkedFeedItems.add(articleId);
}
if (result === 'destroy') {
updatedBookmarkedFeedItems.delete(articleId);
}
renderNewSidebarCount(button, json);
return {
...previousState,
bookmarkedFeedItems: updatedBookmarkedFeedItems,
};
});
});
}
});
};
render() {
const { renderFeed } = this.props;
const {
feedItems = [],
podcastEpisodes = [],
bookmarkedFeedItems = new Set(),
} = this.state;
return (
<div
ref={element => {
this.feedContainer = element;
}}
>
{renderFeed({
feedItems,
feedIcons: FEED_ICONS,
podcastEpisodes,
bookmarkedFeedItems,
bookmarkClick: this.bookmarkClick,
})}
</div>
);
}
}
Feed.defaultProps = {
timeFrame: '',
};
Feed.propTypes = {
timeFrame: PropTypes.string,
renderFeed: PropTypes.func.isRequired,
};
Feed.displayName = 'Feed';