Skip to content

Commit

Permalink
Merge pull request #90 from JohnsonMao/refactor/code-box-component
Browse files Browse the repository at this point in the history
♻️ refactor CodeBox: Abstract useAutoRest hook
  • Loading branch information
JohnsonMao authored Sep 22, 2023
2 parents 116b183 + ad9e174 commit d726b5e
Showing 1 changed file with 7 additions and 22 deletions.
29 changes: 7 additions & 22 deletions src/components/CodeBox/CodeBox.tsx
Original file line number Diff line number Diff line change
@@ -1,38 +1,23 @@
'use client';

import { HTMLAttributes, useRef, useState } from 'react';
import { HTMLAttributes, useRef } from 'react';
import { AiOutlineCopy } from 'react-icons/ai';

import useAutoReset from '@/hooks/useAutoReset';
import cn from '@/utils/cn';
import { copyToClipboard } from '@/utils/clipboard';

type CodeBoxProps = HTMLAttributes<HTMLPreElement>;

function CodeBox(props: CodeBoxProps) {
const preRef = useRef<HTMLPreElement>(null);
const timerRef = useRef<NodeJS.Timeout | null>(null);
const [copied, setCopied] = useState(false);

const resetCopiedState = () => {
setCopied(false);
timerRef.current = null;
};
const preElementRef = useRef<HTMLPreElement>(null);
const [copied, setCopied] = useAutoReset(false);

const handleClick = () => {
const text = preRef.current?.textContent;

if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
const text = preElementRef.current?.textContent;

if (text) {
copyToClipboard(text)
.then(() => {
setCopied(true);
timerRef.current = setTimeout(resetCopiedState, 1000);
})
.catch(resetCopiedState);
copyToClipboard(text).then(() => setCopied(true));
}
};

Expand All @@ -53,7 +38,7 @@ function CodeBox(props: CodeBoxProps) {
<AiOutlineCopy />
</button>
</div>
<pre {...props} ref={preRef} />
<pre {...props} ref={preElementRef} />
</div>
);
}
Expand Down

0 comments on commit d726b5e

Please sign in to comment.