cg / hackerproducts
63 files · 5,740 lines · 159.1 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.
Quick jump: page.tsxpage.tsxglobals.cssschema.sqlpackage.json
root / src / components / ShareButton.tsx
src/components/ShareButton.tsx · 39 lines · 1.2 KB← back to folder
| 1 | "use client"; |
| 2 | |
| 3 | import { useRef, useState } from "react"; |
| 4 | |
| 5 | export function ShareButton({ url }: { url: string }) { |
| 6 | const [copied, setCopied] = useState(false); |
| 7 | const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 8 | |
| 9 | async function handleCopy() { |
| 10 | const cleanUrl = url.trim(); |
| 11 | try { |
| 12 | if (navigator.clipboard && window.isSecureContext) { |
| 13 | await navigator.clipboard.writeText(cleanUrl); |
| 14 | } else { |
| 15 | const textarea = document.createElement("textarea"); |
| 16 | textarea.value = cleanUrl; |
| 17 | textarea.setAttribute("readonly", ""); |
| 18 | textarea.style.position = "fixed"; |
| 19 | textarea.style.opacity = "0"; |
| 20 | document.body.appendChild(textarea); |
| 21 | textarea.select(); |
| 22 | document.execCommand("copy"); |
| 23 | document.body.removeChild(textarea); |
| 24 | } |
| 25 | setCopied(true); |
| 26 | if (timerRef.current) clearTimeout(timerRef.current); |
| 27 | timerRef.current = setTimeout(() => setCopied(false), 2000); |
| 28 | } catch { |
| 29 | window.prompt("Copy link:", cleanUrl); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | return ( |
| 34 | <button type="button" className="link-button" onClick={() => void handleCopy()}> |
| 35 | {copied ? "copied link" : "share"} |
| 36 | </button> |
| 37 | ); |
| 38 | } |
| 39 |