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

Commit

Permalink
Support code copy button
Browse files Browse the repository at this point in the history
  • Loading branch information
otoyo committed Feb 27, 2023
1 parent 7497df0 commit 913f2c6
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions components/notion-blocks/code.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client'

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


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

const handleClick = (ev) => {
navigator.clipboard
.writeText(ev.target.getAttribute('data-code'))
.then(() => {
setState(true)
})
}

return (
<div className={styles.code}>
{language === 'mermaid' ? (
<Mermaid id={`mermaid-${block.Id}`} definition={code} />
) : (
<pre>
<code
dangerouslySetInnerHTML={{
__html: Prism.highlight(code, grammer, language),
}}
/>
</pre>
<div>
<div>
<button data-code={code} onClick={handleClick}>{state ? 'Copied!' : 'Copy'}</button>
</div>
<pre>
<code
dangerouslySetInnerHTML={{
__html: Prism.highlight(code, grammer, language),
}}
/>
</pre>
</div>
)}
{block.Code.Caption.length > 0 && block.Code.Caption[0].Text.Content ? (
<div className={styles.caption}>
Expand Down

0 comments on commit 913f2c6

Please sign in to comment.