Skip to content

Commit 0e22295

Browse files
Add Segment track calls to code copy button (#178)
* add track call to copy button * clean up sample code sent to segment
1 parent 37340d7 commit 0e22295

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/js/07-copy-to-clipboard.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,12 @@
4949
toolbox.appendChild(copy)
5050
}
5151
if (copy) {
52-
copy.addEventListener('click', writeToClipboard.bind(copy, code))
52+
copy.addEventListener('click', function () {
53+
var text = code.innerText.replace(TRAILING_SPACE_RX, '')
54+
if (code.dataset.lang === 'console' && text.startsWith('$ ')) text = extractCommands(text)
55+
writeToClipboard(text, copy)
56+
trackCopy(code.dataset.lang, title?.childNodes[0]?.nodeValue, text)
57+
})
5358
content.prepend(toolbox)
5459
}
5560
if (lang && !title && !nolang) {
@@ -69,9 +74,7 @@
6974
return cmds.join(' && ')
7075
}
7176

72-
function writeToClipboard (code) {
73-
var text = code.innerText.replace(TRAILING_SPACE_RX, '')
74-
if (code.dataset.lang === 'console' && text.startsWith('$ ')) text = extractCommands(text)
77+
function writeToClipboard (text, button) {
7578
window.navigator.clipboard.writeText(text).then(
7679
function () {
7780
const icon = this.querySelector('.material-icons')
@@ -83,8 +86,19 @@
8386
setTimeout(function () {
8487
icon.innerText = 'content_paste'
8588
}, 500)
86-
}.bind(this),
89+
}.bind(button),
8790
function () {}
8891
)
8992
}
93+
94+
function trackCopy (language, title, text) {
95+
if (window.analytics) {
96+
var sample = text.slice(0, 50).replace(/\s+/g, ' ').trim()
97+
window.analytics.track('Code Snippet Copied', {
98+
snippetLanguage: language,
99+
snippetTitle: title,
100+
snippetSample: sample,
101+
})
102+
}
103+
}
90104
})()

0 commit comments

Comments
 (0)