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

291 lines
11 KiB
Text

'use strict';
/* global algoliasearch, insertAfter, insertArticles, buildArticleHTML, nextPage:writable, fetching:writable, done:writable */
var client;
function fetchNext(el, endpoint, insertCallback) {
var indexParams = JSON.parse(el.dataset.params);
var urlParams = Object.keys(indexParams).map(function handleMap(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(indexParams[k])
}).join('&');
if (urlParams.indexOf("q=") > -1 ) {
return;
}
var fetchUrl = (endpoint+"?page="+nextPage+"&"+urlParams+"&signature="+parseInt(Date.now()/400000, 10)).replace("&&","&");
window.fetch(fetchUrl)
.then(function handleResponse(response) {
response.json().then(function insertEntries(entries) {
nextPage += 1;
insertCallback(entries);
if (entries.length === 0) {
document.getElementById("loading-articles").style.display = "none";
done = true;
}
});
}).catch(function logError(err) {
// eslint-disable-next-line no-console
console.log(err);
});
}
function insertNext(params, buildCallback) {
return function insertEntries(entries) {
var list = document.getElementById(params.listId || "sublist");
var newFollowersHTML = "";
entries.forEach(function insertAnEntry(entry) {
let existingEl = document.getElementById((params.elId || "element") + "-" + entry.id);
if(!existingEl) {
var newHTML = buildCallback(entry)
newFollowersHTML += newHTML
}
});
var distanceFromBottom = document.documentElement.scrollHeight - document.body.scrollTop;
var newNode = document.createElement("div");
newNode.innerHTML = newFollowersHTML;
var singleArticles = document.getElementsByClassName("single-article");
var lastElement = singleArticles[singleArticles.length - 1];
insertAfter(newNode, lastElement);
if (nextPage > 0) {
fetching = false;
}
}
}
function buildFollowsHTML(follows) {
return '<div id="follows-' + follows.id + '" class="single-article">\n' +
' <a href="' + follows.path +'" class="block-link">\n' +
' <h2>\n' +
' <img alt="' + follows.username + ' profile image" src="' + follows.profile_image + '" />\n' +
' ' + follows.name + '\n' +
' <span class="dashboard-username">@' + follows.username + '</span>\n' +
' </h2>\n' +
' </a>\n' +
'</div>';
}
var negativeFollow = -1;
function buildTagsHTML(tag) {
var tagHTML = '';
if (tag.points < 0 && negativeFollow === -1) {
tagHTML += '<h2>Negative Tags (anti-follows)</h2>';
negativeFollow = 0;
}
return tagHTML +
'<div id="follows-' + tag.id + '" class="single-article" style="border: 1px solid ' + tag.color + ';box-shadow: 3px 3px 0px ' + tag.color + '">\n' +
' <h2>\n' +
' <a href="/t/' + tag.name + '">\n' +
' ' + tag.name + '\n' +
' </a>\n' +
' <form class="edit_follow" id="edit_follow_' + tag.id + '" action="/follows/' + tag.id + '" accept-charset="UTF-8" method="post">\n' +
' <input name="utf8" type="hidden" value="✓">\n' +
' <input type="hidden" name="_method" value="patch">\n' +
' <input type="hidden" name="authenticity_token" value="' + tag.token + '">\n' +
' <label for="follow_points">Follow Weight:</label>\n' +
' <input step="any" required="required" type="number" value="' + tag.points + '" name="follow[points]" id="follow_points">\n' +
' <input type="submit" name="commit" value="Submit">\n' +
' </form>\n' +
' </h2>\n' +
'</div>';
}
function fetchNextFollowingPage(el) {
var indexParams = JSON.parse(el.dataset.params);
var action = indexParams.action;
if (action.includes("users")) {
fetchNext(el, "/api/followings/users", insertNext({ elId: "follows" }, buildFollowsHTML));
} else if (action.includes("podcasts")) {
fetchNext(el, "/api/followings/podcasts", insertNext({ elId: "follows" }, buildFollowsHTML));
} else if (action.includes("organizations")) {
fetchNext(el, "/api/followings/organizations", insertNext({ elId: "follows" }, buildFollowsHTML));
} else {
fetchNext(el, "/api/followings/tags", insertNext({ elId: "follows" }, buildTagsHTML));
}
}
function fetchNextFollowersPage(el) {
fetchNext(el, "/api/followers/users", insertNext({ elId: "follows" }, buildFollowsHTML));
}
function buildVideoArticleHTML(videoArticle) {
return '<a class="single-video-article single-article" href="' + videoArticle.path + '" id="video-article-' + videoArticle.id + '">\n' +
' <div class="video-image" style="background-image: url(' + videoArticle.cloudinary_video_url + ')">\n' +
' <span class="video-timestamp">' + videoArticle.video_duration_in_minutes + '</span>\n' +
' </div>\n' +
' <p><strong>' + videoArticle.title + '</strong></p>\n' +
' <p>' + videoArticle.user.name + '</p>\n' +
'</a>';
}
function insertVideos(videoArticles) {
var list = document.getElementById("subvideos");
var newVideosHTML = "";
videoArticles.forEach(function insertAVideo(videoArticle) {
var existingEl = document.getElementById("video-article-"+videoArticle.id);
if(!existingEl) {
var newHTML = buildVideoArticleHTML(videoArticle)
newVideosHTML += newHTML
}
});
var distanceFromBottom = document.documentElement.scrollHeight - document.body.scrollTop;
var newNode = document.createElement("div");
newNode.innerHTML = newVideosHTML;
newNode.className += "video-collection"
var singleArticles = document.getElementsByClassName("single-article");
var lastElement = singleArticles[singleArticles.length - 1];
insertAfter(newNode, lastElement);
if (nextPage > 0) {
fetching = false;
}
}
function fetchNextVideoPage(el) {
fetchNext(el, "/api/videos", insertVideos)
}
function insertArticles(articles) {
var list = document.getElementById("substories");
var newArticlesHTML = "";
var el = document.getElementById("home-articles-object")
if (el) {el.outerHTML = "";}
articles.forEach(function insertAnArticle(article) {
var existingEl = document.getElementById("article-link-"+article.id);
if ( !['/', '/top/week', '/top/month', '/top/year', '/top/infinity', '/latest'].includes(window.location.pathname) &&
existingEl &&
existingEl.parentElement &&
existingEl.parentElement.classList.contains('single-article-small-pic') &&
!document.getElementById("video-player-"+article.id)) {
existingEl.parentElement.outerHTML = buildArticleHTML(article);
} else if(!existingEl) {
var newHTML = buildArticleHTML(article)
newArticlesHTML += newHTML
initializeReadingListIcons();
}
});
var distanceFromBottom = document.documentElement.scrollHeight - document.body.scrollTop;
var newNode = document.createElement("div");
newNode.innerHTML = newArticlesHTML;
var singleArticles = document.getElementsByClassName("single-article");
var lastElement = singleArticles[singleArticles.length - 1];
insertAfter(newNode, lastElement);
if (nextPage > 0) {
fetching = false;
}
}
function fetchNextPodcastPage(el) {
fetchNext(el, "/api/podcast_episodes", insertArticles)
}
function algoliaPaginate(tag, requiresApproval) {
var tagFilters = [];
if (tag && tag.length > 0) {
tagFilters.push(tag);
}
var searchObj = {
hitsPerPage: 15,
page: nextPage,
attributesToHighlight: [],
tagFilters,
filters: (requiresApproval === 'true') ? 'approved:true' : ''
}
var homeEl = document.getElementById("index-container");
var paginationArticlesIndex;
if (homeEl.dataset.feed === "base-feed") {
paginationArticlesIndex = client.initIndex('ordered_articles_<%= Rails.env %>');
} else if (homeEl.dataset.feed === "latest") {
paginationArticlesIndex = client.initIndex('ordered_articles_by_published_at_<%= Rails.env %>');
} else {
var preamble = (requiresApproval === 'true') ? ' AND ' : ''
searchObj.filters += ( preamble +'published_at_int > ' + homeEl.dataset.articlesSince);
paginationArticlesIndex = client.initIndex('ordered_articles_by_positive_reactions_count_<%= Rails.env %>');
}
paginationArticlesIndex.search("*", searchObj)
.then(function searchDone(content) {
nextPage += 1;
insertArticles(content.hits);
const checkBlockedContentEvent = new CustomEvent('checkBlockedContent')
window.dispatchEvent(checkBlockedContentEvent);
initializeReadingListIcons();
if (content.hits.length === 0) {
document.getElementById("loading-articles").style.display = "none"
done = true;
}
});
}
function fetchNextPageIfNearBottom() {
var indexContainer = document.getElementById("index-container");
var elCheck = indexContainer && !document.getElementById("query-wrapper");
if (!elCheck) {
return;
}
var indexWhich = indexContainer.dataset.which;
var fetchCallback;
var scrollableElemId;
if (indexWhich === "podcast-episodes") {
scrollableElemId = "articles-list";
fetchCallback = function fetch() {
fetchNextPodcastPage(indexContainer);
};
} else if (indexWhich === "videos") {
scrollableElemId = "video-collection";
fetchCallback = function fetch() {
fetchNextVideoPage(indexContainer);
};
} else if (indexWhich === "followers") {
scrollableElemId = "user-dashboard";
fetchCallback = function fetch() {
fetchNextFollowersPage(indexContainer);
}
} else if (indexWhich === "following") {
scrollableElemId = "user-dashboard";
fetchCallback = function fetch() {
fetchNextFollowingPage(indexContainer);
}
} else {
scrollableElemId = "articles-list";
fetchCallback = function fetch() {
algoliaPaginate(indexContainer.dataset.algoliaTag, indexContainer.dataset.requiresApproval);
};
}
var scrollableElem = document.getElementById(scrollableElemId);
if ( !done && !fetching && (window.scrollY) > (scrollableElem.scrollHeight - 3700) ) {
fetching = true;
fetchCallback();
}
}
function checkIfNearBottomOfPage() {
var publicSearchKey = '<%= ALGOLIASEARCH_PUBLIC_SEARCH_ONLY_KEY %>';
client = algoliasearch('<%= ApplicationConfig["ALGOLIASEARCH_APPLICATION_ID"] %>', publicSearchKey);
if (document.getElementsByClassName("single-article").length < 2 || window.location.search.indexOf("q=") > -1 ) {
document.getElementById("loading-articles").style.display = "none";
done = true;
} else {
document.getElementById("loading-articles").style.display = "block";
}
fetchNextPageIfNearBottom();
setInterval(function handleInterval() {
fetchNextPageIfNearBottom();
}, 210)
}
function initScrolling() {
var elCheck = document.getElementById("index-container");
if (elCheck) {
initScrolling.called = true;
checkIfNearBottomOfPage();
}
}