80 lines
2.2 KiB
TypeScript
80 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
/**
|
|
* "Copy link to this page" — copies the full, unshortened absolute URL of
|
|
* the active page. Deliberately bypasses useCopyFeedback (which rewrites
|
|
* `?hl=` highlight URLs into short /share links); here we want the literal
|
|
* page URL. The write is synchronous within the click so a single tap works.
|
|
*
|
|
* Shared by the PageHeader controls row and pages with their own header
|
|
* (e.g. a quiz).
|
|
*/
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { Check, Link2 } from "lucide-react";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
export function CopyPageLinkButton({
|
|
label = "Copy link to this page",
|
|
className,
|
|
}: {
|
|
label?: string;
|
|
className?: string;
|
|
}) {
|
|
const [copied, setCopied] = useState(false);
|
|
const copyTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
useEffect(() => {
|
|
return () => {
|
|
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
|
|
};
|
|
}, []);
|
|
|
|
async function copyPageLink() {
|
|
const url = window.location.href;
|
|
try {
|
|
await navigator.clipboard.writeText(url);
|
|
} catch {
|
|
// Fallback for browsers without the async clipboard API.
|
|
const ta = document.createElement("textarea");
|
|
ta.value = url;
|
|
ta.style.position = "fixed";
|
|
ta.style.opacity = "0";
|
|
document.body.appendChild(ta);
|
|
ta.focus();
|
|
ta.select();
|
|
try {
|
|
document.execCommand("copy");
|
|
} catch {
|
|
// silent fail
|
|
}
|
|
document.body.removeChild(ta);
|
|
}
|
|
setCopied(true);
|
|
if (copyTimerRef.current) clearTimeout(copyTimerRef.current);
|
|
copyTimerRef.current = setTimeout(() => setCopied(false), 1500);
|
|
}
|
|
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={copyPageLink}
|
|
aria-label={label}
|
|
title={label}
|
|
className={cn(
|
|
"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs transition-colors",
|
|
copied
|
|
? "text-foreground border-primary/40"
|
|
: "text-muted-foreground hover:text-foreground hover:bg-muted",
|
|
className,
|
|
)}
|
|
>
|
|
{copied ? (
|
|
<Check className="size-3.5 text-primary" />
|
|
) : (
|
|
<Link2 className="size-3.5" />
|
|
)}
|
|
{copied ? "Link copied" : label}
|
|
</button>
|
|
);
|
|
}
|