| 1 |
(function () { |
| 2 |
'use strict'; |
| 3 |
|
| 4 |
function initCodeBlock(wrap) { |
| 5 |
var copyBtn = wrap.querySelector('.bkbg-cb-copy-btn'); |
| 6 |
var pre = wrap.querySelector('.bkbg-cb-pre'); |
| 7 |
|
| 8 |
if (copyBtn && pre) { |
| 9 |
var copyLabel = copyBtn.dataset.copyLabel || 'Copy'; |
| 10 |
var copiedLabel = copyBtn.dataset.copiedLabel || 'Copied!'; |
| 11 |
var labelEl = copyBtn.querySelector('.bkbg-cb-copy-label'); |
| 12 |
var timer; |
| 13 |
|
| 14 |
copyBtn.addEventListener('click', function () { |
| 15 |
var text = pre.textContent; |
| 16 |
var setCopied = function () { |
| 17 |
clearTimeout(timer); |
| 18 |
copyBtn.classList.add('is-copied'); |
| 19 |
if (labelEl) labelEl.textContent = copiedLabel; |
| 20 |
timer = setTimeout(function () { |
| 21 |
copyBtn.classList.remove('is-copied'); |
| 22 |
if (labelEl) labelEl.textContent = copyLabel; |
| 23 |
}, 2000); |
| 24 |
}; |
| 25 |
|
| 26 |
if (navigator.clipboard && navigator.clipboard.writeText) { |
| 27 |
navigator.clipboard.writeText(text).then(setCopied).catch(function () { |
| 28 |
fallbackCopy(text, setCopied); |
| 29 |
}); |
| 30 |
} else { |
| 31 |
fallbackCopy(text, setCopied); |
| 32 |
} |
| 33 |
}); |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
function fallbackCopy(text, cb) { |
| 38 |
try { |
| 39 |
var ta = document.createElement('textarea'); |
| 40 |
ta.value = text; |
| 41 |
ta.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0;'; |
| 42 |
document.body.appendChild(ta); |
| 43 |
ta.select(); |
| 44 |
document.execCommand('copy'); |
| 45 |
document.body.removeChild(ta); |
| 46 |
if (cb) cb(); |
| 47 |
} catch (e) {} |
| 48 |
} |
| 49 |
|
| 50 |
function initAll() { |
| 51 |
var blocks = document.querySelectorAll('.bkbg-cb-wrap'); |
| 52 |
blocks.forEach(initCodeBlock); |
| 53 |
} |
| 54 |
|
| 55 |
if (document.readyState === 'loading') { |
| 56 |
document.addEventListener('DOMContentLoaded', initAll); |
| 57 |
} else { |
| 58 |
initAll(); |
| 59 |
} |
| 60 |
})(); |
| 61 |
|