Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Nobel script quickSearch widget extend
- *
- * @category Nobel
- * @package Nobel\Search
- * @author Andrii Ravskyi <anrav@smile.fr>
- * @copyright 2017 Smile
- */
- /*jshint browser:true jquery:true*/
- /*global alert*/
- define([
- 'ko',
- 'jquery',
- 'mage/template',
- 'Magento_Customer/js/customer-data',
- 'Magento_Catalog/js/price-utils',
- 'jquery/ui',
- 'mageQuickSearch',
- 'Smile_ElasticsuiteCore/js/form-mini',
- 'Nobel_CustomerPrice/js/view/custom-customer-prices',
- 'underscore',
- "mage/cookies",
- 'mage/translate'
- ], function (ko, $, mageTemplate, customerData, utils, _) {
- 'use strict';
- $.widget('nobel.quickSearchUpdate', $.smileEs.quickSearch, {
- options: {
- enableToggleSearch: true,
- ajaxLoader: false,
- elementsSelector: '[data-role=price-amount-element]'
- },
- priceTemplate: mageTemplate('<span class="price update-price"><%- priceFormatted %></span>'),
- productAmong: mageTemplate('<span class="product-among">(<%- data.size %>)</span>'),
- _create: function () {
- this._switchBetweenTabs();
- if(this.options.enableToggleSearch) {
- this._toggleSearchField();
- }
- this._super();
- this.element.off('blur');
- this.element.off('mouseleave');
- },
- /**
- * Toggle search field after click on icon
- */
- _toggleSearchField: function() {
- $('.toggle-search-icon').on('click', function () {
- var overlay = $('.search-overlay');
- if($('.search-autocomplete').is(':hidden')) {
- overlay.show();
- } else {
- overlay.hide();
- }
- $('.block-search').toggle();
- });
- },
- /**
- * Switch between search tabs
- */
- _switchBetweenTabs: function () {
- var self = this;
- $(document).on('click', '.search-toggle .item', function(){
- self.paramScope = $(this).attr('data-role');
- $('.search-toggle .item').removeClass('active');
- $(this).addClass('active');
- self._onPropertyChange();
- });
- },
- /**
- * Form add to cart 'submit' ajax request
- */
- ajaxSubmit: function(form) {
- $.ajax({
- url: form.attr('action'),
- data: form.serialize(),
- type: 'post',
- dataType: 'json',
- showLoader: true
- });
- },
- /**
- * Override to add specific type
- */
- _getSectionHeader: function(type, data) {
- var title = '';
- var header = $('<dl role="listbox" class="autocomplete-list-' + type + '"></dl>');
- if (type !== undefined) {
- title = this._getSectionTitle(type, data);
- header.append(title);
- }
- return header;
- },
- /**
- * Add submit event on show all button
- */
- _showAllAction: function(){
- $('.search.autocomplete').on('click', function() {
- document.getElementById('search_mini_form').submit();
- });
- },
- /**
- * Call search search tabs template
- */
- _callSearchTabs: function () {
- var searchToggleTemplate = mageTemplate('#search-tabs-template');
- $('.smile-elasticsuite-autocomplete-result').prepend(searchToggleTemplate);
- },
- /**
- * Call show all button template
- */
- _callShowAll: function () {
- var searchShowAllTemplate = mageTemplate('#search-show-all');
- $('.autocomplete-list-product').append(searchShowAllTemplate);
- },
- /**
- * Get search overlay
- */
- getOverlay: function() {
- var body = $('body'),
- overlay = $('<div></div>').addClass('search-overlay');
- body.find('.search-overlay').remove();
- body.append(overlay);
- overlay.on('click', function(){
- setTimeout(function() {
- overlay.hide();
- $('.block-search').toggle();
- }, 500);
- });
- },
- updateDefaultPrice: function (message) {
- if (message) {
- console.log('2');
- $('.price-wrapper').html(this.priceTemplate({ priceFormatted: message }));
- } else {
- var priceAmount = $('.price-wrapper').data('priceAmount');
- this._updatePriceValue('.price-wrapper', priceAmount);
- console.log(priceAmount);
- }
- },
- _updatePriceValue: function (element, priceAmount) {
- var priceFormatted = utils.formatPrice(priceAmount, this.priceFormat);
- console.log('3');
- $('.price-wrapper').html(this.priceTemplate({ priceFormatted: priceFormatted}));
- console.log($('.price-wrapper'));
- },
- updateCustomerPrice: function(data) {
- var itemId = $('.price-wrapper').data('itemId');
- if ((_.isUndefined(data.status) || data.status == 0) && !this.timerId) {
- this.timerId = setTimeout(this.reloadPriceData.bind(this), 10000);
- }
- console.log('4');
- this.elements.each(function (index, element) {
- var itemId = $(element).data('itemId');
- if (!_.isEmpty(data.items[itemId])) {
- var priceType = $(element).data('priceType');
- if (!_.isEmpty(data.items[itemId][priceType])) {
- var priceAmount = data.items[itemId][priceType]['amount'];
- this._updatePriceValue(element, priceAmount);
- }
- }
- }.bind(this));
- },
- reloadPriceData: function () {
- this.timerId = null;
- customerData.reload(['custom-customer-prices']);
- },
- /**
- * Set special url for discover tab
- */
- getRequestUrl: function() {
- if(this.paramScope == 'discover' && this.options.urlDiscover !== ''){
- return this.options.urlDiscover
- } else {
- return this.options.url
- }
- },
- /**
- * Override to :
- * - Add toggle buttons to search popup
- * - Add additional elements to popup
- * - Add elements filter depends of search category
- * - Extend current functionality
- */
- _onPropertyChange: function () {
- var value = this.element.val(),
- searchWrapper = $('.search-autocomplete'),
- preloader = $('<div></div>').addClass('search-loader');
- this.submitBtn.disabled = this._isEmpty(value);
- if (value.length >= parseInt(this.options.minSearchLength, 10)) {
- this.currentRequest = $.ajax({
- method: "GET",
- url: this.getRequestUrl(),
- data:{
- product_type: this.paramScope,
- q: value
- },
- // This function will ensure proper killing of the last Ajax call.
- // In order to prevent requests of an old request to pop up later and replace results.
- beforeSend: function() {
- if (this.currentRequest !== null)
- this.currentRequest.abort();
- searchWrapper.find('.search-loader').remove();
- searchWrapper.prepend(preloader);
- }.bind(this),
- success: $.proxy(function (data) {
- var self = this,
- tabsParam = self.paramScope,
- lastElement = false,
- content = this._getResultWrapper(),
- sectionDropdown = this._getSectionHeader(),
- productItem = '.product-item',
- productElement = '.product-item-wrapper',
- groupId = parseInt($.mage.cookies.get('mage-customer-group-id'));
- self.firstProduct = 0;
- var priceValue = [];
- if (tabsParam == 'simple' || tabsParam == undefined) {
- $.each(data, function (index, element) {
- if (!lastElement || (lastElement && lastElement.type !== element.type)) {
- sectionDropdown = this._getSectionHeader(element.type, data);
- }
- var elementHtml = this._renderItem(element, index);
- sectionDropdown.append(elementHtml);
- if (!lastElement || (lastElement && lastElement.type !== element.type)) {
- content.append(sectionDropdown);
- }
- lastElement = element;
- if (element.type == "product") {
- self.firstProduct = element
- }
- if(element.price !== undefined) {
- priceValue.push(element.price)
- }
- }.bind(this));
- } else {
- $.each(data, function (index, element) {
- if (element.type !== "product") {
- return;
- } else {
- self.firstProduct = element
- }
- if (!lastElement || (lastElement && lastElement.type !== element.type)) {
- sectionDropdown = this._getSectionHeader(element.type, data);
- }
- var elementHtml = this._renderItem(element, index);
- sectionDropdown.append(elementHtml);
- if (!lastElement || (lastElement && lastElement.type !== element.type)) {
- content.append(sectionDropdown);
- }
- lastElement = element;
- }.bind(this));
- }
- this.responseList.indexList = this.autoComplete.html(content)
- .show()
- .find(this.options.responseFieldElements + ':visible');
- this._resetResponseList(false);
- this.element.removeAttr('aria-activedescendant');
- if (this.responseList.indexList.length) {
- this._updateAriaHasPopup(true);
- } else {
- this._updateAriaHasPopup(false);
- }
- $(productElement).on('click', function (e) {
- self.responseList.selected = $(this).closest(productItem);
- if (self.responseList.selected.attr("href")) {
- window.location.href = self.responseList.selected.attr("href");
- e.stopPropagation();
- return false;
- }
- $(this).closest(productItem).searchForm.trigger('submit');
- });
- this.responseList.indexList.on('mouseenter mouseleave', function (e) {
- self.responseList.indexList.removeClass(self.options.selectClass);
- $(this).addClass(self.options.selectClass);
- self.responseList.selected = $(e.target);
- self.element.attr('aria-activedescendant', $(e.target).attr('id'));
- })
- .on('mouseout', function () {
- if (!self._getLastElement() && self._getLastElement().hasClass(self.options.selectClass)) {
- $(this).removeClass(self.options.selectClass);
- self._resetResponseList(false);
- }
- });
- $('form.action-wrapper').on('submit', function(e) {
- var form = $(this);
- e.preventDefault();
- self.ajaxSubmit(form);
- });
- this._callShowAll();
- this._callSearchTabs();
- this.getOverlay();
- this._showAllAction();
- console.log(priceValue);
- $('.product-secondary').each(function (index) {
- $(this).append(priceValue[index]);
- console.log(priceValue[index]);
- });
- this.myElements = $(self.options.elementsSelector);
- if (groupId) {
- console.log('10');
- this.updateDefaultPrice();
- this.customerPrices = customerData.get('custom-customer-prices');
- this.customerPrices.subscribe(this.updateCustomerPrice.bind(this));
- // this.updateCustomerPrice(this.customerPrices());
- } else {
- console.log('20');
- this.updateDefaultPrice(this.options.pricePlaceholder);
- }
- if(this.paramScope === undefined) {
- $('.item.shop').addClass('active');
- $('#show-all-param').val('simple');
- } else {
- $('.smile-elasticsuite-autocomplete-result')
- .find("[data-role ='" + this.paramScope + "']")
- .addClass('active');
- $('#show-all-param').val(self.paramScope);
- }
- var findeElem = 0;
- if(this.firstProduct.size != undefined)
- findeElem = this.firstProduct.size;
- $('.search-toggle .active').append(this.productAmong({ data: { size: findeElem }}));
- $(preloader).remove();
- },this)
- });
- } else {
- this._resetResponseList(true);
- this.autoComplete.hide();
- this._updateAriaHasPopup(false);
- this.element.removeAttr('aria-activedescendant');
- }
- }
- });
- return $.nobel.quickSearchUpdate;
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement