@salla.sa/twilight-components
Version:
Salla Web Component
167 lines (163 loc) • 8.76 kB
JavaScript
/*!
* Crafted with ❤ by Salla
*/
import { r as registerInstance, h, a as getElement } from './index-BQQ2x3w_.js';
import { S as Search } from './search-BscTeWDc.js';
import { H as Helper } from './Helper-DFMXF2_h.js';
import './anime.es-CgtvEd63.js';
const sallaSearchCss = ".s-search-placeholder-wrapper{position:relative;display:inline-block}.s-search-input-wrapper{position:relative}.s-search-placeholder-trigger{cursor:pointer;appearance:none;text-align:start}";
const SallaSearch = class {
constructor(hostRef) {
registerInstance(this, hostRef);
this.inputValue = '';
this.translationLoaded = false;
this.loading = false;
this.typing = false;
this.debounce = setTimeout(() => '', 1000);
/**
* Set the component to display as a placeholder (button) that will open the modal. Defaults to `false`
*/
this.placeholder = false;
/**
* Set the component display without modal window. Defaults to `false`
*/
this.inline = false;
/**
* Adds a border radius to the input. Half of the height.
*/
this.oval = false;
/**
* Sets the height of the input
*/
this.height = 60;
/**
* Maximum number of words allowed in the input
*/
this.maxWords = 5;
/**
* Show submit action buttons at the end.
*/
this.showAction = false;
this.productSlot =
this.host.querySelector('[slot="product"]')?.innerHTML || this.getDefaultProductSlot();
salla.event.on('search::open', () => this.open());
salla.lang.onLoaded(() => {
this.translationLoaded = true;
});
salla.event.on('modalClosed', () => this.onModalClose());
}
async open() {
if (!this.inline) {
await this.modal.open().then(() => setTimeout(() => this.searchInput.focus(), 300));
}
}
onModalClose() {
this.searchInput.value = '';
this.results = undefined;
this.afterSearching();
this.container.classList.remove('s-search-no-results');
}
handleKeyDown(ev) {
if (ev.key === 'Enter' && this.search_term?.length) {
window.location.href = salla.url.get('search?q=' + encodeURI(this.search_term));
}
}
getDefaultProductSlot() {
return ('<div class="s-search-product-image-container">' +
' <img class="s-search-product-image" src="{image}" alt="{name}"/>' +
'</div>' +
'<div class="s-search-product-details">' +
' <div class="s-search-product-title">{name}</div> <div class="s-search-product-price">{price} <span class="s-search-product-regular-price">{regular_price}</span></div>' +
'</div>');
}
debounceSearch(event) {
this.typing = true;
clearTimeout(this.debounce);
this.debounce = setTimeout(() => {
this.typing = false;
this.search_term = event.target.value;
}, 700);
}
limitWordsAndSearch(event) {
let value = event.target.value;
const words = value.trim().split(/\s+/);
if (words.length > this.maxWords) {
const truncatedInput = words.slice(0, this.maxWords).join(' ');
this.searchInput.value = truncatedInput;
}
this.debounceSearch(event);
}
getQueryParam(param) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(param);
}
handleActionClick() {
if (!!this.search_term && this.search_term.length > 2) {
return this.search(this.search_term);
}
}
handleSearch(val) {
this.inputValue = val;
if (val.length > 2) {
this.search(val);
}
else {
this.results = undefined;
this.afterSearching();
}
}
search(val) {
this.noResults.style.display = 'none';
//run loading spinner or stop it
this.loading = true;
salla.product
.fetch({ source: 'search', source_value: val })
.then(response => {
this.results = response;
salla.event.emit('Products Searched', val);
})
.catch(err => (err !== 'Query is same as previous one!' ? (this.results = undefined) : null))
.finally(() => this.afterSearching(/*isEmpty*/ false));
}
afterSearching(isEmpty = true) {
this.noResults.style.display = isEmpty || this.results?.data.length > 0 ? 'none' : 'block';
Helper.toggleElementClassIf(this.container, 's-search-container-open', 's-search-no-results', () => this.results?.data.length);
this.loading = false;
salla.product.api.previousQuery = ''; //avoid having error 'Query is same as previous one!' after reopen modal;
this.inputValue.length < 3 ? this.container.classList.remove('s-search-no-results') : '';
}
render() {
const searchContent = (h("div", { key: '25857ea8c54c56875ed665e9163db0b0dfc23d48', class: { 's-search-container': true, 's-search-inline': this.inline }, ref: container => (this.container = container) }, h("div", { key: '2d75789cec346377f1ad6e27605868a747f57ec0', class: "s-search-input-wrapper" }, h("span", { key: '68f3d318d8a1a54aff7da564f571bb7e1521d600', class: "s-search-icon-wrap" }, h("span", { key: '479b33adc20e2e6c34eff5fda4e303bfae16e445', class: "s-search-icon", innerHTML: this.loading ? '<i class="s-search-spinner-loader"/>' : Search })), h("input", { key: '4577ea9dbec8175e52603a0934a2d6f22aa26a02', type: "search", enterkeyhint: "search", autocomplete: "off", class: "s-search-input", placeholder: salla.lang.get('blocks.header.search_placeholder'), onInput: (e) => this.limitWordsAndSearch(e), onKeyDown: e => this.handleKeyDown(e), ref: input => (this.searchInput = input), style: {
height: this.height + 'px',
borderRadius: this.oval ? this.height / 2 + 'px' : '',
} }), this.showAction ? (h("salla-button", { loading: this.loading, class: { 's-search-action': true, 's-search-action-oval': this.oval }, onClick: () => this.handleActionClick() }, !this.loading && h("span", { innerHTML: Search }))) : null), h("div", { key: '0607676854eefa6966ec38c0d2e6dd5a3c6423bb', class: "s-search-results" }, this.results?.data.map(product => (h("a", { href: product.url + '?from=search-bar', class: {
's-search-product': true,
's-search-product-not-available': !product.is_available,
}, innerHTML: this.productSlot
.replace(/\{name\}/g, product.name)
.replace(/\{price\}/g, product.price ? salla.money(product.price) : '')
.replace(/\{regular_price\}/g, product.is_on_sale && product.regular_price
? salla.money(product.regular_price)
: '')
.replace(/\{image\}/g, product.image.url) }))), h("p", { key: '7136791cf4dc3d523cdba41367bd7691fd4ad9ba', ref: el => (this.noResults = el), class: "s-search-no-results-placeholder" }, salla.lang.get('common.elements.no_options')))));
const modalContent = (h("salla-modal", { key: 'ec8705a09e4993459d92569a5b71836cb0acefd8', position: "top", class: "s-search-modal", ref: modal => (this.modal = modal) }, searchContent));
const placeholderContent = (h("div", { key: '19b7e1c22e3a40c780eff0c74a23413f089ec96b', class: "s-search-placeholder-wrapper s-search-inline" }, h("div", { key: 'd87fc19fce928f230edb427e952903262a9ba32c', class: "s-search-input-wrapper" }, h("span", { key: '6475d41b267a2b35027016b5de474463cc7e6055', class: "s-search-icon-wrap" }, h("span", { key: 'e6ebac28c76a8a9824188da7ad2c290db610094f', class: "s-search-icon", innerHTML: Search })), h("button", { key: '3d7db311a4c348d4baaf1cb50eb5a0ed7953b28e', type: "button", class: "s-search-input s-search-placeholder-trigger", onClick: () => this.open(), style: {
height: this.height + 'px',
borderRadius: this.oval ? this.height / 2 + 'px' : '',
} }, salla.lang.get('blocks.header.search_placeholder'))), modalContent));
return this.placeholder ? (placeholderContent) : this.inline ? (h("div", { class: "s-search-modal" }, searchContent)) : (modalContent);
}
/**
* Run it one time after load
*/
componentDidLoad() {
this.afterSearching();
this.searchInput.value = this.getQueryParam('q');
}
get host() { return getElement(this); }
static get watchers() { return {
"search_term": ["handleSearch"]
}; }
};
SallaSearch.style = sallaSearchCss;
export { SallaSearch as salla_search };