| 1 |
/* Color Palette — frontend */ |
| 2 |
(function () { |
| 3 |
'use strict'; |
| 4 |
|
| 5 |
function hexToRgb(hex) { |
| 6 |
var clean = (hex || '').replace('#', ''); |
| 7 |
if (clean.length === 3) { clean = clean.split('').map(function (c) { return c + c; }).join(''); } |
| 8 |
var r = parseInt(clean.substring(0, 2), 16) || 0; |
| 9 |
var g = parseInt(clean.substring(2, 4), 16) || 0; |
| 10 |
var b = parseInt(clean.substring(4, 6), 16) || 0; |
| 11 |
return 'rgb(' + r + ', ' + g + ', ' + b + ')'; |
| 12 |
} |
| 13 |
|
| 14 |
function init() { |
| 15 |
document.querySelectorAll('.bkcp-wrap').forEach(function (wrap) { |
| 16 |
if (wrap._bkcpInit) { return; } |
| 17 |
wrap._bkcpInit = true; |
| 18 |
|
| 19 |
/* fill in RGB labels */ |
| 20 |
wrap.querySelectorAll('.bkcp-rgb[data-hex]').forEach(function (el) { |
| 21 |
el.textContent = hexToRgb(el.getAttribute('data-hex')); |
| 22 |
}); |
| 23 |
|
| 24 |
/* copy buttons */ |
| 25 |
wrap.querySelectorAll('.bkcp-copy').forEach(function (btn) { |
| 26 |
/* pre-populate rgb data attr */ |
| 27 |
var hex = btn.getAttribute('data-hex') || ''; |
| 28 |
var rgb = hexToRgb(hex); |
| 29 |
var cssVar = btn.getAttribute('data-cssvar') || ''; |
| 30 |
var format = btn.getAttribute('data-format') || 'hex'; |
| 31 |
|
| 32 |
btn.setAttribute('data-rgb', rgb); |
| 33 |
|
| 34 |
btn.addEventListener('click', function () { |
| 35 |
var text = format === 'rgb' ? rgb |
| 36 |
: format === 'css' ? (cssVar || hex) |
| 37 |
: hex.toUpperCase(); |
| 38 |
|
| 39 |
if (navigator.clipboard) { |
| 40 |
navigator.clipboard.writeText(text).then(function () { showCopied(btn); }); |
| 41 |
} else { |
| 42 |
/* fallback */ |
| 43 |
var ta = document.createElement('textarea'); |
| 44 |
ta.value = text; |
| 45 |
ta.style.cssText = 'position:fixed;opacity:0;left:-9999px'; |
| 46 |
document.body.appendChild(ta); |
| 47 |
ta.select(); |
| 48 |
document.execCommand('copy'); |
| 49 |
document.body.removeChild(ta); |
| 50 |
showCopied(btn); |
| 51 |
} |
| 52 |
}); |
| 53 |
}); |
| 54 |
}); |
| 55 |
} |
| 56 |
|
| 57 |
function showCopied(btn) { |
| 58 |
var orig = btn.textContent; |
| 59 |
btn.textContent = 'Copied!'; |
| 60 |
btn.classList.add('bkcp-copied'); |
| 61 |
setTimeout(function () { |
| 62 |
btn.textContent = orig; |
| 63 |
btn.classList.remove('bkcp-copied'); |
| 64 |
}, 1800); |
| 65 |
} |
| 66 |
|
| 67 |
if (document.readyState === 'loading') { |
| 68 |
document.addEventListener('DOMContentLoaded', init); |
| 69 |
} else { |
| 70 |
init(); |
| 71 |
} |
| 72 |
}()); |
| 73 |
|