All files / packages/design-system-2-site/src/components ViewMarkdownButton.tsx

100% Statements 11/11
100% Branches 6/6
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 394x                     29x   29x 4x 4x 3x     1x   4x     29x   29x                        
'use client';
 
import { useCallback, useState } from 'react';
import { CanvasContentIcon } from './icons';
import { Button } from './ui/Button';
 
/**
 * "Copy Markdown" action in the page-bottom actions row. Copies the page's raw
 * markdown source to the clipboard; the label briefly confirms.
 */
export function ViewMarkdownButton({ markdown }: { markdown: string }) {
  const [status, setStatus] = useState<'idle' | 'copied' | 'failed'>('idle');
 
  const handleCopy = useCallback(async () => {
    try {
      await navigator.clipboard.writeText(markdown);
      setStatus('copied');
    } catch {
      // Clipboard access denied or unavailable (e.g. an insecure context).
      setStatus('failed');
    }
    setTimeout(() => setStatus('idle'), 2000);
  }, [markdown]);
 
  const result = status === 'copied' ? 'Copied!' : status === 'failed' ? 'Copy failed' : '';
 
  return (
    <>
      <Button variant="ghost" size="sm" iconLeft={<CanvasContentIcon />} onClick={handleCopy}>
        {result || 'Copy Markdown'}
      </Button>
      {/* Always rendered so the text change is announced; a region inserted with its text often isn't. */}
      <span className="site-visually-hidden" role="status">
        {result}
      </span>
    </>
  );
}