diff --git a/src/ts/index.ts b/src/ts/index.ts index 71ee7af..2d887c1 100644 --- a/src/ts/index.ts +++ b/src/ts/index.ts @@ -360,6 +360,21 @@ export default class CookieNotice { ); } + /** + * Get a cookie status + * + * @param key + * @returns + */ + getCookieStatus(key: string): CookieStatus { + const statusList: CookieStatusList = this.getCookieStatusList(); + const cookieIndex = Object.keys(statusList).find((cookieName) => cookieName === key); + if (cookieIndex === undefined) { + throw new Error(`Cookie options ${key} not found in list`); + } + return statusList[cookieIndex]; + } + /** * Set the cookie value * @@ -748,22 +763,16 @@ export default class CookieNotice { cnSwitch.setAttribute("aria-labelledby", `${cookieName}-desc`); cnSwitch.setAttribute("aria-describedby", `${cookieName}-desc`); - const toggleCookie = (activate:boolean) => { + const toggleCookie = (cookieName: string) => { + const cookieStatus = this.getCookieStatus(cookieName); this.setCookieStatus( cookieName, - activate ? CookieStatus.true : CookieStatus.false, + this.invertCookieStatus(cookieStatus), cookieConfig ); }; - this.addEvent(cnSwitch, "click", () => { - toggleCookie(cnSwitchInput.checked); - cnSwitch.ariaChecked = cnSwitchInput.checked ? "true" : "false"; - }); - this.addEventKbdValidate(cnSwitch, () => { - toggleCookie(cnSwitchInput.checked); - cnSwitchInput.checked = !cnSwitchInput.checked; - cnSwitch.ariaChecked = cnSwitchInput.checked ? "true" : "false"; - }); + this.addEvent(cnSwitchInput, "click", () => toggleCookie(cookieName)); + this.addEventKbdValidate(cnSwitch, () => cnSwitchInput.click()); this.cookiesUnorderedList.append(cookie); @@ -845,6 +854,24 @@ export default class CookieNotice { isOnBannerPage(): boolean { return this.modalContainer.classList.contains("d-none"); } + + /** + * Invert cookie status + * + * @param status + * @returns Inverted cookie status, `wait` will give `false`. + */ + private invertCookieStatus(status: CookieStatus): CookieStatus { + switch (status) { + case CookieStatus.true: + case CookieStatus.wait: + return CookieStatus.false; + case CookieStatus.false: + return CookieStatus.true; + default: + throw new Error(`Un handled cookie status ${status}`); + } + } } enum CookieStatus { @@ -853,7 +880,7 @@ enum CookieStatus { wait = "wait", } -type CookieStatusList = Record; +type CookieStatusList = Record; type CookiePolicy = { sameSite: CookiePolicySameSite;