refactor copy code button

change pre component to server component
This commit is contained in:
DefectingCat
2023-12-26 11:05:06 +08:00
parent 40775b98f7
commit cf0c91edb6
7 changed files with 124 additions and 73 deletions

View File

@ -6,6 +6,7 @@ import RUACodeSandbox from 'components/rua/rua-code-sandbox';
import RUASandpack from 'components/rua/rua-sandpack';
import Tab from 'components/rua/tab';
import TabItem from 'components/rua/tab/tab-item';
import GistCode from 'components/common/gist-code';
const components = {
RUASandpack,
@ -16,6 +17,7 @@ const components = {
TabItem,
RUACodeSandbox,
RUACodepen,
GistCode,
};
export default components;

View File

@ -1,7 +1,6 @@
'use client';
import clsx from 'clsx';
import CopyButton from 'components/post/copy-button';
import CopyCode from 'components/post/copy-code';
import useCopyToClipboard from 'lib/hooks/use-copy-to-clipboard';
import {
DetailedHTMLProps,
@ -19,26 +18,11 @@ type Props = {} & DetailedHTMLProps<
const Pre = ({ ...rest }: Props) => {
const { children, className, ...props } = rest;
const preRef = useRef<HTMLPreElement>(null);
const { copy } = useCopyToClipboard();
const handleCopy = useCallback(() => {
if (!preRef.current) throw new Error('Can not access pre element.');
if (preRef.current.textContent == null) return;
copy(preRef.current.textContent);
}, [copy]);
return (
<>
<pre
ref={preRef}
className={clsx(className, 'relative group')}
{...props}
>
<pre className={clsx(className, 'relative group')} {...props}>
{children}
<CopyButton
className={clsx('absolute top-4 right-4', 'translate-y-[-17%]')}
onCopy={handleCopy}
/>
<CopyCode />
</pre>
</>
);