Skip to content
This repository was archived by the owner on Mar 12, 2023. It is now read-only.

Commit 6329a18

Browse files
authored
Merge pull request #175 from otoyo/code-copy-button
Code copy button
2 parents 7497df0 + a963536 commit 6329a18

File tree

2 files changed

+42
-10
lines changed

2 files changed

+42
-10
lines changed

components/notion-blocks/code.tsx

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
'use client'
22

3+
import React, { useState } from 'react';
34
import Prism from 'prismjs'
45
import 'prismjs/components/prism-css'
56
import 'prismjs/components/prism-diff'
@@ -21,22 +22,36 @@ import styles from '../../styles/notion-block.module.css'
2122

2223

2324
const Code = ({ block }) => {
25+
const [state, setState] = useState(false)
2426
const code = block.Code.RichTexts.map((richText: RichText) => richText.Text.Content).join('')
2527
const language = block.Code.Language.toLowerCase()
2628
const grammer = Prism.languages[language.toLowerCase()] || Prism.languages.javascript
2729

30+
const handleClick = (ev) => {
31+
navigator.clipboard
32+
.writeText(ev.target.getAttribute('data-code'))
33+
.then(() => {
34+
setState(true)
35+
})
36+
}
37+
2838
return (
2939
<div className={styles.code}>
3040
{language === 'mermaid' ? (
3141
<Mermaid id={`mermaid-${block.Id}`} definition={code} />
3242
) : (
33-
<pre>
34-
<code
35-
dangerouslySetInnerHTML={{
36-
__html: Prism.highlight(code, grammer, language),
37-
}}
38-
/>
39-
</pre>
43+
<div>
44+
<div>
45+
<button data-code={code} onClick={handleClick}>{state ? 'Copied!' : 'Copy'}</button>
46+
</div>
47+
<pre>
48+
<code
49+
dangerouslySetInnerHTML={{
50+
__html: Prism.highlight(code, grammer, language),
51+
}}
52+
/>
53+
</pre>
54+
</div>
4055
)}
4156
{block.Code.Caption.length > 0 && block.Code.Caption[0].Text.Content ? (
4257
<div className={styles.caption}>

styles/notion-block.module.css

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,36 @@
2222
display: block;
2323
width: 100%;
2424
}
25+
.code > div:first-child {
26+
background: rgb(247, 246, 243);
27+
border-radius: var(--radius);
28+
}
29+
.code > div div {
30+
display: flex;
31+
justify-content: flex-end;
32+
}
33+
.code button {
34+
display: block;
35+
width: 4rem;
36+
border: 0;
37+
border-radius: var(--radius);
38+
background-color: rgba(227, 226, 224, 0.5);
39+
color: var(--fg);
40+
line-height: 1.2rem;
41+
cursor: pointer;
42+
}
2543
.code pre {
2644
display: block;
2745
overflow: auto;
28-
padding: 2rem;
29-
background: rgb(247, 246, 243);
46+
padding: 0.8rem 2rem 2rem;
3047
font-size: 0.9rem;
3148
line-height: 1.2rem;
32-
border-radius: var(--radius);
3349
}
3450
.code pre code {
3551
color: var(--fg);
3652
padding: 0;
3753
background: rgb(247, 246, 243) !important;
54+
border-radius: 0;
3855
}
3956

4057
.callout {

0 commit comments

Comments
 (0)