((win, doc) => { 'use strict'; const APPLICATIONS_DATA = { IMAGE: 'webImageUrl', URL: 'detailUrl', TITLE: 'displayName', DESCRIPTION: 'description', OPTIONS: 'options', CATEGORIES: 'categories' }; const CONFIG = { MAX_ARTICLES: 9, SP_MAX_PAGERS: 5, IS_CURRENT: 'is-current', IS_HIDE: 'is-hide', INDEX_PARAM: 'index_page', CATEGORY_PARAM: 'category_id', PRODUCTS_PARAM: 'group_id', APPLICATION_CATEGORY_GROUP_API_DATA: 1, APPLICATION_CATEGORY_GROUP_API_PARAM: 'applicationCategoryGroupID', SITE_API_PARAM: 'siteID', LANGUAGE_API_PARAM: 'languageID', CATEGORY_API_PARAM: 'applicationCategoryID', PRODUCTS_API_PARAM: 'groupID', LIMIT_API_PARAM: 'limit', OFFSET_API_PARAM: 'offset', SMALL_SCREEN: win.matchMedia('(max-width: 969px)') }; const GLOBAL_SETTINGS = { SITE_ID: win.kpi_siteSettings.siteId ? win.kpi_siteSettings.siteId : null, SITE_LANG: win.kpi_siteSettings.siteLang ? win.kpi_siteSettings.siteLang : null, ORIGINAL_DOMAIN: win.kpi_originalDomain ? win.kpi_originalDomain : null }; const API_PATH = { APPLICATIONS: GLOBAL_SETTINGS.ORIGINAL_DOMAIN + '/data/application/cases?' }; class Utility { static notElementText(element) { const notElementText = element.replace(/(<([^>]+)>)/gi, ''); return notElementText; } static checkNumber(value) { return !isNaN(parseFloat(value)); } static getParam(paramName) { const url = new URLSearchParams(location.search); const param = url.get(paramName); return param; } static getCheckedData(items) { const selectedDataArray = []; items.forEach((item) => { selectedDataArray.push(item.value); }); return selectedDataArray; } static getJoinedArray(arrayItem) { if (!Array.isArray(arrayItem) || !arrayItem.length) { return ''; } return arrayItem.join(','); } } class SelectApplications { constructor() { this.selectors = { applicationFilter: 'js-filterApplications', categoryFilterTrigger: 'js-selectApplications-category', productFilterTrigger: 'js-selectApplications-group', resultNumber: 'js-selectApplications-resultsNumber', resetButton: 'js-resetFilter-trigger', changeDisplayTarget: '.js-changeDisplay-target', articlesList: '.js-articlesList', categoriesList: '.js-articlesList-categories', pagerList: '.js-pagerList', listItem: '.prd-pager-body', prevButton: '.js-pagerList-prevButton', pagerButton: '.js-pagerList-pagerButton', nextButton: '.js-pagerList-nextButton', spPrevButton: '.prd-largeScreen-hidden.js-pagerList-prevButton', spNextButton: '.prd-largeScreen-hidden.js-pagerList-nextButton' }; this.templateIdName = { articles: 'js-articlesList-articlesTemplate', categories: 'js-articlesList-categoriesTemplate', prevButton: 'js-pagerList-prevButtonTemplate', pager: 'js-pagerList-pagerTemplate', omit: 'js-pagerList-omitTemplate', nextButton: 'js-pagerList-nextButtonTemplate' }; this.applicationFilter = doc.getElementById(this.selectors.applicationFilter); this.categoryFilterTrigger = doc.getElementById(this.selectors.categoryFilterTrigger); this.productFilterTrigger = doc.getElementById(this.selectors.productFilterTrigger); this.allCheckBoxItem = null; this.categoryCheckBoxItems = null; this.categoryParamValue = ''; this.productParamValue = ''; this.resultNumber = doc.getElementById(this.selectors.resultNumber); this.articlesTarget = doc.querySelector(this.selectors.articlesList); this.articleTemplate = doc.getElementById(this.templateIdName.articles); this.categoriesTemplate = doc.getElementById(this.templateIdName.categories); this.pagerTarget = doc.querySelector(this.selectors.pagerList); this.prevButtonTemplate = doc.getElementById(this.templateIdName.prevButton); this.pagerTemplate = doc.getElementById(this.templateIdName.pager); this.omitTemplate = doc.getElementById(this.templateIdName.omit); this.nextButtonTemplate = doc.getElementById(this.templateIdName.nextButton); this.currentNumber = 1; this.resetButton = doc.getElementById(this.selectors.resetButton); this.changeDisplayTarget = doc.querySelectorAll(this.selectors.changeDisplayTarget); this.resetEvent = { handleEvent: null }; } init() { if (!this.applicationFilter || !this.categoryFilterTrigger || !this.productFilterTrigger) { return; } this.allCheckBoxItem = this.applicationFilter.querySelector('[name="all"]'); this.categoryCheckBoxItems = this.applicationFilter.querySelectorAll('[name="category"]'); if (!this.allCheckBoxItem || !this.categoryCheckBoxItems.length) { return; } this.attachChangeEvent(); this.getAllCategoryValue(); this.getFilterParam(); this.updateTriggerStatus(); this.setSelectedData(); this.getApiData(); this.setMutationObserver(); CONFIG.SMALL_SCREEN.addEventListener('change', this.getApiData.bind(this)); } attachChangeEvent() { this.allCheckBoxItem.addEventListener('change', this.setSelectedData.bind(this)); this.productFilterTrigger.addEventListener('change', this.setSelectedData.bind(this)); this.categoryCheckBoxItems.forEach((item) => { item.addEventListener('change', this.setSelectedData.bind(this)); }); } getAllCategoryValue() { this.allCategoryIdArray = Utility.getCheckedData(this.categoryCheckBoxItems); if (this.allCategoryIdArray.length) { this.allCategoryId = Utility.getJoinedArray(this.allCategoryIdArray); } } getFilterParam() { this.categoryParamValue = Utility.getParam(CONFIG.CATEGORY_PARAM); this.productParamValue = Utility.getParam(CONFIG.PRODUCTS_PARAM); } updateTriggerStatus() { if (this.categoryParamValue) { this.changeChecked(); } if (this.productParamValue) { this.selectOption(); } } changeChecked() { let checkbox = null; this.categoryCheckBoxItems.forEach((item) => { item.checked = false; }); this.categoryParamValue.split(',').forEach((data) => { if (data === '') { return; } checkbox = this.categoryFilterTrigger.querySelector('[value="' + data + '"]'); if (checkbox) { checkbox.checked = true; } }); if (this.categoryParamValue === this.allCategoryId) { this.allCheckBoxItem.checked = true; } else { this.allCheckBoxItem.checked = false; this.allCheckBoxItem.indeterminate = true; } } selectOption() { let targetOption = null; if (this.productParamValue) { targetOption = this.productFilterTrigger.querySelector('[value="' + this.productParamValue + '"]'); if (targetOption) { targetOption.selected = true; } } } setSelectedData() { const checkedItems = this.categoryFilterTrigger.querySelectorAll('[name="category"]:checked'); const selectedNumber = this.productFilterTrigger.selectedIndex; let checkedValueArray = []; let checkedValue = ''; let selectedValue = ''; if (checkedItems.length) { checkedValueArray = Utility.getCheckedData(checkedItems); checkedValue = Utility.getJoinedArray(checkedValueArray); this.applicationFilter.dataset.selectedCategory = checkedValue; } else { this.applicationFilter.dataset.selectedCategory = ''; } if (Utility.checkNumber(selectedNumber)) { selectedValue = this.productFilterTrigger[selectedNumber].value; this.applicationFilter.dataset.selectedGroup = selectedValue; } } setApiUrl() { const apiUrl = new URL(API_PATH.APPLICATIONS); const newParam = new URLSearchParams(''); const paramCategory = Utility.getParam(CONFIG.CATEGORY_PARAM); const paramCaseTag = Utility.getParam(CONFIG.PRODUCTS_PARAM); const paramIndex = Utility.getParam(CONFIG.INDEX_PARAM); let paramOffset = null; newParam.set(CONFIG.APPLICATION_CATEGORY_GROUP_API_PARAM, CONFIG.APPLICATION_CATEGORY_GROUP_API_DATA); newParam.set(CONFIG.SITE_API_PARAM, GLOBAL_SETTINGS.SITE_ID); newParam.set(CONFIG.LANGUAGE_API_PARAM, GLOBAL_SETTINGS.SITE_LANG); newParam.set(CONFIG.LIMIT_API_PARAM, CONFIG.MAX_ARTICLES); if (paramIndex !== null && paramIndex !== '1') { paramOffset = (paramIndex * CONFIG.MAX_ARTICLES) - CONFIG.MAX_ARTICLES; newParam.set(CONFIG.OFFSET_API_PARAM, paramOffset); } else { newParam.set(CONFIG.OFFSET_API_PARAM, 0); } if (paramCategory) { newParam.set(CONFIG.CATEGORY_API_PARAM, paramCategory); } else { newParam.delete(CONFIG.CATEGORY_API_PARAM); } if (paramCaseTag) { newParam.set(CONFIG.PRODUCTS_API_PARAM, paramCaseTag); } else { newParam.delete(CONFIG.PRODUCTS_API_PARAM); } this.newApiUrl = apiUrl + newParam.toString(); return this.newApiUrl; } getApiData() { const apiUrl = this.setApiUrl(); fetch(apiUrl).then((response) => { if (!response.ok) { throw new Error('Response was not OK'); } else { return response.json(); } }).then((data) => { this.totalArticleItems = data.total ? data.total : 0; this.applicationsObjArray = data.cases.length ? data.cases : []; this.totalArticleLength = this.applicationsObjArray.length; this.setResultNumber(); this.getCurrentIndex(); this.setArticlesHtml(); if (CONFIG.SMALL_SCREEN.matches) { this.setPagerHtmlSp(); } else { this.setPagerHtml(); } }).catch((error) => { console.error(error); }); } getCurrentIndex() { const param = Utility.getParam(CONFIG.INDEX_PARAM); const newParam = Utility.checkNumber(param) ? parseFloat(param) : null; if (newParam) { this.currentNumber = newParam; } } setResultNumber() { this.resultNumber.textContent = this.totalArticleItems; } setArticlesHtml() { const fragment = doc.createDocumentFragment(); const startItemIndex = 0; const displayArticleItems = this.totalArticleLength; const newParam = new URLSearchParams(''); const paramCategory = Utility.getParam(CONFIG.CATEGORY_PARAM); const paramCaseTag = Utility.getParam(CONFIG.PRODUCTS_PARAM); const paramIndex = Utility.getParam(CONFIG.INDEX_PARAM); if (!this.articlesTarget) { return; } if (this.totalArticleLength === 0) { this.articlesTarget.innerHTML = ''; this.displayResetButton(); return; } if (paramCategory) { newParam.set(CONFIG.CATEGORY_PARAM, paramCategory); } if (paramCaseTag) { newParam.set(CONFIG.PRODUCTS_PARAM, paramCaseTag); } if (paramIndex) { newParam.set(CONFIG.INDEX_PARAM, paramIndex); } this.hideResetButton(); this.articlesTarget.innerHTML = ''; for (let i = startItemIndex; i < displayArticleItems; i++) { const articleClone = this.articleTemplate ? this.articleTemplate.content.cloneNode(true) : null; const articleUrl = articleClone ? articleClone.querySelector(`[data-articles="${APPLICATIONS_DATA.URL}"]`) : null; const articleImage = articleClone ? articleClone.querySelectorAll(`[data-articles="${APPLICATIONS_DATA.IMAGE}"]`) : null; const articleTitle = articleClone ? articleClone.querySelector(`[data-articles="${APPLICATIONS_DATA.TITLE}"]`) : null; const articleDescription = articleClone ? articleClone.querySelector(`[data-articles="${APPLICATIONS_DATA.DESCRIPTION}"]`) : null; const articleListCategories = articleClone ? articleClone.querySelector(this.selectors.categoriesList) : null; const articleObj = this.applicationsObjArray[i]; for (const key in articleObj) { if (articleObj.hasOwnProperty(key)) { switch (key) { case APPLICATIONS_DATA.URL: if (articleUrl) { if (articleObj[key] === null || articleObj[key] === '') { articleUrl.removeAttribute('href'); } else { if (paramCategory || paramCaseTag || paramIndex) { articleUrl.href = articleObj[key] + '&' + newParam.toString(); } else { articleUrl.href = articleObj[key]; } } } break; case APPLICATIONS_DATA.IMAGE: if (articleImage.length) { articleImage.forEach((item) => { if (articleObj[key] === null || articleObj[key] === '') { item.src = ''; } else { item.src = articleObj[key]; } }); } break; case APPLICATIONS_DATA.TITLE: if (articleTitle) { if (articleObj[key] === null || articleObj[key] === '') { articleTitle.remove(); } else { articleTitle.textContent = Utility.notElementText(articleObj[key]); } } break; case APPLICATIONS_DATA.DESCRIPTION: if (articleDescription) { if (articleObj[key] === null || articleObj[key] === '') { articleDescription.remove(); } else { articleDescription.textContent = Utility.notElementText(articleObj[key]); } } break; case APPLICATIONS_DATA.OPTIONS: if (articleListCategories) { if (articleObj[key] === null || articleObj[key].length === 0) { articleListCategories.remove(); } else { articleListCategories.append(this.setCategoriesHtml(articleObj[key].categories)); } } break; default: break; } } } fragment.appendChild(articleClone); } this.articlesTarget.append(fragment); } setCategoriesHtml(categoriesList) { const fragment = doc.createDocumentFragment(); for (let i = 0; i < categoriesList.length; i++) { const categoriesClone = this.categoriesTemplate ? this.categoriesTemplate.content.cloneNode(true) : null; const articleCategories = categoriesClone ? categoriesClone.querySelector(`[data-articles="${APPLICATIONS_DATA.CATEGORIES}"]`) : null; if (articleCategories) { articleCategories.textContent = categoriesList[i].displayName; fragment.appendChild(categoriesClone); } } return fragment; } displayResetButton() { if (!this.resetButton) { return; } this.resetEvent.handleEvent = this.resetFilter.bind(this); this.changeDisplayTarget.forEach((item) => { item.classList.remove(CONFIG.IS_HIDE); }); this.resetButton.addEventListener('click', this.resetEvent, false); } resetFilter() { this.productFilterTrigger.options[0].selected = true; if (!this.allCheckBoxItem.checked) { this.allCheckBoxItem.indeterminate = false; this.allCheckBoxItem.checked = false; } this.categoryCheckBoxItems.forEach((item) => { item.checked = false; }); this.hideResetButton(); this.setSelectedData(); win.scroll({top: 0}); } hideResetButton() { if (!this.changeDisplayTarget.length) { return; } this.changeDisplayTarget.forEach((item) => { item.classList.add(CONFIG.IS_HIDE); }); this.resetButton.removeEventListener('click', this.resetEvent, false); } setMutationObserver() { const observerConfig = { attributes: true, attributeOldValue: true }; const callback = (record) => { record.forEach((data) => { if (!data) { return; } if (((data.attributeName === 'data-selected-category') && (data.oldValue !== data.target.dataset.selectedCategory)) || ((data.attributeName === 'data-selected-group') && (data.oldValue !== data.target.dataset.selectedGroup))) { this.currentNumber = 1; this.updateFilterParam(); this.getApiData(); } }); }; const observer = new MutationObserver(callback.bind(this)); observer.observe(this.applicationFilter, observerConfig); } updateFilterParam() { const urlSearchParams = new URLSearchParams(location.search); const categoryFilterDate = this.applicationFilter.dataset.selectedCategory; const productFilterDate = this.applicationFilter.dataset.selectedGroup; const baseUrl = urlSearchParams.toString(); const urlHash = location.hash; if (categoryFilterDate) { urlSearchParams.set(CONFIG.CATEGORY_PARAM, categoryFilterDate); } else { urlSearchParams.delete(CONFIG.CATEGORY_PARAM); } if (productFilterDate) { urlSearchParams.set(CONFIG.PRODUCTS_PARAM, productFilterDate); } else { urlSearchParams.delete(CONFIG.PRODUCTS_PARAM); } urlSearchParams.delete(CONFIG.INDEX_PARAM); if (baseUrl === urlSearchParams.toString()) { return; } if (urlSearchParams.toString() === '') { history.pushState(null, null, location.pathname + urlHash); } else { history.pushState(null, null, `?${urlSearchParams.toString()}${urlHash}`); } } setPagerHtml() { const fragment = doc.createDocumentFragment(); const pageRange = 2; const totalPage = Math.ceil(this.totalArticleItems / CONFIG.MAX_ARTICLES); let rangeStart = this.currentNumber - pageRange; let rangeEnd = this.currentNumber + pageRange; const displayPages = []; const items = []; let previousPage; if (!this.pagerTarget) { return; } this.pagerTarget.innerHTML = ''; if (!this.totalArticleLength) { this.pagerTarget.classList.add(CONFIG.IS_HIDE); return; } this.pagerTarget.classList.remove(CONFIG.IS_HIDE); if (rangeEnd > totalPage) { rangeEnd = totalPage; rangeStart = totalPage - (pageRange * 2); rangeStart = rangeStart < 1 ? 1 : rangeStart; } if (rangeStart <= 1) { rangeStart = 1; rangeEnd = Math.min((pageRange * 2) + 1, totalPage); } if (rangeStart <= 3) { for (let i = 1; i < rangeStart; i++) { displayPages.push(i); } } else { displayPages.push(1); } for (let i = rangeStart; i <= rangeEnd; i++) { displayPages.push(i); } if (rangeEnd >= totalPage - 2) { for (let i = rangeEnd + 1; i <= totalPage; i++) { displayPages.push(i); } } else { displayPages.push(totalPage); } if (this.currentNumber !== 1) { const newPrevList = this.createPrevListContents(); fragment.append(newPrevList); } for (const page of displayPages) { if ((page - previousPage) === 2) { const pagerListItem = this.createPagerListContents(previousPage + 1); fragment.append(pagerListItem); } else if ((page - previousPage) > 2) { const omitClone = this.omitTemplate ? this.omitTemplate.content.cloneNode(true) : null; const omitItem = omitClone ? omitClone.querySelector(this.selectors.listItem) : null; fragment.append(omitItem); } items.push(page); const pagerListItem = this.createPagerListContents(page); fragment.append(pagerListItem); previousPage = page; } if (this.currentNumber !== totalPage) { const newNextList = this.createNextListContents(); fragment.append(newNextList); } this.pagerTarget.append(fragment); this.setCurrent(); } setPagerHtmlSp() { const fragment = doc.createDocumentFragment(); const totalPage = Math.ceil(this.totalArticleItems / CONFIG.MAX_ARTICLES); const displayPages = []; const items = []; let startPage = 1; let previousPage; if (!this.pagerTarget) { return; } this.pagerTarget.innerHTML = ''; if (!this.totalArticleLength) { this.pagerTarget.classList.add(CONFIG.IS_HIDE); return; } this.pagerTarget.classList.remove(CONFIG.IS_HIDE); if (totalPage > CONFIG.SP_MAX_PAGERS) { if (this.currentNumber > Math.ceil((CONFIG.SP_MAX_PAGERS / 2))) { startPage = (this.currentNumber + 1) - (Math.ceil((CONFIG.SP_MAX_PAGERS / 2))); if (startPage + (CONFIG.SP_MAX_PAGERS - 1) > totalPage) { startPage = totalPage - (CONFIG.SP_MAX_PAGERS - 1); } } } for (let i = 0; i < CONFIG.SP_MAX_PAGERS; i++) { displayPages.push(startPage); startPage++; if (startPage > totalPage) { break; } } if (this.currentNumber !== 1) { const newPrevList = this.createPrevListContents(); fragment.append(newPrevList); } for (const page of displayPages) { if ((page - previousPage) === 2) { const pagerListItem = this.createPagerListContents(previousPage + 1); fragment.append(pagerListItem); } items.push(page); const pagerListItem = this.createPagerListContents(page); fragment.append(pagerListItem); previousPage = page; } if (this.currentNumber !== totalPage) { const newNextList = this.createNextListContents(); fragment.append(newNextList); } this.pagerTarget.append(fragment); this.setCurrent(); } createPagerListContents(item) { const pagerClone = this.pagerTemplate ? this.pagerTemplate.content.cloneNode(true) : null; const pagerButton = pagerClone ? pagerClone.querySelector(this.selectors.pagerButton) : null; const pagerListItem = pagerClone ? pagerClone.querySelector(this.selectors.listItem) : null; if (pagerButton) { pagerButton.textContent = item; pagerButton.dataset.pageNumber = item; pagerButton.addEventListener('click', this.onClickPagerButton.bind(this)); } return pagerListItem; } createPrevListContents() { const prevButtonClone = this.prevButtonTemplate ? this.prevButtonTemplate.content.cloneNode(true) : null; const pcPrevButton = prevButtonClone ? prevButtonClone.querySelector(this.selectors.prevButton) : null; const spPrevButton = prevButtonClone ? prevButtonClone.querySelector(this.selectors.spPrevButton) : null; const prevListItem = prevButtonClone ? prevButtonClone.querySelector(this.selectors.listItem) : null; let prevButton; if (CONFIG.SMALL_SCREEN.matches) { prevButton = spPrevButton; } else { prevButton = pcPrevButton; } if (prevButton) { prevButton.addEventListener('click', this.onClickForPrevButton.bind(this)); } return prevListItem; } createNextListContents() { const nextButtonClone = this.nextButtonTemplate ? this.nextButtonTemplate.content.cloneNode(true) : null; const pcNextButton = nextButtonClone ? nextButtonClone.querySelector(this.selectors.nextButton) : null; const spNextButton = nextButtonClone ? nextButtonClone.querySelector(this.selectors.spNextButton) : null; const nextListItem = nextButtonClone ? nextButtonClone.querySelector(this.selectors.listItem) : null; let nextButton; if (CONFIG.SMALL_SCREEN.matches) { nextButton = spNextButton; } else { nextButton = pcNextButton; } if (nextButton) { nextButton.addEventListener('click', this.onClickForNextButton.bind(this)); } return nextListItem; } setCurrent() { const pagerButton = doc.querySelectorAll(this.selectors.pagerButton); if (pagerButton.length) { pagerButton.forEach((targetButton) => { const dataNumber = Utility.checkNumber(targetButton.dataset.pageNumber) ? parseFloat(targetButton.dataset.pageNumber) : null; if (this.currentNumber === dataNumber) { targetButton.classList.add(CONFIG.IS_CURRENT); targetButton.setAttribute('disabled', true); } else { targetButton.classList.remove(CONFIG.IS_CURRENT); targetButton.removeAttribute('disabled', true); } }); } } onClickPagerButton(event) { const dataNumber = event.target.dataset.pageNumber; const currentNumber = Utility.checkNumber(dataNumber) ? parseFloat(dataNumber) : null; this.currentNumber = currentNumber; this.changePageItems(); } onClickForPrevButton() { const currentNumber = this.currentNumber; this.currentNumber = currentNumber - 1; this.changePageItems(); } onClickForNextButton() { const currentNumber = this.currentNumber; this.currentNumber = currentNumber + 1; this.changePageItems(); } changePageItems() { this.setPagerParam(); this.getApiData(); win.scroll({top: 0}); } setPagerParam() { const urlSearchParams = new URLSearchParams(location.search); urlSearchParams.set(CONFIG.INDEX_PARAM, this.currentNumber); history.pushState(null, null, `?${urlSearchParams.toString()}`); } } doc.addEventListener('DOMContentLoaded', () => { const selectApplications = new SelectApplications(); selectApplications.init(); }); })(window, document);