From ec8f33ce0c80b491ca5af84abb83572e3be64149 Mon Sep 17 00:00:00 2001 From: Phil Ricketts <812139+replete@users.noreply.github.com> Date: Tue, 17 Sep 2024 22:13:07 +0100 Subject: [PATCH] Integrate dynamic dialog polyfill loading --- README.md | 50 +- dist/biscuitman.js | 17 +- dist/biscuitman.min.js | 2 +- dist/biscuitman.withcss.js | 17 +- dist/biscuitman.withcss.min.js | 2 +- dist/dialog-polyfill.withcss.js | 910 ++++++++++++++++++++++++++++ dist/dialog-polyfill.withcss.min.js | 1 + dist/esm/biscuitman.min.mjs | 2 +- dist/esm/biscuitman.mjs | 17 +- dist/esm/biscuitman.withcss.min.mjs | 2 +- dist/esm/biscuitman.withcss.mjs | 17 +- index-esm.html | 17 - index.html | 17 - package-lock.json | 7 + package.json | 3 +- run.js | 47 +- src/biscuitman.js | 16 + src/biscuitman.mjs | 17 +- 18 files changed, 1079 insertions(+), 82 deletions(-) create mode 100644 dist/dialog-polyfill.withcss.js create mode 100644 dist/dialog-polyfill.withcss.min.js diff --git a/README.md b/README.md index 4e31e1c..4877891 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ // more: '(Show more)', // Show more button text // noCookies: 'No cookies to display', // Displayed in expanded sections within modal // acceptNonEU: false, // When enabled biscuitman checks browser locale timezone to see if it matches EU, if not it will auto consent + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js', // set to false to disable dialog polyfill loading message: 'By clicking "Accept All", you agree to the use of cookies for improving browsing, providing personalized ads or content, and analyzing traffic. {link}', // {link} inside any configuration string will be replaced with an link @@ -176,46 +177,29 @@ html.bm-show::after { ## Browser Support -With browserlist, we're targeting `">= 2%, last 2 years"`. The earliest versions tested working are: +Biscuitman is written in modern Javascript and transpiled `swc` to target browsers less than two years old. The included distributables are tested to support the following browsers: - Chrome/Edge/Opera: 85+ (released June 2020) - Firefox: 98+ (released March 2022) - Safari (inc iOS): 15.4+ (released March 2022) - Samsung Internet: 14+ (released April 2021) -### Extend browser support with Dialog polyfill +### \ polyfill -Include this script alongside the biscuitman config to extend browser support to: +To support older than the browsers above, a polyfill for `` is required. Biscuitman checks for this and will load the [dialog polyfill](https://github.com/GoogleChrome/dialog-polyfill) automatically if it is not already loaded, and then correctly bind. + +For this to work, you must host `dist/dialog-polyfill.withcss.js` and set the biscuitman config property, `dialogPolyfill`, to the correct URL. + +This will extend the browser support to: - Safari (inc iOS) 13.1+ (released March 2020) - Firefox 77+ (released June 2020) - Firefox Android 79+ (released August 2020) -```html - -``` +If the dialog polyfill is already loaded (`window.dialogPolyfill` exists), the polyfill will not be loaded again. To disable this on-demand functionality altogether, set `dialogPolyfill` property to `false`. -### Extend browser support even further with javascript polyfills +### Extending Browser support -You can extend support to these browsers, by including the following script _before_ biscuitman.js: +You can extend support to the following browsers by including the following script _before_ biscuitman.js: - Safari 11.1+ (released Jan 2018) - Safari iOS 11.3+ (released Mar 2018) - Firefox 55+ (released Aug 2017) @@ -225,14 +209,11 @@ You can extend support to these browsers, by including the following script _bef ``` -Obviously a third party hosted polyfill is not good for performance, so in this scenario you'd want to self-host the `replaceAll` and `Object.fromEntries` polyfills. - -This does not apply to the ESM version, the support for ESM more like 2020. - -If you need to support earlier than these browsers, biscuitman would need to be compiled for an earlier javascript target as things like the spread operator are unsupported in earlier versions, which is possible by specifying an earlier `browserlist` target in package.json. +Obviously a third party hosted polyfill is not good for performance, so in this scenario you'd want to self-host the `replaceAll` and `Object.fromEntries` polyfills. This is the lazy approach, if you really need to support older browsers it would make more sense to rebuild biscuitman with an earlier javascript target (update `package.json` `browserlist` property and rebuild with `npm run build`). If there was enough need for this, I'd consider adding a build target for older browsers and release as `biscuitman.legacy.js`. ## Globals -- `biscuitman` – configuration object, must be `window.biscuitman` (`biscuitman.create(options)` for ESM version) +- `biscuitman` – configuration object, must be `window.biscuitman` + - `biscuitman.create(options)` for the ESM version - `Consent` – object for accessing consents (override: `global` in config) ``` { @@ -249,7 +230,6 @@ If you need to support earlier than these browsers, biscuitman would need to be - `bmOpen()` – Opens My Consent Settings modal (you might want to link this on your Privacy policy or footer nav) - example usage: ` Update my consent settings` -The ESM version currently does still use some globals. ## CSS Classes @@ -276,8 +256,6 @@ document.addEventListener('bm:save', ({ detail }) => { let { data, time } = detail console.log(data) }) - -TODO: Switch to `postMessage` to support web workers. ``` ## Development diff --git a/dist/biscuitman.js b/dist/biscuitman.js index 672297f..0c9b7c0 100644 --- a/dist/biscuitman.js +++ b/dist/biscuitman.js @@ -18,7 +18,8 @@ info: '', more: 'Show more', noCookies: 'No cookies to display', - acceptNonEU: false + acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js' }; const o = { ...defaults, @@ -84,6 +85,7 @@ dialog = ui.querySelector('dialog'); dialog.addEventListener('close', closeModalHandler); dialog.addEventListener('cancel', cancelModalHandler); + if (o.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog); const moreLink = ui.querySelector('.more'); if (moreLink) moreLink.addEventListener('click', moreLink.remove); ui.querySelectorAll('[data-s]').forEach((checkbox)=>checkbox.addEventListener('change', (e)=>{ @@ -154,6 +156,19 @@ })); console.debug(name, payload); } + function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill'); + w.dialogPolyfill.registerDialog(dialog); + } + if (w.dialogPolyfill) mount(); + else { + const script = d.createElement('script'); + script.onload = mount; + script.src = o.dialogPolyfill; + d.head.appendChild(script); + } + } // Data: const getConsents = ()=>w[o.global] || {}; function setConsents(consents) { diff --git a/dist/biscuitman.min.js b/dist/biscuitman.min.js index 16961e8..4a99517 100644 --- a/dist/biscuitman.min.js +++ b/dist/biscuitman.min.js @@ -1 +1 @@ -/*! biscuitman.js 0.4.1 */((e,t,o,a)=>{let n;let i={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,...t.biscuitman},s=e.createElement("div"),c=()=>{a.style.setProperty("--bm-height",`${s.offsetHeight}px`)},l=e=>{a.classList.toggle("bm-show",e),c()},r=()=>{let{consentTime:e,...t}=f();for(let[n,s]of(e||(t=o.fromEntries(i.sections.slice(1).map(e=>[e,!1]))),o.entries(t)))a.classList.toggle(`bm-${n}`,s),a.classList.toggle(`bm-no-${n}`,!s)};function d(e){let t=e.target.dataset.id;switch(b("button",{id:t}),t){case"accept":h(!0);break;case"close":n.close();break;case"settings":u();break;case"save":h();break;case"reject":h(!1)}}function m(){b("close")}function p(e){i.force&&e.preventDefault()}function u(){b("open"),n.showModal()}function b(t,o){let a=`bm:${t}`,n={...void 0!==o&&o,time:+new Date};e.dispatchEvent(new CustomEvent(a,{detail:n})),console.debug(a,n)}let f=()=>t[i.global]||{};function $(e){t[i.global]=e,r()}function g(e,t){for(let o in e)e[o]&&!1===t[o]&&b("revoke",{section:o})}function v(){try{return JSON.parse(localStorage.getItem(i.key))}catch(e){return console.error(e),localStorage.removeItem(i.key),{}}}function k(){let t=o.fromEntries(o.entries(localStorage)),a=o.fromEntries(e.cookie.split("; ").map(e=>e.split("="))),{consentTime:n,...s}=v()||i.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[n,c]of o.entries(s)){if(c)continue;let s=o.keys(i[`${n}Cookies`]||{});for(let n of(s.filter(e=>e.endsWith("*")).map(e=>{o.keys({...a,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&s.push(t)})}),s)){if(a[n]){let t=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;e.cookie=t,e.cookie=`${t}domain=${location.hostname};`,e.cookie=`${t}domain=.${location.hostname};`,b("delete",{cookie:n})}t[n]&&(localStorage.removeItem(n),b("delete",{localStorage:n}))}}}function h(e){let t=void 0===e,o={consentTime:+new Date};i.sections.forEach(a=>{if("essential"===a)return!1;let n=s.querySelector(`[data-s=${a}]`),i=t?n.checked:e;o[a]=i,t||(n.checked=e)}),g(f(),o),$(o),localStorage.setItem(i.key,JSON.stringify(o)),b("save",{data:o}),k(),E(),n.open&&n.close(),l(!1)}function E(){e.querySelectorAll("script[data-consent]").forEach(t=>{if(!f()[t.dataset.consent])return!1;let o=e.createElement("script");for(let{name:e,value:a}of t.attributes)e.startsWith("data-")||"type"===e||o.setAttribute(e,a);o.setAttribute("type",t.dataset.type||"text/javascript"),t.src||(o.textContent=t.textContent),t.parentNode.replaceChild(o,t),b("inject",{el:t,...t.id&&{id:t.id}}),t.src&&""!==t.textContent.trim()&&o.addEventListener("load",()=>{let a=e.createElement("script");a.textContent=t.textContent,t.id&&(a.id=t.id+"-after"),o.insertAdjacentElement("afterend",a),b("inject",{el:a,parent:t,...a.id&&{id:a.id}})})})}$(v()||{});let y=Intl.DateTimeFormat().resolvedOptions().timeZone,T=/^(GMT|UTC)$/.test(y)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(y);i.acceptNonEU&&!T&&(h(!0),l(!1)),function(){s.classList.add("biscuitman"),s.innerHTML=`
${i.title}

${i.message}

${i.settingsTitle}

${i.message}

${i.info.split("\n").map((e,t,o)=>`${e}${o.length>1&&i.enableMore&&0==t?`${i.more}`:""}`).join("")}

${i.sections.map(e=>{let t=f()[e],a="essential"===e,n=a?"disabled":"",s=a?"checked":"";void 0!==t&&(s=t?"checked":"");let c=i[`${e}Cookies`];return`
${i[`${e}Title`]}

${i[`${e}Message`]}

${c?o.entries(c).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${i.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${i.linkText}`),s.querySelectorAll("button").forEach(e=>e.addEventListener("click",d)),(n=s.querySelector("dialog")).addEventListener("close",m),n.addEventListener("cancel",p);let a=s.querySelector(".more");a&&a.addEventListener("click",a.remove),s.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),e.body.appendChild(s),t.addEventListener("resize",c)}(),k(),t[i.global].consentTime?(l(!1),E()):(l(!0),i.force&&u()),t.bmInvalidate=()=>{b("invalidate",{data:f()}),g({}),h(!1),$({}),localStorage.removeItem(i.key),l(!0)},t.bmUpdate=()=>{b("update",{data:f()}),u()}})(document,window,Object,document.documentElement); \ No newline at end of file +/*! biscuitman.js 0.4.1 */((e,t,o,a)=>{let i;let n={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,dialogPolyfill:"/dist/dialog-polyfill.withcss.min.js",...t.biscuitman},s=e.createElement("div"),l=()=>{a.style.setProperty("--bm-height",`${s.offsetHeight}px`)},c=e=>{a.classList.toggle("bm-show",e),l()},r=()=>{let{consentTime:e,...t}=b();for(let[i,s]of(e||(t=o.fromEntries(n.sections.slice(1).map(e=>[e,!1]))),o.entries(t)))a.classList.toggle(`bm-${i}`,s),a.classList.toggle(`bm-no-${i}`,!s)};function d(e){let t=e.target.dataset.id;switch(f("button",{id:t}),t){case"accept":y(!0);break;case"close":i.close();break;case"settings":u();break;case"save":y();break;case"reject":y(!1)}}function m(){f("close")}function p(e){n.force&&e.preventDefault()}function u(){f("open"),i.showModal()}function f(t,o){let a=`bm:${t}`,i={...void 0!==o&&o,time:+new Date};e.dispatchEvent(new CustomEvent(a,{detail:i})),console.debug(a,i)}let b=()=>t[n.global]||{};function g(e){t[n.global]=e,r()}function $(e,t){for(let o in e)e[o]&&!1===t[o]&&f("revoke",{section:o})}function v(){try{return JSON.parse(localStorage.getItem(n.key))}catch(e){return console.error(e),localStorage.removeItem(n.key),{}}}function h(){let t=o.fromEntries(o.entries(localStorage)),a=o.fromEntries(e.cookie.split("; ").map(e=>e.split("="))),{consentTime:i,...s}=v()||n.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[i,l]of o.entries(s)){if(l)continue;let s=o.keys(n[`${i}Cookies`]||{});for(let i of(s.filter(e=>e.endsWith("*")).map(e=>{o.keys({...a,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&s.push(t)})}),s)){if(a[i]){let t=`${i}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;e.cookie=t,e.cookie=`${t}domain=${location.hostname};`,e.cookie=`${t}domain=.${location.hostname};`,f("delete",{cookie:i})}t[i]&&(localStorage.removeItem(i),f("delete",{localStorage:i}))}}}function y(e){let t=void 0===e,o={consentTime:+new Date};n.sections.forEach(a=>{if("essential"===a)return!1;let i=s.querySelector(`[data-s=${a}]`),n=t?i.checked:e;o[a]=n,t||(i.checked=e)}),$(b(),o),g(o),localStorage.setItem(n.key,JSON.stringify(o)),f("save",{data:o}),h(),k(),i.open&&i.close(),c(!1)}function k(){e.querySelectorAll("script[data-consent]").forEach(t=>{if(!b()[t.dataset.consent])return!1;let o=e.createElement("script");for(let{name:e,value:a}of t.attributes)e.startsWith("data-")||"type"===e||o.setAttribute(e,a);o.setAttribute("type",t.dataset.type||"text/javascript"),t.src||(o.textContent=t.textContent),t.parentNode.replaceChild(o,t),f("inject",{el:t,...t.id&&{id:t.id}}),t.src&&""!==t.textContent.trim()&&o.addEventListener("load",()=>{let a=e.createElement("script");a.textContent=t.textContent,t.id&&(a.id=t.id+"-after"),o.insertAdjacentElement("afterend",a),f("inject",{el:a,parent:t,...a.id&&{id:a.id}})})})}g(v()||{});let E=Intl.DateTimeFormat().resolvedOptions().timeZone,T=/^(GMT|UTC)$/.test(E)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(E);n.acceptNonEU&&!T&&(y(!0),c(!1)),function(){s.classList.add("biscuitman"),s.innerHTML=`
${n.title}

${n.message}

${n.settingsTitle}

${n.message}

${n.info.split("\n").map((e,t,o)=>`${e}${o.length>1&&n.enableMore&&0==t?`${n.more}`:""}`).join("")}

${n.sections.map(e=>{let t=b()[e],a="essential"===e,i=a?"disabled":"",s=a?"checked":"";void 0!==t&&(s=t?"checked":"");let l=n[`${e}Cookies`];return`
${n[`${e}Title`]}

${n[`${e}Message`]}

${l?o.entries(l).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${n.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${n.linkText}`),s.querySelectorAll("button").forEach(e=>e.addEventListener("click",d)),(i=s.querySelector("dialog")).addEventListener("close",m),i.addEventListener("cancel",p),(!n.dialogPolyfill||i.close)&&i.showModal||function(o){function a(){e.documentElement.classList.add("bm-dialog-polyfill"),t.dialogPolyfill.registerDialog(o)}if(t.dialogPolyfill)a();else{let t=e.createElement("script");t.onload=a,t.src=n.dialogPolyfill,e.head.appendChild(t)}}(i);let a=s.querySelector(".more");a&&a.addEventListener("click",a.remove),s.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),e.body.appendChild(s),t.addEventListener("resize",l)}(),h(),t[n.global].consentTime?(c(!1),k()):(c(!0),n.force&&u()),t.bmInvalidate=()=>{f("invalidate",{data:b()}),$({}),y(!1),g({}),localStorage.removeItem(n.key),c(!0)},t.bmUpdate=()=>{f("update",{data:b()}),u()}})(document,window,Object,document.documentElement); \ No newline at end of file diff --git a/dist/biscuitman.withcss.js b/dist/biscuitman.withcss.js index 1a29088..ec487e2 100644 --- a/dist/biscuitman.withcss.js +++ b/dist/biscuitman.withcss.js @@ -18,7 +18,8 @@ info: '', more: 'Show more', noCookies: 'No cookies to display', - acceptNonEU: false + acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js' }; const o = { ...defaults, @@ -84,6 +85,7 @@ dialog = ui.querySelector('dialog'); dialog.addEventListener('close', closeModalHandler); dialog.addEventListener('cancel', cancelModalHandler); + if (o.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog); const moreLink = ui.querySelector('.more'); if (moreLink) moreLink.addEventListener('click', moreLink.remove); ui.querySelectorAll('[data-s]').forEach((checkbox)=>checkbox.addEventListener('change', (e)=>{ @@ -154,6 +156,19 @@ })); console.debug(name, payload); } + function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill'); + w.dialogPolyfill.registerDialog(dialog); + } + if (w.dialogPolyfill) mount(); + else { + const script = d.createElement('script'); + script.onload = mount; + script.src = o.dialogPolyfill; + d.head.appendChild(script); + } + } // Data: const getConsents = ()=>w[o.global] || {}; function setConsents(consents) { diff --git a/dist/biscuitman.withcss.min.js b/dist/biscuitman.withcss.min.js index 2ee1710..eadb7bc 100644 --- a/dist/biscuitman.withcss.min.js +++ b/dist/biscuitman.withcss.min.js @@ -1 +1 @@ -/*! biscuitman.js 0.4.1 */((e,t,o,a)=>{let n;let i={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,...t.biscuitman},s=e.createElement("div"),c=()=>{a.style.setProperty("--bm-height",`${s.offsetHeight}px`)},l=e=>{a.classList.toggle("bm-show",e),c()},r=()=>{let{consentTime:e,...t}=f();for(let[n,s]of(e||(t=o.fromEntries(i.sections.slice(1).map(e=>[e,!1]))),o.entries(t)))a.classList.toggle(`bm-${n}`,s),a.classList.toggle(`bm-no-${n}`,!s)};function d(e){let t=e.target.dataset.id;switch(b("button",{id:t}),t){case"accept":h(!0);break;case"close":n.close();break;case"settings":u();break;case"save":h();break;case"reject":h(!1)}}function m(){b("close")}function p(e){i.force&&e.preventDefault()}function u(){b("open"),n.showModal()}function b(t,o){let a=`bm:${t}`,n={...void 0!==o&&o,time:+new Date};e.dispatchEvent(new CustomEvent(a,{detail:n})),console.debug(a,n)}let f=()=>t[i.global]||{};function $(e){t[i.global]=e,r()}function g(e,t){for(let o in e)e[o]&&!1===t[o]&&b("revoke",{section:o})}function v(){try{return JSON.parse(localStorage.getItem(i.key))}catch(e){return console.error(e),localStorage.removeItem(i.key),{}}}function k(){let t=o.fromEntries(o.entries(localStorage)),a=o.fromEntries(e.cookie.split("; ").map(e=>e.split("="))),{consentTime:n,...s}=v()||i.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[n,c]of o.entries(s)){if(c)continue;let s=o.keys(i[`${n}Cookies`]||{});for(let n of(s.filter(e=>e.endsWith("*")).map(e=>{o.keys({...a,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&s.push(t)})}),s)){if(a[n]){let t=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;e.cookie=t,e.cookie=`${t}domain=${location.hostname};`,e.cookie=`${t}domain=.${location.hostname};`,b("delete",{cookie:n})}t[n]&&(localStorage.removeItem(n),b("delete",{localStorage:n}))}}}function h(e){let t=void 0===e,o={consentTime:+new Date};i.sections.forEach(a=>{if("essential"===a)return!1;let n=s.querySelector(`[data-s=${a}]`),i=t?n.checked:e;o[a]=i,t||(n.checked=e)}),g(f(),o),$(o),localStorage.setItem(i.key,JSON.stringify(o)),b("save",{data:o}),k(),E(),n.open&&n.close(),l(!1)}function E(){e.querySelectorAll("script[data-consent]").forEach(t=>{if(!f()[t.dataset.consent])return!1;let o=e.createElement("script");for(let{name:e,value:a}of t.attributes)e.startsWith("data-")||"type"===e||o.setAttribute(e,a);o.setAttribute("type",t.dataset.type||"text/javascript"),t.src||(o.textContent=t.textContent),t.parentNode.replaceChild(o,t),b("inject",{el:t,...t.id&&{id:t.id}}),t.src&&""!==t.textContent.trim()&&o.addEventListener("load",()=>{let a=e.createElement("script");a.textContent=t.textContent,t.id&&(a.id=t.id+"-after"),o.insertAdjacentElement("afterend",a),b("inject",{el:a,parent:t,...a.id&&{id:a.id}})})})}$(v()||{});let y=Intl.DateTimeFormat().resolvedOptions().timeZone,T=/^(GMT|UTC)$/.test(y)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(y);i.acceptNonEU&&!T&&(h(!0),l(!1)),function(){s.classList.add("biscuitman"),s.innerHTML=`
${i.title}

${i.message}

${i.settingsTitle}

${i.message}

${i.info.split("\n").map((e,t,o)=>`${e}${o.length>1&&i.enableMore&&0==t?`${i.more}`:""}`).join("")}

${i.sections.map(e=>{let t=f()[e],a="essential"===e,n=a?"disabled":"",s=a?"checked":"";void 0!==t&&(s=t?"checked":"");let c=i[`${e}Cookies`];return`
${i[`${e}Title`]}

${i[`${e}Message`]}

${c?o.entries(c).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${i.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${i.linkText}`),s.querySelectorAll("button").forEach(e=>e.addEventListener("click",d)),(n=s.querySelector("dialog")).addEventListener("close",m),n.addEventListener("cancel",p);let a=s.querySelector(".more");a&&a.addEventListener("click",a.remove),s.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),e.body.appendChild(s),t.addEventListener("resize",c)}(),k(),t[i.global].consentTime?(l(!1),E()):(l(!0),i.force&&u()),t.bmInvalidate=()=>{b("invalidate",{data:f()}),g({}),h(!1),$({}),localStorage.removeItem(i.key),l(!0)},t.bmUpdate=()=>{b("update",{data:f()}),u()}})(document,window,Object,document.documentElement);;((d)=>{let c=d.createElement('style');c.textContent=`/*! biscuitman.js 0.4.1 */.biscuitman{--ui:0,0,0;--tx:#444;--bg:#fff;--c:#105d89;background:var(--bg);box-sizing:border-box;z-index:3;width:100%;padding:20px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;display:none;position:fixed;bottom:0;box-shadow:0 -2px 10px rgba(0,0,0,.16)}.bm-show .biscuitman{display:block}.biscuitman *{box-sizing:border-box;color:var(--tx);margin:0;padding:0;font-family:inherit;font-size:16px;line-height:1.4em}.biscuitman:has([open]){transform:translateY(100%)}.biscuitman article{padding:0;position:relative}@media (min-width:770px){.biscuitman article{padding-right:calc(max(300px,30vw) + 20px)}.biscuitman article nav{width:30vw;min-width:300px;position:absolute;bottom:50%;right:0;transform:translateY(50%)}}.biscuitman article p{color:var(--tx);margin:10px 0;font-size:13px}@media (min-width:575px){.biscuitman article p{font-size:14px}}.biscuitman button{background:var(--bg);border:2px solid var(--c);color:var(--c);cursor:pointer;border-radius:3px;margin-top:10px;padding:.8em;font-size:13px;line-height:1em}.biscuitman button[data-id=accept]{background:var(--c);color:var(--bg)!important}.biscuitman button[data-id=close]{color:rgba(var(--ui),.5);opacity:.6;-webkit-user-select:none;user-select:none;z-index:2;background:0 0;border:none;outline:none;padding:10px;font-size:24px;line-height:1em;position:absolute;top:0;right:10px}.biscuitman button[disabled]{display:none}.biscuitman button:hover{opacity:.8}@media (min-width:576px){.biscuitman nav{flex-direction:row-reverse;gap:10px;width:100%;display:flex}.biscuitman nav button{flex-grow:1;margin-bottom:0}}@media (max-width:575px){.biscuitman nav{flex-direction:column;flex-grow:1;display:flex}}.biscuitman dialog{background:var(--bg);border:0;width:100%;max-width:100%;height:100%;max-height:100%}@media (min-width:576px){.biscuitman dialog{border-radius:10px;width:90vw;max-width:860px;max-height:80vh;margin:auto;box-shadow:0 0 8px rgba(0,0,0,.3)}}@media (min-width:576px) and (min-height:1134px){.biscuitman dialog{max-height:950px}}.biscuitman dialog nav{justify-self:flex-end;position:relative}.biscuitman .bm-dialog{flex-direction:column;height:100%;padding:20px;display:flex}.biscuitman .bm-dialog b{padding-bottom:8px;position:relative}.biscuitman .bm-dialog>b:after{content:"";background:linear-gradient(180deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;z-index:1;width:100%;height:25px;margin-bottom:-24px;position:absolute;bottom:0;left:0}.biscuitman .bm-dialog nav:after{content:"";background:linear-gradient(0deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;width:100%;height:25px;position:absolute;top:-24px;left:0}.biscuitman .bm-sections{scrollbar-color:rgba(var(--ui),.2)var(--bg);flex-shrink:1;height:100%;padding:15px 0;position:relative;overflow-y:scroll}@media (min-width:576px){.biscuitman .bm-sections{margin-right:-18px;padding-right:4px}}.biscuitman .bm-sections>p{padding-right:30px;font-size:13px;line-height:18px}@media (min-width:576px){.biscuitman .bm-sections>p{font-size:14px}}.biscuitman .bm-sections>p span{font-size:inherit;padding-bottom:5px;display:inline-block}.biscuitman .bm-sections>p .more~span{display:none}.biscuitman a{font-size:inherit;color:var(--c);cursor:pointer;text-decoration:none;display:inline-block}.biscuitman a:hover{text-decoration:underline}.biscuitman section{margin-bottom:10px;position:relative}.biscuitman section:first-of-type{margin-top:10px}.biscuitman details{border:1px solid rgba(var(--ui),.2);border-radius:5px;padding:10px;list-style:none;box-shadow:0 2px 4px rgba(0,0,0,.1)}.biscuitman details[open] summary b:after{margin:-3px 0 0 -2px;transform:rotate(45deg)scale(.3)}.biscuitman summary{cursor:pointer;flex-direction:column;width:100%;padding:5px 80px 10px 10px;list-style:none;display:flex;position:relative}.biscuitman summary b{margin-bottom:3px}.biscuitman summary b:after{content:"";border:5px solid rgba(var(--ui),.4);border-top-color:transparent;border-left-color:transparent;border-radius:2px;width:1em;height:1em;margin:-2px 0 0 -4px;display:block;transform:rotate(-45deg)scale(.3)}.biscuitman summary p{color:var(--tx);font-size:14px}.biscuitman summary>*{display:inline-flex}.biscuitman summary::marker{display:none}.biscuitman summary::-webkit-details-marker{display:none}.biscuitman dl{background:rgba(var(--ui),.08);margin:10px;padding:10px;display:flex}.biscuitman dl dt{color:var(--tx);font-size:12px}.biscuitman dl dd{color:var(--tx);font-size:12px}.biscuitman dl dt{min-width:120px;padding-right:30px;font-weight:700}.biscuitman label{--height:1.2em;--width:2.3em;--gap:2px;height:var(--height);width:var(--width);background-color:rgba(var(--ui),.3);border-radius:var(--height);margin-top:-2px;display:block;position:absolute;top:50%;right:20px;transform:translateY(-50%);font-size:20px!important}.biscuitman label:before{content:"";background:var(--bg);height:calc(var(--height) - calc(var(--gap)*2));width:calc(var(--height) - calc(var(--gap)*2));height:var(--height);width:var(--height);left:var(--gap);transform-origin:50%;border-radius:100%;display:block;position:absolute;top:50%;left:0;transform:translateY(-50%)scale(.8)}.biscuitman label.checked{background-color:var(--c)}.biscuitman label.checked:before{left:auto;right:0}.biscuitman label:has(:focus-visible){outline:auto highlight}.biscuitman label.disabled.checked{opacity:.5}.biscuitman label input{opacity:0}.bm-dialog-polyfill .biscuitman dialog{position:fixed;top:50%;transform:translateY(-50%)}`;d.head.appendChild(c)})(document); \ No newline at end of file +/*! biscuitman.js 0.4.1 */((e,t,o,a)=>{let i;let n={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,dialogPolyfill:"/dist/dialog-polyfill.withcss.min.js",...t.biscuitman},s=e.createElement("div"),l=()=>{a.style.setProperty("--bm-height",`${s.offsetHeight}px`)},c=e=>{a.classList.toggle("bm-show",e),l()},r=()=>{let{consentTime:e,...t}=b();for(let[i,s]of(e||(t=o.fromEntries(n.sections.slice(1).map(e=>[e,!1]))),o.entries(t)))a.classList.toggle(`bm-${i}`,s),a.classList.toggle(`bm-no-${i}`,!s)};function d(e){let t=e.target.dataset.id;switch(f("button",{id:t}),t){case"accept":y(!0);break;case"close":i.close();break;case"settings":u();break;case"save":y();break;case"reject":y(!1)}}function m(){f("close")}function p(e){n.force&&e.preventDefault()}function u(){f("open"),i.showModal()}function f(t,o){let a=`bm:${t}`,i={...void 0!==o&&o,time:+new Date};e.dispatchEvent(new CustomEvent(a,{detail:i})),console.debug(a,i)}let b=()=>t[n.global]||{};function g(e){t[n.global]=e,r()}function $(e,t){for(let o in e)e[o]&&!1===t[o]&&f("revoke",{section:o})}function v(){try{return JSON.parse(localStorage.getItem(n.key))}catch(e){return console.error(e),localStorage.removeItem(n.key),{}}}function h(){let t=o.fromEntries(o.entries(localStorage)),a=o.fromEntries(e.cookie.split("; ").map(e=>e.split("="))),{consentTime:i,...s}=v()||n.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[i,l]of o.entries(s)){if(l)continue;let s=o.keys(n[`${i}Cookies`]||{});for(let i of(s.filter(e=>e.endsWith("*")).map(e=>{o.keys({...a,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&s.push(t)})}),s)){if(a[i]){let t=`${i}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;e.cookie=t,e.cookie=`${t}domain=${location.hostname};`,e.cookie=`${t}domain=.${location.hostname};`,f("delete",{cookie:i})}t[i]&&(localStorage.removeItem(i),f("delete",{localStorage:i}))}}}function y(e){let t=void 0===e,o={consentTime:+new Date};n.sections.forEach(a=>{if("essential"===a)return!1;let i=s.querySelector(`[data-s=${a}]`),n=t?i.checked:e;o[a]=n,t||(i.checked=e)}),$(b(),o),g(o),localStorage.setItem(n.key,JSON.stringify(o)),f("save",{data:o}),h(),k(),i.open&&i.close(),c(!1)}function k(){e.querySelectorAll("script[data-consent]").forEach(t=>{if(!b()[t.dataset.consent])return!1;let o=e.createElement("script");for(let{name:e,value:a}of t.attributes)e.startsWith("data-")||"type"===e||o.setAttribute(e,a);o.setAttribute("type",t.dataset.type||"text/javascript"),t.src||(o.textContent=t.textContent),t.parentNode.replaceChild(o,t),f("inject",{el:t,...t.id&&{id:t.id}}),t.src&&""!==t.textContent.trim()&&o.addEventListener("load",()=>{let a=e.createElement("script");a.textContent=t.textContent,t.id&&(a.id=t.id+"-after"),o.insertAdjacentElement("afterend",a),f("inject",{el:a,parent:t,...a.id&&{id:a.id}})})})}g(v()||{});let E=Intl.DateTimeFormat().resolvedOptions().timeZone,T=/^(GMT|UTC)$/.test(E)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(E);n.acceptNonEU&&!T&&(y(!0),c(!1)),function(){s.classList.add("biscuitman"),s.innerHTML=`
${n.title}

${n.message}

${n.settingsTitle}

${n.message}

${n.info.split("\n").map((e,t,o)=>`${e}${o.length>1&&n.enableMore&&0==t?`${n.more}`:""}`).join("")}

${n.sections.map(e=>{let t=b()[e],a="essential"===e,i=a?"disabled":"",s=a?"checked":"";void 0!==t&&(s=t?"checked":"");let l=n[`${e}Cookies`];return`
${n[`${e}Title`]}

${n[`${e}Message`]}

${l?o.entries(l).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${n.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${n.linkText}`),s.querySelectorAll("button").forEach(e=>e.addEventListener("click",d)),(i=s.querySelector("dialog")).addEventListener("close",m),i.addEventListener("cancel",p),(!n.dialogPolyfill||i.close)&&i.showModal||function(o){function a(){e.documentElement.classList.add("bm-dialog-polyfill"),t.dialogPolyfill.registerDialog(o)}if(t.dialogPolyfill)a();else{let t=e.createElement("script");t.onload=a,t.src=n.dialogPolyfill,e.head.appendChild(t)}}(i);let a=s.querySelector(".more");a&&a.addEventListener("click",a.remove),s.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),e.body.appendChild(s),t.addEventListener("resize",l)}(),h(),t[n.global].consentTime?(c(!1),k()):(c(!0),n.force&&u()),t.bmInvalidate=()=>{f("invalidate",{data:b()}),$({}),y(!1),g({}),localStorage.removeItem(n.key),c(!0)},t.bmUpdate=()=>{f("update",{data:b()}),u()}})(document,window,Object,document.documentElement);;((d)=>{let c=d.createElement('style');c.textContent=`/*! biscuitman.js 0.4.1 */.biscuitman{--ui:0,0,0;--tx:#444;--bg:#fff;--c:#105d89;background:var(--bg);box-sizing:border-box;z-index:3;width:100%;padding:20px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;display:none;position:fixed;bottom:0;box-shadow:0 -2px 10px rgba(0,0,0,.16)}.bm-show .biscuitman{display:block}.biscuitman *{box-sizing:border-box;color:var(--tx);margin:0;padding:0;font-family:inherit;font-size:16px;line-height:1.4em}.biscuitman:has([open]){transform:translateY(100%)}.biscuitman article{padding:0;position:relative}@media (min-width:770px){.biscuitman article{padding-right:calc(max(300px,30vw) + 20px)}.biscuitman article nav{width:30vw;min-width:300px;position:absolute;bottom:50%;right:0;transform:translateY(50%)}}.biscuitman article p{color:var(--tx);margin:10px 0;font-size:13px}@media (min-width:575px){.biscuitman article p{font-size:14px}}.biscuitman button{background:var(--bg);border:2px solid var(--c);color:var(--c);cursor:pointer;border-radius:3px;margin-top:10px;padding:.8em;font-size:13px;line-height:1em}.biscuitman button[data-id=accept]{background:var(--c);color:var(--bg)!important}.biscuitman button[data-id=close]{color:rgba(var(--ui),.5);opacity:.6;-webkit-user-select:none;user-select:none;z-index:2;background:0 0;border:none;outline:none;padding:10px;font-size:24px;line-height:1em;position:absolute;top:0;right:10px}.biscuitman button[disabled]{display:none}.biscuitman button:hover{opacity:.8}@media (min-width:576px){.biscuitman nav{flex-direction:row-reverse;gap:10px;width:100%;display:flex}.biscuitman nav button{flex-grow:1;margin-bottom:0}}@media (max-width:575px){.biscuitman nav{flex-direction:column;flex-grow:1;display:flex}}.biscuitman dialog{background:var(--bg);border:0;width:100%;max-width:100%;height:100%;max-height:100%}@media (min-width:576px){.biscuitman dialog{border-radius:10px;width:90vw;max-width:860px;max-height:80vh;margin:auto;box-shadow:0 0 8px rgba(0,0,0,.3)}}@media (min-width:576px) and (min-height:1134px){.biscuitman dialog{max-height:950px}}.biscuitman dialog nav{justify-self:flex-end;position:relative}.biscuitman .bm-dialog{flex-direction:column;height:100%;padding:20px;display:flex}.biscuitman .bm-dialog b{padding-bottom:8px;position:relative}.biscuitman .bm-dialog>b:after{content:"";background:linear-gradient(180deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;z-index:1;width:100%;height:25px;margin-bottom:-24px;position:absolute;bottom:0;left:0}.biscuitman .bm-dialog nav:after{content:"";background:linear-gradient(0deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;width:100%;height:25px;position:absolute;top:-24px;left:0}.biscuitman .bm-sections{scrollbar-color:rgba(var(--ui),.2)var(--bg);flex-shrink:1;height:100%;padding:15px 0;position:relative;overflow-y:scroll}@media (min-width:576px){.biscuitman .bm-sections{margin-right:-18px;padding-right:4px}}.biscuitman .bm-sections>p{padding-right:30px;font-size:13px;line-height:18px}@media (min-width:576px){.biscuitman .bm-sections>p{font-size:14px}}.biscuitman .bm-sections>p span{font-size:inherit;padding-bottom:5px;display:inline-block}.biscuitman .bm-sections>p .more~span{display:none}.biscuitman a{font-size:inherit;color:var(--c);cursor:pointer;text-decoration:none;display:inline-block}.biscuitman a:hover{text-decoration:underline}.biscuitman section{margin-bottom:10px;position:relative}.biscuitman section:first-of-type{margin-top:10px}.biscuitman details{border:1px solid rgba(var(--ui),.2);border-radius:5px;padding:10px;list-style:none;box-shadow:0 2px 4px rgba(0,0,0,.1)}.biscuitman details[open] summary b:after{margin:-3px 0 0 -2px;transform:rotate(45deg)scale(.3)}.biscuitman summary{cursor:pointer;flex-direction:column;width:100%;padding:5px 80px 10px 10px;list-style:none;display:flex;position:relative}.biscuitman summary b{margin-bottom:3px}.biscuitman summary b:after{content:"";border:5px solid rgba(var(--ui),.4);border-top-color:transparent;border-left-color:transparent;border-radius:2px;width:1em;height:1em;margin:-2px 0 0 -4px;display:block;transform:rotate(-45deg)scale(.3)}.biscuitman summary p{color:var(--tx);font-size:14px}.biscuitman summary>*{display:inline-flex}.biscuitman summary::marker{display:none}.biscuitman summary::-webkit-details-marker{display:none}.biscuitman dl{background:rgba(var(--ui),.08);margin:10px;padding:10px;display:flex}.biscuitman dl dt{color:var(--tx);font-size:12px}.biscuitman dl dd{color:var(--tx);font-size:12px}.biscuitman dl dt{min-width:120px;padding-right:30px;font-weight:700}.biscuitman label{--height:1.2em;--width:2.3em;--gap:2px;height:var(--height);width:var(--width);background-color:rgba(var(--ui),.3);border-radius:var(--height);margin-top:-2px;display:block;position:absolute;top:50%;right:20px;transform:translateY(-50%);font-size:20px!important}.biscuitman label:before{content:"";background:var(--bg);height:calc(var(--height) - calc(var(--gap)*2));width:calc(var(--height) - calc(var(--gap)*2));height:var(--height);width:var(--height);left:var(--gap);transform-origin:50%;border-radius:100%;display:block;position:absolute;top:50%;left:0;transform:translateY(-50%)scale(.8)}.biscuitman label.checked{background-color:var(--c)}.biscuitman label.checked:before{left:auto;right:0}.biscuitman label:has(:focus-visible){outline:auto highlight}.biscuitman label.disabled.checked{opacity:.5}.biscuitman label input{opacity:0}.bm-dialog-polyfill .biscuitman dialog{position:fixed;top:50%;transform:translateY(-50%)}`;d.head.appendChild(c)})(document); \ No newline at end of file diff --git a/dist/dialog-polyfill.withcss.js b/dist/dialog-polyfill.withcss.js new file mode 100644 index 0000000..c80acff --- /dev/null +++ b/dist/dialog-polyfill.withcss.js @@ -0,0 +1,910 @@ +/*! biscuitman.js 0.4.1 *//* dialog-polyfill.js ^0.5.6*/ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.dialogPolyfill = factory()); +}(this, function () { 'use strict'; + + // nb. This is for IE10 and lower _only_. + var supportCustomEvent = window.CustomEvent; + if (!supportCustomEvent || typeof supportCustomEvent === 'object') { + supportCustomEvent = function CustomEvent(event, x) { + x = x || {}; + var ev = document.createEvent('CustomEvent'); + ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null); + return ev; + }; + supportCustomEvent.prototype = window.Event.prototype; + } + + /** + * Dispatches the passed event to both an "on" handler as well as via the + * normal dispatch operation. Does not bubble. + * + * @param {!EventTarget} target + * @param {!Event} event + * @return {boolean} + */ + function safeDispatchEvent(target, event) { + var check = 'on' + event.type.toLowerCase(); + if (typeof target[check] === 'function') { + target[check](event); + } + return target.dispatchEvent(event); + } + + /** + * @param {Element} el to check for stacking context + * @return {boolean} whether this el or its parents creates a stacking context + */ + function createsStackingContext(el) { + while (el && el !== document.body) { + var s = window.getComputedStyle(el); + var invalid = function(k, ok) { + return !(s[k] === undefined || s[k] === ok); + }; + + if (s.opacity < 1 || + invalid('zIndex', 'auto') || + invalid('transform', 'none') || + invalid('mixBlendMode', 'normal') || + invalid('filter', 'none') || + invalid('perspective', 'none') || + s['isolation'] === 'isolate' || + s.position === 'fixed' || + s.webkitOverflowScrolling === 'touch') { + return true; + } + el = el.parentElement; + } + return false; + } + + /** + * Finds the nearest from the passed element. + * + * @param {Element} el to search from + * @return {HTMLDialogElement} dialog found + */ + function findNearestDialog(el) { + while (el) { + if (el.localName === 'dialog') { + return /** @type {HTMLDialogElement} */ (el); + } + if (el.parentElement) { + el = el.parentElement; + } else if (el.parentNode) { + el = el.parentNode.host; + } else { + el = null; + } + } + return null; + } + + /** + * Blur the specified element, as long as it's not the HTML body element. + * This works around an IE9/10 bug - blurring the body causes Windows to + * blur the whole application. + * + * @param {Element} el to blur + */ + function safeBlur(el) { + // Find the actual focused element when the active element is inside a shadow root + while (el && el.shadowRoot && el.shadowRoot.activeElement) { + el = el.shadowRoot.activeElement; + } + + if (el && el.blur && el !== document.body) { + el.blur(); + } + } + + /** + * @param {!NodeList} nodeList to search + * @param {Node} node to find + * @return {boolean} whether node is inside nodeList + */ + function inNodeList(nodeList, node) { + for (var i = 0; i < nodeList.length; ++i) { + if (nodeList[i] === node) { + return true; + } + } + return false; + } + + /** + * @param {HTMLFormElement} el to check + * @return {boolean} whether this form has method="dialog" + */ + function isFormMethodDialog(el) { + if (!el || !el.hasAttribute('method')) { + return false; + } + return el.getAttribute('method').toLowerCase() === 'dialog'; + } + + /** + * @param {!DocumentFragment|!Element} hostElement + * @return {?Element} + */ + function findFocusableElementWithin(hostElement) { + // Note that this is 'any focusable area'. This list is probably not exhaustive, but the + // alternative involves stepping through and trying to focus everything. + var opts = ['button', 'input', 'keygen', 'select', 'textarea']; + var query = opts.map(function(el) { + return el + ':not([disabled])'; + }); + // TODO(samthor): tabindex values that are not numeric are not focusable. + query.push('[tabindex]:not([disabled]):not([tabindex=""])'); // tabindex != "", not disabled + var target = hostElement.querySelector(query.join(', ')); + + if (!target && 'attachShadow' in Element.prototype) { + // If we haven't found a focusable target, see if the host element contains an element + // which has a shadowRoot. + // Recursively search for the first focusable item in shadow roots. + var elems = hostElement.querySelectorAll('*'); + for (var i = 0; i < elems.length; i++) { + if (elems[i].tagName && elems[i].shadowRoot) { + target = findFocusableElementWithin(elems[i].shadowRoot); + if (target) { + break; + } + } + } + } + return target; + } + + /** + * Determines if an element is attached to the DOM. + * @param {Element} element to check + * @return {boolean} whether the element is in DOM + */ + function isConnected(element) { + return element.isConnected || document.body.contains(element); + } + + /** + * @param {!Event} event + * @return {?Element} + */ + function findFormSubmitter(event) { + if (event.submitter) { + return event.submitter; + } + + var form = event.target; + if (!(form instanceof HTMLFormElement)) { + return null; + } + + var submitter = dialogPolyfill.formSubmitter; + if (!submitter) { + var target = event.target; + var root = ('getRootNode' in target && target.getRootNode() || document); + submitter = root.activeElement; + } + + if (!submitter || submitter.form !== form) { + return null; + } + return submitter; + } + + /** + * @param {!Event} event + */ + function maybeHandleSubmit(event) { + if (event.defaultPrevented) { + return; + } + var form = /** @type {!HTMLFormElement} */ (event.target); + + // We'd have a value if we clicked on an imagemap. + var value = dialogPolyfill.imagemapUseValue; + var submitter = findFormSubmitter(event); + if (value === null && submitter) { + value = submitter.value; + } + + // There should always be a dialog as this handler is added specifically on them, but check just + // in case. + var dialog = findNearestDialog(form); + if (!dialog) { + return; + } + + // Prefer formmethod on the button. + var formmethod = submitter && submitter.getAttribute('formmethod') || form.getAttribute('method'); + if (formmethod !== 'dialog') { + return; + } + event.preventDefault(); + + if (value != null) { + // nb. we explicitly check against null/undefined + dialog.close(value); + } else { + dialog.close(); + } + } + + /** + * @param {!HTMLDialogElement} dialog to upgrade + * @constructor + */ + function dialogPolyfillInfo(dialog) { + this.dialog_ = dialog; + this.replacedStyleTop_ = false; + this.openAsModal_ = false; + + // Set a11y role. Browsers that support dialog implicitly know this already. + if (!dialog.hasAttribute('role')) { + dialog.setAttribute('role', 'dialog'); + } + + dialog.show = this.show.bind(this); + dialog.showModal = this.showModal.bind(this); + dialog.close = this.close.bind(this); + + dialog.addEventListener('submit', maybeHandleSubmit, false); + + if (!('returnValue' in dialog)) { + dialog.returnValue = ''; + } + + if ('MutationObserver' in window) { + var mo = new MutationObserver(this.maybeHideModal.bind(this)); + mo.observe(dialog, {attributes: true, attributeFilter: ['open']}); + } else { + // IE10 and below support. Note that DOMNodeRemoved etc fire _before_ removal. They also + // seem to fire even if the element was removed as part of a parent removal. Use the removed + // events to force downgrade (useful if removed/immediately added). + var removed = false; + var cb = function() { + removed ? this.downgradeModal() : this.maybeHideModal(); + removed = false; + }.bind(this); + var timeout; + var delayModel = function(ev) { + if (ev.target !== dialog) { return; } // not for a child element + var cand = 'DOMNodeRemoved'; + removed |= (ev.type.substr(0, cand.length) === cand); + window.clearTimeout(timeout); + timeout = window.setTimeout(cb, 0); + }; + ['DOMAttrModified', 'DOMNodeRemoved', 'DOMNodeRemovedFromDocument'].forEach(function(name) { + dialog.addEventListener(name, delayModel); + }); + } + // Note that the DOM is observed inside DialogManager while any dialog + // is being displayed as a modal, to catch modal removal from the DOM. + + Object.defineProperty(dialog, 'open', { + set: this.setOpen.bind(this), + get: dialog.hasAttribute.bind(dialog, 'open') + }); + + this.backdrop_ = document.createElement('div'); + this.backdrop_.className = 'backdrop'; + this.backdrop_.addEventListener('mouseup' , this.backdropMouseEvent_.bind(this)); + this.backdrop_.addEventListener('mousedown', this.backdropMouseEvent_.bind(this)); + this.backdrop_.addEventListener('click' , this.backdropMouseEvent_.bind(this)); + } + + dialogPolyfillInfo.prototype = /** @type {HTMLDialogElement.prototype} */ ({ + + get dialog() { + return this.dialog_; + }, + + /** + * Maybe remove this dialog from the modal top layer. This is called when + * a modal dialog may no longer be tenable, e.g., when the dialog is no + * longer open or is no longer part of the DOM. + */ + maybeHideModal: function() { + if (this.dialog_.hasAttribute('open') && isConnected(this.dialog_)) { return; } + this.downgradeModal(); + }, + + /** + * Remove this dialog from the modal top layer, leaving it as a non-modal. + */ + downgradeModal: function() { + if (!this.openAsModal_) { return; } + this.openAsModal_ = false; + this.dialog_.style.zIndex = ''; + + // This won't match the native exactly because if the user set top on a centered + // polyfill dialog, that top gets thrown away when the dialog is closed. Not sure it's + // possible to polyfill this perfectly. + if (this.replacedStyleTop_) { + this.dialog_.style.top = ''; + this.replacedStyleTop_ = false; + } + + // Clear the backdrop and remove from the manager. + this.backdrop_.parentNode && this.backdrop_.parentNode.removeChild(this.backdrop_); + dialogPolyfill.dm.removeDialog(this); + }, + + /** + * @param {boolean} value whether to open or close this dialog + */ + setOpen: function(value) { + if (value) { + this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', ''); + } else { + this.dialog_.removeAttribute('open'); + this.maybeHideModal(); // nb. redundant with MutationObserver + } + }, + + /** + * Handles mouse events ('mouseup', 'mousedown', 'click') on the fake .backdrop element, redirecting them as if + * they were on the dialog itself. + * + * @param {!Event} e to redirect + */ + backdropMouseEvent_: function(e) { + if (!this.dialog_.hasAttribute('tabindex')) { + // Clicking on the backdrop should move the implicit cursor, even if dialog cannot be + // focused. Create a fake thing to focus on. If the backdrop was _before_ the dialog, this + // would not be needed - clicks would move the implicit cursor there. + var fake = document.createElement('div'); + this.dialog_.insertBefore(fake, this.dialog_.firstChild); + fake.tabIndex = -1; + fake.focus(); + this.dialog_.removeChild(fake); + } else { + this.dialog_.focus(); + } + + var redirectedEvent = document.createEvent('MouseEvents'); + redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window, + e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, + e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); + this.dialog_.dispatchEvent(redirectedEvent); + e.stopPropagation(); + }, + + /** + * Focuses on the first focusable element within the dialog. This will always blur the current + * focus, even if nothing within the dialog is found. + */ + focus_: function() { + // Find element with `autofocus` attribute, or fall back to the first form/tabindex control. + var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); + if (!target && this.dialog_.tabIndex >= 0) { + target = this.dialog_; + } + if (!target) { + target = findFocusableElementWithin(this.dialog_); + } + safeBlur(document.activeElement); + target && target.focus(); + }, + + /** + * Sets the zIndex for the backdrop and dialog. + * + * @param {number} dialogZ + * @param {number} backdropZ + */ + updateZIndex: function(dialogZ, backdropZ) { + if (dialogZ < backdropZ) { + throw new Error('dialogZ should never be < backdropZ'); + } + this.dialog_.style.zIndex = dialogZ; + this.backdrop_.style.zIndex = backdropZ; + }, + + /** + * Shows the dialog. If the dialog is already open, this does nothing. + */ + show: function() { + if (!this.dialog_.open) { + this.setOpen(true); + this.focus_(); + } + }, + + /** + * Show this dialog modally. + */ + showModal: function() { + if (this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.'); + } + if (!isConnected(this.dialog_)) { + throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.'); + } + if (!dialogPolyfill.dm.pushDialog(this)) { + throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.'); + } + + if (createsStackingContext(this.dialog_.parentElement)) { + console.warn('A dialog is being shown inside a stacking context. ' + + 'This may cause it to be unusable. For more information, see this link: ' + + 'https://github.com/GoogleChrome/dialog-polyfill/#stacking-context'); + } + + this.setOpen(true); + this.openAsModal_ = true; + + // Optionally center vertically, relative to the current viewport. + if (dialogPolyfill.needsCentering(this.dialog_)) { + dialogPolyfill.reposition(this.dialog_); + this.replacedStyleTop_ = true; + } else { + this.replacedStyleTop_ = false; + } + + // Insert backdrop. + this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling); + + // Focus on whatever inside the dialog. + this.focus_(); + }, + + /** + * Closes this HTMLDialogElement. This is optional vs clearing the open + * attribute, however this fires a 'close' event. + * + * @param {string=} opt_returnValue to use as the returnValue + */ + close: function(opt_returnValue) { + if (!this.dialog_.hasAttribute('open')) { + throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); + } + this.setOpen(false); + + // Leave returnValue untouched in case it was set directly on the element + if (opt_returnValue !== undefined) { + this.dialog_.returnValue = opt_returnValue; + } + + // Triggering "close" event for any attached listeners on the . + var closeEvent = new supportCustomEvent('close', { + bubbles: false, + cancelable: false + }); + safeDispatchEvent(this.dialog_, closeEvent); + } + + }); + + var dialogPolyfill = {}; + + dialogPolyfill.reposition = function(element) { + var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; + var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2; + element.style.top = Math.max(scrollTop, topValue) + 'px'; + }; + + dialogPolyfill.isInlinePositionSetByStylesheet = function(element) { + for (var i = 0; i < document.styleSheets.length; ++i) { + var styleSheet = document.styleSheets[i]; + var cssRules = null; + // Some browsers throw on cssRules. + try { + cssRules = styleSheet.cssRules; + } catch (e) {} + if (!cssRules) { continue; } + for (var j = 0; j < cssRules.length; ++j) { + var rule = cssRules[j]; + var selectedNodes = null; + // Ignore errors on invalid selector texts. + try { + selectedNodes = document.querySelectorAll(rule.selectorText); + } catch(e) {} + if (!selectedNodes || !inNodeList(selectedNodes, element)) { + continue; + } + var cssTop = rule.style.getPropertyValue('top'); + var cssBottom = rule.style.getPropertyValue('bottom'); + if ((cssTop && cssTop !== 'auto') || (cssBottom && cssBottom !== 'auto')) { + return true; + } + } + } + return false; + }; + + dialogPolyfill.needsCentering = function(dialog) { + var computedStyle = window.getComputedStyle(dialog); + if (computedStyle.position !== 'absolute') { + return false; + } + + // We must determine whether the top/bottom specified value is non-auto. In + // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but + // Firefox returns the used value. So we do this crazy thing instead: check + // the inline style and then go through CSS rules. + if ((dialog.style.top !== 'auto' && dialog.style.top !== '') || + (dialog.style.bottom !== 'auto' && dialog.style.bottom !== '')) { + return false; + } + return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog); + }; + + /** + * @param {!Element} element to force upgrade + */ + dialogPolyfill.forceRegisterDialog = function(element) { + if (window.HTMLDialogElement || element.showModal) { + console.warn('This browser already supports , the polyfill ' + + 'may not work correctly', element); + } + if (element.localName !== 'dialog') { + throw new Error('Failed to register dialog: The element is not a dialog.'); + } + new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element)); + }; + + /** + * @param {!Element} element to upgrade, if necessary + */ + dialogPolyfill.registerDialog = function(element) { + if (!element.showModal) { + dialogPolyfill.forceRegisterDialog(element); + } + }; + + /** + * @constructor + */ + dialogPolyfill.DialogManager = function() { + /** @type {!Array} */ + this.pendingDialogStack = []; + + var checkDOM = this.checkDOM_.bind(this); + + // The overlay is used to simulate how a modal dialog blocks the document. + // The blocking dialog is positioned on top of the overlay, and the rest of + // the dialogs on the pending dialog stack are positioned below it. In the + // actual implementation, the modal dialog stacking is controlled by the + // top layer, where z-index has no effect. + this.overlay = document.createElement('div'); + this.overlay.className = '_dialog_overlay'; + this.overlay.addEventListener('click', function(e) { + this.forwardTab_ = undefined; + e.stopPropagation(); + checkDOM([]); // sanity-check DOM + }.bind(this)); + + this.handleKey_ = this.handleKey_.bind(this); + this.handleFocus_ = this.handleFocus_.bind(this); + + this.zIndexLow_ = 100000; + this.zIndexHigh_ = 100000 + 150; + + this.forwardTab_ = undefined; + + if ('MutationObserver' in window) { + this.mo_ = new MutationObserver(function(records) { + var removed = []; + records.forEach(function(rec) { + for (var i = 0, c; c = rec.removedNodes[i]; ++i) { + if (!(c instanceof Element)) { + continue; + } else if (c.localName === 'dialog') { + removed.push(c); + } + removed = removed.concat(c.querySelectorAll('dialog')); + } + }); + removed.length && checkDOM(removed); + }); + } + }; + + /** + * Called on the first modal dialog being shown. Adds the overlay and related + * handlers. + */ + dialogPolyfill.DialogManager.prototype.blockDocument = function() { + document.documentElement.addEventListener('focus', this.handleFocus_, true); + document.addEventListener('keydown', this.handleKey_); + this.mo_ && this.mo_.observe(document, {childList: true, subtree: true}); + }; + + /** + * Called on the first modal dialog being removed, i.e., when no more modal + * dialogs are visible. + */ + dialogPolyfill.DialogManager.prototype.unblockDocument = function() { + document.documentElement.removeEventListener('focus', this.handleFocus_, true); + document.removeEventListener('keydown', this.handleKey_); + this.mo_ && this.mo_.disconnect(); + }; + + /** + * Updates the stacking of all known dialogs. + */ + dialogPolyfill.DialogManager.prototype.updateStacking = function() { + var zIndex = this.zIndexHigh_; + + for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) { + dpi.updateZIndex(--zIndex, --zIndex); + if (i === 0) { + this.overlay.style.zIndex = --zIndex; + } + } + + // Make the overlay a sibling of the dialog itself. + var last = this.pendingDialogStack[0]; + if (last) { + var p = last.dialog.parentNode || document.body; + p.appendChild(this.overlay); + } else if (this.overlay.parentNode) { + this.overlay.parentNode.removeChild(this.overlay); + } + }; + + /** + * @param {Element} candidate to check if contained or is the top-most modal dialog + * @return {boolean} whether candidate is contained in top dialog + */ + dialogPolyfill.DialogManager.prototype.containedByTopDialog_ = function(candidate) { + while (candidate = findNearestDialog(candidate)) { + for (var i = 0, dpi; dpi = this.pendingDialogStack[i]; ++i) { + if (dpi.dialog === candidate) { + return i === 0; // only valid if top-most + } + } + candidate = candidate.parentElement; + } + return false; + }; + + dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) { + var target = event.composedPath ? event.composedPath()[0] : event.target; + + if (this.containedByTopDialog_(target)) { return; } + + if (document.activeElement === document.documentElement) { return; } + + event.preventDefault(); + event.stopPropagation(); + safeBlur(/** @type {Element} */ (target)); + + if (this.forwardTab_ === undefined) { return; } // move focus only from a tab key + + var dpi = this.pendingDialogStack[0]; + var dialog = dpi.dialog; + var position = dialog.compareDocumentPosition(target); + if (position & Node.DOCUMENT_POSITION_PRECEDING) { + if (this.forwardTab_) { + // forward + dpi.focus_(); + } else if (target !== document.documentElement) { + // backwards if we're not already focused on + document.documentElement.focus(); + } + } + + return false; + }; + + dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) { + this.forwardTab_ = undefined; + if (event.keyCode === 27) { + event.preventDefault(); + event.stopPropagation(); + var cancelEvent = new supportCustomEvent('cancel', { + bubbles: false, + cancelable: true + }); + var dpi = this.pendingDialogStack[0]; + if (dpi && safeDispatchEvent(dpi.dialog, cancelEvent)) { + dpi.dialog.close(); + } + } else if (event.keyCode === 9) { + this.forwardTab_ = !event.shiftKey; + } + }; + + /** + * Finds and downgrades any known modal dialogs that are no longer displayed. Dialogs that are + * removed and immediately readded don't stay modal, they become normal. + * + * @param {!Array} removed that have definitely been removed + */ + dialogPolyfill.DialogManager.prototype.checkDOM_ = function(removed) { + // This operates on a clone because it may cause it to change. Each change also calls + // updateStacking, which only actually needs to happen once. But who removes many modal dialogs + // at a time?! + var clone = this.pendingDialogStack.slice(); + clone.forEach(function(dpi) { + if (removed.indexOf(dpi.dialog) !== -1) { + dpi.downgradeModal(); + } else { + dpi.maybeHideModal(); + } + }); + }; + + /** + * @param {!dialogPolyfillInfo} dpi + * @return {boolean} whether the dialog was allowed + */ + dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) { + var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1; + if (this.pendingDialogStack.length >= allowed) { + return false; + } + if (this.pendingDialogStack.unshift(dpi) === 1) { + this.blockDocument(); + } + this.updateStacking(); + return true; + }; + + /** + * @param {!dialogPolyfillInfo} dpi + */ + dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) { + var index = this.pendingDialogStack.indexOf(dpi); + if (index === -1) { return; } + + this.pendingDialogStack.splice(index, 1); + if (this.pendingDialogStack.length === 0) { + this.unblockDocument(); + } + this.updateStacking(); + }; + + dialogPolyfill.dm = new dialogPolyfill.DialogManager(); + dialogPolyfill.formSubmitter = null; + dialogPolyfill.imagemapUseValue = null; + + /** + * Installs global handlers, such as click listers and native method overrides. These are needed + * even if a no dialog is registered, as they deal with
. + */ + if (window.HTMLDialogElement === undefined) { + + /** + * If HTMLFormElement translates method="DIALOG" into 'get', then replace the descriptor with + * one that returns the correct value. + */ + var testForm = document.createElement('form'); + testForm.setAttribute('method', 'dialog'); + if (testForm.method !== 'dialog') { + var methodDescriptor = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'method'); + if (methodDescriptor) { + // nb. Some older iOS and older PhantomJS fail to return the descriptor. Don't do anything + // and don't bother to update the element. + var realGet = methodDescriptor.get; + methodDescriptor.get = function() { + if (isFormMethodDialog(this)) { + return 'dialog'; + } + return realGet.call(this); + }; + var realSet = methodDescriptor.set; + /** @this {HTMLElement} */ + methodDescriptor.set = function(v) { + if (typeof v === 'string' && v.toLowerCase() === 'dialog') { + return this.setAttribute('method', v); + } + return realSet.call(this, v); + }; + Object.defineProperty(HTMLFormElement.prototype, 'method', methodDescriptor); + } + } + + /** + * Global 'click' handler, to capture the or
${e.settingsTitle}

${e.message}

${e.info.split("\n").map((t,o,n)=>`${t}${n.length>1&&e.enableMore&&0==o?`${e.more}`:""}`).join("")}

${e.sections.map(t=>{let o=v()[t],n="essential"===t,a=n?"disabled":"",s=n?"checked":"";void 0!==o&&(s=o?"checked":"");let c=e[`${t}Cookies`];return`
${e[`${t}Title`]}

${e[`${t}Message`]}

${c?i.entries(c).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${e.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${e.linkText}`),l.querySelectorAll("button").forEach(e=>e.addEventListener("click",p)),(t=l.querySelector("dialog")).addEventListener("close",b),t.addEventListener("cancel",f);let o=l.querySelector(".more");o&&o.addEventListener("click",o.remove),l.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),n.body.appendChild(l),a.addEventListener("resize",d),g("render",{dialog:t,ui:l})}(),T(),a[e.global].consentTime?(m(!1),C()):(m(!0),e.force&&$()),o={consent:k,invalidate:u,update:j,on:(e,t)=>{let n=`bm:${e}`;return r[n]||(r[n]=[]),r[n].push(t),o},off:(e,t)=>{let o=`bm:${e}`;r[o]&&(r[o]=r[o].filter(e=>e!==t))}}}}; \ No newline at end of file +/*! biscuitman.js 0.4.1 */let e,t,o;let{document:n,window:a,Object:i}=globalThis,l=n.documentElement,s={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,dialogPolyfill:"/dist/dialog-polyfill.withcss.min.js"},c=document.createElement("div"),r={},d=()=>{l.style.setProperty("--bm-height",`${c.offsetHeight}px`)},m=e=>{l.classList.toggle("bm-show",e),d()},p=()=>{let{consentTime:t,...o}=h();for(let[n,a]of(t||(o=i.fromEntries(e.sections.slice(1).map(e=>[e,!1]))),i.entries(o)))l.classList.toggle(`bm-${n}`,a),l.classList.toggle(`bm-no-${n}`,!a)};function u(e){let o=e.target.dataset.id;switch($("button",{id:o}),o){case"accept":S(!0);break;case"close":t.close();break;case"settings":g();break;case"save":S();break;case"reject":S(!1)}}function f(){$("close")}function b(t){e.force&&t.preventDefault()}function g(){$("open"),t.showModal()}function $(e,t){let o=`bm:${e}`,a={...void 0!==t&&t,time:+new Date};n.dispatchEvent(new CustomEvent(o,{detail:a})),console.debug(o,a),r[o]&&r[o].forEach(e=>e(a))}let h=()=>a[e.global]||{};function v(t){a[e.global]=t,p()}let y=e=>!!h()[e];function k(e,t){for(let o in e)e[o]&&!1===t[o]&&$("revoke",{section:o})}function E(){try{return JSON.parse(localStorage.getItem(e.key))}catch(t){return console.error(t),localStorage.removeItem(e.key),{}}}function T(){let t=i.fromEntries(i.entries(localStorage)),o=i.fromEntries(n.cookie.split("; ").map(e=>e.split("="))),{consentTime:a,...l}=E()||e.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[a,s]of i.entries(l)){if(s)continue;let l=i.keys(e[`${a}Cookies`]||{});for(let e of(l.filter(e=>e.endsWith("*")).map(e=>{i.keys({...o,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&l.push(t)})}),l)){if(o[e]){let t=`${e}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;n.cookie=t,n.cookie=`${t}domain=${location.hostname};`,n.cookie=`${t}domain=.${location.hostname};`,$("delete",{cookie:e})}t[e]&&(localStorage.removeItem(e),$("delete",{localStorage:e}))}}}function S(o){let n=void 0===o,a={consentTime:+new Date};e.sections.forEach(e=>{if("essential"===e)return!1;let t=c.querySelector(`[data-s=${e}]`),i=n?t.checked:o;a[e]=i,n||(t.checked=o)}),k(h(),a),v(a),localStorage.setItem(e.key,JSON.stringify(a)),$("save",{data:a}),T(),C(),t.open&&t.close(),m(!1)}function C(){n.querySelectorAll("script[data-consent]").forEach(e=>{if(!h()[e.dataset.consent])return!1;let t=n.createElement("script");for(let{name:o,value:n}of e.attributes)o.startsWith("data-")||"type"===o||t.setAttribute(o,n);t.setAttribute("type",e.dataset.type||"text/javascript"),e.src||(t.textContent=e.textContent),e.parentNode.replaceChild(t,e),$("inject",{el:e,...e.id&&{id:e.id}}),e.src&&""!==e.textContent.trim()&&t.addEventListener("load",()=>{let o=n.createElement("script");o.textContent=e.textContent,e.id&&(o.id=e.id+"-after"),t.insertAdjacentElement("afterend",o),$("inject",{el:o,parent:e,...o.id&&{id:o.id}})})})}export default{create:function(){let l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(o)return o;e={...s,...l};let p=a.bmInvalidate=()=>{$("invalidate",{data:h()}),k({}),S(!1),v({}),localStorage.removeItem(e.key),m(!0)},j=a.bmUpdate=()=>{$("update",{data:h()}),g()};return v(E()||{}),function(){let t=Intl.DateTimeFormat().resolvedOptions().timeZone,o=/^(GMT|UTC)$/.test(t)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(t);e.acceptNonEU&&!o&&(S(!0),m(!1))}(),function(){c.classList.add("biscuitman"),c.innerHTML=`
${e.title}

${e.message}

${e.settingsTitle}

${e.message}

${e.info.split("\n").map((t,o,n)=>`${t}${n.length>1&&e.enableMore&&0==o?`${e.more}`:""}`).join("")}

${e.sections.map(t=>{let o=h()[t],n="essential"===t,a=n?"disabled":"",l=n?"checked":"";void 0!==o&&(l=o?"checked":"");let s=e[`${t}Cookies`];return`
${e[`${t}Title`]}

${e[`${t}Message`]}

${s?i.entries(s).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${e.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${e.linkText}`),c.querySelectorAll("button").forEach(e=>e.addEventListener("click",u)),(t=c.querySelector("dialog")).addEventListener("close",f),t.addEventListener("cancel",b),(!e.dialogPolyfill||t.close)&&t.showModal||function(t){function o(){n.documentElement.classList.add("bm-dialog-polyfill"),a.dialogPolyfill.registerDialog(t)}if(a.dialogPolyfill)o();else{let t=n.createElement("script");t.onload=o,t.src=e.dialogPolyfill,n.head.appendChild(t)}}(t);let o=c.querySelector(".more");o&&o.addEventListener("click",o.remove),c.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),n.body.appendChild(c),a.addEventListener("resize",d),$("render",{dialog:t,ui:c})}(),T(),a[e.global].consentTime?(m(!1),C()):(m(!0),e.force&&g()),o={consent:y,invalidate:p,update:j,on:(e,t)=>{let n=`bm:${e}`;return r[n]||(r[n]=[]),r[n].push(t),o},off:(e,t)=>{let o=`bm:${e}`;r[o]&&(r[o]=r[o].filter(e=>e!==t))}}}}; \ No newline at end of file diff --git a/dist/esm/biscuitman.mjs b/dist/esm/biscuitman.mjs index 6d3c2f9..5d2d101 100644 --- a/dist/esm/biscuitman.mjs +++ b/dist/esm/biscuitman.mjs @@ -19,7 +19,8 @@ const defaults = { info: '', more: 'Show more', noCookies: 'No cookies to display', - acceptNonEU: false + acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js' }; let options; // UI & Events: @@ -83,6 +84,7 @@ function render() { dialog = ui.querySelector('dialog'); dialog.addEventListener('close', closeModalHandler); dialog.addEventListener('cancel', cancelModalHandler); + if (options.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog); const moreLink = ui.querySelector('.more'); if (moreLink) moreLink.addEventListener('click', moreLink.remove); ui.querySelectorAll('[data-s]').forEach((checkbox)=>checkbox.addEventListener('change', (e)=>{ @@ -158,6 +160,19 @@ function dispatch(eventName, data) { console.debug(name, payload); if (listeners[name]) listeners[name].forEach((callback)=>callback(payload)); } +function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill'); + w.dialogPolyfill.registerDialog(dialog); + } + if (w.dialogPolyfill) mount(); + else { + const script = d.createElement('script'); + script.onload = mount; + script.src = options.dialogPolyfill; + d.head.appendChild(script); + } +} // Data: const getConsents = ()=>w[options.global] || {}; function setConsents(newConsents) { diff --git a/dist/esm/biscuitman.withcss.min.mjs b/dist/esm/biscuitman.withcss.min.mjs index b8898dd..5412432 100644 --- a/dist/esm/biscuitman.withcss.min.mjs +++ b/dist/esm/biscuitman.withcss.min.mjs @@ -1 +1 @@ -/*! biscuitman.js 0.4.1 */let e,t,o;let{document:n,window:a,Object:i}=globalThis,s=n.documentElement,c={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1},l=document.createElement("div"),r={},d=()=>{s.style.setProperty("--bm-height",`${l.offsetHeight}px`)},m=e=>{s.classList.toggle("bm-show",e),d()},u=()=>{let{consentTime:t,...o}=v();for(let[n,a]of(t||(o=i.fromEntries(e.sections.slice(1).map(e=>[e,!1]))),i.entries(o)))s.classList.toggle(`bm-${n}`,a),s.classList.toggle(`bm-no-${n}`,!a)};function p(e){let o=e.target.dataset.id;switch(g("button",{id:o}),o){case"accept":S(!0);break;case"close":t.close();break;case"settings":$();break;case"save":S();break;case"reject":S(!1)}}function b(){g("close")}function f(t){e.force&&t.preventDefault()}function $(){g("open"),t.showModal()}function g(e,t){let o=`bm:${e}`,a={...void 0!==t&&t,time:+new Date};n.dispatchEvent(new CustomEvent(o,{detail:a})),console.debug(o,a),r[o]&&r[o].forEach(e=>e(a))}let v=()=>a[e.global]||{};function h(t){a[e.global]=t,u()}let k=e=>!!v()[e];function E(e,t){for(let o in e)e[o]&&!1===t[o]&&g("revoke",{section:o})}function y(){try{return JSON.parse(localStorage.getItem(e.key))}catch(t){return console.error(t),localStorage.removeItem(e.key),{}}}function T(){let t=i.fromEntries(i.entries(localStorage)),o=i.fromEntries(n.cookie.split("; ").map(e=>e.split("="))),{consentTime:a,...s}=y()||e.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[a,c]of i.entries(s)){if(c)continue;let s=i.keys(e[`${a}Cookies`]||{});for(let e of(s.filter(e=>e.endsWith("*")).map(e=>{i.keys({...o,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&s.push(t)})}),s)){if(o[e]){let t=`${e}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;n.cookie=t,n.cookie=`${t}domain=${location.hostname};`,n.cookie=`${t}domain=.${location.hostname};`,g("delete",{cookie:e})}t[e]&&(localStorage.removeItem(e),g("delete",{localStorage:e}))}}}function S(o){let n=void 0===o,a={consentTime:+new Date};e.sections.forEach(e=>{if("essential"===e)return!1;let t=l.querySelector(`[data-s=${e}]`),i=n?t.checked:o;a[e]=i,n||(t.checked=o)}),E(v(),a),h(a),localStorage.setItem(e.key,JSON.stringify(a)),g("save",{data:a}),T(),C(),t.open&&t.close(),m(!1)}function C(){n.querySelectorAll("script[data-consent]").forEach(e=>{if(!v()[e.dataset.consent])return!1;let t=n.createElement("script");for(let{name:o,value:n}of e.attributes)o.startsWith("data-")||"type"===o||t.setAttribute(o,n);t.setAttribute("type",e.dataset.type||"text/javascript"),e.src||(t.textContent=e.textContent),e.parentNode.replaceChild(t,e),g("inject",{el:e,...e.id&&{id:e.id}}),e.src&&""!==e.textContent.trim()&&t.addEventListener("load",()=>{let o=n.createElement("script");o.textContent=e.textContent,e.id&&(o.id=e.id+"-after"),t.insertAdjacentElement("afterend",o),g("inject",{el:o,parent:e,...o.id&&{id:o.id}})})})}export default{create:function(){let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(o)return o;e={...c,...s};let u=a.bmInvalidate=()=>{g("invalidate",{data:v()}),E({}),S(!1),h({}),localStorage.removeItem(e.key),m(!0)},j=a.bmUpdate=()=>{g("update",{data:v()}),$()};return h(y()||{}),function(){let t=Intl.DateTimeFormat().resolvedOptions().timeZone,o=/^(GMT|UTC)$/.test(t)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(t);e.acceptNonEU&&!o&&(S(!0),m(!1))}(),function(){l.classList.add("biscuitman"),l.innerHTML=`
${e.title}

${e.message}

${e.settingsTitle}

${e.message}

${e.info.split("\n").map((t,o,n)=>`${t}${n.length>1&&e.enableMore&&0==o?`${e.more}`:""}`).join("")}

${e.sections.map(t=>{let o=v()[t],n="essential"===t,a=n?"disabled":"",s=n?"checked":"";void 0!==o&&(s=o?"checked":"");let c=e[`${t}Cookies`];return`
${e[`${t}Title`]}

${e[`${t}Message`]}

${c?i.entries(c).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${e.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${e.linkText}`),l.querySelectorAll("button").forEach(e=>e.addEventListener("click",p)),(t=l.querySelector("dialog")).addEventListener("close",b),t.addEventListener("cancel",f);let o=l.querySelector(".more");o&&o.addEventListener("click",o.remove),l.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),n.body.appendChild(l),a.addEventListener("resize",d),g("render",{dialog:t,ui:l})}(),T(),a[e.global].consentTime?(m(!1),C()):(m(!0),e.force&&$()),o={consent:k,invalidate:u,update:j,on:(e,t)=>{let n=`bm:${e}`;return r[n]||(r[n]=[]),r[n].push(t),o},off:(e,t)=>{let o=`bm:${e}`;r[o]&&(r[o]=r[o].filter(e=>e!==t))}}}};;if(typeof BMCSS==='undefined'){let c=document.createElement('style');c.id='BMCSS';c.textContent=`/*! biscuitman.js 0.4.1 */.biscuitman{--ui:0,0,0;--tx:#444;--bg:#fff;--c:#105d89;background:var(--bg);box-sizing:border-box;z-index:3;width:100%;padding:20px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;display:none;position:fixed;bottom:0;box-shadow:0 -2px 10px rgba(0,0,0,.16)}.bm-show .biscuitman{display:block}.biscuitman *{box-sizing:border-box;color:var(--tx);margin:0;padding:0;font-family:inherit;font-size:16px;line-height:1.4em}.biscuitman:has([open]){transform:translateY(100%)}.biscuitman article{padding:0;position:relative}@media (min-width:770px){.biscuitman article{padding-right:calc(max(300px,30vw) + 20px)}.biscuitman article nav{width:30vw;min-width:300px;position:absolute;bottom:50%;right:0;transform:translateY(50%)}}.biscuitman article p{color:var(--tx);margin:10px 0;font-size:13px}@media (min-width:575px){.biscuitman article p{font-size:14px}}.biscuitman button{background:var(--bg);border:2px solid var(--c);color:var(--c);cursor:pointer;border-radius:3px;margin-top:10px;padding:.8em;font-size:13px;line-height:1em}.biscuitman button[data-id=accept]{background:var(--c);color:var(--bg)!important}.biscuitman button[data-id=close]{color:rgba(var(--ui),.5);opacity:.6;-webkit-user-select:none;user-select:none;z-index:2;background:0 0;border:none;outline:none;padding:10px;font-size:24px;line-height:1em;position:absolute;top:0;right:10px}.biscuitman button[disabled]{display:none}.biscuitman button:hover{opacity:.8}@media (min-width:576px){.biscuitman nav{flex-direction:row-reverse;gap:10px;width:100%;display:flex}.biscuitman nav button{flex-grow:1;margin-bottom:0}}@media (max-width:575px){.biscuitman nav{flex-direction:column;flex-grow:1;display:flex}}.biscuitman dialog{background:var(--bg);border:0;width:100%;max-width:100%;height:100%;max-height:100%}@media (min-width:576px){.biscuitman dialog{border-radius:10px;width:90vw;max-width:860px;max-height:80vh;margin:auto;box-shadow:0 0 8px rgba(0,0,0,.3)}}@media (min-width:576px) and (min-height:1134px){.biscuitman dialog{max-height:950px}}.biscuitman dialog nav{justify-self:flex-end;position:relative}.biscuitman .bm-dialog{flex-direction:column;height:100%;padding:20px;display:flex}.biscuitman .bm-dialog b{padding-bottom:8px;position:relative}.biscuitman .bm-dialog>b:after{content:"";background:linear-gradient(180deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;z-index:1;width:100%;height:25px;margin-bottom:-24px;position:absolute;bottom:0;left:0}.biscuitman .bm-dialog nav:after{content:"";background:linear-gradient(0deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;width:100%;height:25px;position:absolute;top:-24px;left:0}.biscuitman .bm-sections{scrollbar-color:rgba(var(--ui),.2)var(--bg);flex-shrink:1;height:100%;padding:15px 0;position:relative;overflow-y:scroll}@media (min-width:576px){.biscuitman .bm-sections{margin-right:-18px;padding-right:4px}}.biscuitman .bm-sections>p{padding-right:30px;font-size:13px;line-height:18px}@media (min-width:576px){.biscuitman .bm-sections>p{font-size:14px}}.biscuitman .bm-sections>p span{font-size:inherit;padding-bottom:5px;display:inline-block}.biscuitman .bm-sections>p .more~span{display:none}.biscuitman a{font-size:inherit;color:var(--c);cursor:pointer;text-decoration:none;display:inline-block}.biscuitman a:hover{text-decoration:underline}.biscuitman section{margin-bottom:10px;position:relative}.biscuitman section:first-of-type{margin-top:10px}.biscuitman details{border:1px solid rgba(var(--ui),.2);border-radius:5px;padding:10px;list-style:none;box-shadow:0 2px 4px rgba(0,0,0,.1)}.biscuitman details[open] summary b:after{margin:-3px 0 0 -2px;transform:rotate(45deg)scale(.3)}.biscuitman summary{cursor:pointer;flex-direction:column;width:100%;padding:5px 80px 10px 10px;list-style:none;display:flex;position:relative}.biscuitman summary b{margin-bottom:3px}.biscuitman summary b:after{content:"";border:5px solid rgba(var(--ui),.4);border-top-color:transparent;border-left-color:transparent;border-radius:2px;width:1em;height:1em;margin:-2px 0 0 -4px;display:block;transform:rotate(-45deg)scale(.3)}.biscuitman summary p{color:var(--tx);font-size:14px}.biscuitman summary>*{display:inline-flex}.biscuitman summary::marker{display:none}.biscuitman summary::-webkit-details-marker{display:none}.biscuitman dl{background:rgba(var(--ui),.08);margin:10px;padding:10px;display:flex}.biscuitman dl dt{color:var(--tx);font-size:12px}.biscuitman dl dd{color:var(--tx);font-size:12px}.biscuitman dl dt{min-width:120px;padding-right:30px;font-weight:700}.biscuitman label{--height:1.2em;--width:2.3em;--gap:2px;height:var(--height);width:var(--width);background-color:rgba(var(--ui),.3);border-radius:var(--height);margin-top:-2px;display:block;position:absolute;top:50%;right:20px;transform:translateY(-50%);font-size:20px!important}.biscuitman label:before{content:"";background:var(--bg);height:calc(var(--height) - calc(var(--gap)*2));width:calc(var(--height) - calc(var(--gap)*2));height:var(--height);width:var(--height);left:var(--gap);transform-origin:50%;border-radius:100%;display:block;position:absolute;top:50%;left:0;transform:translateY(-50%)scale(.8)}.biscuitman label.checked{background-color:var(--c)}.biscuitman label.checked:before{left:auto;right:0}.biscuitman label:has(:focus-visible){outline:auto highlight}.biscuitman label.disabled.checked{opacity:.5}.biscuitman label input{opacity:0}.bm-dialog-polyfill .biscuitman dialog{position:fixed;top:50%;transform:translateY(-50%)}`;document.head.appendChild(c)} \ No newline at end of file +/*! biscuitman.js 0.4.1 */let e,t,o;let{document:n,window:a,Object:i}=globalThis,l=n.documentElement,s={key:"myconsent",global:"Consent",force:!1,enableMore:!0,sections:["essential"],title:"Your privacy matters",message:"We use cookies",settings:"Settings",reject:"Reject All",accept:"Accept All",save:"Save My Settings",settingsTitle:"My Consent Settings",info:"",more:"Show more",noCookies:"No cookies to display",acceptNonEU:!1,dialogPolyfill:"/dist/dialog-polyfill.withcss.min.js"},c=document.createElement("div"),r={},d=()=>{l.style.setProperty("--bm-height",`${c.offsetHeight}px`)},m=e=>{l.classList.toggle("bm-show",e),d()},p=()=>{let{consentTime:t,...o}=h();for(let[n,a]of(t||(o=i.fromEntries(e.sections.slice(1).map(e=>[e,!1]))),i.entries(o)))l.classList.toggle(`bm-${n}`,a),l.classList.toggle(`bm-no-${n}`,!a)};function u(e){let o=e.target.dataset.id;switch($("button",{id:o}),o){case"accept":S(!0);break;case"close":t.close();break;case"settings":g();break;case"save":S();break;case"reject":S(!1)}}function f(){$("close")}function b(t){e.force&&t.preventDefault()}function g(){$("open"),t.showModal()}function $(e,t){let o=`bm:${e}`,a={...void 0!==t&&t,time:+new Date};n.dispatchEvent(new CustomEvent(o,{detail:a})),console.debug(o,a),r[o]&&r[o].forEach(e=>e(a))}let h=()=>a[e.global]||{};function v(t){a[e.global]=t,p()}let y=e=>!!h()[e];function k(e,t){for(let o in e)e[o]&&!1===t[o]&&$("revoke",{section:o})}function E(){try{return JSON.parse(localStorage.getItem(e.key))}catch(t){return console.error(t),localStorage.removeItem(e.key),{}}}function T(){let t=i.fromEntries(i.entries(localStorage)),o=i.fromEntries(n.cookie.split("; ").map(e=>e.split("="))),{consentTime:a,...l}=E()||e.sections.slice(1).reduce((e,t)=>(e[t]=!1,{consentTime:void 0,...e}),{});for(let[a,s]of i.entries(l)){if(s)continue;let l=i.keys(e[`${a}Cookies`]||{});for(let e of(l.filter(e=>e.endsWith("*")).map(e=>{i.keys({...o,...t}).map(t=>{t.startsWith(e.slice(0,-1))&&l.push(t)})}),l)){if(o[e]){let t=`${e}=;expires=Thu, 01 Jan 1970 00:00:01 UTC;path=/;`;n.cookie=t,n.cookie=`${t}domain=${location.hostname};`,n.cookie=`${t}domain=.${location.hostname};`,$("delete",{cookie:e})}t[e]&&(localStorage.removeItem(e),$("delete",{localStorage:e}))}}}function S(o){let n=void 0===o,a={consentTime:+new Date};e.sections.forEach(e=>{if("essential"===e)return!1;let t=c.querySelector(`[data-s=${e}]`),i=n?t.checked:o;a[e]=i,n||(t.checked=o)}),k(h(),a),v(a),localStorage.setItem(e.key,JSON.stringify(a)),$("save",{data:a}),T(),C(),t.open&&t.close(),m(!1)}function C(){n.querySelectorAll("script[data-consent]").forEach(e=>{if(!h()[e.dataset.consent])return!1;let t=n.createElement("script");for(let{name:o,value:n}of e.attributes)o.startsWith("data-")||"type"===o||t.setAttribute(o,n);t.setAttribute("type",e.dataset.type||"text/javascript"),e.src||(t.textContent=e.textContent),e.parentNode.replaceChild(t,e),$("inject",{el:e,...e.id&&{id:e.id}}),e.src&&""!==e.textContent.trim()&&t.addEventListener("load",()=>{let o=n.createElement("script");o.textContent=e.textContent,e.id&&(o.id=e.id+"-after"),t.insertAdjacentElement("afterend",o),$("inject",{el:o,parent:e,...o.id&&{id:o.id}})})})}export default{create:function(){let l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(o)return o;e={...s,...l};let p=a.bmInvalidate=()=>{$("invalidate",{data:h()}),k({}),S(!1),v({}),localStorage.removeItem(e.key),m(!0)},j=a.bmUpdate=()=>{$("update",{data:h()}),g()};return v(E()||{}),function(){let t=Intl.DateTimeFormat().resolvedOptions().timeZone,o=/^(GMT|UTC)$/.test(t)||/(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(t);e.acceptNonEU&&!o&&(S(!0),m(!1))}(),function(){c.classList.add("biscuitman"),c.innerHTML=`
${e.title}

${e.message}

${e.settingsTitle}

${e.message}

${e.info.split("\n").map((t,o,n)=>`${t}${n.length>1&&e.enableMore&&0==o?`${e.more}`:""}`).join("")}

${e.sections.map(t=>{let o=h()[t],n="essential"===t,a=n?"disabled":"",l=n?"checked":"";void 0!==o&&(l=o?"checked":"");let s=e[`${t}Cookies`];return`
${e[`${t}Title`]}

${e[`${t}Message`]}

${s?i.entries(s).map(e=>{let[t,o]=e;return`
${t}
${o}
`}).join(""):`
${e.noCookies}
`}
`}).join("")}
`.replaceAll("{link}",`${e.linkText}`),c.querySelectorAll("button").forEach(e=>e.addEventListener("click",u)),(t=c.querySelector("dialog")).addEventListener("close",f),t.addEventListener("cancel",b),(!e.dialogPolyfill||t.close)&&t.showModal||function(t){function o(){n.documentElement.classList.add("bm-dialog-polyfill"),a.dialogPolyfill.registerDialog(t)}if(a.dialogPolyfill)o();else{let t=n.createElement("script");t.onload=o,t.src=e.dialogPolyfill,n.head.appendChild(t)}}(t);let o=c.querySelector(".more");o&&o.addEventListener("click",o.remove),c.querySelectorAll("[data-s]").forEach(e=>e.addEventListener("change",t=>{e.parentElement.classList.toggle("checked",t.target.checked)})),n.body.appendChild(c),a.addEventListener("resize",d),$("render",{dialog:t,ui:c})}(),T(),a[e.global].consentTime?(m(!1),C()):(m(!0),e.force&&g()),o={consent:y,invalidate:p,update:j,on:(e,t)=>{let n=`bm:${e}`;return r[n]||(r[n]=[]),r[n].push(t),o},off:(e,t)=>{let o=`bm:${e}`;r[o]&&(r[o]=r[o].filter(e=>e!==t))}}}};;if(typeof BMCSS==='undefined'){let c=document.createElement('style');c.id='BMCSS';c.textContent=`/*! biscuitman.js 0.4.1 */.biscuitman{--ui:0,0,0;--tx:#444;--bg:#fff;--c:#105d89;background:var(--bg);box-sizing:border-box;z-index:3;width:100%;padding:20px;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;display:none;position:fixed;bottom:0;box-shadow:0 -2px 10px rgba(0,0,0,.16)}.bm-show .biscuitman{display:block}.biscuitman *{box-sizing:border-box;color:var(--tx);margin:0;padding:0;font-family:inherit;font-size:16px;line-height:1.4em}.biscuitman:has([open]){transform:translateY(100%)}.biscuitman article{padding:0;position:relative}@media (min-width:770px){.biscuitman article{padding-right:calc(max(300px,30vw) + 20px)}.biscuitman article nav{width:30vw;min-width:300px;position:absolute;bottom:50%;right:0;transform:translateY(50%)}}.biscuitman article p{color:var(--tx);margin:10px 0;font-size:13px}@media (min-width:575px){.biscuitman article p{font-size:14px}}.biscuitman button{background:var(--bg);border:2px solid var(--c);color:var(--c);cursor:pointer;border-radius:3px;margin-top:10px;padding:.8em;font-size:13px;line-height:1em}.biscuitman button[data-id=accept]{background:var(--c);color:var(--bg)!important}.biscuitman button[data-id=close]{color:rgba(var(--ui),.5);opacity:.6;-webkit-user-select:none;user-select:none;z-index:2;background:0 0;border:none;outline:none;padding:10px;font-size:24px;line-height:1em;position:absolute;top:0;right:10px}.biscuitman button[disabled]{display:none}.biscuitman button:hover{opacity:.8}@media (min-width:576px){.biscuitman nav{flex-direction:row-reverse;gap:10px;width:100%;display:flex}.biscuitman nav button{flex-grow:1;margin-bottom:0}}@media (max-width:575px){.biscuitman nav{flex-direction:column;flex-grow:1;display:flex}}.biscuitman dialog{background:var(--bg);border:0;width:100%;max-width:100%;height:100%;max-height:100%}@media (min-width:576px){.biscuitman dialog{border-radius:10px;width:90vw;max-width:860px;max-height:80vh;margin:auto;box-shadow:0 0 8px rgba(0,0,0,.3)}}@media (min-width:576px) and (min-height:1134px){.biscuitman dialog{max-height:950px}}.biscuitman dialog nav{justify-self:flex-end;position:relative}.biscuitman .bm-dialog{flex-direction:column;height:100%;padding:20px;display:flex}.biscuitman .bm-dialog b{padding-bottom:8px;position:relative}.biscuitman .bm-dialog>b:after{content:"";background:linear-gradient(180deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;z-index:1;width:100%;height:25px;margin-bottom:-24px;position:absolute;bottom:0;left:0}.biscuitman .bm-dialog nav:after{content:"";background:linear-gradient(0deg,var(--bg)20%,rgba(255,255,255,0));pointer-events:none;width:100%;height:25px;position:absolute;top:-24px;left:0}.biscuitman .bm-sections{scrollbar-color:rgba(var(--ui),.2)var(--bg);flex-shrink:1;height:100%;padding:15px 0;position:relative;overflow-y:scroll}@media (min-width:576px){.biscuitman .bm-sections{margin-right:-18px;padding-right:4px}}.biscuitman .bm-sections>p{padding-right:30px;font-size:13px;line-height:18px}@media (min-width:576px){.biscuitman .bm-sections>p{font-size:14px}}.biscuitman .bm-sections>p span{font-size:inherit;padding-bottom:5px;display:inline-block}.biscuitman .bm-sections>p .more~span{display:none}.biscuitman a{font-size:inherit;color:var(--c);cursor:pointer;text-decoration:none;display:inline-block}.biscuitman a:hover{text-decoration:underline}.biscuitman section{margin-bottom:10px;position:relative}.biscuitman section:first-of-type{margin-top:10px}.biscuitman details{border:1px solid rgba(var(--ui),.2);border-radius:5px;padding:10px;list-style:none;box-shadow:0 2px 4px rgba(0,0,0,.1)}.biscuitman details[open] summary b:after{margin:-3px 0 0 -2px;transform:rotate(45deg)scale(.3)}.biscuitman summary{cursor:pointer;flex-direction:column;width:100%;padding:5px 80px 10px 10px;list-style:none;display:flex;position:relative}.biscuitman summary b{margin-bottom:3px}.biscuitman summary b:after{content:"";border:5px solid rgba(var(--ui),.4);border-top-color:transparent;border-left-color:transparent;border-radius:2px;width:1em;height:1em;margin:-2px 0 0 -4px;display:block;transform:rotate(-45deg)scale(.3)}.biscuitman summary p{color:var(--tx);font-size:14px}.biscuitman summary>*{display:inline-flex}.biscuitman summary::marker{display:none}.biscuitman summary::-webkit-details-marker{display:none}.biscuitman dl{background:rgba(var(--ui),.08);margin:10px;padding:10px;display:flex}.biscuitman dl dt{color:var(--tx);font-size:12px}.biscuitman dl dd{color:var(--tx);font-size:12px}.biscuitman dl dt{min-width:120px;padding-right:30px;font-weight:700}.biscuitman label{--height:1.2em;--width:2.3em;--gap:2px;height:var(--height);width:var(--width);background-color:rgba(var(--ui),.3);border-radius:var(--height);margin-top:-2px;display:block;position:absolute;top:50%;right:20px;transform:translateY(-50%);font-size:20px!important}.biscuitman label:before{content:"";background:var(--bg);height:calc(var(--height) - calc(var(--gap)*2));width:calc(var(--height) - calc(var(--gap)*2));height:var(--height);width:var(--height);left:var(--gap);transform-origin:50%;border-radius:100%;display:block;position:absolute;top:50%;left:0;transform:translateY(-50%)scale(.8)}.biscuitman label.checked{background-color:var(--c)}.biscuitman label.checked:before{left:auto;right:0}.biscuitman label:has(:focus-visible){outline:auto highlight}.biscuitman label.disabled.checked{opacity:.5}.biscuitman label input{opacity:0}.bm-dialog-polyfill .biscuitman dialog{position:fixed;top:50%;transform:translateY(-50%)}`;document.head.appendChild(c)} \ No newline at end of file diff --git a/dist/esm/biscuitman.withcss.mjs b/dist/esm/biscuitman.withcss.mjs index b194096..fb892dc 100644 --- a/dist/esm/biscuitman.withcss.mjs +++ b/dist/esm/biscuitman.withcss.mjs @@ -19,7 +19,8 @@ const defaults = { info: '', more: 'Show more', noCookies: 'No cookies to display', - acceptNonEU: false + acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js' }; let options; // UI & Events: @@ -83,6 +84,7 @@ function render() { dialog = ui.querySelector('dialog'); dialog.addEventListener('close', closeModalHandler); dialog.addEventListener('cancel', cancelModalHandler); + if (options.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog); const moreLink = ui.querySelector('.more'); if (moreLink) moreLink.addEventListener('click', moreLink.remove); ui.querySelectorAll('[data-s]').forEach((checkbox)=>checkbox.addEventListener('change', (e)=>{ @@ -158,6 +160,19 @@ function dispatch(eventName, data) { console.debug(name, payload); if (listeners[name]) listeners[name].forEach((callback)=>callback(payload)); } +function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill'); + w.dialogPolyfill.registerDialog(dialog); + } + if (w.dialogPolyfill) mount(); + else { + const script = d.createElement('script'); + script.onload = mount; + script.src = options.dialogPolyfill; + d.head.appendChild(script); + } +} // Data: const getConsents = ()=>w[options.global] || {}; function setConsents(newConsents) { diff --git a/index-esm.html b/index-esm.html index a9d2b78..7af42d3 100644 --- a/index-esm.html +++ b/index-esm.html @@ -122,23 +122,6 @@ diff --git a/package-lock.json b/package-lock.json index 39e29bc..8af15a7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "@swc/jest": "^0.2.36", "browser-sync": "^3.0.2", "browserslist": "^4.23.3", + "dialog-polyfill": "^0.5.6", "doiuse": "^6.0.2", "eslint": "^9.10.0", "globals": "^15.9.0", @@ -2946,6 +2947,12 @@ "integrity": "sha512-pzh6YQ8zZfz3iKlCvgzVCu22NdpZ8hNmwU6WnQjNVquh0A9iVosPtNLWDwaWVGyrntQlltPFztTMK5Cg6lfCuw==", "dev": true }, + "node_modules/dialog-polyfill": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/dialog-polyfill/-/dialog-polyfill-0.5.6.tgz", + "integrity": "sha512-ZbVDJI9uvxPAKze6z146rmfUZjBqNEwcnFTVamQzXH+svluiV7swmVIGr7miwADgfgt1G2JQIytypM9fbyhX4w==", + "dev": true + }, "node_modules/diff-sequences": { "version": "29.6.3", "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", diff --git a/package.json b/package.json index b5c39c4..250f03b 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "lint": "eslint", "coverage": "node --experimental-vm-modules --disable-warning=ExperimentalWarning ./node_modules/jest/bin/jest.js --runInBand --openHandlesTimeout=2000 --collectCoverage --", "makecerts": "mkcert -cert-file server.crt -key-file server.key localhost 127.0.0.1 ::1", - "http": "npx http-server -p 8000" + "http": "npx http-server -p 8000" }, "test": "npm run test", "devDependencies": { @@ -34,6 +34,7 @@ "@swc/jest": "^0.2.36", "browser-sync": "^3.0.2", "browserslist": "^4.23.3", + "dialog-polyfill": "^0.5.6", "doiuse": "^6.0.2", "eslint": "^9.10.0", "globals": "^15.9.0", diff --git a/run.js b/run.js index 5143098..877d25f 100644 --- a/run.js +++ b/run.js @@ -8,7 +8,8 @@ import doiuse from 'doiuse/stream' import zlib from 'zlib' const { readFile, writeFile } = fs.promises const log = (level,msg) => console.log(`\x1b[33m[${level}]\x1b[0m ${msg}`) -const { name, version, browserslist: browserlistString } = JSON.parse(await readFile('./package.json')) +const packageJson = JSON.parse(await readFile('./package.json')) +const { name, version, browserslist: browserlistString } = packageJson const comment = `/*! ${name}.js ${version} */` const filenames = { @@ -21,7 +22,9 @@ const filenames = { mjs: 'biscuitman.mjs', minMjs: 'biscuitman.min.mjs', mjsWithCss: 'biscuitman.withcss.mjs', - minMjsWithCss: 'biscuitman.withcss.min.mjs' + minMjsWithCss: 'biscuitman.withcss.min.mjs', + dialogPolyfillJsWithCss: 'dialog-polyfill.withcss.js', + dialogPolyfillJsWithCssMin: 'dialog-polyfill.withcss.min.js' } export async function styles(skipFileSave) { @@ -171,6 +174,46 @@ ${css[0]}\`; log('build',`Saved dist/esm/${filenames.mjsWithCss} ${getCompressedSizes(mjsCss)}`) log('build',`Saved dist/esm/${filenames.minMjsWithCss} ${getCompressedSizes(mjsCssMin)}`) + // Build Dialog Polyfill + const dialogPolyfillJs = await readFile('node_modules/dialog-polyfill/dist/dialog-polyfill.js', 'utf8') + const dialogPolyfillJsMin = await swc.transform(dialogPolyfillJs, { + sourceMaps: false, + isModule: false, + jsc: { + minify: { + compress: { + unused: true + }, + mangle: false + } + }, + minify: true + }) + + const dialogPolyfillCss = await readFile('node_modules/dialog-polyfill/dist/dialog-polyfill.css', 'utf8') + const dialogPolyfillCssMin = transformCss({ + code: Buffer.from(dialogPolyfillCss), + minify: true, + sourceMap: false + }) + + const dialogPolyfillJsCss = `${comment}/* dialog-polyfill.js ${packageJson.devDependencies['dialog-polyfill']}*/ +${dialogPolyfillJs} +((d)=>{ + let css=d.createElement('style'); + css.textContent=\`${comment} +${dialogPolyfillCss}\`; + d.head.appendChild(css) +})(document);` + const dialogPolyfillJsCssMin = `${comment}/* dialog-polyfill.js ${packageJson.devDependencies['dialog-polyfill']}*/${dialogPolyfillJsMin.code};((d)=>{let c=d.createElement('style');c.textContent=\`${comment}${dialogPolyfillCssMin.code}\`;d.head.appendChild(c)})(document);` + + await Promise.all([ + writeFile(`dist/${filenames.dialogPolyfillJsWithCss}`, dialogPolyfillJsCss), + writeFile(`dist/${filenames.dialogPolyfillJsWithCssMin}`, dialogPolyfillJsCssMin), + ]) + log('build',`Saved dist/${filenames.dialogPolyfillJsWithCss}`) + log('build',`Saved dist/${filenames.dialogPolyfillJsWithCssMin} ${getCompressedSizes(dialogPolyfillJsCssMin)}`) + console.timeEnd('Build Time') } diff --git a/src/biscuitman.js b/src/biscuitman.js index 213495b..7ee777e 100644 --- a/src/biscuitman.js +++ b/src/biscuitman.js @@ -16,6 +16,7 @@ more: 'Show more', noCookies: 'No cookies to display', acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js', // set to false to disable dialog polyfill loading // message: 'By clicking "Accept All", you agree to the use of cookies for improving browsing, providing personalized ads or content, and analyzing traffic. {link}', // info: `Cookies categorized as "Essential" are stored in your browser to enable basic site functionalities. // Additionally, third-party cookies are utilized to analyze website usage, store preferences, and deliver relevant content and advertisements with your consent. @@ -106,6 +107,7 @@ dialog = ui.querySelector('dialog') dialog.addEventListener('close', closeModalHandler) dialog.addEventListener('cancel', cancelModalHandler) + if (o.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog) const moreLink = ui.querySelector('.more') if (moreLink) moreLink.addEventListener('click', moreLink.remove) ui.querySelectorAll('[data-s]').forEach(checkbox => checkbox.addEventListener('change', e => { @@ -166,6 +168,20 @@ console.debug(name, payload) } + function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill') + w.dialogPolyfill.registerDialog(dialog) + } + if (w.dialogPolyfill) mount() + else { + const script = d.createElement('script') + script.onload = mount + script.src = o.dialogPolyfill + d.head.appendChild(script) + } + } + // Data: const getConsents = () => w[o.global] || {} diff --git a/src/biscuitman.mjs b/src/biscuitman.mjs index 34e6ec1..403610f 100644 --- a/src/biscuitman.mjs +++ b/src/biscuitman.mjs @@ -18,6 +18,7 @@ const defaults = { more: 'Show more', noCookies: 'No cookies to display', acceptNonEU: false, + dialogPolyfill: '/dist/dialog-polyfill.withcss.min.js', // set to false to disable dialog polyfill loading // message: 'By clicking "Accept All", you agree to the use of cookies for improving browsing, providing personalized ads or content, and analyzing traffic. {link}', // info: `Cookies categorized as "Essential" are stored in your browser to enable basic site functionalities. // Additionally, third-party cookies are utilized to analyze website usage, store preferences, and deliver relevant content and advertisements with your consent. @@ -108,6 +109,7 @@ function render() { dialog = ui.querySelector('dialog') dialog.addEventListener('close', closeModalHandler) dialog.addEventListener('cancel', cancelModalHandler) + if (options.dialogPolyfill && !dialog.close || !dialog.showModal) loadDialogPolyfill(dialog) const moreLink = ui.querySelector('.more') if (moreLink) moreLink.addEventListener('click', moreLink.remove) ui.querySelectorAll('[data-s]').forEach(checkbox => checkbox.addEventListener('change', e => { @@ -115,7 +117,6 @@ function render() { })) d.body.appendChild(ui) w.addEventListener('resize', updateBannerHeight) - dispatch('render', { dialog, ui }) } const updateBannerHeight = () => { h.style.setProperty('--bm-height', `${ui.offsetHeight}px`) } @@ -170,6 +171,20 @@ function dispatch(eventName, data) { if (listeners[name]) listeners[name].forEach(callback => callback(payload)) } +function loadDialogPolyfill(dialog) { + function mount() { + d.documentElement.classList.add('bm-dialog-polyfill') + w.dialogPolyfill.registerDialog(dialog) + } + if (w.dialogPolyfill) mount() + else { + const script = d.createElement('script') + script.onload = mount + script.src = options.dialogPolyfill + d.head.appendChild(script) + } +} + // Data: const getConsents = () => w[options.global] || {}