fix: 🐛 Click on toggle with trigger twice the toggle action

This commit is contained in:
Jérémy Munsch 2024-05-29 14:36:43 +02:00
parent 89a05cb342
commit f38236dcda
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC

View file

@ -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<string, keyof typeof CookieStatus>;
type CookieStatusList = Record<string, CookieStatus>;
type CookiePolicy = {
sameSite: CookiePolicySameSite;