Skip to content

Instantly share code, notes, and snippets.

@philcon93
Last active October 13, 2017 05:23
Show Gist options
  • Select an option

  • Save philcon93/168bb69ef7d177c16c6bfc5a8a7125af to your computer and use it in GitHub Desktop.

Select an option

Save philcon93/168bb69ef7d177c16c6bfc5a8a7125af to your computer and use it in GitHub Desktop.
Neto Swiftype

Neto Swiftype

This is a custom design setup which integrates Swiftype onto a Neto site, using the following jQuery libraries:

Inlcudes

  • Global search with autocomplete dropdown
  • Search results pages
    • Change sort order,
    • Filter by price and custom facets; "Genres", "Formats", "Brands","Categories"

Please Note: This isn't a plug and play example, if you are trying to implement this onto another Neto site then your data will dicate how the filtering/templating/results display. You will still need to have a good knownledge of your data and it's interaction with Swiftype to edit and use this example.

<!-- header.template.html -->
<!-- Setup search bar and include custom swiftype javascript -->
<!-- Ensure [%url id:'185'/%] points to custom search page -->
<div class="header-search">
<form id="searchShop" method="get" action="[%url id:'185'/%]" role="search" aria-label="Site Search">
<div class="input-group">
<input id="st-search-input" class="form-control st-search-input" type="search" aria-label="Input Search"/>
<span class="input-group-btn">
<button type="submit" value="Search" class="btn btn-default" aria-label="Search Site"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
[%site_value id:'footer_javascript'%]
[%load_template file:"cms/includes/swiftype_abc.template.html"/%]
[%/site_value%]
</div>
<!-- footer.template.html -->
<!-- Include all the dependencies -_- -->
<!-- jQuery is needed as well, but Neto sites come standard with that -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hogan.js/3.0.2/hogan.min.js"></script>
<script type='text/javascript' src='[%ntheme_asset%]js/jquery.swiftype.autocomplete.js[%/ntheme_asset%]'></script>
<script type='text/javascript' src='[%ntheme_asset%]js/jquery.ba-hashchange.min.js[%/ntheme_asset%]'></script>
<script type='text/javascript' src='[%ntheme_asset%]js/jquery.swiftype.search.js[%/ntheme_asset%]'></script>
<!-- Search Page -->
<!-- Custom Search Template -->
<!-- Need to setup information page to display results with this custom template -->
<aside class="col-xs-12 col-sm-3" id="left-sidebar">
<div class="panel panel-default st-custom-facets">
<div class="panel-heading panel-heading-thumbnails">
<h3 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#filters-accordion" href="#filters">Filter Price</a>
</h3>
</div>
<ul id="filters" class="panel-collapse collapse list-group" role="group">
<li id="price-search" class="list-group-item hidden-sm hidden-xs">
<p id="price-range"></p>
<p id="price-range-text" class="price_range"></p>
<a href="#" class="filter btn btn-default btn-xs" data-from="0" data-to="1">Filter By Price</a>
<a href="#" class="reset btn btn-default btn-xs" rel="nofollow" data-name="price"> clear</a>
</li>
</ul>
</div>
<div class="st-dynamic-facets"></div>
</aside>
<div class="col-xs-12 col-md-9">
<h1 class="page-header">Swiftype Search</h1>
<div class="row sort_container">
<div class="col-md-8 hidden-xs hidden-sm">
<div class="btn-text st-results"></div>
</div>
<div class="col-xs-12 col-md-4">
<div class="form-group">
<label class="control-label col-xs-2">Sort</label>
<div class="col-xs-10">
<select id="change-search-order" class="form-control js-swiftype-sort-box" title="Sort by">
<option>Relevance</option>
<option data-field="price" data-direction="desc">Highest Price First</option>
<option data-field="price" data-direction="asc">Lowest Price First</option>
<option data-field="rolling_sales_count" data-direction="desc">Bestsellers First</option>
<option data-field="published_at" data-direction="desc">New Releases First</option>
<option data-field="avg_review" data-direction="desc">Highest Rated</option>
</select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<hr>
</div>
</div>
<div id="st-results-container" class="row st-result-listing"></div>
</div>
<script>
// Product thumbnail template
var resultTemplate = Hogan.compile([
"<article class='wrapper-thumbnail col-xs-6 col-sm-6 col-md-4' aria-label='Product thumbnail'>",
"<div class='thumbnail' itemscope itemtype='http://schema.org/Product'>",
"{{#misc2}}{{#misc5}}<a href='{{misc5}}' style='color:{{misc3}};background:{{misc4}};' class='thumb-label text'>{{misc2}}</a>{{/misc5}}{{/misc2}}",
"{{#misc2}}{{^misc5}}<div class='thumb-label text' style='color:{{misc3}};background:{{misc4}};'>{{misc2}}</div>{{/misc5}}{{/misc2}}",
"{{#misc11}}{{^multibuy}}<div class='thumb-label text {{misc11ClassName}}'>{{misc11}}</div>{{/multibuy}}{{/misc11}}",
"{{#misc11}}{{#multibuy}}<div class='thumb-label text {{misc11ClassName}}' data-multibuy='{{misc11}}'>{{misc11}}</div>{{/multibuy}}{{/misc11}}",
"<span class='thumb-label spacer' role='presentation'></span>",
"<meta itemprop='mpn' content='{{sku}}'/>",
"<meta itemprop='brand' content='{{brand}}'/>",
"<a href='{{url}}' class='thumbnail-image'>",
"<img src='{{#product_image}}{{product_image}}{{/product_image}}{{^product_image}}{{image}}{{/product_image}}' itemprop='image' class='product-image' alt='{{name}}' rel='itmimg{{sku}}'>",
"{{#preorderImg}}{{{preorderImg}}}{{/preorderImg}}",
"{{#saleImg}}{{{saleImg}}}{{/saleImg}}",
"{{#newImg}}{{{newImg}}}{{/newImg}}",
"{{#bestImg}}{{{bestImg}}}{{/bestImg}}",
"<div class='caption'>",
"<div class='thumb-review'>",
"{{#reviews}}<span class='star' itemprop='aggregateRating' itemscope itemtype='http://schema.org/AggregateRating'>{{/reviews}}",
"{{#reviews}}{{{starsTemplate}}}{{/reviews}}",
"{{#reviews}}<span class='count'>({{reviews}})</span>{{/reviews}}",
"{{#reviews}}</span>{{/reviews}}",
"</div>",
"<h3 itemprop='name'>{{name}}</h3>",
"<p class='price' itemprop='offers' itemscope itemtype='http://schema.org/Offer'>",
"{{^inpromo}}<span itemprop='price' content='{{store_price}}'>{{#has_child}}from&nbsp;{{/has_child}} [@config:currency_symbol@]{{store_price}}</span>{{/inpromo}}",
"{{#inpromo}}<span itemprop='price' content='{{promo_price}}'>now&nbsp; {{#has_child}}from&nbsp;{{/has_child}} [@config:currency_symbol@]{{promo_price}}</span>{{/inpromo}}",
"<meta itemprop='priceCurrency' content='[@config:defaultcurrency@]'>",
"</p>",
"<div class='thumb-sub-price'>",
"{{#subPriceWas}}{{{subPriceWas}}}{{/subPriceWas}}",
"{{#subPriceSave}}{{{subPriceSave}}}{{/subPriceSave}}",
"</div>",
"</div>",
"</a>",
"<form class='form-inline buying-options' action='{{url}}'>",
'<input type="hidden" id="sku{{rndm}}{{sku}}" name="sku{{rndm}}{{sku}}" value="{{sku}}">',
'<input type="hidden" id="model{{rndm}}{{sku}}" name="model{{rndm}}{{sku}}" value="{{name}}">',
'<input type="hidden" id="thumb{{rndm}}{{sku}}" name="thumb{{rndm}}{{sku}}" value="{{image}}">',
"{{{button}}}",
"</form>",
"</div>",
"</article>",
].join(''));
// Search results template
var searchTemplate = Hogan.compile([
"{{#sku}}",
"<li role='option' tabindex='0'><a href='{{url}}' search-keyword='{{name}}'>",
"<img border='0' src='{{product_image}}'/>",
"<div class='caption'>",
"<p class='title'>{{name}}</p>",
"<p class='price'>",
"{{^inpromo}}{{#has_child}}from&nbsp;{{/has_child}}[@config:currency_symbol@]{{store_price}}{{/inpromo}}",
"{{#inpromo}}now&nbsp;{{#has_child}}from&nbsp;{{/has_child}}[@config:currency_symbol@]{{promo_price}}{{/inpromo}}",
"</p>",
"<p class='thumb-review'>",
"{{#reviews}}{{{starsTemplate}}}{{/reviews}}",
"</p>",
"</div>",
"<div class='clearfix'></div>",
"</a></li>",
"{{/sku}}",
"{{^sku}}",
"<li role='option' tabindex='0'><a href='{{url}}' search-keyword='{{name}}'>",
"<p class='contentTitle'>{{type}} > {{name}}</p>",
"</a></li>",
"{{/sku}}"
].join(''));
// Converts number to percentage
jQuery.extend({
percentage: function(a, b) {
return Math.round((a / b) * 100) + '%';
}
});
// Generates stars icons
function generateStars(amount){
var stars = "";
for (i = 0; i < amount; i++) {
stars += '<i class="fa fa-star"></i>'
}
var j = 5 - amount;
for (k = 0; k < j; k++) {
stars += '<i class="fa fa-star-o"></i>';
}
return stars;
}
// Render Thumbnail Template
var abcThumbnailRender = function(document_type, item) {
var item = item;
if (item.reviews) {
item.starsTemplate = generateStars(item.rating);
}
if(item.misc11){
if(item.misc11 == 'Exclusive' || item.misc11 == 'Signed copy' || item.misc11 == 'Award winner' || item.misc11 == 'Introductory price' || item.misc11 == 'Clearance' || item.misc11 == 'Reduced to Clear'){
item.misc11ClassName = item.misc11.replace(/ /g,'').toLowerCase();
}else if (item.misc11 == '3 for $20' || item.misc11 == '3 for $25' || item.misc11 == '2 for $40' || item.misc11 == '4 for $50' || item.misc11 == '3 for $50'){
item.multibuy = true;
item.misc11ClassName = item.misc11.toLowerCase();
}
}
if(!item.product_image){
item.product_image = 'https://cdn.neto.com.au/assets/neto-cdn/images/default_product.gif';
}
var ntheme = '/assets/themes/[@CONFIG:TEMPLATELANG@]/images';
if(item.qty > 0 && item.preorder == 1){ item.preorderImg = '<svg width="99.85" height="45" viewBox="0 0 99.85 45" role="presentation" class="thumb-label image preorder"><use xlink:href="#pre-order"></use></svg>';}
else if (item.inpromo == "1"){ item.saleImg = '<svg width="84.55" height="45" viewBox="0 0 84.55 45" role="presentation" class="thumb-label image sale"><use xlink:href="#on-sale"></use></svg>';}
else if(item.new_product == 1){ item.newImg = '<svg width="130.6" height="45" viewBox="0 0 130.6 45" role="presentation" class="thumb-label image new"><use xlink:href="#new-release"></use></svg>';}
else if(item.best_seller == 1){ item.bestImg = '<svg width="109.69" height="45" viewBox="0 0 109.69 45" role="presentation" class="thumb-label image best"><use xlink:href="#best-sellers"></use></svg>';}
if(item.inpromo === "1"){
item.inpromo = true;
}else if(item.inpromo === "0"){
item.inpromo = false;
}
if(item.promo_save > 0 || item.save > 0){
if(item.retail > 0){
item.subPriceWas = `<span class="was">was [@config:currency_symbol@]${item.retail}</span>`;
}else{
item.subPriceWas = `<span class="was">was [@config:currency_symbol@]${item.store_price}</span>`;
}
}
if(item.retail > 0){
if(item.save > 5 && !item.has_child){
var savePercentage = $.percentage(item.save, 100);
item.subPriceSave = `<span class="save">Save ${savePercentage}</span>`;
}else if(item.save && item.save < 6 && !item.has_child){
item.subPriceSave = `<span class="save">Save [@config:currency_symbol@]${item.save_price}</span>`;
}
}else if(item.promo_save > 0){
var savePercentage = $.percentage(item.promo_save, 100);
item.subPriceSave = `<span class="save">Save ${savePercentage}</span>`;
}
item.rndm = $.randString(5, "abcdefghijklmnopqrstuvwxyz0123456789");
var allow_nostock_checkout = [@config:ALLOW_NOSTOCK_CHECKOUT@];
var user_group = [@user:group_id@];
if(user_group == 2){
item.button = `<button type="submit" title="View ${item.name}" class="btn btn-success btn-block btn-loads"><svg class="svg-icon" width="18" height="14" viewBox="0 0 18 14" role="presentation"><use xlink:href="#arrow-right"></use></svg> <span>View Product</span></button>`;
}else if(item.buying_options == 1){
item.button = `<button type="submit" title="View ${item.name} Buying Options" class="btn btn-success btn-block btn-loads"><svg class="svg-icon" width="16" height="17" viewBox="0 0 16 17" role="presentation"><use xlink:href="#cart-white"></use></svg> <span>See Options</span></button>`;
}else if(item.qty > 0 || item.preorder && item.qty > 0 - item.preorderQty){
item.button = `<button type="button" title="Add ${item.name} to Cart" class="addtocart btn btn-success btn-block btn-loads" rel="${item.rndm}${item.sku}"><svg class="svg-icon" width="16" height="17" viewBox="0 0 16 17" role="presentation"><use xlink:href="#cart-white"></use></svg> <span>Add to Cart</span></button>`;
}else if(item.qty < 1 && allow_nostock_checkout){
item.button = `<button type="button" title="Add ${item.name} to Cart" class="addtocart btn btn-success btn-block btn-loads" rel="${item.rndm}${item.sku}"><svg class="svg-icon" width="16" height="17" viewBox="0 0 16 17" role="presentation"><use xlink:href="#cart-white"></use></svg> <span>Backorder</span></button>`;
}else{
item.button = `<button type="submit" title="Notify Me When ${item.name} Is Back In Stock" class="btn btn-default btn-out-of-stock btn-block btn-loads"> Out Of Stock</button>`;
}
return resultTemplate.render(item);
};
// Removes duplicate items in array
function scrubContentLinks(array){
var newArray = [];
$.each(array, function(i, el){
if($.inArray(el, newArray) === -1) newArray.push(el);
});
if(newArray.length > 5){
return newArray.slice(0, 5);
}else{
return newArray;
}
}
// Extract title and url from link
function linkItems(link){
o = {};
o.type = $(link).attr('data-type');
o.title = $(link).attr('title');
o.url = $(link).attr('href');
return o;
}
var abcSearchResultRender = function(ctx, results) {
var $resultContainer = ctx.list,
config = ctx.config,
contentLinks = [];
$resultContainer.html('');
$resultContainer.addClass('nav nav-list').attr('id', 'swiftype-results-list')
.attr('aria-hidden', 'false').attr('aria-activedescendant', 'active').attr('role', 'listbox');
$.each(results, function(document_type, items) {
$.each(items, function(idx, item) {
ctx.registerResult($(config.renderFunction(document_type, item)).appendTo($resultContainer), item);
if (item['content_links']) {
contentLinks = contentLinks.concat(item['content_links']);
}
});
});
// Display brand links under the product results
contentLinks = (scrubContentLinks(contentLinks));
$.each(contentLinks, function(i, item){
var itemObject = linkItems(item);
var pseudoAutocompleteItem = {
id: null,
type: itemObject.type,
name: itemObject.title,
url: itemObject.url
};
ctx.registerResult($(config.renderFunction(i, pseudoAutocompleteItem)).appendTo($resultContainer), pseudoAutocompleteItem);
});
};
// Render Product Search Results Template
var abcSearchRender = function(document_type, item) {
if (item.reviews) {
item.starsTemplate = generateStars(item.rating);
}
if(item.inpromo === "1"){
item.inpromo = true;
}else if(item.inpromo === "0"){
item.inpromo = false;
}
return searchTemplate.render(item);
};
var priceRange = {
from: 0,
to: 1
}
// Price slider functionality
var priceSlider = function() {
var vals = [window.priceRange.from, window.priceRange.to];
for (var i = 0; i < vals.length; i++) {
vals[i] = parseInt(vals[i]);
}
$("#price-range").slider({
range: true,
min: vals[0],
max: vals[1],
values: vals,
slide: function(event, ui) {
$("#price-range-text").html('[@config:currency_symbol@]' + ui.values[0] + ' to [@config:currency_symbol@]' + ui.values[1]);
$('#price-search a.filter')
.attr('data-from', ui.values[0])
.attr('data-to', ui.values[1]);
},
create: function(event, ui) {
$("#price-range-text").html('[@config:currency_symbol@]' + vals[0] + ' to [@config:currency_symbol@]' + vals[1]);
$('#price-search a.filter')
.attr('data-from', vals[0])
.attr('data-to', vals[1]);
}
});
};
// Search query settings
var searchConfig = {
facets: {},
sort: {
field: undefined,
direction: undefined
},
price: {
from: undefined,
to: undefined
}
};
// Reloads the results
var reloadResults = function() {
location.hash = location.hash.split('&')[0];
$(window).hashchange();
};
// Access the sort properties from the searchConfig variable
var abcSortField = function() {
return { page: window.searchConfig.sort.field };
};
// Access the sort properties from the searchConfig variable
var abcSortDirection = function() {
return { page: window.searchConfig.sort.direction };
};
var bindControls = function(data) {
var resultInfo = data['info'],
facets = '';
// Template for sidebar filters
$.each(resultInfo, function(documentType, typeInfo) {
$.each(typeInfo.facets, function(field, facetCounts) {
// Do not show price as a filter. It will display as a slider
if (field !== 'price') {
// Do not show filters with no options
if(!$.isEmptyObject(facetCounts)){
// Update filter labels
if(field == 'in_stock'){
var filterLabel = 'stock';
}else{
var filterLabel = field;
}
facets += ['<li class="list-group-item"><h4><a data-toggle="collapse" class="active" href="#filter-collapse-' + field + '" aria-controls="filter-collapse-' + field + '" role="tab"><span>By ', filterLabel, '<svg width="25px" height="24px" viewBox="0 0 25 24" role="presentation" class="success" aria-hidden="true"><use xlink:href="#dropup-success"></use></svg><svg width="25px" height="24px" viewBox="0 0 25 24" role="presentation" class="black" aria-hidden="true"><use xlink:href="#dropdown-black"></use></svg></span></a></h4></li>'].join('');
facets += '<li id="'+filterLabel+'Group"><ul class="filter-collapse collapse in" id="filter-collapse-' + field + '"role="tabpanel" aria-label="' + filterLabel + ' filters">';
$.each(facetCounts, function(label, count) {
if (label !== "") {
var status = "",
id = encodeURIComponent(label).toLowerCase();
if (window.searchConfig.facets[field] && window.searchConfig.facets[field].indexOf(label) > -1) {
status = ' checked="checked"'
}
if (field == 'in_stock'){
if(label == 'true'){
facets += '<li class="filter"><label class="list-group-item" for="' + id + '"><input type="checkbox"' + status + ' name="' + field + '" value="' + label + '" id="' + id + '"> In stock (' + count + ')</label></li>';
}
}else{
facets += '<li class="filter"><label class="list-group-item" for="' + id + '"><input type="checkbox"' + status + ' name="' + field + '" value="' + label + '" id="' + id + '"> ' + label + ' (' + count + ')</label></li>';
}
}
});
facets += '<li><a href="#" class="clear-selection list-group-item" data-name="' + field + '">Clear all</a></li></ul></li>';
}
}
});
$('#filter-collapse-price').parent().nextAll().remove();
$('#filters').append(facets);
});
};
// Returns a hash with filter settings
var readFilters = function() {
return {
page: {
type: 'product',
Format: window.searchConfig.facets['Format'],
Genres: window.searchConfig.facets['Genres'],
brand: window.searchConfig.facets['brand'],
category: window.searchConfig.facets['category'],
in_stock: window.searchConfig.facets['in_stock'],
price: {
type: 'range',
from: window.searchConfig.price.from,
to: window.searchConfig.price.to
}
}
}
}
// Render results from swiftype
var renderResults = function(data) {
var query = data.info.page.query,
total = data.info.page.total_result_count;
prices = data.info.page.facets.price,
maxPrice = Math.ceil(Math.max.apply(null, Object.keys(prices))),
minPrice = Math.ceil(Math.min.apply(null, Object.keys(prices)));
window.priceRange.from = minPrice;
window.priceRange.to = maxPrice;
window.priceSlider();
$('#price-search a.filter').attr('data-from', minPrice);
$('#price-search a.filter').attr('data-to', maxPrice);
var from = $('#price-search a.filter').attr('data-from');
var to = $('#price-search a.filter').attr('data-to');
$("#price-range-text").html('$' + from + ' to $' + to);
if(query == 1){
$(".st-results").html("Products [@content_name@] (" + total + " Results)");
}else{
$(".st-results").html("Search results for '" + query + "' (" + total + " Results)");
}
}
var renderNoResults = function(data) {
$('.st-result-listing').html("<div id='st-no-results' class='st-no-results col-xs-12'>No results found.</div>");
}
// Loading fucntion
var abcLoadingFunction = function(query, $resultContainer) {
$resultContainer.html('<p class="st-loading-message col-xs-12">loading...</p>');
};
// Pagination render function
var abcRenderPagination = function(type, currentPage, totalPages) {
var pages = '<div class="col-xs-12"><div class="st-page text-center"><ul class="pagination" role="navigation">',
previousPage, nextPage;
if (currentPage != 1) {
previousPage = currentPage - 1;
pages = pages + '<li><a href="#" class="st-prev" data-hash="true" data-page="' + previousPage + '" aria-label="Go back one page"><i class="fa fa-chevron-left" aria-hidden="true"></i></a></li>';
if (previousPage != 1) {
pages = pages + '<li><a href="#" class="st-next" data-hash="true" data-page="' + (previousPage - 1) + '">' + (previousPage - 1) + '</a></li>';
}
pages = pages + '<li><a href="#" class="st-prev" data-hash="true" data-page="' + previousPage + '">' + previousPage + '</a></li>';
}
pages = pages + '<li class="active"><a>' + currentPage + '</a></li>';
if (currentPage < totalPages) {
nextPage = currentPage + 1;
pages = pages + '<li><a href="#" class="st-next" data-hash="true" data-page="' + nextPage + '">' + nextPage + '</a></li>';
if (nextPage < totalPages) {
pages = pages + '<li><a href="#" class="st-next" data-hash="true" data-page="' + (nextPage + 1) + '">' + (nextPage + 1) + '</a></li>';
}
pages = pages + '<li><a href="#" class="st-next" data-hash="true" data-page="' + nextPage + '" aria-label="Go forward one page"><i class="fa fa-chevron-right" aria-hidden="true"></i></a></li>';
}
pages += '</ul></div></div>';
return pages;
};
// Update the sort order
$('.js-swiftype-sort-box').on('change', function(e) {
e.preventDefault();
window.searchConfig.sort.field = $(this).find(":selected").attr('data-field');
window.searchConfig.sort.direction = $(this).find(":selected").attr('data-direction');
reloadResults();
});
// Update to price range - there are two buttons; one to filter, one to reset
$('#price-search a.filter').on('click', function(e) {
e.preventDefault();
window.searchConfig.price.from = $(this).attr('data-from');
window.searchConfig.price.to = $(this).attr('data-to');
reloadResults();
});
$('#price-search a.reset').on('click', function(e) {
e.preventDefault();
window.searchConfig.price = {
from: undefined,
to: undefined
};
reloadResults();
});
// Add selected filter
$('#filters').on('click', 'input', function(e) {
window.searchConfig.facets = {}; // Set the hash to empty
$('#filters input[type="checkbox"]').each(function(idx, obj) {
var checkboxName = $(obj).attr('name');
var checkboxChecked = $(obj).is(':checked');
if (!window.searchConfig.facets[checkboxName]) {
window.searchConfig.facets[checkboxName] = [];
}
if (checkboxChecked) {
window.searchConfig.facets[checkboxName].push($(obj).attr('value'));
}
});
reloadResults();
});
// Clears selected filter
$('#filters').on('click', 'a.clear-selection', function(e) {
e.preventDefault();
var name = $(this).attr('data-name');
$('input[name=' + name + ']').attr('checked', false);
window.searchConfig.facets[name] = [];
reloadResults();
});
// Update url with correct search query
$("#searchShop").on("submit", function(e) {
e.preventDefault();
var a = $("#st-search-input").val();
a = encodeURIComponent(a);
var n = $(this).attr("action") + "#stq=" + a + '&stp=1';
window.location = n;
});
// Take user to the top of the page
$('#main-content').on('click', '.pagination > li:not(.active) > a',function(){
$("html, body").animate({ scrollTop: 100 }, 2500);
});
var checkQueryString = function(value){
var field = value;
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1){
return true;
}else if(url.indexOf('&' + field + '=') != -1){
return true;
}
return false;
}
var setSearchFacet = function(){
var value = "[@form:category@]";
window.searchConfig.facets = {};
if (!window.searchConfig.facets['category']) {
window.searchConfig.facets['category'] = [];
}
window.searchConfig.facets['category'].push(value);
}
// Update url based on query
var setSearchHash = function (query, page) {
if(checkQueryString('category')){
setSearchFacet();
}
location.hash = "stq=" + encodeURIComponent(query) + "&stp=" + page;
};
var abcEngineKey = 'ENGINE_API_KEY';
var abcFetchFields = function(){
return
['sku', 'brand', 'url', 'product_image', 'image', 'name', 'inpromo', 'store_price', 'promo_price','qty', 'reviews', 'has_child']
}
function abcPageResults(container, searchFields, input){
if($(container).length > 0 ){
var input = input || '#st-search-input',
container = container || '#st-results-container',
searchFields = searchFields || { page: ["name"] },
facets = ["brand", "category", "in_stock", "Formats", "Genres", "price"]
if(container !== '#st-results-container'){
if(container == '#st-4183-results-container'){
setSearchHash('1',1);
}else if(container == '#st-5494-results-container' || container == '#st-5493-results-container'){
setSearchHash(1,1);
}else if(container == '#st-5495-results-container'){
setSearchHash('Exclusive',1);
}else{
console.log('Issue with container!');
}
}
$(input).swiftypeSearch({
resultContainingElement: container,
engineKey: abcEngineKey,
searchFields: {page: searchFields},
renderFunction: abcThumbnailRender,
sortField: abcSortField,
sortDirection: abcSortDirection,
facets: { page: facets },
filters: readFilters,
postRenderFunction: function(data) {
if (data.record_count === 0) {
renderNoResults(data);
} else {
bindControls(data);
renderResults(data);
}
},
loadingFunction: abcLoadingFunction,
renderPaginationForType: abcRenderPagination,
perPage: 24
});
}
}
function abcSiteSearch(input, fetchFields, searchFields, resultRenderFunction, renderFunction, resultLimit){
$(input).swiftype({
engineKey: abcEngineKey,
fetchFields: { product: fetchFields },
searchFields: { product: searchFields },
resultRenderFunction: resultRenderFunction,
renderFunction: renderFunction,
resultLimit: resultLimit,
});
}
$(document).ready(function(){
// Main search
abcPageResults('#st-results-container',["name", "sku", "brand", "Formats", "Genres"]);
// On sale
abcPageResults('#st-4183-results-container',["inpromo"]);
// Coming soon
abcPageResults('#st-5494-results-container',["coming_soon"]);
// New releases
abcPageResults('#st-5493-results-container',["new_release"]);
// Exclusives
abcPageResults('#st-5495-results-container',["misc11"]);
// Header product search
abcSiteSearch('#st-search-input', abcFetchFields, ["name", "sku", "brand"], abcSearchResultRender, abcSearchRender, 5);
});
</script>
// swiftype
@media (min-width: 992px) {
.sidebar-filter {
height: auto !important;
display: block;
}
}
.st-loading-message {
font-size: 16px;
font-style: italic;
color: #999;
margin: 10px auto;
}
#left-sidebar #price-search .filter,
#left-sidebar #price-search .reset {
padding: 1px 5px;
font-size: 12px;
}
#left-sidebar #filters > .list-group-item h4 a span {
text-transform: capitalize;
}
.swiftype-widget{
.autocomplete{
border-color: rgba(0, 0, 0, 0.15);
background-color: #fff;
z-index: 99999 !important;
.nav{
border: 1px solid;
border-color: #262e31;
border-top: none;
li{
&.active{
background: @brand-primary;
a{
color: #000;
.caption{
p{
&.thumb-review{
color: #000;
}
}
}
}
}
a {
border-top: 1px solid #262e31;
img, .caption{
float: left;
}
img{
width: 12%;
height: auto;
}
.caption{
width: 88%;
padding-left: 10px;
p{
height: auto;
margin-bottom: 0;
&.price{
color: #000;
}
&.thumb-review{
color: #fec52e;
}
}
}
.contentTitle{
margin-bottom: 0;
text-transform: capitalize;
}
}
&:first-child{
a{
border-top: none;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment