Add clipboard to next code block

The begining

https://kafka-tutorials.confluent.io/kafka-console-consumer-producer-basics/kafka.html
i saw confluent.io‘s code block is great.
it have feature like clipboard/ collapsible, even font looke good.
so i want add clipboard function to my blog at first.

at first i search by markdown code block copy, but no article helps.
then i search by hexo next theme code block, finally find the article i want.

Hexo NexT 代码块复制功能

implement

Download clipboard.js

Download js file from https://github.com/zenorocha/clipboard.js

save file to themes\next\source\js\

or use cdn resource directly:
https://github.com/zenorocha/clipboard.js/wiki/CDN-Providers

Use clipboard.js

create file clipboard-use.js in themes\next\source\js\ as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*create copy button when page loaded*/
!function (e, t, a) {
/* code */
var initCopyCode = function(){
var copyHtml = '';
copyHtml += '<button class="btn-copy" data-clipboard-snippet>';
copyHtml += ' <i class="fa fa-globe"></i><span>copy</span>';
copyHtml += '</button>';
$(".highlight .code pre").before(copyHtml);
new ClipboardJS('.btn-copy', {
target: function(trigger) {
return trigger.nextElementSibling;
}
});
}
initCopyCode();
}(window, document);

append style in themes\next\source\css\_custom\custom.styl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//copy button in code block
.highlight{
position: relative;
}
.btn-copy {
display: inline-block;
cursor: pointer;
background-color: #eee;
background-image: linear-gradient(#fcfcfc,#eee);
border: 1px solid #d5d5d5;
border-radius: 3px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-appearance: none;
font-size: 13px;
font-weight: 700;
line-height: 20px;
color: #333;
-webkit-transition: opacity .3s ease-in-out;
-o-transition: opacity .3s ease-in-out;
transition: opacity .3s ease-in-out;
padding: 2px 6px;
position: absolute;
right: 5px;
top: 5px;
opacity: 0;
}
.btn-copy span {
margin-left: 5px;
}
.highlight:hover .btn-copy{
opacity: 1;
}

reference

modify themes\next\layout\_layout.swig, add tag before </body>
if you use cdn resource, replace it with cdn src.

1
2
3
<!-- 代码块复制功能 -->
<script type="text/javascript" src="/js/clipboard.min.js"></script>
<script type="text/javascript" src="/js/clipboard-use.js"></script>

defects

  • the button style is not very harmonious with blog
  • when copy success no remind tip copyed!
    the offical recommend use https://github.com/primer/css, but it’s not easy for me to get started.
  • when copy success the paragraph well be selected, it’s not what i want.