commercetools-8.x-1.2-alpha1/modules/commercetools_decoupled/components/blocks/search-block/js/SearchBlock.js

modules/commercetools_decoupled/components/blocks/search-block/js/SearchBlock.js
class SearchBlock extends HTMLElement {
  connectedCallback() {
    this.componentConfig = window.commercetools.getComponentConfig(this);

    const url = new URL(window.location);
    this.setActiveFilters(url.searchParams);
    this.handlerFormSubmit = this.handlerFormSubmit.bind(this);

    this.paramName = window.commercetools.getParamNameByIndex(
      'search',
      this.componentConfig.productListIndex,
    );
    this.searchValue = '';

    const searchForm = document.createElement('ct-search-form');
    searchForm.name = this.paramName;
    searchForm.value = this.searchValue;
    searchForm.formSubmitHandler = this.handlerFormSubmit;
    this.append(searchForm);
  }

  applyProductListConfiguration(configuration) {
    if (this.searchValue) {
      configuration.text = this.searchValue;
    }
    return configuration;
  }

  setActiveFilters(params) {
    this.searchValue = params.get(this.paramName) || '';
  }

  handlerFormSubmit(e) {
    e.preventDefault();
    const newUrl = window.commercetools.generateNewUrl(e.currentTarget);
    this.setActiveFilters(newUrl.searchParams);
    newUrl.searchParams.delete('page');

    if (
      this.componentConfig.targetPage.trim() !== '' &&
      newUrl.pathname !== this.componentConfig.targetPage
    ) {
      newUrl.pathname = this.componentConfig.targetPage;
      window.location = newUrl.toString();
    } else {
      window.history.pushState(
        { path: newUrl.toString() },
        '',
        newUrl.toString(),
      );
    }

    window.commercetools.resetProductListResult(
      this.componentConfig.productListIndex,
    );
    const changeEvent = new CustomEvent('ct.filters.change', {
      detail: {
        productListIndex: this.componentConfig.productListIndex,
        newUrl,
      },
    });
    document.dispatchEvent(changeEvent);
  }
}

customElements.define('ct-search-block', SearchBlock);

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc