import React, { useState, useEffect, useRef } from "react" import { useRouter } from "next/router" const GITHUB_REPO = "Kilo-Org/kilocode" const GITHUB_BRANCH = "main" interface CopyPageButtonProps { className?: string } function getRoutePath(asPath: string) { const path = asPath.split("#")[0].split("?")[0] return path === "/" ? "/index" : path } export function CopyPageButton({ className }: CopyPageButtonProps) { const router = useRouter() const [open, setOpen] = useState(false) const [copied, setCopied] = useState(false) const [error, setError] = useState(false) const [isLoading, setIsLoading] = useState(false) const ref = useRef(null) useEffect(() => { if (copied || error) { const timer = setTimeout(() => { setCopied(false) setError(false) }, 3000) return () => clearTimeout(timer) } }, [copied, error]) useEffect(() => { function handleClickOutside(event: MouseEvent) { if (ref.current && !ref.current.contains(event.target as Node)) { setOpen(false) } } if (open) { document.addEventListener("mousedown", handleClickOutside) } return () => { document.removeEventListener("mousedown", handleClickOutside) } }, [open]) const handleCopy = async () => { if (copied || error || isLoading) return setIsLoading(true) setOpen(false) try { const mdPath = getRoutePath(router.asPath) const response = await fetch(`/docs/api/raw-markdown?path=${encodeURIComponent(mdPath)}`) if (!response.ok) { throw new Error("Failed to fetch markdown") } const markdown = await response.text() await navigator.clipboard.writeText(markdown) setCopied(true) } catch (err) { console.error("Failed to copy page:", err) setError(true) } finally { setIsLoading(false) } } const openGitHubUrl = async (mode: "raw" | "edit") => { setOpen(false) try { const mdPath = getRoutePath(router.asPath) const response = await fetch(`/docs/api/resolve-path?path=${encodeURIComponent(mdPath)}`) if (!response.ok) { throw new Error("Failed to resolve file path") } const { filePath } = await response.json() const url = mode === "raw" ? `https://raw.githubusercontent.com/${GITHUB_REPO}/${GITHUB_BRANCH}/${filePath}` : `https://github.com/${GITHUB_REPO}/edit/${GITHUB_BRANCH}/${filePath}` window.open(url, "_blank", "noopener,noreferrer") } catch (err) { console.error(`Failed to open ${mode} URL:`, err) } } const label = copied ? "Copied" : error ? "Copy failed" : "Copy page" return ( <>
{open && (
)}
) } function CopyIcon() { return ( ) } function CheckIcon() { return ( ) } function ChevronDownIcon() { return ( ) } function FileIcon() { return ( ) } function EditIcon() { return ( ) }