|
| 1 | +import useBaseUrl from '@docusaurus/useBaseUrl'; |
| 2 | +import React, { useState } from 'react'; |
| 3 | + |
| 4 | +import styles from '../styles.module.css'; |
| 5 | + |
| 6 | +// Custom component for button text |
| 7 | +function ButtonText({ isLoading, isCopied }: { isLoading: boolean; isCopied: boolean }) { |
| 8 | + if (isLoading) { |
| 9 | + return <>Copying...</>; |
| 10 | + } |
| 11 | + if (isCopied) { |
| 12 | + return <>Copied!</>; |
| 13 | + } |
| 14 | + return <>Copy for LLM</>; |
| 15 | +} |
| 16 | + |
| 17 | +export default function CopyForLLM() { |
| 18 | + const copyIcon = useBaseUrl('/img/copy.svg'); |
| 19 | + const [isLoading, setIsLoading] = useState(false); |
| 20 | + const [isCopied, setIsCopied] = useState(false); |
| 21 | + |
| 22 | + const handleCopy = async () => { |
| 23 | + try { |
| 24 | + setIsLoading(true); |
| 25 | + |
| 26 | + const currentUrl = window.location.href; |
| 27 | + const markdownUrl = `${currentUrl}.md`; |
| 28 | + |
| 29 | + // Fetch the markdown content |
| 30 | + const response = await fetch(markdownUrl); |
| 31 | + |
| 32 | + if (!response.ok) { |
| 33 | + throw new Error(`Failed to fetch markdown: ${response.status}`); |
| 34 | + } |
| 35 | + |
| 36 | + const markdownContent = await response.text(); |
| 37 | + |
| 38 | + // Copy to clipboard |
| 39 | + await navigator.clipboard.writeText(markdownContent); |
| 40 | + |
| 41 | + // Show success feedback |
| 42 | + setIsCopied(true); |
| 43 | + setTimeout(() => setIsCopied(false), 2000); |
| 44 | + } catch (error) { |
| 45 | + console.error('Failed to copy markdown content:', error); |
| 46 | + } finally { |
| 47 | + setIsLoading(false); |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + return ( |
| 52 | + <button |
| 53 | + className={styles.llmButton} |
| 54 | + title="Copy for LLM" |
| 55 | + onClick={handleCopy} |
| 56 | + disabled={isLoading} |
| 57 | + > |
| 58 | + <span |
| 59 | + className={styles.llmButtonIcon} |
| 60 | + style={{ |
| 61 | + backgroundImage: `url(${copyIcon})`, |
| 62 | + backgroundSize: 'contain', |
| 63 | + backgroundRepeat: 'no-repeat', |
| 64 | + backgroundPosition: 'center', |
| 65 | + display: 'inline-block', |
| 66 | + }} |
| 67 | + aria-label="Copy for LLM" |
| 68 | + /> |
| 69 | + <ButtonText isLoading={isLoading} isCopied={isCopied} /> |
| 70 | + </button> |
| 71 | + ); |
| 72 | +} |
0 commit comments