docbrown/app/assets/javascripts/initializers/initializeReadingListIcons.js
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

181 lines
5.2 KiB
JavaScript

/* eslint-disable no-use-before-define */
/* eslint-disable no-undef */
/* eslint-disable func-names */
/* eslint-disable consistent-return */
/* eslint-disable no-unused-vars */
function initializeReadingListIcons() {
setReadingListButtonsState();
addReadingListCountToHomePage();
addHoverEffectToReadingListButtons();
}
// set SAVE or SAVED articles buttons
function setReadingListButtonsState() {
var readingListButtons = document.querySelectorAll(
'.bookmark-button:not([data-initial-feed])',
);
Array.from(readingListButtons).forEach(highlightButton);
}
// private
function highlightButton(button) {
var user = userData();
var buttonIdInt = parseInt(button.dataset.reactableId, 10);
if (user && user.reading_list_ids.indexOf(buttonIdInt) > -1) {
button.classList.add('selected');
} else {
button.classList.remove('selected');
}
button.addEventListener('click', reactToReadingListButtonClick);
}
function addReadingListCountToHomePage() {
var user = userData();
var readingListCount;
if (user && document.getElementById('reading-list-count')) {
readingListCount =
user.reading_list_ids.length > 0 ? user.reading_list_ids.length : 'empty';
document.getElementById('reading-list-count').innerHTML =
'(' + readingListCount + ')';
document.getElementById('reading-list-count').dataset.count =
user.reading_list_ids.length;
}
}
function reactToReadingListButtonClick(event) {
var button;
var userStatus;
event.preventDefault();
sendHapticMessage('medium');
userStatus = document
.getElementsByTagName('body')[0]
.getAttribute('data-user-status');
if (userStatus === 'logged-out') {
showModal('add-to-readinglist-from-index');
return;
}
button = properButtonFromEvent(event);
renderOptimisticResult(button);
getCsrfToken()
.then(sendFetch('reaction-creation', buttonFormData(button)))
.then(function(response) {
if (response.status === 200) {
return response.json().then(function(json) {
renderButtonState(button, json);
renderNewSidebarCount(button, json);
});
} // else {
// there's currently no errorCb.
// }
})
.catch(function(error) {
// there's currently no error handling.
});
}
function renderButtonState(button, json) {
if (json.result === 'create') {
button.classList.add('selected');
addHoverEffectToReadingListButtons(button);
} else {
button.classList.remove('selected');
}
}
function renderNewSidebarCount(button, json) {
var newCount;
var count = document.getElementById('reading-list-count').dataset.count;
count = parseInt(count, 10);
if (json.result === 'create') {
newCount = count + 1;
} else if (count !== 0) {
newCount = count - 1;
}
document.getElementById('reading-list-count').dataset.count = newCount;
document.getElementById('reading-list-count').innerHTML =
'(' + newCount + ')';
}
function buttonFormData(button) {
var formData = new FormData();
formData.append('reactable_type', 'Article');
formData.append('reactable_id', button.dataset.reactableId);
formData.append('category', 'readinglist');
return formData;
}
function renderOptimisticResult(button) {
renderButtonState(button, { result: 'create' }); // optimistic create only for now
}
function properButtonFromEvent(event) {
var properElement;
if (event.target.tagName === 'BUTTON') {
properElement = event.target;
} else {
properElement = event.target.parentElement;
}
return properElement;
}
/*
Add the hover effect to reading list buttons.
This function makes use of mouseover/mouseevent bubbling behaviors to attach
only two event handlers to the articles container for performance reasons.
*/
function addHoverEffectToReadingListButtons() {
var articlesList = document.getElementsByClassName('articles-list');
Array.from(articlesList).forEach(function(container) {
// we use `bind` so that the event handler will have the correct text in its
// `this` local variable
container.addEventListener(
'mouseover',
readingListButtonMouseHandler.bind('UNSAVE'),
);
container.addEventListener(
'mouseout',
readingListButtonMouseHandler.bind('SAVED'),
);
});
}
/*
Determines if the element is the target of the reading list button hover.
*/
function isReadingListButtonHoverTarget(element) {
var classList = element.classList;
return (
(element.tagName === 'BUTTON' &&
classList.contains('bookmark-button') &&
classList.contains('selected')) ||
(element.tagName === 'SPAN' && classList.contains('bm-success'))
);
}
function readingListButtonMouseHandler(event) {
var target = event.target;
if (isReadingListButtonHoverTarget(target)) {
event.preventDefault();
var textReplacement = this; // `this` is the text to be replaced
var textSpan;
if (target.tagName === 'BUTTON') {
textSpan = target.getElementsByClassName('bm-success')[0];
} else {
textSpan = target;
}
textSpan.innerHTML = textReplacement;
}
}
/* eslint-enable no-use-before-define */
/* eslint-enable no-undef */
/* eslint-enable func-names */
/* eslint-enable consistent-return */
/* eslint-enable no-unused-vars */