Skip to content

Commit 1f1ae00

Browse files
authored
add copy to clipboard feature (#728)
1 parent a5f3785 commit 1f1ae00

2 files changed

Lines changed: 50 additions & 14 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { useState } from "react";
2+
3+
type Props = {
4+
codeText: string;
5+
lang?: string;
6+
};
7+
8+
const CopyToClipboard = ({ codeText, lang = "language-python" }: Props): JSX.Element => {
9+
const [copied, setCopied] = useState(false);
10+
11+
const textToCopy = codeText.trim();
12+
13+
const handleCopy = async () => {
14+
try {
15+
await navigator.clipboard.writeText(textToCopy);
16+
setCopied(true);
17+
setTimeout(() => setCopied(false), 1500);
18+
} catch (e) {
19+
console.error("Copy failed", e);
20+
}
21+
};
22+
23+
return (
24+
<dd className="mt-2 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
25+
<div className="relative">
26+
<pre className="overflow-auto rounded-md bg-gray-100 p-4">
27+
<code className={lang}>{codeText}</code>
28+
</pre>
29+
30+
<button
31+
type="button"
32+
onClick={handleCopy}
33+
aria-label="Copy code"
34+
className="absolute right-2 top-2 rounded bg-white/90 px-2 py-1 text-xs font-medium text-gray-700 shadow"
35+
>
36+
{copied ? "Copied" : "Copy"}
37+
</button>
38+
</div>
39+
</dd>
40+
);
41+
};
42+
43+
export default CopyToClipboard;

frontend/src/components/SingleView.tsx

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
} from '@/utils/ExtractThumbnails'
1010
import { PageTitle } from '@/components/Typography'
1111
import { MiniCard } from '@/components/Card'
12+
import CopyToClipboard from "@/components/CopyToClipboard"
1213

1314
import ReactMarkdown from 'react-markdown'
1415

@@ -46,14 +47,10 @@ export function ModelSingleView({
4647
</Link>
4748
:
4849
</dt>
49-
<dd className="mt-2 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
50-
<pre>
51-
<code className="language-python">
52-
{`from scivision import load_pretrained_model
50+
<CopyToClipboard
51+
codeText={`from scivision import load_pretrained_model
5352
load_pretrained_model("${url}")`}
54-
</code>
55-
</pre>
56-
</dd>
53+
/>
5754
</div>
5855
</>
5956
) : (
@@ -115,13 +112,9 @@ load_pretrained_model("${url}")`}
115112
<dt className="text-sm font-medium leading-6 text-gray-900">
116113
Install with pip
117114
</dt>
118-
<dd className="mt-2 text-sm text-gray-900 sm:col-span-2 sm:mt-0">
119-
<pre>
120-
<code className="language-python">
121-
pip install {pkg_url}
122-
</code>
123-
</pre>
124-
</dd>
115+
<CopyToClipboard
116+
codeText={`pip install ${pkg_url}`}
117+
/>
125118
</div>
126119
{scivision_code}
127120
</dl>

0 commit comments

Comments
 (0)