Skip to content

Commit

Permalink
Add Segment track calls to code copy button (#178)
Browse files Browse the repository at this point in the history
* add track call to copy button

* clean up sample code sent to segment
  • Loading branch information
colegoldsmith authored Dec 19, 2024
1 parent 37340d7 commit 0e22295
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/js/07-copy-to-clipboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@
toolbox.appendChild(copy)
}
if (copy) {
copy.addEventListener('click', writeToClipboard.bind(copy, code))
copy.addEventListener('click', function () {
var text = code.innerText.replace(TRAILING_SPACE_RX, '')
if (code.dataset.lang === 'console' && text.startsWith('$ ')) text = extractCommands(text)
writeToClipboard(text, copy)
trackCopy(code.dataset.lang, title?.childNodes[0]?.nodeValue, text)
})
content.prepend(toolbox)
}
if (lang && !title && !nolang) {
Expand All @@ -69,9 +74,7 @@
return cmds.join(' && ')
}

function writeToClipboard (code) {
var text = code.innerText.replace(TRAILING_SPACE_RX, '')
if (code.dataset.lang === 'console' && text.startsWith('$ ')) text = extractCommands(text)
function writeToClipboard (text, button) {
window.navigator.clipboard.writeText(text).then(
function () {
const icon = this.querySelector('.material-icons')
Expand All @@ -83,8 +86,19 @@
setTimeout(function () {
icon.innerText = 'content_paste'
}, 500)
}.bind(this),
}.bind(button),
function () {}
)
}

function trackCopy (language, title, text) {
if (window.analytics) {
var sample = text.slice(0, 50).replace(/\s+/g, ' ').trim()
window.analytics.track('Code Snippet Copied', {
snippetLanguage: language,
snippetTitle: title,
snippetSample: sample,
})
}
}
})()

0 comments on commit 0e22295

Please sign in to comment.