-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCodeBlock.tsx
More file actions
66 lines (60 loc) · 1.74 KB
/
CodeBlock.tsx
File metadata and controls
66 lines (60 loc) · 1.74 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import React, { useState } from 'react';
import toast from 'react-hot-toast';
import { FaCheck, FaCopy } from 'react-icons/fa';
import styled from 'styled-components';
import { Button } from './Button';
interface CodeBlockProps {
content?: string;
loading?: boolean;
wrapContent?: boolean;
}
/** Codeblock with copy feature */
export function CodeBlock({ content, loading, wrapContent }: CodeBlockProps) {
const [isCopied, setIsCopied] = useState<string | undefined>(undefined);
function copyToClipboard() {
setIsCopied(content);
navigator.clipboard.writeText(content || '');
toast.success('Copied to clipboard');
}
return (
<CodeBlockStyled data-code-content={content} wrapContent={wrapContent}>
{loading ? (
'loading...'
) : (
<>
{content}
<Button
subtle
style={{
position: 'absolute',
bottom: 0,
top: 0,
margin: 0,
right: 0,
}}
onClick={copyToClipboard}
title={isCopied === content ? 'Copied!' : 'Copy to clipboard'}
data-test='copy-response'
>
{isCopied === content ? <FaCheck /> : <FaCopy />}
</Button>
</>
)}
</CodeBlockStyled>
);
}
interface Props {
wrapContent?: boolean;
}
export const CodeBlockStyled = styled.pre<Props>`
position: relative;
background-color: ${p => p.theme.colors.bg1};
border-radius: ${p => p.theme.radius};
border: solid 1px ${p => p.theme.colors.bg2};
padding: 0.3rem;
font-family: monospace;
width: 100%;
overflow-x: auto;
word-wrap: ${p => (p.wrapContent ? 'break-word' : 'initial')};
white-space: ${p => (p.wrapContent ? 'pre-wrap' : 'initial')};
`;