From e57bd5180939f4f134c5a3fb47db7f7203ad6f4a Mon Sep 17 00:00:00 2001 From: Yifei Zhang Date: Sun, 26 Mar 2023 12:29:02 +0000 Subject: [PATCH] feat: #9 add copy code button --- app/components/markdown.tsx | 29 +++++++++++++++++++++++++---- app/page.tsx | 2 +- app/styles/globals.scss | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/app/components/markdown.tsx b/app/components/markdown.tsx index 83bfe4ef..6e0e6d86 100644 --- a/app/components/markdown.tsx +++ b/app/components/markdown.tsx @@ -4,15 +4,36 @@ import RemarkMath from "remark-math"; import RehypeKatex from "rehype-katex"; import RemarkGfm from "remark-gfm"; import RehypePrsim from "rehype-prism-plus"; +import { useRef } from "react"; +import { copyToClipboard } from "../utils"; + +export function PreCode(props: { children: any }) { + const ref = useRef(null); + + return ( +
+       {
+          if (ref.current) {
+            const code = ref.current.innerText;
+            copyToClipboard(code);
+          }
+        }}
+      >
+      {props.children}
+    
+ ); +} export function Markdown(props: { content: string }) { return ( {props.content} diff --git a/app/page.tsx b/app/page.tsx index a986da3f..54300e71 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,5 +1,5 @@ import { Analytics } from "@vercel/analytics/react"; -import { Home } from './components/home' +import { Home } from "./components/home"; export default function App() { return ( diff --git a/app/styles/globals.scss b/app/styles/globals.scss index e7d35226..46f074df 100644 --- a/app/styles/globals.scss +++ b/app/styles/globals.scss @@ -206,3 +206,36 @@ div.math { text-decoration: underline; } } + +pre { + position: relative; + + &:hover .copy-code-button { + pointer-events: all; + transform: translateX(0px); + opacity: 0.5; + } + + .copy-code-button { + position: absolute; + right: 10px; + cursor: pointer; + padding: 0px 5px; + background-color: var(--black); + color: var(--white); + border: var(--border-in-light); + border-radius: 10px; + transform: translateX(10px); + pointer-events: none; + opacity: 0; + transition: all ease 0.3s; + + &:after { + content: "copy"; + } + + &:hover { + opacity: 1; + } + } +}