-
Notifications
You must be signed in to change notification settings - Fork 68.3k
Expand file tree
/
Copy pathCopyButton.tsx
More file actions
68 lines (58 loc) · 2.42 KB
/
Copy pathCopyButton.tsx
File metadata and controls
68 lines (58 loc) · 2.42 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { useCallback, useEffect, useRef, useState } from 'react'
import type { ComponentPropsWithoutRef } from 'react'
import { announce } from '@primer/live-region-element'
type CopyButtonProps = ComponentPropsWithoutRef<'button'> & {
'data-clipboard'?: string
}
// React replacement for the imperative `copy-code.ts` enhancer. The code-block
// header (`content-render/unified/code-header.ts`) emits this button into the
// HTML AST next to a hidden `<pre data-clipboard="<id>">` holding the raw code.
// When the article body is rendered from hast (instead of dangerouslySetInnerHTML),
// `MarkdownContent` maps that `<button class="js-btn-copy">` to this component so
// React owns the node rather than a post-hydration `document.querySelectorAll`.
//
// Analytics is intentionally NOT sent here: a global delegated click listener in
// `events/components/events.ts` already records `.js-btn-copy` clicks.
export function CopyButton({ className, children, ...props }: CopyButtonProps) {
const [copied, setCopied] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
}
}, [])
const clipboardId = props['data-clipboard']
const handleClick = useCallback(async () => {
if (!clipboardId) return
// The hidden <pre> is a sibling of this button inside the code-block header,
// so look it up locally to avoid copying a different block that happens to
// share the same content hash.
const scope: Element | Document = buttonRef.current?.parentElement ?? document
const pre = scope.querySelector<HTMLElement>(`pre[data-clipboard="${CSS.escape(clipboardId)}"]`)
const text = pre?.innerText
if (!text) return
try {
await navigator.clipboard.writeText(text)
} catch {
// Clipboard write can be blocked (permissions, insecure context, etc.).
// Don't show a false "Copied!" state.
return
}
setCopied(true)
announce('Copied!')
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => setCopied(false), 2000)
}, [clipboardId])
return (
<button
type="button"
{...props}
ref={buttonRef}
className={copied ? `${className ?? ''} copied`.trim() : className}
onClick={handleClick}
>
{children}
</button>
)
}