import type { Localized } from '../types';
declare const localized: Localized;
const template = `
`;
export const SearchBar: ng.IComponentOptions = {
bindings: {
btnClass: '@',
},
controller,
template,
};
controller.$inject = ['Products', 'User', 'Utils'];
function controller(Products, User, Utils) {
const vm = this;
this.$onInit = () => {
vm.catalogUrl = Utils.getPageUrl('catalog');
vm.isPunchoutOnly = User.punchoutOnly && !User.mixedPunchout;
vm.productSlug = localized.settings.general.product_slug || 'products';
vm.query = '';
initPopover();
};
const initPopover = () => {
jQuery(() => {
vm.el = jQuery('#search-bar');
vm.el.on('hidden.bs.popover', () => {
vm.el.popover('dispose');
});
});
};
const getProducts = () => {
vm.el.popover('hide');
const params = {
q: vm.query,
};
if (vm.query.length >= 2) {
vm.isInProgress = true;
Products.list(params)
.then((response) => response.data)
.then((data) => {
vm.results = processResults(data.product_briefs);
vm.el
.popover({
content: getPopoverContent(),
html: true,
placement: 'bottom',
template:
'',
title: getPopoverTitle(),
})
.popover('show');
vm.isInProgress = false;
});
}
};
const getPopoverContent = (): string => {
const limit = 5;
let content = '';
vm.results.forEach((result, i) => {
if (i < limit) {
content =
content +
`
`;
}
});
content = content + '
';
content =
content +
`See all results`;
return content;
};
const getPopoverTitle = (): string => {
return `Results for ${vm.query}:`;
};
this.onChange = () => {
getProducts();
};
const processResults = (data) => {
const products = data.map((product) => {
return {
url: `/${vm.productSlug}/${product.slug}`,
name: product.description,
price: new Intl.NumberFormat().format(product.price),
sku: product.sku,
uom: product.uom ? `/${product.uom}` : '',
imageUrl: getProductImage(product.images),
};
});
return products;
};
const getProductImage = (images): string => {
// eslint-disable-next-line space-unary-ops
if (!images || images.length === 0) {
return '/wp-content/plugins/vendorfuel/assets/img/placeholder-150px.png';
}
return Object.values(images)[0].thumb_url;
};
this.onSubmit = () => {
const page = vm.query
? `${vm.catalogUrl}?q=${vm.query}`
: vm.catalogUrl;
Utils.goToPage(page);
};
}