refactor; add share status state

This commit is contained in:
mahiro72 2025-12-17 02:46:01 +09:00
parent a5c81d7207
commit 21fe750933
1 changed files with 17 additions and 8 deletions

View File

@ -1,21 +1,23 @@
import { useEffect, useState } from "react";
import AstralButton from "./AstralButton";
type ShareStatus = "initial" | "copying" | "copied";
export default function ShareButton({
onShare,
}: {
onShare: () => Promise<void>;
}) {
const [copied, setCopied] = useState(false);
const [status, setStatus] = useState<ShareStatus>("initial");
useEffect(() => {
if (copied) {
const timeout = setTimeout(() => setCopied(false), 2000);
if (status === "copied") {
const timeout = setTimeout(() => setStatus("initial"), 2000);
return () => clearTimeout(timeout);
}
}, [copied]);
}, [status]);
return copied ? (
return status === "copied" ? (
<AstralButton
type="button"
className="relative flex-none leading-6 py-1.5 px-3 cursor-auto dark:shadow-copied"
@ -32,10 +34,17 @@ export default function ShareButton({
<AstralButton
type="button"
className="relative flex-none leading-6 py-1.5 px-3 shadow-xs disabled:opacity-50"
disabled={copied}
disabled={status === "copying"}
onClick={async () => {
setStatus("copying");
try {
await onShare();
setCopied(true);
setStatus("copied");
} catch (error) {
// eslint-disable-next-line no-console
console.error("Failed to share playground", error);
setStatus("initial");
}
}}
>
<span