From a51dd88254e53df978eb6110281cc60466710c25 Mon Sep 17 00:00:00 2001 From: Orest Bida Date: Sun, 23 Apr 2023 23:01:06 +0200 Subject: [PATCH] Feat: discard unsaved preferences on modal close (ref. #481) --- src/core/api.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/core/api.js b/src/core/api.js index a5731faf..d84dc2a6 100644 --- a/src/core/api.js +++ b/src/core/api.js @@ -277,6 +277,41 @@ export const showPreferences = () => { fireEvent(globalObj._customEvents._onModalShow, PREFERENCES_MODAL_NAME); }; +/** + * https://github.com/orestbida/cookieconsent/issues/481 + */ +const discardUnsavedPreferences = () => { + + const consentIsValid = validConsent(); + const allDefinedCategories = globalObj._state._allDefinedCategories; + const categoryInputs = globalObj._dom._categoryCheckboxInputs; + const serviceInputs = globalObj._dom._serviceCheckboxInputs; + + /** + * @param {string} category + */ + const categoryEnabledByDefault = (category) => globalObj._state._userConfig.mode === OPT_OUT_MODE && !!allDefinedCategories[category].enabled; + + for(const category in categoryInputs) { + + const isReadOnly = !!allDefinedCategories[category].readOnly; + + categoryInputs[category].checked = isReadOnly || (consentIsValid + ? acceptedCategory(category) + : categoryEnabledByDefault(category) + ); + + for(const service in serviceInputs[category]) { + serviceInputs[category][service].checked = isReadOnly || (consentIsValid + ? acceptedService(service, category) + : categoryEnabledByDefault(category) + ); + } + } + + +}; + /** * Hide preferences modal */ @@ -289,6 +324,8 @@ export const hidePreferences = () => { state._preferencesModalVisible = false; + discardUnsavedPreferences(); + /** * Fix focus restoration */