';
var base = window.location.origin + '/wp-json/wp/v2/';
var url = base + 'posts?per_page=' + state.perPage + '&page=' + state.page + '&_embed=wp:featuredmedia,wp:term';
if (state.categoryId) url += '&categories=' + state.categoryId;
if (state.tagId) url += '&tags=' + state.tagId;
if (state.search) url += '&search=' + encodeURIComponent(state.search);
fetch(url)
.then(function(r){
if (!r.ok) throw new Error('posts');
state.totalPages = parseInt(r.headers.get('X-WP-TotalPages'), 10) || 1;
return r.json();
})
.then(function(posts){
if (!posts || !posts.length) throw new Error('no posts');
list.innerHTML = '';
posts.forEach(function(post){ list.appendChild(buildRow(post)); });
state.loaded = true;
renderPager(section, state);
})
.catch(function(){ showFallback(section, state.fallbackUrl); });
}
function initSection(section){
var state = {
page: 1,
perPage: parseInt(section.getAttribute('data-per-page'), 10) || 10,
categoryId: null,
tagId: null,
search: '',
totalPages: 1,
loaded: false,
fallbackUrl: (section.getAttribute('data-fallback-url') || '').trim() || (window.location.origin + '/category/reports/')
};
var categorySlug = (section.getAttribute('data-category') || '').trim();
var base = window.location.origin + '/wp-json/wp/v2/';
section.querySelectorAll('.c5li-toolbar__btn').forEach(function(btn){
btn.addEventListener('click', function(){
var per = parseInt(btn.getAttribute('data-per'), 10);
if (per === state.perPage) return;
state.perPage = per;
state.page = 1;
section.querySelectorAll('.c5li-toolbar__btn').forEach(function(b){ b.classList.remove('is-active'); });
btn.classList.add('is-active');
fetchAndRender(section, state);
});
});
// Listen to the news search engine (separate widget): when it shoots
// "c5-filter-reports" with {search, category, tag}, request again
// page 1 to WordPress with those filters.
document.addEventListener('c5-filter-reports', function(ev){
var detail = ev.detail || {};
state.page = 1;
state.search = (detail.search || '').trim();
var catStep = ('category' in detail)
? resolveCategoryId(base, (detail.category || '').trim()).catch(function(){ return null; })
: Promise.resolve(state.categoryId);
var tagStep = ('tag' in detail)
? resolveTagId(base, (detail.tag || '').trim()).catch(function(){ return null; })
: Promise.resolve(state.tagId);
Promise.all([catStep, tagStep]).then(function(ids){
state.categoryId = ids[0];
state.tagId = ids[1];
fetchAndRender(section, state);
});
});
resolveCategoryId(base, categorySlug)
.then(function(id){ state.categoryId = id; fetchAndRender(section, state); })
.catch(function(){ showFallback(section, state.fallbackUrl); });
}
function init(){
document.querySelectorAll('[data-c5li-wrap]').forEach(initSection);
}
if (document.readyState === 'loading'){
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();