globalThis.spotler_search_templates = globalThis.spotler_search_templates || {};
globalThis.spotler_search_templates['3cc6eefd-c500-47f1-a8d1-d13cdb622ab5'] = (function (props) {
const currencyFormatter = new Intl.NumberFormat('nl-NL', {
// style: 'currency',
// currency: props.spotler.getConfig('currency') || 'EUR',
minimumFractionDigits: 2, maximumFractionDigits: 2
});
function formatCurrency(price) {
return currencyFormatter.format(price);
}
function matchQueryInBold(str) {
if (str === undefined) {
return '';
}
const escapedSearchTerm = props.spotler.getSearchTerm().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$&");
return str.replace(new RegExp(escapedSearchTerm, 'gi'), '$& ');
}
function triggerChangeView(event, view) {
event.preventDefault();
props.spotler.triggerViewChange(view);
}
function revertToPreviousSuccessfulState() {
props.spotler.revertToPreviousSuccessfulState();
}
async function SuggestView(props) {
const { items, content } = await props.spotler.fetchResults();
return `
Zoeksuggesties
Makita accu
Makita accuboormachine
Makita bithouder
Productsuggesties
${items.data?.map(item => `
${matchQueryInBold(item.properties.title)}
★★★★☆ 53 reviews
€299
${formatCurrency(item.properties.price)}
`).join("")}
Meer informatie
${content.data?.map(content => `
${matchQueryInBold(content.properties.title)}
`).join('')}
`;
}
async function ItemsView(props) {
const { items } = await props.spotler.fetchResults();
await attachStock(items);
props.state.datasets['items'].filterStates = items.facets.reduce((obj, f) => {
obj[f.id] = { collapsed: f.is_default_collapsed, ...obj[f.id] };
return obj;
}, props.state.datasets['items'].filterStates ?? {});
if (items.meta.total > (items.meta.offset + items.meta.limit)) {
props.spotler.registerInfiniteScroll('items', '[data-sqr-infinite-scroll-item]:last-child', async ({ items }) => {
await attachStock(items);
return Items(items.data);
});
}
return `
${ActiveFilters(props.state.datasets['items'], items?.facets)}
${Filters(items?.facets)}
Filter
${items?.sort_fields?.map(sortField => `
${sortField.label}
`).join('')}
${items?.meta?.total} ${items?.meta?.total === 1 ? 'résultat' : 'résultats'}
Afficher en
Grille
Liste
Fast
Fermer
${items.meta.total === 0 ? `
Nous n'avons trouvé aucun résultat
${props.spotler.hasPreviousSuccessfulState() ? `
Afficher les résultats précédents
` : ``}
` : `
${SpellcheckMessage(items?.spellcheck, items?.meta?.total)}
${Banners(items?.banners)}
${props.state.variables['list_view'] === 'fast' ? `
Photo
Nom / Référence
Prix de référence HT
Disponibilité
Document
Action
${Items(items?.data)}
` : `
${Items(items?.data)}
`}
`}
`;
}
async function attachStock(items) {
const itemIds = items.data?.map(item => item.properties.id);
if (!Array.isArray(itemIds) || itemIds.length === 0) {
return;
}
try {
const response = await fetch(`https://www.eshop-alliance.com/rest/eshopalliance_fr/V1/getStockAvailability?productIds=${itemIds.join(',')}`, {
// const response = await fetch(`https://nexitup.eshop-alliance.com/rest/nexitup_fr/V1/getStockAvailability?productIds=${itemIds.join(',')}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
const results = await response.json();
if (results.length === 0) {
return;
}
const stockMap = results[0];
for (const item of items.data) {
item.properties.stock = stockMap[item.properties.id] ?? false;
}
} catch (error) {
console.log('Failed to retrieve stock');
}
}
function gridToggle() {
if (props.state.variables['list_view'] === 'list') {
document.querySelector('.sooqrSearchContainer .products').classList.add('grid','columns4','products-grid','no-padding','divider-line');
document.querySelector('.sooqrSearchContainer .products').classList.remove('list','products-list');
document.querySelector('button.modes-mode.mode-grid').classList.add('active');
document.querySelector('button.modes-mode.mode-list').classList.remove('active');
}
if (props.state.variables['list_view'] === 'fast') {
document.querySelector('.sooqrSearchContainer .products').classList.add('grid','columns4','products-grid','no-padding','divider-line');
document.querySelector('.sooqrSearchContainer .products').classList.remove('fast','products-fast');
document.querySelector('button.modes-mode.mode-fast').classList.remove('active');
document.querySelector('button.modes-mode.mode-grid').classList.add('active');
};
props.spotler.setVariable('list_view', 'grid');
props.spotler.handleChanges()
}
function listToggle() {
if (props.state.variables['list_view'] === 'grid') {
document.querySelector('.sooqrSearchContainer .products').classList.add('list','products-list');
document.querySelector('.sooqrSearchContainer .products').classList.remove('grid','columns4','products-grid','no-padding','divider-line');
document.querySelector('button.modes-mode.mode-grid').classList.remove('active');
document.querySelector('button.modes-mode.mode-list').classList.add('active');
};
if (props.state.variables['list_view'] === 'fast') {
document.querySelector('.sooqrSearchContainer .products').classList.add('list','products-list');
document.querySelector('.sooqrSearchContainer .products').classList.remove('fast','products-fast');
document.querySelector('button.modes-mode.mode-fast').classList.remove('active');
document.querySelector('button.modes-mode.mode-list').classList.add('active');
};
props.spotler.setVariable('list_view', 'list');
props.spotler.handleChanges()
}
function fastToggle() {
if (props.state.variables['list_view'] === 'grid') {
document.querySelector('.sooqrSearchContainer .products').classList.add('fast','products-fast');
document.querySelector('.sooqrSearchContainer .products').classList.remove('grid','columns4','products-grid','no-padding','divider-line');
document.querySelector('button.modes-mode.mode-grid').classList.remove('active');
document.querySelector('button.modes-mode.mode-fast').classList.add('active');
};
if (props.state.variables['list_view'] === 'list') {
document.querySelector('.sooqrSearchContainer .products').classList.add('fast','products-fast');
document.querySelector('.sooqrSearchContainer .products').classList.remove('list','products-list');
document.querySelector('button.modes-mode.mode-list').classList.remove('active');
document.querySelector('button.modes-mode.mode-fast').classList.add('active');
};
props.spotler.setVariable('list_view', 'fast');
props.spotler.handleChanges()
}
function ActiveFilters(dataset, facets) {
if (!Array.isArray(dataset.filters) || dataset.filters.length === 0) {
return '';
}
const filters = [];
for (const filter of dataset.filters) {
const facet = facets.find(f => f.name === filter.field);
if (!facet) {
continue;
}
switch (facet.type) {
case 'dualslider':
filters.push({ name: facet.name, label: facet.label, value: `${renderFilterLabel(filter.start, facet.prefix, facet.suffix)} - ${renderFilterLabel(filter.end, facet.prefix, facet.suffix)}` });
break;
case 'multiselect':
filters.push({ name: facet.name, label: facet.label, value: facet.values.filter(v => filter.values.includes(v.value)).map(v => renderFilterLabel(v.label, facet.prefix, facet.suffix)).join(', ') });
break;
default:
filters.push({ name: facet.name, label: facet.label, value: renderFilterLabel(filter.value, facet.prefix, facet.suffix) });
}
}
if (filters.length === 0) {
return '';
}
function clearFilters(event, dataset) {
event.preventDefault();
props.spotler.clearAllFilters(dataset);
}
return `
Filtres sélectionnés
${filters.map(ActiveFilter).join('')}
Tout supprimer
`;
}
function ActiveFilter(filter) {
function removeFilter(event, dataset, filterId) {
props.spotler.triggerFilterChange(dataset, filterId);
}
return `
${filter.label}: ${filter.value}
Remove badge
`;
}
function Filters(filters) {
return filters?.map(facet => {
switch (facet.type) {
case 'select':
return renderSelectFilter({ ...facet, dataset: 'items' });
case 'multiselect':
return renderMultiSelectFilter({ ...facet, dataset: 'items' });
case 'radio':
return renderRadioFilter({ ...facet, dataset: 'items' });
case 'slider':
return renderSliderFilter({ ...facet, dataset: 'items' });
case 'dualslider':
return renderDualSliderFilter({ ...facet, dataset: 'items' });
}
}).join('');
}
function SpellcheckMessage(spellcheck, total) {
if (!spellcheck) {
return '';
}
return `
Votre recherche de /${spellcheck.old}/ n'a donné aucun résultat. Nous avons recherché /${spellcheck.new}/ avec ${total} ${total === 1 ? 'résultat' : 'résultats'}.
`;
}
function Banners(banners) {
if (!Array.isArray(banners) || banners.length === 0) {
return '';
}
const banner = banners.pop();
const bannerTypes = Object.keys(banner);
let bannerHtml = '';
for (let i = 0, l = bannerTypes.length; i < l; i++) {
const bannerType = bannerTypes[i];
switch (bannerType) {
case 'mobile':
bannerHtml += Banner(banner, bannerType, 'sqr-block tablet:sqr-hidden');
break;
case 'tablet':
bannerHtml += Banner(banner, bannerType, 'sqr-hidden tablet:sqr-block desktop:sqr-hidden');
break;
case 'desktop':
bannerHtml += Banner(banner, bannerType, 'sqr-hidden desktop:sqr-block');
break;
}
}
return bannerHtml;
}
function Banner(banner, type, mediaClasses) {
if (!(type in banner)) {
return '';
}
if (banner[type].url) {
return `
`;
}
return ` `;
}
function Items(items) {
return items?.map(Item).join('');
}
var loggedIn = document.querySelectorAll('body.loggedin');
function getCookie(name) {
let cookieArr = document.cookie.split(";");
for(let i = 0; i < cookieArr.length; i++) {
let cookiePair = cookieArr[i].split("=");
// Removing whitespace at the beginning of the cookie name and compare it with the given name
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
var formKey = getCookie('form_key');
var addToCartEnabled = false;
function Item(item) {
if (props.state.variables['list_view'] === 'grid' || props.state.variables['list_view'] === 'list' || !props.state.variables['list_view']){
return `
${item.properties.title}
${props.state.variables['list_view'] === 'list' ? `
${
item.properties['sqr:description']
? (function(encodedString) {
let tempElement = document.createElement('div');
tempElement.innerHTML = encodedString;
return tempElement.textContent || tempElement.innerText;
})(item.properties['sqr:description'])
: ''
}
`:``}
${loggedIn.length !== 0 ? `
Prix net
${formatCurrency(item.properties.double_normal_price)}€ HT
`:``}
Prix de référence HT
${formatCurrency(item.properties.price)}€ HT
Référence : ${item.properties['sqr:sku']}
${props.state.variables['list_view'] === 'list' ? `
${item.properties['sqr:ac_ns_reference_fabriquant'] ? `
Réf. fournisseur : ${item.properties['sqr:ac_ns_reference_fabriquant']}
`:``}
${item.properties['sqr:ac_ns_ean_code'] ? `
Code EAN : ${item.properties['sqr:ac_ns_ean_code']}
`:``}
`:``}
${item.properties.stock ? 'En stock' : 'Sur commande'}
`;
}
else {
return `
${item.properties.title} Référence : ${item.properties['sqr:sku']}
${item.properties['sqr:ac_ns_ean_code'] || item.properties['sqr:ac_ns_reference_fabriquant'] ? `
Réf. fournisseur : ${item.properties['sqr:ac_ns_reference_fabriquant']}
`:``}
${item.properties['sqr:ac_ns_ean_code'] ? `
Code EAN : ${item.properties['sqr:ac_ns_ean_code']}
`:''}
${formatCurrency(item.properties.double_normal_price)} € HT
Prix net
${formatCurrency(item.properties.price)} € HT
${item.properties.stock ? 'En stock' : 'Sur commande'}
${item.properties['sqr:ac_ns_lien_fiche_technique'] || item.properties['sqr:ac_ns_nom_fiche_technique'] ? `
${item.properties['sqr:ac_ns_nom_fiche_technique'] ? item.properties['sqr:ac_ns_nom_fiche_technique'] : item.properties['sqr:ac_ns_lien_fiche_technique']}
`:``}
${addToCartEnabled && loggedIn.length !== 0 && item.properties.stock ? `
`:`
Lire la suite
`}
`
}
}
function renderFilter(facet, children) {
const filterState = props.state.datasets[facet.dataset].filterStates?.[facet.id];
const collapsed = filterState?.collapsed ?? facet.is_default_collapsed;
function collapse(e, dataset, filterId) {
e.preventDefault();
const element = e.currentTarget;
const filterState = props.state.datasets[dataset].filterStates?.[filterId];
const active = element.classList.contains('sqr-active');
element.classList.toggle('sqr-active', !active);
element.nextElementSibling.classList.toggle('sqr-hidden', active);
filterState.collapsed = active;
}
return `
${facet.label}
${children}
`;
}
function renderSelectFilter(facet) {
return renderFilter(facet, `
Choose
${facet.values.map((filterValue) => `
${renderFilterLabel(filterValue.label, facet.prefix, facet.suffix)} (${filterValue.count})
`).join("")}
`);
}
function showMore(e, dataset, filterId) {
e.preventDefault();
const element = e.currentTarget;
const parentElement = element.closest('[data-sqr-filter]');
const filterState = props.state.datasets[dataset].filterStates?.[filterId];
filterState.showing_more = !filterState.showing_more;
element.textContent = filterState.showing_more ? 'Show fewer' : 'Show more';
parentElement.dataset.sqrFilterShowingMore = filterState.showing_more;
parentElement.querySelectorAll('[data-initially-hidden]').forEach(element => {
element.classList.toggle('sqr-hidden', !filterState.showing_more);
});
}
function renderMultiSelectFilter(facet) {
const hasMoreValues = facet.values.length > facet.result_limit;
const filterState = props.state.datasets[facet.dataset].filterStates?.[facet.id];
const showingMore = filterState.showing_more ?? false;
return renderFilter(facet, `
${facet.searchable ? `
` : ''}
${facet.values.map((filterValue, index) => `
= facet.result_limit ? 'data-initially-hidden' : ''} class="sqr-flex sqr-items-center ${(!showingMore && index >= facet.result_limit) ? 'sqr-hidden' : ''}">
${renderFilterLabel(filterValue.label, facet.prefix, facet.suffix)}
(${filterValue.count})
`).join("")}
${hasMoreValues ? `
${showingMore ? 'Show fewer' : 'Show more'}
` : ''}
`);
}
function renderRadioFilter(facet) {
const hasMoreValues = facet.values.length > facet.result_limit;
const filterState = props.state.datasets[facet.dataset].filterStates?.[facet.id];
const showingMore = filterState.showing_more ?? false;
return renderFilter(facet, `
${facet.values.map((filterValue) => `
${renderFilterLabel(filterValue.label, facet.prefix, facet.suffix)}
(${filterValue.count})
`).join("")}
${hasMoreValues ? `
${showingMore ? 'Show fewer' : 'Show more'}
` : ''}
`);
}
function renderSliderFilter(facet) {
return renderFilter(facet, `
`);
}
function renderDualSliderFilter(facet) {
return renderFilter(facet, `
${facet.use_input ? `
` : `
${facet.prefix ?? ''}
${facet.min}
${facet.suffix ?? ''}
${facet.prefix ?? ''}
${facet.max}
${facet.suffix ?? ''}
`}
`);
}
function renderFilterLabel(label, prefix, suffix) {
return `${prefix ?? ''} ${label} ${suffix ?? ''}`.trim();
}
if (props.state.view === 'items') {
return ItemsView(props);
}
return SuggestView(props);
});