ldc-web-cookie-notice/dist/browser/cookie-cn.js
2024-06-04 15:37:41 +02:00

1 line
12 KiB
JavaScript
Vendored

!function(){class e{constructor(e){this.browserCookieName="cn-init",this.cookieTimeLife=6,this.cookieExpirationName="_expiration",this.cookiePolicies={sameSite:o.lax,secure:""},this.config=e;let i=this.readCookiesExpirationDate();i||(i=new Date,i.setMonth(i.getMonth()+this.cookieTimeLife)),this.cookieExpirationDate=i;const n=document.createElement("div");n.classList.add("cn-modal-bg"),document.body.append(n),this.modalBg=n;const s=document.querySelector("div#cn-wrapper"),a=document.querySelector("button#cn-cookie-btn"),r=document.querySelector("button#cn-close-modal"),c=document.querySelectorAll(".cn-cookie-link"),l=document.querySelector("div#cn-banner"),d=document.querySelector("div.cn-banner-content"),h=document.querySelector("div.cn-modal-container"),u=document.querySelector("button#cn-accept-banner"),k=document.querySelector("button#cn-deny-banner"),C=document.querySelector("button#cn-settings-banner"),m=document.querySelector("ul#cn-modal-list"),b=document.querySelector("div.cn-modal-wrapper"),p=document.querySelector("div#cn-li-template");if(!s)throw new Error("Cannot find div#cn-wrapper");if(!a)throw new Error("Cannot find 'button#cn-cookie-btn' element");if(!r)throw new Error("Cannot find 'button#cn-close-modal' element");if(!l)throw new Error("Cannot find 'div#cn-banner' element");if(!d)throw new Error("Cannot find 'div.cn-banner-content' element");if(!h)throw new Error("Cannot find 'div.cn-modal-container' element");if(!u)throw new Error("Cannot find 'button#cn-accept-banner' element");if(!k)throw new Error("Cannot find 'button#cn-deny-banner' element");if(!C)throw new Error("Cannot find 'button.cn-settings-banner' element");if(!m)throw new Error("Cannot find 'ul#cn-modal-list' element");if(!b)throw new Error("Cannot find 'div.cn-modal-wrapper' element");if(!p)throw new Error("Cannot find 'div#cn-li-template' element");this.cookieShowModalBtn=a,this.cookieCloseModalBtn=r,this.cookieLinkShowCustomizeModalList=c,this.cookieContainer=s,this.bannerContainer=l,this.bannerContent=d,this.cookiesUnorderedList=m,this.modalWrapper=b,this.modalContainer=h,this.acceptAllBtn=u,this.denyAllBtn=k,this.customizeBtn=C,this.template=p;const g=this.template.cloneNode(!0);this.template.remove(),this.template=g,this.restrictCloseModal=!0,this.addEventPrevent(this.modalBg,"click",this.closeCookieModal),this.addEventPrevent(this.cookieCloseModalBtn,"click",this.closeCookieModal),this.addEventPrevent(this.acceptAllBtn,"click",this.acceptAllCookies),this.addEventPrevent(this.denyAllBtn,"click",this.denyAllCookies),this.addEventPrevent(this.customizeBtn,"click",this.switchToModalPageOrClose),this.addEventPrevent(this.cookieShowModalBtn,"click",this.toggleCookieModal),this.cookieLinkShowCustomizeModalList.forEach((e=>{this.addEventPrevent(e,"click",this.openCookieModalToCookiePage),this.addEventKbdValidate(e,this.openCookieModalToCookiePage)})),this.cookiesMatchesConfig()&&!this.cookiesOlderThan(new Date)||(this.resetBrowserCookie(),this.openCookieModalToBannerPage()),this.updateRestrictCloseModal(),Object.entries(this.getCookieStatusList()).forEach((([e,o])=>{o!==t.wait?this.config[e]&&(o!==t.true?null!=this.config[e].fallback&&this.config[e].fallback():this.config[e].script()):this.openCookieModalToBannerPage()}))}updateRestrictCloseModal(){this.restrictCloseModal=!!Object.values(this.getCookieStatusList()).includes(t.wait),this.restrictCloseModal?this.cookieCloseModalBtn.classList.add("d-none"):this.cookieCloseModalBtn.classList.remove("d-none"),this.restrictCloseModal?this.modalBg.classList.add("cn-modal-bg-active"):this.modalBg.classList.remove("cn-modal-bg-active")}readCookiesExpirationDate(){var e;const t=(null!==(e=this.getBrowserCookieValue())&&void 0!==e?e:"").split(",").find((e=>e.startsWith(this.cookieExpirationName)));if(!t)return null;try{const e=Number.parseInt(t.replace(`${this.cookieExpirationName}=`,""));return isNaN(e)?null:new Date(e)}catch(e){return null}}cookiesOlderThan(e){return this.cookieExpirationDate.getTime()<e.getTime()}cookiesMatchesConfig(){const e=this.getCookieStatusList();return Object.keys(e).length===Object.keys(this.config).length}acceptAllCookies(){Object.keys(this.config).forEach((e=>this.acceptCookie(e))),this.closeCookieModal()}acceptCookie(e){const o=this.getCookie(e);this.setCookieStatus(e,t.true,o);const i=document.getElementById(`${e}-switch`),n=null==i?void 0:i.querySelector("input");i&&n&&(n.checked=!0,i.ariaChecked="true")}denyAllCookies(){Object.keys(this.config).forEach((e=>this.denyCookie(e))),this.closeCookieModal()}denyCookie(e){const o=this.getCookie(e);this.setCookieStatus(e,t.false,o);const i=document.getElementById(`${e}-switch`),n=null==i?void 0:i.querySelector("input");i&&n&&(n.checked=!1,i.ariaChecked="false")}denyAllWaitingCookies(){Object.entries(this.getCookieStatusList()).forEach((([e,o])=>{o!==t.wait||this.setBrowserCookieStatus(e,t.false)})),this.updateRestrictCloseModal()}getCookie(e){var t;const o=null===(t=Object.entries(this.config).find((t=>t[0]===e)))||void 0===t?void 0:t[1];if(void 0===o)throw new Error(`Cookie options ${e} not found in list`);return o}getCookieStatusList(){const e=this.getBrowserCookieValue(),t={};return void 0===e||e.split(",").filter((e=>!e.startsWith(this.cookieExpirationName))).forEach((e=>{const o=e.split("=");t[o[0]]=o[1]})),t}containsCookieStatus(e){const t=this.getCookieStatusList();return void 0!==Object.keys(t).find((t=>t===e))}getCookieStatus(e){const t=this.getCookieStatusList(),o=Object.keys(t).find((t=>t===e));if(void 0===o)throw new Error(`Cookie options ${e} not found in list`);return t[o]}setCookieStatus(e,o,i){o!==t.true?o!==t.false?this.setBrowserCookieStatus(e,t.wait):this.removeCookieStatus(e,i):this.addCookieStatus(e,i)}addCookieStatus(e,o){o.script&&o.script(),this.setBrowserCookieStatus(e,t.true)}removeCookieStatus(e,o){const i=document.getElementById(e);i&&i.remove(),o.fallback&&o.fallback(),this.setBrowserCookieStatus(e,t.false)}setBrowserCookieStatus(e,t){const o=this.getCookieStatusList();this.deleteBrowserCookie(),o[e]=t,this.saveBrowserCookie(o),this.updateRestrictCloseModal()}hasBrowserCookie(){return Boolean(this.getBrowserCookieValue())}getBrowserCookieValue(){const e=document.cookie.match(new RegExp("(?:^|; )"+this.browserCookieName.replace(/([.$?*|{}()[\]\\/+^])/g,"\\$1")+"=([^;]*)"));return e?decodeURIComponent(e[1]):void 0}saveBrowserCookie(e){const t=new Date,o=Object.entries(e).map((([e,t])=>`${e}=${t}`));this.cookieExpirationDate=new Date(t.setMonth(t.getMonth()+this.cookieTimeLife)),o.push(`${this.cookieExpirationName}=${this.cookieExpirationDate.getTime()}`),document.cookie=`${this.browserCookieName}=${o.join(",")};path=/${location.hostname?`;domain=${location.hostname}`:""};expires=${this.cookieExpirationDate.toUTCString()};${this.getCookiePoliciesAsString()}`}deleteBrowserCookie(){this.hasBrowserCookie()&&(document.cookie=`${this.browserCookieName}=;path=/${location.hostname?`;domain=.${location.hostname}`:""};expires=Thu, 01 Jan 1970 00:00:01 GMT;`,document.cookie=`${this.browserCookieName}=;path=/${location.hostname?`;domain=${location.hostname}`:""};expires=Thu, 01 Jan 1970 00:00:01 GMT;`)}getCookiePoliciesAsString(){return Object.entries(this.cookiePolicies).map((([e,t])=>`${e}=${t}`)).join(";")}resetBrowserCookie(){const e={};Object.entries(this.config).forEach((([o])=>e[o]=t.wait)),this.saveBrowserCookie(e)}addEvent(e,t,o){return e.addEventListener(t,o.bind(this),!1)}addEventPrevent(e,t,o){return e.addEventListener(t,(e=>{e.preventDefault(),o.call(this,e)}),!1)}addEventKbdValidate(e,t){return this.addEvent(e,"keydown",(e=>{const o=e;" "!=o.key&&"Space"!=o.code&&32!=o.keyCode&&"Enter"!=o.key&&"Enter"!=o.code&&13!=o.keyCode||(t.call(this,o),e.preventDefault())}))}toggleCookieModal(){document.body.classList.contains("cn-open")?this.closeCookieModal():this.openCookieModalToBannerPage()}openCookieModalToBannerPage(){this.openCookieModalToCookiePage(),this.toggleCookieModalPages()}openCookieModalToCookiePage(){document.body.classList.add("cn-open"),this.resetCookieModal(),this.bannerContent.classList.add("d-none"),this.modalContainer.classList.remove("d-none"),this.bannerContainer.classList.add("cn-modal-page"),this.modalWrapper.scrollTop=0,this.setupCookieModalList(),this.setTabIndex()}closeCookieModal(){if(this.updateRestrictCloseModal(),this.restrictCloseModal)throw new Error("You need to accept or refuse all cookies");document.body.classList.remove("cn-open"),this.isOnBannerPage()||(this.bannerContent.classList.toggle("d-none"),this.modalContainer.classList.toggle("d-none"),this.bannerContainer.classList.remove("cn-modal-page")),this.unsetTabIndex(),this.setupCookieModalList()}setTabIndex(){document.documentElement.setAttribute("tabindex","-1"),setTimeout((()=>{const e='a[href], button, [role="button"], input, embed, object, iframe, textarea, select, details, [tabindex]:not([tabindex="-1"])';[...document.body.querySelectorAll(e)].filter((e=>!e.hasAttribute("disabled")&&!e.getAttribute("aria-hidden")&&!this.cookieContainer.contains(e))).forEach((e=>{e.setAttribute("tabindex","-1"),e.classList.add("cn-disabled")})),[...this.cookieContainer.querySelectorAll(e)].filter((e=>!(e.hasAttribute("disabled")||e.getAttribute("aria-hidden")||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)||this.cookieContainer.contains(e)))).forEach((e=>{e.setAttribute("tabindex","0"),e.classList.remove("cn-disabled")})),this.cookieShowModalBtn.setAttribute("tabindex","-1")}),500)}unsetTabIndex(){document.documentElement.setAttribute("tabindex","0"),setTimeout((()=>{document.body.querySelectorAll(".cn-disabled").forEach((e=>{e.setAttribute("tabindex","0"),e.classList.remove("cn-disabled")})),this.cookieShowModalBtn.setAttribute("tabindex","0")}),500)}resetCookieModal(){if(this.bannerContent.classList.remove("d-none"),this.modalContainer.classList.add("d-none"),this.bannerContainer.classList.remove("cn-modal-page"),!this.customizeBtn.dataset.openModal)throw new Error("Cannot find attribut data-open-modal");this.customizeBtn.innerHTML=this.customizeBtn.dataset.openModal}setupCookieModalList(){this.cookiesUnorderedList.innerHTML="",Object.entries(this.config).forEach((([e,o])=>{const i=document.createElement("li"),n=this.template.children.item(0);if(null===n)throw new Error("Cannot find child item");i.append(n.cloneNode(!0));const s=i.querySelector("span.cn-cookie-name"),a=i.querySelector("span.cn-cookie-description"),r=i.querySelector(".cn-cookie-link"),c=i.querySelector(".cn-switch"),l=i.querySelector(".cn-switch > input");l.indeterminate=!0,l.checked=!1,s.textContent=o.name,a.id=`${e}-desc`,a.textContent=o.description,r.textContent=o.labelLink,r.setAttribute("href",o.link),c.id=`${e}-switch`,c.name=e,c.dataset.name=e,c.setAttribute("aria-labelledby",`${e}-desc`),c.setAttribute("aria-describedby",`${e}-desc`);const d=e=>{const t=this.getCookieStatus(e);this.setCookieStatus(e,this.invertCookieStatus(t),o)};this.addEvent(l,"click",(()=>d(e))),this.addEventKbdValidate(c,(()=>l.click())),this.cookiesUnorderedList.append(i),this.hasBrowserCookie()&&Object.entries(this.getCookieStatusList()).forEach((([o,i])=>{if(o===e)switch(i){case t.true:l.indeterminate=!1,l.checked=!0;break;case t.false:l.indeterminate=!1,l.checked=!1;break;case t.wait:l.indeterminate=!0,l.checked=!1}}))}))}switchToModalPageOrClose(){this.isOnBannerPage()?this.toggleCookieModalPages():this.closeCookieModal()}toggleCookieModalPages(){this.bannerContent.classList.toggle("d-none"),this.modalContainer.classList.toggle("d-none"),this.bannerContainer.classList.toggle("cn-modal-page"),this.isOnBannerPage()||(this.bannerContainer.classList.add("cn-modal-page"),this.denyAllWaitingCookies()),this.setTabIndex(),this.setupCookieModalList(),this.togglePersonalizeBtn()}togglePersonalizeBtn(){const e=this.customizeBtn.dataset;this.modalWrapper.scrollTop=0,this.bannerContent.classList.contains("d-none")?(this.customizeBtn.innerHTML=e.openModal,this.customizeBtn.title=e.openModal):(this.customizeBtn.innerHTML=e.closeModal,this.customizeBtn.title=e.closeModal)}isOnBannerPage(){return this.modalContainer.classList.contains("d-none")}invertCookieStatus(e){switch(e){case t.true:case t.wait:return t.false;case t.false:return t.true;default:throw new Error(`Un handled cookie status ${e}`)}}}var t,o;!function(e){e.true="true",e.false="false",e.wait="wait"}(t||(t={})),function(e){e.lax="lax",e.strict="strict",e.none="none"}(o||(o={}));const i=window.CookieNotice;e.noConflict=function(t=!1){return t&&window.CookieNotice===e&&(window.CookieNotice=i),e},window.CookieNotice=e.noConflict()}();