docbrown/app/assets/javascripts/initializers/initializeFetchFollowedArticles.js.erb
Ben Halpern 924d66f95d
Fix algolia index on tabbing (#75)
* Fix algolia index on tabbing
2018-03-13 12:52:07 -04:00

55 lines
No EOL
2.1 KiB
Text

function initializeFetchFollowedArticles() {
if ( document.getElementById("featured-story-marker") && checkUserLoggedIn() ) {
algoliaFollowedArticles();
}
}
function insertArticle(article,parent,insertPlace) {
if (article){
var newItem = document.createElement("DIV");
newItem.innerHTML = buildArticleHTML(article)
parent.insertBefore(newItem, insertPlace);
initializeReadingListIcons();
}
}
function algoliaFollowedArticles(){
var user = userData();
if (user && user.followed_tag_names && user.followed_tag_names.length > 0) {
var followedUsersArray = [];
if (user.followed_user_ids){
followedUsersArray = user.followed_user_ids.map(function(id){return 'user_'+id});
}
var client = algoliasearch('<%= ENV["ALGOLIASEARCH_APPLICATION_ID"] %>', '<%= ENV["ALGOLIASEARCH_SEARCH_ONLY_KEY"] %>');
var index = client.initIndex('ordered_articles_<%= Rails.env %>');
var searchObj = {
hitsPerPage: 20,
page: "0",
attributesToHighlight: [],
tagFilters: [user.followed_tag_names.concat(followedUsersArray)],
}
var homeEl = document.getElementById("index-container");
if (homeEl.dataset.feed === "base-feed") {
articlesIndex = client.initIndex('ordered_articles_<%= Rails.env %>');
} else if (homeEl.dataset.feed === "latest") {
articlesIndex = client.initIndex('ordered_articles_by_published_at_<%= Rails.env %>');
} else {
searchObj["filters"] = ('published_at_int > ' + homeEl.dataset.articlesSince);
articlesIndex = client.initIndex('ordered_articles_by_positive_reactions_count_<%= Rails.env %>');
}
articlesIndex.search("*", searchObj)
.then(function searchDone(content) {
var insertPlace = document.getElementById("article-index-hidden-div");
if (insertPlace) {
var parent = insertPlace.parentNode;
content.hits.forEach(function(article){
if ( !document.getElementById("article-link-"+article.id) ) {
insertArticle(article,parent,insertPlace);
}
});
}
});
}
}