Skip to content

Commit f71e1dc

Browse files
committed
Tidy up
- Tidy up JS order / comments - Simplify defaults logic - re-order dispatch calls - rename global helpers correctly - optimize CSS hide classes
1 parent 6cabaef commit f71e1dc

9 files changed

Lines changed: 63 additions & 75 deletions

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ While you have the option to enable or disable some or all of these cookies, not
117117

118118
If you want to make sure website content obscured underneath the banner, add these styles to your website CSS:
119119
```css
120-
html:not(.js-bm-hidden)::after {
120+
html:not(:has(.bm-hide))::after {
121121
content:'';
122122
min-height:300px;
123123
display:block;

biscuitman.css

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@
3030
transform: translateY(100%);
3131
}
3232

33+
&.bm-hide {
34+
padding:0;
35+
36+
article {
37+
display:none;
38+
}
39+
}
40+
3341
article {
3442
position:relative;
3543

@@ -342,7 +350,6 @@
342350

343351
&::before {
344352
left: auto;
345-
right:var(--gap);
346353
right:0;
347354
}
348355
}
@@ -362,13 +369,3 @@
362369
}
363370
}
364371

365-
.js-bm-hidden {
366-
.biscuitman {
367-
padding:0;
368-
/* box-shadow:0; */
369-
370-
> article {
371-
display:none;
372-
}
373-
}
374-
}

biscuitman.js

Lines changed: 41 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
((d, w)=>{
2-
const bm = 'biscuitman'
3-
const ui = d.createElement('div')
4-
let dialog
5-
1+
((d, w, bm)=>{
62
const defaults = {
73
storageKey: 'myconsent',
84
global: 'Consent',
@@ -44,14 +40,16 @@
4440
// uncategorizedTitle: 'Uncategorized',
4541
// uncategorizedMessage: 'Uncategorized cookies are those currently under analysis and have not yet been assigned to a specific category',
4642
}
43+
const o = {...defaults, ...w.biscuitman}
4744

48-
// read user options from 'biscuitman' global object
49-
const o = w.biscuitman ? {...defaults, ...w.biscuitman} : defaults
45+
/* UI & Events */
46+
47+
const ui = d.createElement('div')
48+
let dialog
5049

51-
// Apply UI and bind events
5250
function render() {
5351
ui.classList.add(bm)
54-
ui.style = 'position:fixed;background:#fff;bottom:0' // critical css
52+
ui.style = 'position:fixed;background:#fff;bottom:0' // critical CSS
5553
ui.innerHTML = `
5654
<article>
5755
<b>${o.title}</b>
@@ -118,17 +116,18 @@
118116
d.body.appendChild(ui)
119117
}
120118

119+
const displayUI = (show) => ui.classList[show ? 'remove' : 'add']('bm-hide')
120+
121121
function buttonHandler(e) {
122-
id = e.target.dataset.id
122+
let id = e.target.dataset.id
123+
dispatch('button', {id})
123124
switch (id) {
124125
case 'accept': saveConsent(true); break;
125126
case 'close': dialog.close(); break;
126127
case 'settings': openModal(); break;
127128
case 'save': saveConsent(); break;
128129
case 'reject': saveConsent(false); break;
129-
default: break
130130
}
131-
dispatch('button', {id})
132131
}
133132

134133
function closeModalHandler() {
@@ -140,23 +139,32 @@
140139
}
141140

142141
function openModal() {
143-
dialog.showModal()
144142
dispatch('open')
143+
dialog.showModal()
145144
}
146145

147-
const displayUI = (show) => d.documentElement.classList[show ? 'remove' : 'add']('js-bm-hidden')
146+
function dispatch(eventName, data) {
147+
const name = `${bm}:${eventName}`
148+
const payload = {
149+
...(data !== undefined && data),
150+
time: +new Date()
151+
}
152+
d.dispatchEvent(new CustomEvent(name, payload))
153+
console.debug(name, payload);
154+
}
155+
156+
/* Consents & Injection */
148157

149158
function readConsent() {
150159
try {
151160
return JSON.parse(localStorage.getItem(o.storageKey))
152161
} catch (err) {
153-
console.error(bm, err)
154-
localStorage.removeItem(o.storageKey) // If there's an error in localstorage, wipe consent data
162+
console.error(err)
163+
localStorage.removeItem(o.storageKey)
155164
return {}
156165
}
157166
}
158167

159-
// Update global and localstorage with consent options
160168
function saveConsent(value) {
161169
const willReadValues = value === undefined
162170
w[o.global].consentTime = +new Date()
@@ -169,45 +177,28 @@
169177
if (!willReadValues) sectionElement.checked = value
170178
})
171179
localStorage.setItem(o.storageKey, JSON.stringify(w[o.global]))
172-
insertScripts()
173180
dispatch('save', {data: w[o.global]})
181+
insertScripts()
174182
dialog.close()
175183
displayUI(false)
176184
}
177185

178-
// Custom events in case you want to trigger behaviour
179-
function dispatch(eventName, data) {
180-
const name = `${bm}:${eventName}`
181-
const payload = {
182-
...(data !== undefined && data),
183-
time: +new Date()
184-
}
185-
d.dispatchEvent(new CustomEvent(name, payload))
186-
console.debug(name, payload);
187-
}
188-
189-
// replaces neutralized script tags with active script tags
190186
function insertScripts() {
191-
const scripts = d.querySelectorAll('script[data-consent]')
187+
const scripts = ui.querySelectorAll('script[data-consent]')
192188
scripts.forEach(script => {
193-
// Check consent
194189
if (!w[o.global][script.dataset.consent]) return false
195-
// Create new tag
190+
196191
const newScript = d.createElement('script')
197-
// Copy attributes, ignoring data- and type attributes
198192
for (let { name, value } of script.attributes) {
199193
if (name.startsWith('data-') || name === 'type') continue
200194
newScript.setAttribute(name, value)
201195
}
202-
// set type property
203196
newScript.setAttribute('type', script.dataset.type || 'text/javascript')
204-
// copy inline scripts if they do not have a src attribute
205197
if (!script.src) newScript.textContent = script.textContent
206-
// Insert script to DOM
207198
script.parentNode.replaceChild(newScript, script)
208199
dispatch('inject', {el: script})
209200

210-
// If tag has src and inline script, insert dependent inline script as new tag on load
201+
// If tag has src AND tag content, inject new tag adjacent to parent after load
211202
if (script.src && script.textContent.trim() !== '') newScript.addEventListener('load', () => {
212203
let depScript = d.createElement('script')
213204
depScript.textContent = script.textContent
@@ -217,40 +208,38 @@
217208
});
218209
}
219210

220-
// Load consent
211+
/* Start */
212+
221213
w[o.global] = readConsent() || {}
222214

223-
// Optionally auto-accept consent if timezone is not EU
215+
// Optional Non-EU auto-consent
224216
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone
225217
const isEuropeTimezone = /^(GMT|UTC)$/.test(tz) || /(Europe|BST|CEST|CET|EET|IST|WEST|WET|GMT-1|GMT-2|UTC+1|UTC+2|UTC+3)/.test(tz)
226218
if (o.acceptNonEU && !isEuropeTimezone) {
227219
saveConsent(true)
228220
displayUI(false)
229221
}
230222

231-
// Initiate UI
223+
// Render UI
232224
render()
233225

234226
// Consent logic
235227
if (w[o.global].consentTime) {
236228
displayUI(false)
237-
// Consent exists, initiate scripts:
238229
insertScripts()
239-
} else if (o.force) {
240-
// Force consent choice
241-
openModal()
242-
}
230+
} else if (o.force) openModal()
243231

244-
// Helper global methods
245-
// <a onclick="bmUpdateConsent()" href="javascript:void(0)">Update Consent Preferences</a>
246-
w.bmInvalidateConsent = () => {
232+
// Helper methods
233+
// <a onclick="bmInvalidate()" href="javascript:void(0)">Delete Consent Preferences</a>
234+
w.bmInvalidate = () => {
247235
dispatch('invalidate', {data: readConsent()})
248-
saveConsent(false) // resets UI
236+
saveConsent(false)
249237
localStorage.removeItem(o.storageKey)
250238
displayUI(true)
251239
}
252-
w.bmUpdateConsent = () => {
240+
// <a onclick="bmUpdate()" href="javascript:void(0)">Update Consent Preferences</a>
241+
w.bmUpdate = () => {
253242
dispatch('update', {data: readConsent()})
254243
openModal()
255244
}
256-
})(document, window)
245+
})(document, window, 'biscuitman')

build.mjs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,12 @@ swc.transform(js, {
3737
minify: true
3838
})
3939
.then(({code, map}) => {
40-
const codeWithoutWhitespace = code.replace(/[\n\t]/g, '')
41-
fs.writeFileSync('dist/biscuitman.min.js', comment + codeWithoutWhitespace)
40+
const optimizedCode = code
41+
// remove whitespace:
42+
.replace(/[\n\t]/g, '')
43+
fs.writeFileSync('dist/biscuitman.min.js', comment + optimizedCode)
4244
console.log('Wrote dist/biscuitman.min.js')
43-
writeJsWithCss(codeWithoutWhitespace)
45+
writeJsWithCss(optimizedCode)
4446
});
4547

4648
function writeJsWithCss(js) {

dist/biscuitman.min.css

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)