All files / src/merchandising merchandising.js

79.12% Statements 72/91
76.92% Branches 30/39
80% Functions 20/25
79.07% Lines 68/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263                          5x 5x         5x       5x 18x 18x           92x 92x 92x 92x       3x 3x 2x 1x 1x 1x 1x   1x                 1x 1x 1x                   1x   1x 1x             1x     1x 1x 1x   1x 1x     12x     1x 1x 1x 1x 1x 1x 1x 1x     1x 1x   1x 1x         2x 2x         2x 18x 2x               18x 18x               1x 1x                                               1x 1x 2x                       1x 3x                                           1x 1x 1x           1x 1x         3x         1x             2x 2x             1x   1x                                                          
// Local modules
import { 
    panelStatusUpdater,
    setPanelLoading,
    setPanelLoaded
} from '../utils/panel-status-updater';
import { setHtml } from '../utils/setHtml';
import toQueryString from '../utils/toQueryString';
import waitForElementToExist from '../utils/waitForElementToExist';
 
// NPM modules
//import isDomNode from 'is-dom-node';
 
const VYBE_API_ROOT = "http://merch.api.vybe.com/api";
const API = Object.freeze({
    PRODUCTS_GET_PRODUCTS: `${VYBE_API_ROOT}/Products/GetProduct`,
    PRODUCTS_RETRIEVE: `${VYBE_API_ROOT}/products/retrieve`,
});
 
const API_RESPONSE = Object.freeze({
    NO_PAGE_FOUND: "No page found"
});
 
const evaluateTemplate = ( template, data ) => {
    template = template.replace(">",">");
    return eval( '`' + template + '`' );
}
 
// Public API
class Merchandising {
    constructor(options) {
        this.token = options.token;
        this.siteName = options.siteName;
        this._tracking = options._tracking;
        this.sentry = options.sentry;
    }
    
    loadPage(options = {}) {
        try {
            if (!options.filtersContainer) throw new Error("filtersContainer must be set as part of options");
            if (!options.productsContainer) throw new Error("productsContainer must be set as part of options");            
            options.getFilterState = options.getFilterState || function() { return "" };            
            options.skip = options.skip || 0;
            options.take = options.take || 12;
            options.sortBy = options.sortBy || "";
 
            return Promise.all([
                waitForElementToExist(options.filtersContainer),
                waitForElementToExist(options.productsContainer),
                waitForElementToExist(options.pagerContainer)
            ]).then(([
                filterContainer, 
                productContainer,
                pagerContainer
            ]) => {
                setPanelLoading(filterContainer);
                setPanelLoading(productContainer);
                const qs = toQueryString({
                    token: this.token,
                    PageUrls: encodeURI(options.url || location.pathname),
                    siteName: this.siteName,
                    skip: options.skip,
                    take: options.take,
                    SortBy: options.sortBy,
                    AttributeIds: options.attributeIds || options.getFilterState()
                });
                
                fetch(`${API.PRODUCTS_RETRIEVE}?${qs}`)
                    .then(response => {
                        Eif (response.ok) {
                            return response.json()
                        }
                        return {
                            error: "no page"
                        }
                    })
                    .then(data => {
                        Iif (data.error) {
                            return data;
                        }
                        document.title = data.pages[0].metaTitle|| data.pages[0].title;
                        const pageDescriptionElm = document.querySelector('meta[name="description"]');
                        Iif (pageDescriptionElm) pageDescriptionElm.setAttribute("content", data.pages[0].metaDescription);
                        // set internal cmsPageKey
                        this._tracking.set(data.trackingData);
                        this._tracking.track("event", {
                            "category": "Merchandising",
                            "label": "Page Loaded",
                            "vybeProductIds": data.products.map(i => i.vybeProductId)
                        });                        
                        // update the products shown
                        const productTemplate = document.querySelector(options.productTemplate);
                        this.updateContainerWithTemplate(productContainer, productTemplate, data.products, `<div class="row">`, `</div>`);
                        const filterTemplate = document.querySelector(options.filterTemplate);
                        this.updateContainerWithTemplate(filterContainer, filterTemplate, data.attributeGroups);
                        this.updateListingNavigation(options.pagerContainer, options.skip, options.take, data);
                        this.addFilterListeners(options, filterContainer);
                        this.addSortByListeners(options);
                        return data;
                    })
                    .then(data => {
                        Eif (typeof options.onUpdate === "function") {
                            options.onUpdate(data);
                        }
                        setPanelLoaded(filterContainer);
                        setPanelLoaded(productContainer);
                    });
            });
        }
        catch (err) {
            this.sentry.captureException(err);
            throw Error(err);
        }
    }
    
    updateContainerWithTemplate(container, template, data, wrapStart = '', wrapEnd ='') {
        try {
            let newHtml = data.reduce((accumulator,data) => accumulator += this.templatingEngine(template.innerHTML, data), "");
            container.innerHTML = `${wrapStart}${newHtml}${wrapEnd}`;
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    templatingEngine(template, data) {
        try {
            return evaluateTemplate( template, data );
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    addFilterListeners(options, filterContainer) {
        try {
            filterContainer.querySelectorAll('a').forEach(a =>
                a.addEventListener('click', () => {
                    requestAnimationFrame(() => {
 
                        this._tracking.track("event", {
                            category: "Merchandising",
                            action: "Filter",
                        });
 
                        this.loadPage({
                            ...options,
                            attributeIds: options.getFilterState()
                        })
                    })
 
                })
            );
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    addSortByListeners(options) {
        try {
            document.querySelectorAll('.v-sortby').forEach(s => {
                s.addEventListener('change', (e) => {
                    this._tracking.track("event", {
                        category: "Merchandising",
                        action: "Filter",
                        value: "Sort By"
                    });        
                    this.loadPage({
                        ...options,
                        sortBy: e.target.value
                    });
                });
            });
            document.querySelectorAll('.listing-navigation__view .paging').forEach(s => {
                s.addEventListener('click', (e) => {
                    e.preventDefault();
                    const page = e.target.dataset.page || 1;
                    const newSkip = options.take * (page - 1);                    
                    this._tracking.track("event", {
                        category: "Merchandising",
                        action: "Paging",
                        value: page
                    });        
                    this.loadPage({
                        ...options,
                        skip: newSkip
                    });
                });
            });
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
 
    updateListingNavigation(pagerContainer, skip, take, data) {
        try {
            const allPagers = Array.from(document.querySelectorAll(pagerContainer));
            const totalPages = `
                <div class="listing-navigation__showing">
                    <span class="hidden-xs">Showing </span>
                        ${1 + skip} to ${skip + take} of ${data.totalProductCount}
                </div>
            `;
            const sortByOptions = data.sortingOptions;
            const sortByFilter = `
                <div class="listing-navigation__filter">
                    <span class="hidden-xs">Sort by</span>
                    <select class="v-sortby">
                        ${sortByOptions.map(option => {
                            return `<option ${data.sortedBy === option.value ? `selected="selected"` : ``} value="${option.value}">${option.displayName}</option>`
                        }).join("")}
                    </select>
                </div>
            `;
            const pagingLinks = `
                <input type="hidden" name="currentpage" value="1">
                <ul class="listing-navigation__view">
                    ${data.currentPage > 1 ? `
                        <li class="page-prev"><a href="#" data-page="${data.currentPage - 1}" class="paging" rel="next">Prev</a></li>
                    ` : ``}
                    ${Array.from(Array(data.totalPages), (d, i) => {
                        const index = i+1;
                        return `<li class="page-${index} ${index === data.currentPage ? `current`:``}"><a href="#" data-page="${index}" class="paging">${index}</a></li>`
                    }).join("") }
                    ${data.currentPage < data.totalPages ? `
                        <li class="page-next"><a href="#" data-page="${data.currentPage + 1}" class="paging" rel="next">Next</a></li>
                    ` : ``}
                </ul>
            `;
            allPagers.forEach(container => {
                //container.innerHTML = totalPages;
                container.innerHTML = `
                    <div class="row">
                        <div class="col-xs-12 col-sm-6 col-md-4">
                            ${totalPages}
                        </div>
                        <div class="col-md-4 hidden-xs hidden-sm text-center">
                            ${sortByFilter}
                        </div>
                        <div class="col-sm-6 col-md-4 hidden-xs text-right">
                            ${pagingLinks}
                        </div>
                        <div class="col-xs-6 visible-xs">
                            <div class="listing-navigation__btn">
                                <a href="#" class="js-toggle-filters">Show Filters</a>
                            </div>
                        </div>
                        <div class="col-xs-6 visible-xs">
                            ${sortByFilter}
                        </div>
                    </div>
                `;
            })
        }
        catch (err) {
            this.sentry.captureException(err);
        }
    }
}
 
export default Merchandising;