diff --git a/assets/cookie-notice/frontconsent-cookie-notice.css b/assets/cookie-notice/frontconsent-cookie-notice.css index a461752..370de1f 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.css +++ b/assets/cookie-notice/frontconsent-cookie-notice.css @@ -142,6 +142,36 @@ color: var(--frcn-cookie-text); } +/* + * "Customize cookie settings" — a secondary/outline button so it never + * competes visually with Accept/Reject: same shape and sizing as the other + * actions, but a plain border and no filled background. + */ +.frcn-cookie-notice__button--customize { + display: inline-flex; + align-items: center; + gap: 8px; + background-color: transparent; + border: 1px solid var(--frcn-cookie-accent-on-light); + color: var(--frcn-cookie-text); +} + +.frcn-cookie-notice__button-icon { + display: block; + width: 16px; + height: 16px; + flex-shrink: 0; + background-color: var(--frcn-cookie-accent-on-light); + -webkit-mask-image: var(--frcn-cookie-icon-url); + mask-image: var(--frcn-cookie-icon-url); + -webkit-mask-size: contain; + mask-size: contain; + -webkit-mask-repeat: no-repeat; + mask-repeat: no-repeat; + -webkit-mask-position: center; + mask-position: center; +} + /* Bar layout: floating bottom bar, spanning most of the viewport width. */ .frcn-cookie-notice--bar { left: 20px; @@ -390,3 +420,161 @@ body.frcn-cookie-notice-lock-scroll { .frcn-cookie-reopen[hidden] { display: none; } + +/* + * Cookie preferences panel: a true modal dialog, printed unconditionally + * (see CookieNotice::render_preferences_panel()) and hidden by default via + * the `hidden` attribute — frontconsent-cookie-notice.js removes it to open + * the dialog, from either the "Customize" button or the persistent reopen + * trigger. + */ +.frcn-cookie-preferences { + --frcn-cookie-accent: #687df9; + --frcn-cookie-accent-contrast: #ffffff; + --frcn-cookie-accent-on-light: #687df9; + --frcn-cookie-bg: #ffffff; + --frcn-cookie-text: #1f2937; + --frcn-cookie-radius: 12px; + + position: fixed; + z-index: 1000000; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + padding: 20px; + overflow-y: auto; + background-color: rgba(17, 24, 39, 0.5); + font-family: inherit; + line-height: 1.5; + box-sizing: border-box; +} + +.frcn-cookie-preferences * { + box-sizing: border-box; +} + +.frcn-cookie-preferences[hidden] { + display: none; +} + +.frcn-cookie-preferences__panel { + background-color: var(--frcn-cookie-bg); + color: var(--frcn-cookie-text); + border-radius: var(--frcn-cookie-radius); + max-width: 480px; + width: 100%; + max-height: calc(100vh - 40px); + overflow-y: auto; + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.frcn-cookie-preferences__header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.frcn-cookie-preferences__title { + margin: 0; + font-size: 18px; + font-weight: 600; + color: var(--frcn-cookie-text); +} + +.frcn-cookie-preferences__close { + appearance: none; + background: transparent; + border: none; + cursor: pointer; + font-size: 20px; + line-height: 1; + padding: 4px 8px; + color: var(--frcn-cookie-text); +} + +.frcn-cookie-preferences__close:focus-visible { + outline: 2px solid var(--frcn-cookie-accent-on-light); + outline-offset: 2px; +} + +.frcn-cookie-preferences__message { + margin: 0; + font-size: 14px; + color: var(--frcn-cookie-text); +} + +.frcn-cookie-preferences__category { + border: 1px solid rgba(31, 41, 55, 0.12); + border-radius: calc(var(--frcn-cookie-radius) / 2); + padding: 12px 16px; +} + +.frcn-cookie-preferences__category-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.frcn-cookie-preferences__category-title { + font-weight: 600; + font-size: 14px; +} + +.frcn-cookie-preferences__category-badge { + font-size: 12px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.02em; + color: var(--frcn-cookie-accent-on-light); +} + +.frcn-cookie-preferences__category-toggle { + width: 20px; + height: 20px; + flex-shrink: 0; + accent-color: var(--frcn-cookie-accent); + cursor: pointer; +} + +.frcn-cookie-preferences__category-toggle:focus-visible { + outline: 2px solid var(--frcn-cookie-accent); + outline-offset: 2px; +} + +.frcn-cookie-preferences__category-description { + margin: 8px 0 0; + font-size: 13px; + color: var(--frcn-cookie-text); +} + +.frcn-cookie-preferences__actions { + display: flex; + flex-wrap: wrap; + gap: 12px; + justify-content: flex-end; +} + +.frcn-cookie-preferences__actions .frcn-cookie-notice__button { + flex: 1 1 auto; +} + +@media (max-width: 600px) { + .frcn-cookie-preferences__panel { + max-height: calc(100vh - 24px); + } + + .frcn-cookie-preferences__actions { + flex-direction: column; + } + + .frcn-cookie-preferences__actions .frcn-cookie-notice__button { + width: 100%; + text-align: center; + } +} diff --git a/assets/cookie-notice/frontconsent-cookie-notice.js b/assets/cookie-notice/frontconsent-cookie-notice.js index 27fba1c..3f27ea1 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.js @@ -43,6 +43,67 @@ } } + /** + * The visitor's current per-category consent: the frontconsent_categories + * cookie when the visitor made an explicit choice, falling back to the + * binary accepted/rejected cookie (all allowed / none allowed) for a + * visitor who decided before categories existed. Mirrors + * CookieNotice::get_allowed_categories_default() server-side. + * + * @returns {{analytics: boolean, marketing: boolean}} + */ + function getAllowedCategories() { + var accepted = readCookie(frcnCookieNotice.cookieName) === 'accepted'; + var allowed = { analytics: accepted, marketing: accepted }; + var raw = frcnCookieNotice.categoriesCookieName ? readCookie(frcnCookieNotice.categoriesCookieName) : ''; + + if (!raw) { + return allowed; + } + + try { + var parsed = JSON.parse(raw); + + if (parsed && typeof parsed === 'object') { + Object.keys(parsed).forEach(function (key) { + allowed[key] = !!parsed[key]; + }); + } + } catch (e) { + // Malformed/tampered cookie value: keep the binary fallback. + } + + return allowed; + } + + /** + * Google Consent Mode state for a per-category map: Analytics drives + * analytics_storage, Marketing drives the three ad_* signals. + * + * @param {{analytics: boolean, marketing: boolean}} categories + * @returns {Object} + */ + function getConsentModeState(categories) { + var analytics = categories.analytics ? 'granted' : 'denied'; + var marketing = categories.marketing ? 'granted' : 'denied'; + + return { + ad_storage: marketing, + ad_user_data: marketing, + ad_personalization: marketing, + analytics_storage: analytics + }; + } + + // Lets frontconsent-script-blocker.js (and any add-on) ask about a single + // category instead of only the binary accepted/rejected decision. An + // add-on that already defined its own wins. + if (typeof frcnCookieNotice !== 'undefined' && typeof window.frcnCookieNoticeIsCategoryAllowed !== 'function') { + window.frcnCookieNoticeIsCategoryAllowed = function (category) { + return !!getAllowedCategories()[category]; + }; + } + /** * Whether a cookie name matches one of the purge patterns: an exact name * ('_gid') or a prefix ending in '*' ('_ga_*'). @@ -65,11 +126,28 @@ * visitor's device. Each cookie is expired with no domain and with every * parent domain of the current host, since tags such as GA set theirs * on the registrable domain ('.example.com') rather than the exact host. + * + * Category-aware: cookies matching frcnCookieNotice.analyticsCookies are + * kept while Analytics is allowed, and every other pattern is kept while + * Marketing is allowed — so a visitor who accepted only Analytics keeps + * `_ga` but loses `_fbp`. */ function purgeTrackingCookies() { - var patterns = Array.isArray(frcnCookieNotice.purgeCookies) ? frcnCookieNotice.purgeCookies : []; + var allowed = getAllowedCategories(); + var analyticsPatterns = Array.isArray(frcnCookieNotice.analyticsCookies) ? frcnCookieNotice.analyticsCookies : []; + var patterns = (Array.isArray(frcnCookieNotice.purgeCookies) ? frcnCookieNotice.purgeCookies : []).filter(function (pattern) { + var isAnalytics = analyticsPatterns.indexOf(pattern) !== -1; - if (!patterns.length || !document.cookie) { + return isAnalytics ? !allowed.analytics : !allowed.marketing; + }); + + if (!patterns.length) { + return; + } + + purgeTrackingStorage(patterns); + + if (!document.cookie) { return; } @@ -94,6 +172,41 @@ }); } + /** + * Same purge for localStorage/sessionStorage: some tags keep their + * identifiers there instead of (or as well as) in cookies — e.g. the + * OpenAI ChatGPT Ads pixel's `oaiq_cs:` session entry. + * Storage access can throw (blocked site data, private windows), so each + * store is handled on its own and failures are ignored. + * + * @param {string[]} patterns Purge patterns already filtered by category. + */ + function purgeTrackingStorage(patterns) { + ['localStorage', 'sessionStorage'].forEach(function (storeName) { + try { + var store = window[storeName]; + + if (!store) { + return; + } + + var keys = []; + + for (var i = 0; i < store.length; i++) { + keys.push(store.key(i)); + } + + keys.forEach(function (key) { + if (key && matchesPurgePattern(key, patterns)) { + store.removeItem(key); + } + }); + } catch (e) { + // Storage unavailable: nothing to purge. + } + }); + } + function defineActivateGatedHelper() { window.frcnCookieNoticeActivateGated = window.frcnCookieNoticeActivateGated || function (allowedCategories) { if (allowedCategories && !allowedCategories.analytics) { @@ -274,13 +387,7 @@ window.dataLayer.push(arguments); }; - var granted = readCookie(frcnCookieNotice.cookieName) === 'accepted' ? 'granted' : 'denied'; - var state = { - ad_storage: granted, - ad_user_data: granted, - ad_personalization: granted, - analytics_storage: granted - }; + var state = getConsentModeState(getAllowedCategories()); // An add-on tracking per-category consent (analytics vs. marketing) // can define this — reading its own cookie the same way — to send the @@ -329,37 +436,17 @@ window.frcnCookieNoticeBootstrapped = true; } - function hideBannerIfDecided(banner) { - var consent = readCookie(frcnCookieNotice.cookieName); - - // An add-on tracking per-category consent (analytics vs. marketing) can - // define this to say "the categories cookie is stale — e.g. the site - // admin just added a new integration — so re-prompt even though the - // legacy accepted/rejected cookie here still looks decided." - if (typeof window.frcnCookieNoticeIsConsentStale === 'function' && window.frcnCookieNoticeIsConsentStale()) { - return false; - } - - if (banner && (consent === 'accepted' || consent === 'rejected')) { - banner.style.display = 'none'; - return true; - } - - return false; - } - /** * Reveal the persistent "Cookie preferences" trigger once a decision - * cookie exists, and wire it to let the visitor withdraw an acceptance or - * replace a rejection at any time — the only way to do so short of - * deleting the cookie by hand. Reloading the page after clearing the - * cookie is deliberately simple: it lets the server render a fresh, - * undecided banner exactly the way a first-time visitor gets one, - * instead of duplicating that logic client-side. + * cookie exists, and wire it to open the same preferences panel the + * "Customize cookie settings" button opens — the only way to reach it + * again once the original banner is gone. Bound once per page load + * (reopenTriggerWired), same as before; only reveal is repeated when this + * is called again right after an in-page decision. */ var reopenTriggerWired = false; - function setUpReopenTrigger() { + function setUpReopenTrigger(openPreferences) { var reopenBtn = document.getElementById('frcn-cookie-reopen'); if (!reopenBtn) { @@ -383,15 +470,8 @@ reopenTriggerWired = true; reopenBtn.addEventListener('click', function () { - document.cookie = frcnCookieNotice.cookieName + '=; path=' + frcnCookieNotice.cookiePath + '; max-age=0; SameSite=Lax'; - // Withdrawing consent must not leave behind what was set while it - // was granted: the page reloads undecided, so nothing is allowed. - purgeTrackingCookies(); - - if (frcnCookieNotice.isPolicyPage && frcnCookieNotice.homeUrl) { - window.location.href = frcnCookieNotice.homeUrl; - } else { - window.location.reload(); + if (typeof openPreferences === 'function') { + openPreferences(reopenBtn); } }); } @@ -411,31 +491,6 @@ rejected: 'Cookies rejected.' }; - requestTrackingIfNeeded(); - setUpReopenTrigger(); - - // A rejected visitor may still carry cookies from before the decision - // (an earlier acceptance, or a tag that ran before FrontConsent was - // installed): clear them on every page view. - if (readCookie(frcnCookieNotice.cookieName) === 'rejected') { - purgeTrackingCookies(); - } - - var banner = document.getElementById('frcn-cookie-notice'); - - if (!banner) { - return; - } - - if (hideBannerIfDecided(banner)) { - // Already decided: nothing left to wire up. - return; - } - - var acceptBtn = banner.querySelector('[data-frcn-cookie-action="accept"]'); - var rejectBtn = banner.querySelector('[data-frcn-cookie-action="reject"]'); - var isPopup = banner.classList.contains('frcn-cookie-notice--popup'); - var previouslyFocused = document.activeElement; var announcer = document.getElementById('frcn-cookie-notice-announcer'); /** @@ -451,45 +506,242 @@ } } - revealBanner(); + // Hoisted out of any "if (banner) { ... }" gate: the preferences panel + // (and the reopen trigger that opens it) must keep working even when + // the main banner markup isn't rendered at all — e.g. on the + // configured cookie policy page — so the decision-recording flow + // below can't depend on the banner existing. + var decided = false; - if (acceptBtn) { - // preventDefault() is what stops the button's form="..." submit - // attribute (the no-JS fallback — see render_banner_markup() and - // log_consent_form_callback()) from actually navigating the page - // away when JavaScript can run: this handles the decision instead, - // entirely client-side. - acceptBtn.addEventListener('click', function (event) { - event.preventDefault(); - handleDecision('accepted'); - }); + function setConsentCookie(decision) { + var maxAge = parseInt(frcnCookieNotice.expirationDays, 10) * 24 * 60 * 60; + var secure = window.location.protocol === 'https:' ? '; Secure' : ''; + + document.cookie = frcnCookieNotice.cookieName + '=' + decision + + '; path=' + frcnCookieNotice.cookiePath + '; max-age=' + maxAge + '; SameSite=Lax' + secure; } - if (rejectBtn) { - rejectBtn.addEventListener('click', function (event) { - event.preventDefault(); - handleDecision('rejected'); - }); + /** + * Persist the visitor's actual per-category selection (e.g. + * {"analytics":true,"marketing":false}) into its own cookie, right + * alongside the binary consent cookie above — same path/max-age/ + * SameSite conventions, just a separate cookie name (see + * CookieNotice::get_categories_cookie_name()). This is what lets + * get_config_callback() build a real allowedCategories map server-side + * on the next request, purely from the normal cookie header, with no + * new AJAX plumbing needed. + * + * @param {Object} categories Category slug => bool map (see collectPreferencesCategories()). + */ + function setCategoriesCookie(categories) { + var maxAge = parseInt(frcnCookieNotice.expirationDays, 10) * 24 * 60 * 60; + var secure = window.location.protocol === 'https:' ? '; Secure' : ''; + + document.cookie = frcnCookieNotice.categoriesCookieName + '=' + encodeURIComponent(JSON.stringify(categories)) + + '; path=' + frcnCookieNotice.cookiePath + '; max-age=' + maxAge + '; SameSite=Lax' + secure; } - var customizeBtn = banner.querySelector('[data-frcn-cookie-action="customize"]'); + function updateConsentMode(categories) { + window.dataLayer = window.dataLayer || []; + window.gtag = window.gtag || function () { + window.dataLayer.push(arguments); + }; + window.gtag('consent', 'update', getConsentModeState(categories)); + } - if (customizeBtn) { - // Deliberately not routed through handleDecision(): clicking it isn't a - // decision by itself, just a request to see more detail. An add-on - // listens for this to open its own categories dialog. - customizeBtn.addEventListener('click', function () { - var event; + function dispatchConsentEvent(decision) { + var event; - try { - event = new CustomEvent('frcnCookieNoticeCustomize'); - } catch (e) { - event = document.createEvent('CustomEvent'); - event.initCustomEvent('frcnCookieNoticeCustomize', true, true, null); - } + try { + event = new CustomEvent('frcnCookieConsent', { detail: { consent: decision } }); + } catch (e) { + event = document.createEvent('CustomEvent'); + event.initCustomEvent('frcnCookieConsent', true, true, { consent: decision }); + } - document.dispatchEvent(event); + document.dispatchEvent(event); + } + + /** + * Records a decision through the exact same AJAX endpoint regardless + * of which control triggered it (Accept/Reject in the banner, or + * Accept all/Reject all/Save changes in the preferences panel) — the + * optional `categories` map is only ever additive: log_consent_callback() + * runs it through the frcn_cookie_consent_categories filter and never + * requires it for the binary accepted/rejected cookie to keep working. + */ + function logDecision(decision, categories) { + var nonceForm = new FormData(); + nonceForm.append('action', 'frcn_get_cookie_notice_log_nonce'); + + fetch(frcnCookieNotice.ajaxUrl, { + method: 'POST', + credentials: 'same-origin', + body: nonceForm + }) + .then(function (response) { + return response.json(); + }) + .then(function (response) { + if (!response || !response.success || !response.data) { + return; + } + + var formData = new FormData(); + formData.append('action', 'frcn_log_cookie_consent'); + formData.append('nonce', response.data.nonce); + formData.append('decision', decision); + + if (categories) { + formData.append('categories', JSON.stringify(categories)); + } + + return fetch(frcnCookieNotice.ajaxUrl, { + method: 'POST', + credentials: 'same-origin', + body: formData + }); + }) + .catch(function () { + // Best-effort: the aggregate stat is not critical to the consent flow. + }); + } + + /** + * The single decision-recording code path: sets the consent cookie, + * updates Google Consent Mode, announces the outcome, hides the + * banner and preferences panel (whichever are open), reveals the + * reopen trigger, and logs the decision — used identically by the + * banner's own Accept/Reject buttons and by the preferences panel's + * Accept all/Reject all/Save changes actions, per the "no parallel + * consent logic" requirement. + * + * @param {string} decision 'accepted' or 'rejected'. + * @param {Object} categories Optional per-category map (PRO extension point). + */ + function handleDecision(decision, categories) { + if (decided) { + return; + } + + decided = true; + + // The banner's own plain Accept/Reject buttons call this with no + // `categories` argument at all — they still must record an + // explicit, real per-category state (both allowed on Accept, both + // denied on Reject) rather than leaving the categories cookie + // stale or absent, since get_config_callback() treats "cookie + // present" as "the visitor made an explicit per-category choice". + var categoriesToStore = categories || { + necessary: true, + analytics: decision === 'accepted', + marketing: decision === 'accepted' + }; + + // Captured before the new cookies overwrite it: a category that was + // allowed and is now denied means consent was (partly) withdrawn. + var previous = getAllowedCategories(); + var withdrawn = Object.keys(previous).some(function (key) { + return previous[key] && !categoriesToStore[key]; }); + + setConsentCookie(decision); + setCategoriesCookie(categoriesToStore); + updateConsentMode(categoriesToStore); + announce(decision === 'accepted' ? i18n.accepted : i18n.rejected); + hideBannerIfPresent(); + closePreferencesPanel(); + setUpReopenTrigger(openPreferencesPanel); + dispatchConsentEvent(decision); + logDecision(decision, categories); + + // A denied category must not leave behind cookies set while it was + // granted (or by a tag that ran earlier). Reads the cookies just + // written above, so only what is now denied gets deleted. + purgeTrackingCookies(); + + // Tags already running on this page can't be unloaded, so a + // withdrawal reloads it: the next page view only starts what is + // still allowed. Leaves the policy page for home, where the banner + // (and its controls) is guaranteed to render. + if (withdrawn) { + window.setTimeout(function () { + if (frcnCookieNotice.isPolicyPage && frcnCookieNotice.homeUrl) { + window.location.href = frcnCookieNotice.homeUrl; + } else { + window.location.reload(); + } + }, 300); + return; + } + + if (decision === 'accepted') { + fetchAndInjectScripts(); + } + } + + // A visitor who denied any category may still carry cookies from before + // that decision (an earlier acceptance, or a tag that ran before + // FrontConsent was installed): clear them on every page view. + var currentConsent = readCookie(frcnCookieNotice.cookieName); + + if (currentConsent === 'accepted' || currentConsent === 'rejected') { + purgeTrackingCookies(); + } + + var banner = document.getElementById('frcn-cookie-notice'); + var isPopup = !!banner && banner.classList.contains('frcn-cookie-notice--popup'); + var bannerPreviouslyFocused = document.activeElement; + var bannerModalKeydownBound = false; + + function getFocusableElements(container) { + return Array.prototype.slice.call( + container.querySelectorAll('a[href], button, input, [tabindex]:not([tabindex="-1"])') + ); + } + + function trapFocus(event) { + var focusable = getFocusableElements(banner); + + if (!focusable.length) { + return; + } + + var first = focusable[0]; + var last = focusable[focusable.length - 1]; + + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + + /** + * Keydown handler bound only while the popup (true modal) layout is + * open: Tab/Shift+Tab loop within the dialog's own focusable elements + * (trapFocus()) and Escape is treated as an explicit reject — a valid, + * equivalent consent decision, not a silent dismissal — so a keyboard + * user always has a way out that doesn't just abandon the dialog + * without a decision being recorded (see handleDecision()). + * + * Deliberately a no-op while the preferences panel is open on top of + * it — that dialog owns Tab/Escape while it's the visible one; see + * isPreferencesPanelOpen(). + */ + function handleModalKeydown(event) { + if (isPreferencesPanelOpen()) { + return; + } + + if (event.key === 'Tab') { + trapFocus(event); + } else if (event.key === 'Escape' || event.key === 'Esc') { + event.preventDefault(); + handleDecision('rejected'); + } } /** @@ -516,28 +768,66 @@ if (isPopup) { document.body.classList.add('frcn-cookie-notice-lock-scroll'); + var acceptBtnForFocus = banner.querySelector('[data-frcn-cookie-action="accept"]'); + // A true modal (the popup layout blocks the rest of the // page) must move focus into itself on open — the first // focusable control is the reject button in DOM order, // but the accept button is used here to keep the // pre-existing default behavior/tests unchanged. - if (acceptBtn) { - acceptBtn.focus({ preventScroll: true }); + if (acceptBtnForFocus) { + acceptBtnForFocus.focus({ preventScroll: true }); } document.addEventListener('keydown', handleModalKeydown); + bannerModalKeydownBound = true; } }, delay); } - function getFocusableElements() { - return Array.prototype.slice.call( - banner.querySelectorAll('a[href], button, input, [tabindex]:not([tabindex="-1"])') - ); + function hideBannerIfPresent() { + if (!banner) { + return; + } + + banner.classList.add('frcn-cookie-notice--hidden'); + document.body.classList.remove('frcn-cookie-notice-lock-scroll'); + + if (bannerModalKeydownBound) { + document.removeEventListener('keydown', handleModalKeydown); + bannerModalKeydownBound = false; + } + + if (isPopup && bannerPreviouslyFocused && typeof bannerPreviouslyFocused.focus === 'function') { + bannerPreviouslyFocused.focus({ preventScroll: true }); + } + + window.setTimeout(function () { + if (banner.parentNode) { + banner.parentNode.removeChild(banner); + } + }, 300); } - function trapFocus(event) { - var focusable = getFocusableElements(); + // --- Preferences panel: dialog opened from the "Customize cookie + // settings" button (in the banner) or the persistent reopen trigger. + // Always looked up (even when the main banner didn't render, e.g. on + // the policy page) since CookieNotice::render_preferences_panel() + // prints it unconditionally, independently of the banner markup. + var preferencesPanel = document.getElementById('frcn-cookie-preferences'); + var preferencesPanelOpener = null; + var preferencesPanelKeydownBound = false; + + function isPreferencesPanelOpen() { + return !!preferencesPanel && !preferencesPanel.hidden; + } + + function getPreferencesFocusable() { + return getFocusableElements(preferencesPanel); + } + + function trapPreferencesFocus(event) { + var focusable = getPreferencesFocusable(); if (!focusable.length) { return; @@ -555,130 +845,272 @@ } } - /** - * Keydown handler bound only while the popup (true modal) layout is - * open: Tab/Shift+Tab loop within the dialog's own focusable elements - * (trapFocus()) and Escape is treated as an explicit reject — a valid, - * equivalent consent decision, not a silent dismissal — so a keyboard - * user always has a way out that doesn't just abandon the dialog - * without a decision being recorded (see handleDecision()). - */ - function handleModalKeydown(event) { + function handlePreferencesKeydown(event) { if (event.key === 'Tab') { - trapFocus(event); + trapPreferencesFocus(event); } else if (event.key === 'Escape' || event.key === 'Esc') { event.preventDefault(); - handleDecision('rejected'); + closePreferencesPanel(); } } - var decided = false; - - function handleDecision(decision) { - if (decided) { + /** + * Reflects the visitor's current, actually-recorded per-category + * decision onto each [data-frcn-category] toggle independently every + * time the panel opens — reading the frontconsent_categories cookie + * (written by setCategoriesCookie() above), not the single binary + * consent cookie, so unchecking Marketing while leaving Analytics + * checked is reflected as two different states, not one flag mirrored + * onto both toggles. + * + * Backward compatibility: a visitor who accepted before this cookie + * existed has no frontconsent_categories cookie yet — for them, + * 'accepted' previously meant everything was allowed, so both + * toggles show checked (matching that same reality) until they make + * an explicit per-category choice here. Absent or rejected: both + * unchecked. + */ + function syncPreferencesToggles() { + if (!preferencesPanel) { return; } - decided = true; + var accepted = readCookie(frcnCookieNotice.cookieName) === 'accepted'; + var storedCategoriesRaw = readCookie(frcnCookieNotice.categoriesCookieName); + var storedCategories = null; - setConsentCookie(decision); - updateConsentMode(decision); - announce(decision === 'accepted' ? i18n.accepted : i18n.rejected); - hideBanner(); - setUpReopenTrigger(); - dispatchConsentEvent(decision); - logDecision(decision); + if (storedCategoriesRaw) { + try { + var parsed = JSON.parse(storedCategoriesRaw); - if (decision === 'accepted') { - fetchAndInjectScripts(); - } else { - purgeTrackingCookies(); + if (parsed && typeof parsed === 'object') { + storedCategories = parsed; + } + } catch (e) { + // Malformed/tampered cookie value: treat it the same as + // no categories cookie at all (the accepted/rejected + // fallback below). + storedCategories = null; + } } - } - function updateConsentMode(decision) { - var granted = decision === 'accepted' ? 'granted' : 'denied'; + var toggles = preferencesPanel.querySelectorAll('[data-frcn-category]'); - window.dataLayer = window.dataLayer || []; - window.gtag = window.gtag || function () { - window.dataLayer.push(arguments); - }; - window.gtag('consent', 'update', { - ad_storage: granted, - ad_user_data: granted, - ad_personalization: granted, - analytics_storage: granted + Array.prototype.forEach.call(toggles, function (toggle) { + var category = toggle.getAttribute('data-frcn-category'); + + if (storedCategories && Object.prototype.hasOwnProperty.call(storedCategories, category)) { + toggle.checked = !!storedCategories[category]; + } else { + // No explicit stored value for this category (cookie + // missing/unparseable, or simply doesn't mention it yet): + // fall back to the binary cookie's own "everything was + // allowed/nothing was allowed" reality. + toggle.checked = accepted; + } }); } - function setConsentCookie(decision) { - var maxAge = parseInt(frcnCookieNotice.expirationDays, 10) * 24 * 60 * 60; - var secure = window.location.protocol === 'https:' ? '; Secure' : ''; + function openPreferencesPanel(trigger) { + if (!preferencesPanel) { + return; + } - document.cookie = frcnCookieNotice.cookieName + '=' + decision + - '; path=' + frcnCookieNotice.cookiePath + '; max-age=' + maxAge + '; SameSite=Lax' + secure; + // A fresh session of "changing their mind": lets a visitor who + // already decided make (and log) a new decision from the + // reopened panel instead of being silently blocked by the + // same-page debounce above. + decided = false; + syncPreferencesToggles(); + preferencesPanelOpener = trigger || document.activeElement; + preferencesPanel.hidden = false; + document.body.classList.add('frcn-cookie-notice-lock-scroll'); + + var focusable = getPreferencesFocusable(); + + if (focusable.length) { + focusable[0].focus({ preventScroll: true }); + } + + if (!preferencesPanelKeydownBound) { + document.addEventListener('keydown', handlePreferencesKeydown); + preferencesPanelKeydownBound = true; + } + + announce(i18n.bannerOpened); } - function hideBanner() { - banner.classList.add('frcn-cookie-notice--hidden'); - document.body.classList.remove('frcn-cookie-notice-lock-scroll'); - document.removeEventListener('keydown', handleModalKeydown); + function closePreferencesPanel() { + if (!preferencesPanel || preferencesPanel.hidden) { + return; + } + + preferencesPanel.hidden = true; - if (isPopup && previouslyFocused && typeof previouslyFocused.focus === 'function') { - previouslyFocused.focus({ preventScroll: true }); + if (!isPopup || !banner || banner.classList.contains('frcn-cookie-notice--hidden')) { + document.body.classList.remove('frcn-cookie-notice-lock-scroll'); } - window.setTimeout(function () { - if (banner.parentNode) { - banner.parentNode.removeChild(banner); - } - }, 300); + if (preferencesPanelKeydownBound) { + document.removeEventListener('keydown', handlePreferencesKeydown); + preferencesPanelKeydownBound = false; + } + + if (preferencesPanelOpener && typeof preferencesPanelOpener.focus === 'function') { + preferencesPanelOpener.focus({ preventScroll: true }); + } + + preferencesPanelOpener = null; } - function dispatchConsentEvent(decision) { - var event; + /** + * Every non-necessary category toggle a PRO add-on rendered on + * frcn_cookie_preferences_categories (see render_preferences_panel()) + * is expected to carry a `data-frcn-category=""` attribute on a + * checkable control — read back here so "Save changes" can compute + * both the categories map and the binary decision it implies. The + * Free tier renders none, so this is always just { necessary: true } + * until an add-on extends the panel. + */ + function collectPreferencesCategories() { + var categories = { necessary: true }; - try { - event = new CustomEvent('frcnCookieConsent', { detail: { consent: decision } }); - } catch (e) { - event = document.createEvent('CustomEvent'); - event.initCustomEvent('frcnCookieConsent', true, true, { consent: decision }); + if (!preferencesPanel) { + return categories; } - document.dispatchEvent(event); + var toggles = preferencesPanel.querySelectorAll('[data-frcn-category]'); + + Array.prototype.forEach.call(toggles, function (toggle) { + categories[toggle.getAttribute('data-frcn-category')] = !!toggle.checked; + }); + + return categories; } - function logDecision(decision) { - var nonceForm = new FormData(); - nonceForm.append('action', 'frcn_get_cookie_notice_log_nonce'); + if (preferencesPanel) { + var closeBtn = preferencesPanel.querySelector('[data-frcn-cookie-action="close-preferences"]'); + var panelAcceptBtn = preferencesPanel.querySelector('[data-frcn-cookie-action="accept"]'); + var panelRejectBtn = preferencesPanel.querySelector('[data-frcn-cookie-action="reject"]'); + var panelSaveBtn = preferencesPanel.querySelector('[data-frcn-cookie-action="save"]'); - fetch(frcnCookieNotice.ajaxUrl, { - method: 'POST', - credentials: 'same-origin', - body: nonceForm - }) - .then(function (response) { - return response.json(); - }) - .then(function (response) { - if (!response || !response.success || !response.data) { - return; - } + if (closeBtn) { + closeBtn.addEventListener('click', function () { + closePreferencesPanel(); + }); + } - var formData = new FormData(); - formData.append('action', 'frcn_log_cookie_consent'); - formData.append('nonce', response.data.nonce); - formData.append('decision', decision); + if (panelAcceptBtn) { + panelAcceptBtn.addEventListener('click', function () { + var categories = collectPreferencesCategories(); - return fetch(frcnCookieNotice.ajaxUrl, { - method: 'POST', - credentials: 'same-origin', - body: formData + Object.keys(categories).forEach(function (key) { + categories[key] = true; }); - }) - .catch(function () { - // Best-effort: the aggregate stat is not critical to the consent flow. + + handleDecision('accepted', categories); }); + } + + if (panelRejectBtn) { + panelRejectBtn.addEventListener('click', function () { + // Explicit, real "both off" state — not an ambiguous + // absence of analytics/marketing keys — so the categories + // cookie (and the server-side allowedCategories it drives) + // reflects an actual decision rather than "unspecified". + handleDecision('rejected', { necessary: true, analytics: false, marketing: false }); + }); + } + + if (panelSaveBtn) { + panelSaveBtn.addEventListener('click', function () { + var categories = collectPreferencesCategories(); + var hasOptionalConsent = Object.keys(categories).some(function (key) { + return key !== 'necessary' && categories[key]; + }); + + handleDecision(hasOptionalConsent ? 'accepted' : 'rejected', categories); + }); + } + } + + requestTrackingIfNeeded(); + setUpReopenTrigger(openPreferencesPanel); + + if (!banner) { + return; + } + + if (hideBannerIfDecided()) { + // Already decided: nothing left to wire up on the banner itself + // (the preferences panel and reopen trigger stay available). + return; + } + + var acceptBtn = banner.querySelector('[data-frcn-cookie-action="accept"]'); + var rejectBtn = banner.querySelector('[data-frcn-cookie-action="reject"]'); + var customizeBtn = banner.querySelector('[data-frcn-cookie-action="customize"]'); + + function hideBannerIfDecided() { + var consent = readCookie(frcnCookieNotice.cookieName); + + // An add-on tracking per-category consent (analytics vs. marketing) can + // define this to say "the categories cookie is stale — e.g. the site + // admin just added a new integration — so re-prompt even though the + // legacy accepted/rejected cookie here still looks decided." + if (typeof window.frcnCookieNoticeIsConsentStale === 'function' && window.frcnCookieNoticeIsConsentStale()) { + return false; + } + + if (consent === 'accepted' || consent === 'rejected') { + banner.style.display = 'none'; + return true; + } + + return false; + } + + revealBanner(); + + if (acceptBtn) { + // preventDefault() is what stops the button's form="..." submit + // attribute (the no-JS fallback — see render_banner_markup() and + // log_consent_form_callback()) from actually navigating the page + // away when JavaScript can run: this handles the decision instead, + // entirely client-side. + acceptBtn.addEventListener('click', function (event) { + event.preventDefault(); + handleDecision('accepted'); + }); + } + + if (rejectBtn) { + rejectBtn.addEventListener('click', function (event) { + event.preventDefault(); + handleDecision('rejected'); + }); + } + + if (customizeBtn) { + // Opens the same preferences panel the reopen trigger uses — not + // routed through handleDecision(): clicking it isn't a decision by + // itself, just a request to see more detail. A CustomEvent is + // still dispatched afterwards so any existing listener bound to it + // keeps working. + customizeBtn.addEventListener('click', function () { + openPreferencesPanel(customizeBtn); + + var event; + + try { + event = new CustomEvent('frcnCookieNoticeCustomize'); + } catch (e) { + event = document.createEvent('CustomEvent'); + event.initCustomEvent('frcnCookieNoticeCustomize', true, true, null); + } + + document.dispatchEvent(event); + }); } } })(); diff --git a/assets/cookie-notice/frontconsent-cookie-notice.min.css b/assets/cookie-notice/frontconsent-cookie-notice.min.css index 6497c98..bc894b5 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.min.css +++ b/assets/cookie-notice/frontconsent-cookie-notice.min.css @@ -1 +1 @@ -.frcn-cookie-notice{--frcn-cookie-accent:#687df9;--frcn-cookie-accent-contrast:#ffffff;--frcn-cookie-accent-on-light:#687df9;--frcn-cookie-bg:#ffffff;--frcn-cookie-text:#1f2937;--frcn-cookie-radius:12px;position:fixed;z-index:999999;box-sizing:border-box;font-family:inherit;line-height:1.5;opacity:1;transition:opacity .3s,transform .3s}.frcn-cookie-notice *{box-sizing:border-box}.frcn-cookie-notice--hidden,.frcn-cookie-notice--init{opacity:0;pointer-events:none}.frcn-cookie-notice--bar.frcn-cookie-notice--init{transform:translateY(100%)}.frcn-cookie-notice--box.frcn-cookie-notice--init{transform:translateX(100%)}.frcn-cookie-notice--box.frcn-cookie-notice--left.frcn-cookie-notice--init{transform:translateX(-100%)}.frcn-cookie-notice--popup.frcn-cookie-notice--init{transform:scale(.96)}.frcn-cookie-notice__panel{background-color:var(--frcn-cookie-bg);color:var(--frcn-cookie-text);border-radius:var(--frcn-cookie-radius);overflow:hidden;box-shadow:none}.frcn-cookie-notice__message{margin:0;font-size:14px;color:var(--frcn-cookie-text)}.frcn-cookie-notice__link{color:var(--frcn-cookie-accent-on-light);background-color:transparent;text-decoration:underline}.frcn-cookie-notice__link:focus,.frcn-cookie-notice__link:hover{color:var(--frcn-cookie-accent-on-light);background-color:transparent}.frcn-cookie-notice__link:focus-visible{outline:2px solid var(--frcn-cookie-accent-on-light);outline-offset:2px}.frcn-cookie-notice__actions{display:flex;flex-wrap:wrap;gap:12px;flex-shrink:0}.frcn-cookie-notice__button{appearance:none;border-radius:6px;padding:10px 20px;font-size:14px;font-weight:600;line-height:1.2;cursor:pointer;transition:filter .15s,transform .15s;white-space:nowrap}.frcn-cookie-notice__button:hover{filter:brightness(.92)}.frcn-cookie-notice__button:active{transform:scale(.97)}.frcn-cookie-notice__button:focus-visible{outline:2px solid var(--frcn-cookie-accent-on-light);outline-offset:2px}.frcn-cookie-notice__button--accept{background-color:var(--frcn-cookie-accent);border:1px solid var(--frcn-cookie-accent);color:var(--frcn-cookie-accent-contrast)}.frcn-cookie-notice__button--reject{background-color:transparent;border:1px solid #9ca3af;color:var(--frcn-cookie-text)}.frcn-cookie-notice--bar{left:20px;right:20px;bottom:20px;max-height:calc(100vh - 40px);overflow-y:auto}.frcn-cookie-notice--bar.frcn-cookie-notice--generatepress{left:max(20px,calc((100vw - var(--frcn-cookie-content-width))/ 2));right:max(20px,calc((100vw - var(--frcn-cookie-content-width))/ 2))}.frcn-cookie-notice--bar .frcn-cookie-notice__panel{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:16px 24px}.frcn-cookie-notice--bar .frcn-cookie-notice__message{flex:1 1 320px}.frcn-cookie-notice--box{bottom:20px;max-width:380px;width:calc(100% - 40px);max-height:calc(100vh - 40px);overflow-y:auto}.frcn-cookie-notice--box.frcn-cookie-notice--right{right:20px}.frcn-cookie-notice--box.frcn-cookie-notice--left{left:20px}.frcn-cookie-notice--box .frcn-cookie-notice__panel{padding:20px;display:flex;flex-direction:column;gap:16px}.frcn-cookie-notice--box .frcn-cookie-notice__actions{flex-direction:column}.frcn-cookie-notice--box .frcn-cookie-notice__button{width:100%;text-align:center}.frcn-cookie-notice--popup{inset:0;display:flex;align-items:center;justify-content:center;padding:20px;overflow-y:auto;background-color:transparent}.frcn-cookie-notice--popup .frcn-cookie-notice__panel{padding:40px 32px 32px;max-width:420px;width:100%;max-height:calc(100vh - 40px);overflow-y:auto;display:flex;flex-direction:column;align-items:center;text-align:center;gap:16px;box-shadow:none}.frcn-cookie-notice__icon{display:flex;align-items:center;justify-content:center;width:64px;height:64px;flex-shrink:0;border-radius:50%;background-color:var(--frcn-cookie-accent)}.frcn-cookie-notice__icon::before{content:'';display:block;width:32px;height:32px;background-color:var(--frcn-cookie-accent-contrast);-webkit-mask-image:var(--frcn-cookie-icon-url);mask-image:var(--frcn-cookie-icon-url);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center}.frcn-cookie-notice--popup .frcn-cookie-notice__actions{justify-content:center;width:100%}body.frcn-cookie-notice-lock-scroll{overflow:hidden}@media (max-width:600px){.frcn-cookie-notice--bar .frcn-cookie-notice__panel{padding:16px}.frcn-cookie-notice--bar .frcn-cookie-notice__actions,.frcn-cookie-notice--popup .frcn-cookie-notice__actions{flex-direction:column;width:100%}.frcn-cookie-notice--bar .frcn-cookie-notice__button,.frcn-cookie-notice--popup .frcn-cookie-notice__button{width:100%;text-align:center}.frcn-cookie-notice--box,.frcn-cookie-notice--popup .frcn-cookie-notice__panel{width:calc(100% - 24px);max-width:none}.frcn-cookie-notice--popup .frcn-cookie-notice__panel{max-height:calc(100vh - 24px)}.frcn-cookie-notice--bar,.frcn-cookie-notice--box{left:12px;right:12px;bottom:12px;max-height:calc(100vh - 24px)}}@media (prefers-reduced-motion:reduce){.frcn-cookie-notice,.frcn-cookie-notice__button,.frcn-cookie-reopen{transition:none}}.frcn-cookie-notice-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.frcn-cookie-reopen{position:fixed;z-index:999998;left:16px;bottom:16px;display:flex;align-items:center;justify-content:center;width:44px;height:44px;appearance:none;border:none;border-radius:50%;background-color:var(--frcn-cookie-accent);box-shadow:0 1px 3px rgba(0,0,0,.12);cursor:pointer}.frcn-cookie-reopen .frcn-cookie-notice__icon{width:100%;height:100%;background-color:transparent}.frcn-cookie-reopen .frcn-cookie-notice__icon::before{width:22px;height:22px;background-color:var(--frcn-cookie-accent-contrast)}.frcn-cookie-reopen:hover{filter:brightness(.92)}.frcn-cookie-reopen:focus-visible{outline:2px solid var(--frcn-cookie-accent);outline-offset:2px}.frcn-cookie-reopen[hidden]{display:none} \ No newline at end of file +.frcn-cookie-notice{--frcn-cookie-accent:#687df9;--frcn-cookie-accent-contrast:#ffffff;--frcn-cookie-accent-on-light:#687df9;--frcn-cookie-bg:#ffffff;--frcn-cookie-text:#1f2937;--frcn-cookie-radius:12px;position:fixed;z-index:999999;box-sizing:border-box;font-family:inherit;line-height:1.5;opacity:1;transition:opacity .3s,transform .3s}.frcn-cookie-notice *{box-sizing:border-box}.frcn-cookie-notice--hidden,.frcn-cookie-notice--init{opacity:0;pointer-events:none}.frcn-cookie-notice--bar.frcn-cookie-notice--init{transform:translateY(100%)}.frcn-cookie-notice--box.frcn-cookie-notice--init{transform:translateX(100%)}.frcn-cookie-notice--box.frcn-cookie-notice--left.frcn-cookie-notice--init{transform:translateX(-100%)}.frcn-cookie-notice--popup.frcn-cookie-notice--init{transform:scale(.96)}.frcn-cookie-notice__panel{background-color:var(--frcn-cookie-bg);color:var(--frcn-cookie-text);border-radius:var(--frcn-cookie-radius);overflow:hidden;box-shadow:none}.frcn-cookie-notice__message{margin:0;font-size:14px;color:var(--frcn-cookie-text)}.frcn-cookie-notice__link{color:var(--frcn-cookie-accent-on-light);background-color:transparent;text-decoration:underline}.frcn-cookie-notice__link:focus,.frcn-cookie-notice__link:hover{color:var(--frcn-cookie-accent-on-light);background-color:transparent}.frcn-cookie-notice__link:focus-visible{outline:2px solid var(--frcn-cookie-accent-on-light);outline-offset:2px}.frcn-cookie-notice__actions{display:flex;flex-wrap:wrap;gap:12px;flex-shrink:0}.frcn-cookie-notice__button{appearance:none;border-radius:6px;padding:10px 20px;font-size:14px;font-weight:600;line-height:1.2;cursor:pointer;transition:filter .15s,transform .15s;white-space:nowrap}.frcn-cookie-notice__button:hover{filter:brightness(.92)}.frcn-cookie-notice__button:active{transform:scale(.97)}.frcn-cookie-notice__button:focus-visible{outline:2px solid var(--frcn-cookie-accent-on-light);outline-offset:2px}.frcn-cookie-notice__button--accept{background-color:var(--frcn-cookie-accent);border:1px solid var(--frcn-cookie-accent);color:var(--frcn-cookie-accent-contrast)}.frcn-cookie-notice__button--reject{background-color:transparent;border:1px solid #9ca3af;color:var(--frcn-cookie-text)}.frcn-cookie-notice__button--customize{display:inline-flex;align-items:center;gap:8px;background-color:transparent;border:1px solid var(--frcn-cookie-accent-on-light);color:var(--frcn-cookie-text)}.frcn-cookie-notice__button-icon{display:block;width:16px;height:16px;flex-shrink:0;background-color:var(--frcn-cookie-accent-on-light);-webkit-mask-image:var(--frcn-cookie-icon-url);mask-image:var(--frcn-cookie-icon-url);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center}.frcn-cookie-notice--bar{left:20px;right:20px;bottom:20px;max-height:calc(100vh - 40px);overflow-y:auto}.frcn-cookie-notice--bar.frcn-cookie-notice--generatepress{left:max(20px,calc((100vw - var(--frcn-cookie-content-width))/ 2));right:max(20px,calc((100vw - var(--frcn-cookie-content-width))/ 2))}.frcn-cookie-notice--bar .frcn-cookie-notice__panel{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:16px 24px}.frcn-cookie-notice--bar .frcn-cookie-notice__message{flex:1 1 320px}.frcn-cookie-notice--box{bottom:20px;max-width:380px;width:calc(100% - 40px);max-height:calc(100vh - 40px);overflow-y:auto}.frcn-cookie-notice--box.frcn-cookie-notice--right{right:20px}.frcn-cookie-notice--box.frcn-cookie-notice--left{left:20px}.frcn-cookie-notice--box .frcn-cookie-notice__panel{padding:20px;display:flex;flex-direction:column;gap:16px}.frcn-cookie-notice--box .frcn-cookie-notice__actions{flex-direction:column}.frcn-cookie-notice--box .frcn-cookie-notice__button{width:100%;text-align:center}.frcn-cookie-notice--popup{inset:0;display:flex;align-items:center;justify-content:center;padding:20px;overflow-y:auto;background-color:transparent}.frcn-cookie-notice--popup .frcn-cookie-notice__panel{padding:40px 32px 32px;max-width:420px;width:100%;max-height:calc(100vh - 40px);overflow-y:auto;display:flex;flex-direction:column;align-items:center;text-align:center;gap:16px;box-shadow:none}.frcn-cookie-notice__icon{display:flex;align-items:center;justify-content:center;width:64px;height:64px;flex-shrink:0;border-radius:50%;background-color:var(--frcn-cookie-accent)}.frcn-cookie-notice__icon::before{content:'';display:block;width:32px;height:32px;background-color:var(--frcn-cookie-accent-contrast);-webkit-mask-image:var(--frcn-cookie-icon-url);mask-image:var(--frcn-cookie-icon-url);-webkit-mask-size:contain;mask-size:contain;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center}.frcn-cookie-notice--popup .frcn-cookie-notice__actions{justify-content:center;width:100%}body.frcn-cookie-notice-lock-scroll{overflow:hidden}@media (max-width:600px){.frcn-cookie-notice--bar .frcn-cookie-notice__panel{padding:16px}.frcn-cookie-notice--bar .frcn-cookie-notice__actions,.frcn-cookie-notice--popup .frcn-cookie-notice__actions{flex-direction:column;width:100%}.frcn-cookie-notice--bar .frcn-cookie-notice__button,.frcn-cookie-notice--popup .frcn-cookie-notice__button{width:100%;text-align:center}.frcn-cookie-notice--box,.frcn-cookie-notice--popup .frcn-cookie-notice__panel{width:calc(100% - 24px);max-width:none}.frcn-cookie-notice--popup .frcn-cookie-notice__panel{max-height:calc(100vh - 24px)}.frcn-cookie-notice--bar,.frcn-cookie-notice--box{left:12px;right:12px;bottom:12px;max-height:calc(100vh - 24px)}}@media (prefers-reduced-motion:reduce){.frcn-cookie-notice,.frcn-cookie-notice__button,.frcn-cookie-reopen{transition:none}}.frcn-cookie-notice-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.frcn-cookie-reopen{position:fixed;z-index:999998;left:16px;bottom:16px;display:flex;align-items:center;justify-content:center;width:44px;height:44px;appearance:none;border:none;border-radius:50%;background-color:var(--frcn-cookie-accent);box-shadow:0 1px 3px rgba(0,0,0,.12);cursor:pointer}.frcn-cookie-reopen .frcn-cookie-notice__icon{width:100%;height:100%;background-color:transparent}.frcn-cookie-reopen .frcn-cookie-notice__icon::before{width:22px;height:22px;background-color:var(--frcn-cookie-accent-contrast)}.frcn-cookie-reopen:hover{filter:brightness(.92)}.frcn-cookie-reopen:focus-visible{outline:2px solid var(--frcn-cookie-accent);outline-offset:2px}.frcn-cookie-reopen[hidden]{display:none}.frcn-cookie-preferences{--frcn-cookie-accent:#687df9;--frcn-cookie-accent-contrast:#ffffff;--frcn-cookie-accent-on-light:#687df9;--frcn-cookie-bg:#ffffff;--frcn-cookie-text:#1f2937;--frcn-cookie-radius:12px;position:fixed;z-index:1000000;inset:0;display:flex;align-items:center;justify-content:center;padding:20px;overflow-y:auto;background-color:rgba(17,24,39,.5);font-family:inherit;line-height:1.5;box-sizing:border-box}.frcn-cookie-preferences *{box-sizing:border-box}.frcn-cookie-preferences[hidden]{display:none}.frcn-cookie-preferences__panel{background-color:var(--frcn-cookie-bg);color:var(--frcn-cookie-text);border-radius:var(--frcn-cookie-radius);max-width:480px;width:100%;max-height:calc(100vh - 40px);overflow-y:auto;padding:24px;display:flex;flex-direction:column;gap:16px}.frcn-cookie-preferences__header{display:flex;align-items:center;justify-content:space-between;gap:12px}.frcn-cookie-preferences__title{margin:0;font-size:18px;font-weight:600;color:var(--frcn-cookie-text)}.frcn-cookie-preferences__close{appearance:none;background:0 0;border:none;cursor:pointer;font-size:20px;line-height:1;padding:4px 8px;color:var(--frcn-cookie-text)}.frcn-cookie-preferences__close:focus-visible{outline:2px solid var(--frcn-cookie-accent-on-light);outline-offset:2px}.frcn-cookie-preferences__message{margin:0;font-size:14px;color:var(--frcn-cookie-text)}.frcn-cookie-preferences__category{border:1px solid rgba(31,41,55,.12);border-radius:calc(var(--frcn-cookie-radius)/ 2);padding:12px 16px}.frcn-cookie-preferences__category-header{display:flex;align-items:center;justify-content:space-between;gap:12px}.frcn-cookie-preferences__category-title{font-weight:600;font-size:14px}.frcn-cookie-preferences__category-badge{font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.02em;color:var(--frcn-cookie-accent-on-light)}.frcn-cookie-preferences__category-toggle{width:20px;height:20px;flex-shrink:0;accent-color:var(--frcn-cookie-accent);cursor:pointer}.frcn-cookie-preferences__category-toggle:focus-visible{outline:2px solid var(--frcn-cookie-accent);outline-offset:2px}.frcn-cookie-preferences__category-description{margin:8px 0 0;font-size:13px;color:var(--frcn-cookie-text)}.frcn-cookie-preferences__actions{display:flex;flex-wrap:wrap;gap:12px;justify-content:flex-end}.frcn-cookie-preferences__actions .frcn-cookie-notice__button{flex:1 1 auto}@media (max-width:600px){.frcn-cookie-preferences__panel{max-height:calc(100vh - 24px)}.frcn-cookie-preferences__actions{flex-direction:column}.frcn-cookie-preferences__actions .frcn-cookie-notice__button{width:100%;text-align:center}} \ No newline at end of file diff --git a/assets/cookie-notice/frontconsent-cookie-notice.min.js b/assets/cookie-notice/frontconsent-cookie-notice.min.js index 2a75fa2..6178b10 100644 --- a/assets/cookie-notice/frontconsent-cookie-notice.min.js +++ b/assets/cookie-notice/frontconsent-cookie-notice.min.js @@ -1 +1 @@ -!function(){"use strict";function e(e){var o=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));if(!o)return"";try{return decodeURIComponent(o[1])}catch(e){return""}}function o(){var e=Array.isArray(frcnCookieNotice.purgeCookies)?frcnCookieNotice.purgeCookies:[];if(e.length&&document.cookie){for(var o=(window.location&&window.location.hostname?window.location.hostname:"").split("."),n=[""],t=0;t` and + * `'; + $rules = array( array( 'pattern' => 'google.com/maps', 'category' => 'marketing' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'src="about:blank"', $result ); + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + $this->assertStringContainsString( 'data-frcn-src="https://www.google.com/maps/embed?pb=123"', $result ); + // Unrelated attributes must survive the rewrite untouched. + $this->assertStringContainsString( 'width="600"', $result ); + $this->assertStringContainsString( 'height="450"', $result ); + } + + /** + * A self-closing ' + . ''; + + $rules = array( + array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ), + array( 'pattern' => 'google.com/maps', 'category' => 'marketing' ), + ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-src="https://www.youtube.com/embed/one"', $result ); + $this->assertStringContainsString( 'data-frcn-src="https://www.google.com/maps/embed?pb=2"', $result ); + $this->assertStringContainsString( 'src="https://example.com/app.js"', $result ); + $this->assertStringContainsString( 'src="https://example.com/other-embed"', $result ); + $this->assertStringNotContainsString( 'data-frcn-src="https://example.com/app.js"', $result ); + $this->assertStringNotContainsString( 'data-frcn-src="https://example.com/other-embed"', $result ); + } + + /** + * A rule with an unrecognized/missing category falls back to + * 'marketing', matching Settings::parse_rules_text()'s own fallback. + */ + public function test_rule_with_missing_category_falls_back_to_marketing() { + $html = ''; + $rules = array( array( 'pattern' => 'tracker.example.com' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + } + + /** + * Matching is case-insensitive, both for the pattern against the src, + * and regardless of the tag name's own casing. + */ + public function test_matching_is_case_insensitive() { + $html = ''; + $rules = array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ); + + $result = ScriptBlocker::rewrite_html( $html, $rules ); + + $this->assertStringContainsString( 'data-frcn-src="https://www.YouTube.com/Embed/abc"', $result ); + } + + /** + * ScriptBlocker::parse_rules_text() and rules_to_text() round-trip the + * settings screen's one-rule-per-line textarea format. + */ + public function test_parse_rules_text_round_trips_with_rules_to_text() { + $text = "youtube.com/embed|marketing\ntracker.example.com|analytics"; + + $rules = ScriptBlocker::parse_rules_text( $text ); + + $this->assertSame( + array( + array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ), + array( 'pattern' => 'tracker.example.com', 'category' => 'analytics' ), + ), + $rules + ); + $this->assertSame( $text, ScriptBlocker::rules_to_text( $rules ) ); + } + + /** + * Blank lines and a missing/unrecognized category in the textarea + * format are handled gracefully rather than producing a broken rule. + */ + public function test_parse_rules_text_handles_blank_lines_and_unknown_category() { + $rules = ScriptBlocker::parse_rules_text( "\nyoutube.com/embed|not-a-real-category\n\n \n" ); + + $this->assertSame( + array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ), + $rules + ); + } + + /** + * A youtube.com embed is switched to the privacy-enhanced + * youtube-nocookie.com domain, including a lazy-loaded copy of the URL. + */ + public function test_youtube_iframe_is_switched_to_nocookie_domain() { + $html = ''; + + $result = ScriptBlocker::rewrite_privacy_enhanced_embeds( $html ); + + $this->assertStringContainsString( 'src="https://www.youtube-nocookie.com/embed/abc123?rel=0"', $result ); + $this->assertStringContainsString( 'data-lazy-src="https://www.youtube-nocookie.com/embed/abc123"', $result ); + $this->assertStringNotContainsString( '//www.youtube.com/embed', $result ); + } + + /** + * A Vimeo player embed gets dnt=1, appended to an existing query string + * when there is one, and is left alone when it already carries it. + */ + public function test_vimeo_iframe_gets_do_not_track_flag_once() { + $this->assertStringContainsString( + 'src="https://player.vimeo.com/video/123?dnt=1"', + ScriptBlocker::rewrite_privacy_enhanced_embeds( '' ) + ); + $this->assertStringContainsString( + 'src="https://player.vimeo.com/video/123?h=abc&dnt=1"', + ScriptBlocker::rewrite_privacy_enhanced_embeds( '' ) + ); + + $already = ''; + $this->assertSame( $already, ScriptBlocker::rewrite_privacy_enhanced_embeds( $already ) ); + } + + /** + * Only iframes are rewritten: a plain link to a YouTube video stays as is. + */ + public function test_youtube_links_outside_iframes_are_untouched() { + $html = 'Watch'; + + $this->assertSame( $html, ScriptBlocker::rewrite_privacy_enhanced_embeds( $html ) ); + } + + /** + * A blocking rule still matches the original youtube.com URL: rules run + * before the nocookie rewrite, so the held-back embed keeps its real src. + */ + public function test_blocking_rules_run_before_the_nocookie_rewrite() { + update_option( 'frontconsent_settings', array( ScriptBlocker::RULES_OPTION_KEY => array( array( 'pattern' => 'youtube.com/embed', 'category' => 'marketing' ) ) ) ); + + $result = ( new ScriptBlocker() )->rewrite_buffer( '' ); + + delete_option( 'frontconsent_settings' ); + + $this->assertStringContainsString( 'data-frcn-category="marketing"', $result ); + $this->assertStringContainsString( 'src="about:blank"', $result ); + } +} diff --git a/tests/js/cookie-notice-focus-management.test.js b/tests/js/cookie-notice-focus-management.test.js index cecb056..cc4e09e 100644 --- a/tests/js/cookie-notice-focus-management.test.js +++ b/tests/js/cookie-notice-focus-management.test.js @@ -46,11 +46,13 @@ function createElement(id) { var document; // Populated per-test inside createEnvironment() below. -function createEnvironment() { +function createEnvironment(options) { + options = options || {}; var announcer = createElement('frcn-cookie-notice-announcer'); var rejectBtn = createElement('reject'); var acceptBtn = createElement('accept'); var linkEl = createElement('link'); + var customizeBtn = createElement('customize'); var focusable = [rejectBtn, acceptBtn, linkEl]; var triggerEl = createElement('trigger'); // The element that "opened" the banner. var reopenBtn = createElement('frcn-cookie-reopen'); @@ -72,6 +74,9 @@ function createEnvironment() { if ('[data-frcn-cookie-action="reject"]' === selector) { return rejectBtn; } + if ('[data-frcn-cookie-action="customize"]' === selector) { + return customizeBtn; + } return null; }, querySelectorAll() { @@ -80,10 +85,91 @@ function createEnvironment() { style: {} }; + // The cookie preferences panel — a separate dialog the Customize button + // and the reopen trigger both open (see openPreferencesPanel() in + // frontconsent-cookie-notice.js). Its own focus trap and Escape handling + // must act on this element's controls, not the banner's. + var panelCloseBtn = createElement('panel-close'); + var panelAcceptBtn = createElement('panel-accept'); + var panelRejectBtn = createElement('panel-reject'); + var panelSaveBtn = createElement('panel-save'); + var panelFocusable = [panelCloseBtn, panelAcceptBtn, panelRejectBtn, panelSaveBtn]; + + // The two real, independent category checkboxes (see issue: "analytics y + // marketing son diferentes") — a plain object stub is enough since only + // .checked and .getAttribute('data-frcn-category') are ever read/set. + var categoryToggles = options.categoryToggles || [ + { category: 'analytics', checked: false }, + { category: 'marketing', checked: false } + ]; + var categoryToggleElements = categoryToggles.map(function (toggle) { + return { + checked: toggle.checked, + getAttribute(name) { + return 'data-frcn-category' === name ? toggle.category : null; + } + }; + }); + + var preferencesPanel = { + hidden: true, + classList: { add() {}, remove() {}, contains() { return false; } }, + querySelector(selector) { + if ('[data-frcn-cookie-action="close-preferences"]' === selector) { + return panelCloseBtn; + } + if ('[data-frcn-cookie-action="accept"]' === selector) { + return panelAcceptBtn; + } + if ('[data-frcn-cookie-action="reject"]' === selector) { + return panelRejectBtn; + } + if ('[data-frcn-cookie-action="save"]' === selector) { + return panelSaveBtn; + } + return null; + }, + querySelectorAll(selector) { + if ('[data-frcn-category]' === selector) { + return categoryToggleElements; + } + return panelFocusable; + } + }; + + // A minimal accumulating cookie jar (real browsers merge each + // `document.cookie = "name=value; attrs..."` assignment into the + // existing set rather than replacing it wholesale) — needed now that + // handleDecision() writes both the binary consent cookie and the new + // per-category cookie in the same decision, and tests need to read both + // back independently afterwards. + var cookieJar = {}; + + (options.cookie || '').split(';').forEach(function (pair) { + var index = pair.indexOf('='); + + if (index > -1) { + cookieJar[pair.slice(0, index).trim()] = pair.slice(index + 1).trim(); + } + }); + document = { activeElement: triggerEl, body: { classList: { add() {}, remove() {} } }, - cookie: '', + get cookie() { + return Object.keys(cookieJar).map(function (name) { + return name + '=' + cookieJar[name]; + }).join('; '); + }, + set cookie(value) { + var index = value.indexOf('='); + + if (index === -1) { + return; + } + + cookieJar[value.slice(0, index).trim()] = value.slice(index + 1).split(';')[0]; + }, head: { appendChild() {} }, readyState: 'loading', _domListeners: {}, @@ -111,13 +197,16 @@ function createEnvironment() { if ('frcn-cookie-reopen' === id) { return reopenBtn; } + if ('frcn-cookie-preferences' === id) { + return preferencesPanel; + } return banner; }, getElementsByTagName() { return []; } }; var window = { - location: { protocol: 'https:' }, + location: { protocol: 'https:', reload() {} }, setTimeout(callback) { callback(); } }; @@ -138,6 +227,7 @@ function createEnvironment() { frcnCookieNotice: { ajaxUrl: 'https://example.test/wp-admin/admin-ajax.php', cookieName: 'frcn_cookie_consent', + categoriesCookieName: 'frontconsent_categories', cookiePath: '/', expirationDays: 365, isPolicyPage: '', @@ -172,11 +262,19 @@ function createEnvironment() { return { acceptBtn, announcer, + categoryToggleElements, context, + customizeBtn, fireModalKeydown, linkEl, modalKeydownListeners, + panelAcceptBtn, + panelCloseBtn, + panelRejectBtn, + panelSaveBtn, + preferencesPanel, rejectBtn, + reopenBtn, triggerEl, window }; @@ -242,3 +340,219 @@ test('accepting via the button also restores focus to the triggering element and assert.equal(document.activeElement, env.triggerEl); assert.equal(env.modalKeydownListeners.length, 0); }); + +/** + * Tests for the cookie preferences panel (issue #11): a separate dialog the + * "Customize cookie settings" button and the persistent reopen trigger both + * open, with its own focus trap and Escape handling, whose Accept + * all/Reject all/Save changes actions must funnel through the exact same + * decision-recording code path as the banner's own Accept/Reject buttons. + */ + +test('clicking the Customize button opens the preferences panel and moves focus into it', () => { + var env = createEnvironment(); + + env.customizeBtn.dispatchEvent({ type: 'click' }); + + assert.equal(env.preferencesPanel.hidden, false); + assert.equal(env.panelCloseBtn.focusCalls, 1); + // The banner's own modal trap stays bound underneath; the panel's own is + // now bound alongside it. + assert.equal(env.modalKeydownListeners.length, 2); +}); + +test('clicking the reopen trigger also opens the preferences panel', () => { + // Realistically, the reopen trigger only ever reveals/binds for a visitor + // who already decided (see setUpReopenTrigger()) — simulate that here. + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + assert.equal(env.preferencesPanel.hidden, false); + assert.equal(env.panelCloseBtn.focusCalls, 1); + // The visitor already decided, so the banner itself was never revealed — + // only the panel's own keydown handler is bound. + assert.equal(env.modalKeydownListeners.length, 1); +}); + +test('Tab within the preferences panel wraps among its own controls, not the banner\'s', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + document.activeElement = env.panelSaveBtn; // The panel's own last focusable element. + var event = env.fireModalKeydown({ key: 'Tab', shiftKey: false }); + + assert.equal(event.defaultPrevented, true); + assert.equal(document.activeElement, env.panelCloseBtn); +}); + +test('Escape closes the preferences panel (without also rejecting via the banner\'s own handler) and restores focus to whichever trigger opened it', () => { + var env = createEnvironment(); + + env.customizeBtn.dispatchEvent({ type: 'click' }); + + var event = env.fireModalKeydown({ key: 'Escape' }); + + assert.equal(event.defaultPrevented, true); + assert.equal(env.preferencesPanel.hidden, true); + assert.equal(document.activeElement, env.customizeBtn); + // No decision was recorded, so the underlying banner is untouched — only + // the panel's own keydown handler should have unbound. + assert.equal(env.modalKeydownListeners.length, 1); + assert.notEqual(env.announcer.textContent, 'Cookies rejected.'); +}); + +test('the close button also closes the panel and restores focus to the reopen trigger', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + env.panelCloseBtn.dispatchEvent({ type: 'click' }); + + assert.equal(env.preferencesPanel.hidden, true); + assert.equal(document.activeElement, env.reopenBtn); +}); + +test('Accept all in the panel calls the same decision-recording function as the banner\'s own Accept button', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + env.panelAcceptBtn.dispatchEvent({ type: 'click' }); + + assert.ok(/frcn_cookie_consent=accepted/.test(document.cookie)); + assert.equal(env.announcer.textContent, 'Cookies accepted.'); + assert.equal(env.preferencesPanel.hidden, true); +}); + +test('Reject all in the panel calls the same decision-recording function as the banner\'s own Reject button', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + env.panelRejectBtn.dispatchEvent({ type: 'click' }); + + assert.ok(/frcn_cookie_consent=rejected/.test(document.cookie)); + assert.equal(env.announcer.textContent, 'Cookies rejected.'); +}); + +test('Save changes with nothing else to opt into records the same rejection the Reject button would', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + // Opening the panel with an 'accepted' binary cookie and no categories + // cookie yet checks both toggles by default (backward compatibility — + // see syncPreferencesToggles()); simulate the visitor explicitly + // unchecking both before saving, i.e. genuinely "nothing else to opt into". + env.categoryToggleElements.forEach(function (toggle) { + toggle.checked = false; + }); + + env.panelSaveBtn.dispatchEvent({ type: 'click' }); + + assert.ok(/frcn_cookie_consent=rejected/.test(document.cookie)); +}); + +/** + * Tests for the real, independent Analytics/Marketing category split + * (analytics y marketing son diferentes) — the frontconsent_categories + * cookie and syncPreferencesToggles()/collectPreferencesCategories() must + * treat each category on its own, not as two cosmetic mirrors of one flag. + */ + +function readStoredCategories() { + var match = /frontconsent_categories=([^;]*)/.exec(document.cookie); + + if (!match) { + return null; + } + + return JSON.parse(decodeURIComponent(match[1])); +} + +test('opening the panel with a categories cookie present sets each checkbox independently, not both mirroring one flag', () => { + var env = createEnvironment({ + cookie: 'frcn_cookie_consent=accepted; frontconsent_categories=' + + encodeURIComponent(JSON.stringify({ analytics: true, marketing: false })) + }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + var analyticsToggle = env.categoryToggleElements[0]; + var marketingToggle = env.categoryToggleElements[1]; + + assert.equal(analyticsToggle.checked, true); + assert.equal(marketingToggle.checked, false); +}); + +test('opening the panel with no categories cookie but an accepted binary cookie checks both (backward compatibility)', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + var analyticsToggle = env.categoryToggleElements[0]; + var marketingToggle = env.categoryToggleElements[1]; + + assert.equal(analyticsToggle.checked, true); + assert.equal(marketingToggle.checked, true); +}); + +test('opening the panel with no categories cookie and no/rejected binary cookie leaves both unchecked', () => { + var env = createEnvironment({ cookie: '' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + var analyticsToggle = env.categoryToggleElements[0]; + var marketingToggle = env.categoryToggleElements[1]; + + assert.equal(analyticsToggle.checked, false); + assert.equal(marketingToggle.checked, false); +}); + +test('clicking Save changes with only Analytics checked persists {necessary: true, analytics: true, marketing: false}', () => { + var env = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + + // Simulate the visitor's actual click: opening the panel checks both by + // default here (backward-compat fallback, no categories cookie yet) — + // then they explicitly uncheck Marketing while leaving Analytics checked. + env.categoryToggleElements[0].checked = true; + env.categoryToggleElements[1].checked = false; + + env.panelSaveBtn.dispatchEvent({ type: 'click' }); + + // Only Analytics is checked, so the binary decision this implies is + // still 'accepted' (at least one non-necessary category is on). + assert.ok(/frcn_cookie_consent=accepted/.test(document.cookie)); + assert.deepEqual(readStoredCategories(), { necessary: true, analytics: true, marketing: false }); +}); + +test('Reject all explicitly persists {necessary: true, analytics: false, marketing: false}', () => { + var env = createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + categoryToggles: [ + { category: 'analytics', checked: true }, + { category: 'marketing', checked: true } + ] + }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + env.panelRejectBtn.dispatchEvent({ type: 'click' }); + + assert.deepEqual(readStoredCategories(), { necessary: true, analytics: false, marketing: false }); +}); + +test('Accept all persists both categories as true regardless of their prior checked state', () => { + var env = createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + categoryToggles: [ + { category: 'analytics', checked: false }, + { category: 'marketing', checked: false } + ] + }); + + env.reopenBtn.dispatchEvent({ type: 'click' }); + env.panelAcceptBtn.dispatchEvent({ type: 'click' }); + + assert.deepEqual(readStoredCategories(), { necessary: true, analytics: true, marketing: true }); +}); diff --git a/tests/js/cookie-notice-hidden-elements.test.js b/tests/js/cookie-notice-hidden-elements.test.js index 946c9e4..2281a9c 100644 --- a/tests/js/cookie-notice-hidden-elements.test.js +++ b/tests/js/cookie-notice-hidden-elements.test.js @@ -7,16 +7,18 @@ const cookieNoticeCssPath = path.resolve(__dirname, '../../assets/cookie-notice/ /** * Regression test for a real bug: an element rendered with the `hidden` - * HTML attribute (see CookieNotice::render_reopen_trigger()) only actually - * stays hidden if the plugin's own CSS doesn't set `display` on it without - * also handling `[hidden]` — an author `display: flex`/`block` rule always - * wins over the browser's built-in `[hidden] { display: none }` rule - * regardless of selector specificity, so every selector that sets `display` - * on this cache-neutral, hidden-by-default element must carry a matching + * HTML attribute (see CookieNotice::render_reopen_trigger() and + * ::render_preferences_panel()) only actually stays hidden if the plugin's + * own CSS doesn't set `display` on it without also handling `[hidden]` — + * an author `display: flex`/`block` rule always wins over the browser's + * built-in `[hidden] { display: none }` rule regardless of selector + * specificity, so every selector that sets `display` on one of these + * cache-neutral, hidden-by-default elements must carry a matching * `[hidden] { display: none }` override. */ -test('the persistent reopen trigger has a matching [hidden] override', () => { +test('every hidden-by-default cookie-notice element has a matching [hidden] override', () => { const css = fs.readFileSync(cookieNoticeCssPath, 'utf8'); assert.match(css, /\.frcn-cookie-reopen\[hidden\]\s*\{[^}]*display:\s*none/); + assert.match(css, /\.frcn-cookie-preferences\[hidden\]\s*\{[^}]*display:\s*none/); }); diff --git a/tests/js/cookie-notice-injection.test.js b/tests/js/cookie-notice-injection.test.js index ee528c4..4ae1782 100644 --- a/tests/js/cookie-notice-injection.test.js +++ b/tests/js/cookie-notice-injection.test.js @@ -40,22 +40,60 @@ function createEnvironment(options = {}) { }; const reopenBtn = { hidden: true, + focusCalls: 0, + focus() { this.focusCalls += 1; }, addEventListener(event, callback) { reopenListeners[event] = callback; } }; + const preferencesPanel = { + hidden: true, + classList: { add() {}, remove() {}, contains() { return false; } }, + querySelector() { return null; }, + querySelectorAll() { return []; } + }; + // An accumulating cookie jar (real browsers merge each + // `document.cookie = "name=value; attrs..."` assignment into the + // existing set rather than replacing it wholesale) — handleDecision() + // now writes both the binary consent cookie and the per-category cookie + // for a single decision, and both must be readable afterwards. + const cookieJar = {}; + + (options.cookie || '').split(';').forEach((pair) => { + const index = pair.indexOf('='); + + if (index > -1) { + cookieJar[pair.slice(0, index).trim()] = pair.slice(index + 1).trim(); + } + }); + const document = { activeElement: null, body: { classList: { add() {}, remove() {} } }, - cookie: options.cookie || '', + get cookie() { + return Object.keys(cookieJar).map((name) => `${name}=${cookieJar[name]}`).join('; '); + }, + set cookie(value) { + const index = value.indexOf('='); + + if (index === -1) { + return; + } + + cookieJar[value.slice(0, index).trim()] = value.slice(index + 1).split(';')[0]; + }, head: { appendChild(script) { scripts.push(script); } }, readyState: 'loading', addEventListener(event, callback) { listeners[event] = callback; }, + removeEventListener() {}, createElement() { return {}; }, dispatchEvent() {}, - getElementById(id) { return id === 'frcn-cookie-reopen' ? reopenBtn : banner; }, - getElementsByTagName() { return []; }, - removeEventListener() {} + getElementById(id) { + if (id === 'frcn-cookie-reopen') { return reopenBtn; } + if (id === 'frcn-cookie-preferences') { return preferencesPanel; } + return banner; + }, + getElementsByTagName() { return []; } }; const window = { location: { protocol: 'https:' }, @@ -95,6 +133,7 @@ function createEnvironment(options = {}) { frcnCookieNotice: { ajaxUrl: 'https://example.test/wp-admin/admin-ajax.php', cookieName: 'frcn_cookie_consent', + categoriesCookieName: 'frontconsent_categories', cookiePath: '/', expirationDays: 365, isPolicyPage: options.isPolicyPage || '', @@ -105,7 +144,7 @@ function createEnvironment(options = {}) { vm.runInNewContext(cookieNoticeScript, context); listeners.DOMContentLoaded(); - return { actionListeners, fetchActions, fetchCalls: () => fetchCalls, reopenBtn, reopenListeners, scripts, window }; + return { actionListeners, fetchActions, fetchCalls: () => fetchCalls, preferencesPanel, reopenBtn, reopenListeners, scripts, window }; } test('does not load ChatGPT Ads before consent and loads it after acceptance', async () => { @@ -222,21 +261,24 @@ test('reopen trigger stays hidden when no decision has been made yet', () => { assert.equal(environment.reopenListeners.click, undefined); }); -test('reopen trigger is revealed and clears the consent cookie on click', () => { +test('reopen trigger is revealed and opens the preferences panel on click', () => { const environment = createEnvironment({ cookie: 'frcn_cookie_consent=accepted' }); assert.equal(environment.reopenBtn.hidden, false); assert.equal(typeof environment.reopenListeners.click, 'function'); + assert.equal(environment.preferencesPanel.hidden, true); let reloaded = false; environment.window.location.reload = () => { reloaded = true; }; environment.reopenListeners.click(); - assert.equal(reloaded, true); + // The panel opens in place — no reload, no navigation away. + assert.equal(reloaded, false); + assert.equal(environment.preferencesPanel.hidden, false); }); -test('reopen trigger on the policy page navigates home instead of reloading in place', () => { +test('reopen trigger opens the preferences panel on the policy page too', () => { const environment = createEnvironment({ cookie: 'frcn_cookie_consent=accepted', isPolicyPage: '1', @@ -248,8 +290,12 @@ test('reopen trigger on the policy page navigates home instead of reloading in p environment.reopenListeners.click(); + // The preferences panel is rendered unconditionally (including on the + // policy page — see CookieNotice::render_preferences_panel()), so the + // reopen trigger no longer needs to navigate away to reach it. assert.equal(reloaded, false); - assert.equal(environment.window.location.href, 'https://example.test/'); + assert.equal(environment.window.location.href, undefined); + assert.equal(environment.preferencesPanel.hidden, false); }); test('accepting sends the consent update through gtag(), not a raw dataLayer push', async () => { diff --git a/tests/js/cookie-notice-purge.test.js b/tests/js/cookie-notice-purge.test.js index 6743f4a..a130d07 100644 --- a/tests/js/cookie-notice-purge.test.js +++ b/tests/js/cookie-notice-purge.test.js @@ -7,7 +7,9 @@ const vm = require('node:vm'); const scriptPath = path.resolve(__dirname, '../../assets/cookie-notice/frontconsent-cookie-notice.js'); const cookieNoticeScript = fs.readFileSync(scriptPath, 'utf8'); -const PURGE_COOKIES = ['_ga', '_ga_*', '_gid', 'sbjs_*']; +const PURGE_COOKIES = ['_ga', '_ga_*', '_gid', '_fbp', 'oaiq_*', 'sbjs_*']; +const ANALYTICS_COOKIES = ['_ga', '_ga_*', '_gid']; +const CATEGORIES_COOKIE = 'frontconsent_categories'; /** * Minimal cookie jar keyed by name + domain, so a cookie set on @@ -43,7 +45,19 @@ function createCookieJar(initial) { }; } -function createEnvironment(initialCookies) { +function createStorage(initial) { + const items = new Map(Object.entries(initial || {})); + + return { + get length() { return items.size; }, + key(index) { return Array.from(items.keys())[index] || null; }, + removeItem(key) { items.delete(key); }, + keys() { return Array.from(items.keys()); } + }; +} + +function createEnvironment(initialCookies, initialSessionStorage) { + const sessionStorage = createStorage(initialSessionStorage); const cookies = createCookieJar(initialCookies); const listeners = {}; const actionListeners = {}; @@ -69,6 +83,28 @@ function createEnvironment(initialCookies) { hidden: true, addEventListener(event, callback) { reopenListeners[event] = callback; } }; + const panelListeners = {}; + const toggles = ['analytics', 'marketing'].map((category) => ({ + checked: false, + getAttribute() { return category; } + })); + const preferencesPanel = { + hidden: true, + querySelector(selector) { + const actionMatch = selector.match(/^\[data-frcn-cookie-action="([a-z-]+)"\]$/); + if (actionMatch) { + return { + addEventListener(event, callback) { + panelListeners[actionMatch[1]] = callback; + } + }; + } + return null; + }, + querySelectorAll(selector) { + return '[data-frcn-category]' === selector ? toggles : []; + } + }; const document = { activeElement: null, body: { classList: { add() {}, remove() {} } }, @@ -79,13 +115,22 @@ function createEnvironment(initialCookies) { addEventListener(event, callback) { listeners[event] = callback; }, createElement() { return {}; }, dispatchEvent() {}, - getElementById(id) { return id === 'frcn-cookie-reopen' ? reopenBtn : banner; }, + getElementById(id) { + if ('frcn-cookie-reopen' === id) { + return reopenBtn; + } + if ('frcn-cookie-preferences' === id) { + return preferencesPanel; + } + return banner; + }, getElementsByTagName() { return []; }, querySelectorAll() { return []; }, removeEventListener() {} }; const window = { location: { protocol: 'https:', hostname: 'www.example.com', reload() {} }, + sessionStorage, setTimeout(callback) { callback(); } }; @@ -101,17 +146,19 @@ function createEnvironment(initialCookies) { frcnCookieNotice: { ajaxUrl: 'https://www.example.com/wp-admin/admin-ajax.php', cookieName: 'frcn_cookie_consent', + categoriesCookieName: CATEGORIES_COOKIE, cookiePath: '/', expirationDays: 365, isPolicyPage: '', homeUrl: 'https://www.example.com/', - purgeCookies: PURGE_COOKIES + purgeCookies: PURGE_COOKIES, + analyticsCookies: ANALYTICS_COOKIES }, window }); listeners.DOMContentLoaded(); - return { actionListeners, cookieNames: () => Array.from(cookies.jar.values()).map((cookie) => cookie.name), reopenListeners }; + return { actionListeners, cookieNames: () => Array.from(cookies.jar.values()).map((cookie) => cookie.name), panelListeners, reopenListeners, sessionStorage, toggles }; } test('rejecting deletes tracking cookies set on the host and on parent domains', () => { @@ -125,7 +172,7 @@ test('rejecting deletes tracking cookies set on the host and on parent domains', environment.actionListeners.reject({ preventDefault() {} }); - assert.deepEqual(environment.cookieNames().sort(), ['frcn_cookie_consent', 'woocommerce_items_in_cart']); + assert.deepEqual(environment.cookieNames().sort(), ['frcn_cookie_consent', CATEGORIES_COOKIE, 'woocommerce_items_in_cart']); }); test('accepting keeps tracking cookies', () => { @@ -145,7 +192,7 @@ test('a returning rejected visitor has leftover tracking cookies cleared on page assert.deepEqual(environment.cookieNames(), ['frcn_cookie_consent']); }); -test('withdrawing an earlier acceptance deletes tracking cookies', () => { +test('withdrawing an earlier acceptance from the preferences panel deletes tracking cookies', () => { const environment = createEnvironment([ ['frcn_cookie_consent', 'accepted', ''], ['_ga', 'GA1.1.1', '.example.com'], @@ -154,6 +201,40 @@ test('withdrawing an earlier acceptance deletes tracking cookies', () => { assert.ok(environment.cookieNames().includes('_ga')); environment.reopenListeners.click(); + environment.panelListeners.reject(); + + assert.deepEqual(environment.cookieNames().sort(), ['frcn_cookie_consent', CATEGORIES_COOKIE]); +}); + +test('saving Analytics only keeps analytics cookies and deletes marketing ones', () => { + const environment = createEnvironment([ + ['_ga', 'GA1.1.1', '.example.com'], + ['_fbp', 'fb.1.1', '.example.com'] + ]); + + environment.toggles[0].checked = true; + environment.panelListeners.save(); + + assert.ok(environment.cookieNames().includes('_ga')); + assert.ok(!environment.cookieNames().includes('_fbp')); +}); + +test('a returning Analytics-only visitor keeps _ga on page load', () => { + const environment = createEnvironment([ + ['frcn_cookie_consent', 'accepted', ''], + [CATEGORIES_COOKIE, encodeURIComponent(JSON.stringify({ necessary: true, analytics: true, marketing: false })), ''], + ['_ga', 'GA1.1.1', '.example.com'], + ['_fbp', 'fb.1.1', '.example.com'] + ]); + + assert.ok(environment.cookieNames().includes('_ga')); + assert.ok(!environment.cookieNames().includes('_fbp')); +}); + +test('rejecting also clears tracking entries kept in web storage', () => { + const environment = createEnvironment([], { 'oaiq_cs:PIXEL123': '1', 'unrelated': 'keep' }); + + environment.actionListeners.reject({ preventDefault() {} }); - assert.deepEqual(environment.cookieNames(), []); + assert.deepEqual(environment.sessionStorage.keys(), ['unrelated']); }); diff --git a/tests/js/script-blocker.test.js b/tests/js/script-blocker.test.js new file mode 100644 index 0000000..19f8bf1 --- /dev/null +++ b/tests/js/script-blocker.test.js @@ -0,0 +1,245 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const scriptPath = path.resolve(__dirname, '../../assets/cookie-notice/frontconsent-script-blocker.js'); +const scriptBlockerScript = fs.readFileSync(scriptPath, 'utf8'); + +function makeParent() { + const inserted = []; + const removed = []; + + return { + inserted, + removed, + insertBefore(newNode, referenceNode) { + inserted.push({ newNode, referenceNode }); + }, + removeChild(node) { + removed.push(node); + } + }; +} + +function makeElement(tagName, attrs) { + const values = Object.assign({}, attrs); + + const element = { + tagName: tagName.toUpperCase(), + parentNode: null, + src: undefined, + get attributes() { + return Object.keys(values).map(function (name) { + return { name: name, value: values[name] }; + }); + }, + getAttribute(name) { + return Object.prototype.hasOwnProperty.call(values, name) ? values[name] : null; + }, + setAttribute(name, value) { + values[name] = String(value); + }, + removeAttribute(name) { + delete values[name]; + } + }; + + // Mimic the real DOM's src attribute/property reflection: an element + // created from markup with a src="..." attribute also has a matching + // .src property, which is what reviveIframe() reads/writes directly. + if (Object.prototype.hasOwnProperty.call(values, 'src')) { + element.src = values.src; + } + + return element; +} + +function createEnvironment(options) { + options = options || {}; + + const placeholders = options.placeholders || []; + const createdScripts = []; + const listeners = {}; + + const document = { + cookie: options.cookie || '', + readyState: 'loading', + addEventListener(event, callback) { + listeners[event] = callback; + }, + querySelectorAll(selector) { + assert.equal(selector, 'script[data-frcn-category], iframe[data-frcn-category]'); + return placeholders; + }, + createElement(tagName) { + const script = makeElement(tagName, {}); + createdScripts.push(script); + return script; + } + }; + + const context = { Array, document, window: {} }; + + if (Object.prototype.hasOwnProperty.call(options, 'frcnCookieNotice')) { + context.frcnCookieNotice = options.frcnCookieNotice; + } + + if (options.isCategoryAllowed) { + context.window.frcnCookieNoticeIsCategoryAllowed = options.isCategoryAllowed; + } + + vm.createContext(context); + vm.runInContext(scriptBlockerScript, context); + listeners.DOMContentLoaded(); + + return { context, createdScripts, listeners, placeholders }; +} + +test('a placeholder script for an accepted category is revived into a real, freshly-created script', () => { + const parent = makeParent(); + const placeholder = makeElement('script', { + type: 'text/plain', + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://tracker.example.com/pixel.js', + id: 'my-tracker', + async: '' + }); + placeholder.parentNode = parent; + + const environment = createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(environment.createdScripts.length, 1); + + const revived = environment.createdScripts[0]; + assert.equal(revived.src, 'https://tracker.example.com/pixel.js'); + assert.equal(revived.getAttribute('id'), 'my-tracker'); + assert.equal(revived.getAttribute('async'), ''); + // The 'type' attribute (and the data-frcn-* bookkeeping attributes) must + // NOT be copied onto the new element — a text/plain script would still + // never execute, even freshly created. + assert.equal(revived.getAttribute('type'), null); + assert.equal(revived.getAttribute('data-frcn-category'), null); + assert.equal(revived.getAttribute('data-frcn-src'), null); + + assert.equal(parent.inserted.length, 1); + assert.equal(parent.inserted[0].newNode, revived); + assert.equal(parent.inserted[0].referenceNode, placeholder); + assert.equal(parent.removed.length, 1); + assert.equal(parent.removed[0], placeholder); +}); + +test("an accepted iframe's src is restored from data-frcn-src and its bookkeeping attributes are cleaned up", () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank', + width: '600' + }); + placeholder.parentNode = makeParent(); + + createEnvironment({ + cookie: 'frcn_cookie_consent=accepted', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'https://www.google.com/maps/embed?pb=1'); + assert.equal(placeholder.getAttribute('data-frcn-src'), null); + assert.equal(placeholder.getAttribute('data-frcn-category'), null); + assert.equal(placeholder.getAttribute('width'), '600'); +}); + +test('a placeholder for a still-rejected category is left completely alone', () => { + const parent = makeParent(); + const placeholder = makeElement('script', { + type: 'text/plain', + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://tracker.example.com/pixel.js' + }); + placeholder.parentNode = parent; + + const environment = createEnvironment({ + cookie: 'frcn_cookie_consent=rejected', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(environment.createdScripts.length, 0); + assert.equal(parent.inserted.length, 0); + assert.equal(parent.removed.length, 0); + assert.equal(placeholder.getAttribute('data-frcn-src'), 'https://tracker.example.com/pixel.js'); +}); + +test('an undecided visitor (no consent cookie yet) leaves placeholders alone', () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + placeholder.parentNode = makeParent(); + + createEnvironment({ + cookie: '', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'about:blank'); +}); + +test('a per-category override (window.frcnCookieNoticeIsCategoryAllowed) is consulted instead of the binary cookie', () => { + const marketingPlaceholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + marketingPlaceholder.parentNode = makeParent(); + + const analyticsPlaceholder = makeElement('iframe', { + 'data-frcn-category': 'analytics', + 'data-frcn-src': 'https://tracker.example.com/embed', + src: 'about:blank' + }); + analyticsPlaceholder.parentNode = makeParent(); + + createEnvironment({ + // The binary cookie says 'rejected' — without the override, nothing + // would be revived; the override says 'analytics' is allowed anyway. + cookie: 'frcn_cookie_consent=rejected', + isCategoryAllowed: (category) => category === 'analytics', + placeholders: [marketingPlaceholder, analyticsPlaceholder] + }); + + assert.equal(marketingPlaceholder.src, 'about:blank'); + assert.equal(analyticsPlaceholder.src, 'https://tracker.example.com/embed'); +}); + +test('revives newly-accepted placeholders on the frcnCookieConsent event', () => { + const placeholder = makeElement('iframe', { + 'data-frcn-category': 'marketing', + 'data-frcn-src': 'https://www.google.com/maps/embed?pb=1', + src: 'about:blank' + }); + placeholder.parentNode = makeParent(); + + const environment = createEnvironment({ + cookie: '', + frcnCookieNotice: { cookieName: 'frcn_cookie_consent' }, + placeholders: [placeholder] + }); + + assert.equal(placeholder.src, 'about:blank'); + + // A visitor decides to accept: frontconsent-cookie-notice.js sets the + // cookie first, then dispatches this same event. + environment.context.document.cookie = 'frcn_cookie_consent=accepted'; + environment.listeners.frcnCookieConsent({ detail: { consent: 'accepted' } }); + + assert.equal(placeholder.src, 'https://www.google.com/maps/embed?pb=1'); +});