MCPcopy Create free account
hub / github.com/coder/coder / useClipboard

Function useClipboard

site/src/hooks/useClipboard.ts:46–112  ·  view source on GitHub ↗
(
	input: UseClipboardInput = {},
)

Source from the content-addressed store, hash-verified

44}>;
45
46export const useClipboard = (
47 input: UseClipboardInput = {},
48): UseClipboardResult => {
49 const { onError = toast.error, clearErrorOnSuccess = true } = input;
50
51 const [showCopiedSuccess, setShowCopiedSuccess] = useState(false);
52 const [error, setError] = useState<Error>();
53 const timeoutIdRef = useRef<number | undefined>(undefined);
54 const lastCopiedTextRef = useRef("");
55
56 useEffect(() => {
57 return () => window.clearTimeout(timeoutIdRef.current);
58 }, []);
59
60 const copyToClipboard = useCallback(
61 async (textToCopy: string) => {
62 const markSuccess = () => {
63 lastCopiedTextRef.current = textToCopy;
64 setShowCopiedSuccess(true);
65 if (clearErrorOnSuccess) {
66 setError(undefined);
67 }
68 timeoutIdRef.current = window.setTimeout(() => {
69 setShowCopiedSuccess(false);
70 }, CLIPBOARD_TIMEOUT_MS);
71 };
72
73 try {
74 await navigator.clipboard.writeText(textToCopy);
75 markSuccess();
76 } catch (err) {
77 const fallbackCopySuccessful = simulateClipboardWrite(textToCopy);
78 if (fallbackCopySuccessful) {
79 markSuccess();
80 return;
81 }
82
83 const wrappedErr = new Error(COPY_FAILED_MESSAGE);
84 if (err instanceof Error) {
85 wrappedErr.stack = err.stack;
86 }
87
88 console.error(wrappedErr);
89 setError(wrappedErr);
90 onError(COPY_FAILED_MESSAGE);
91 }
92 },
93 [onError, clearErrorOnSuccess],
94 );
95
96 const readFromClipboard = useCallback(async (): Promise<string> => {
97 // Insecure (HTTP) contexts and older browsers cannot read the system
98 // clipboard, so fall back to the last value copied within Coder. In a
99 // secure context, surface read failures (such as a denied permission)
100 // instead of silently pasting a stale cached selection.
101 if (
102 window.isSecureContext &&
103 typeof navigator.clipboard?.readText === "function"

Callers 11

AgentRowFunction · 0.90
WorkspaceTerminalFunction · 0.90
UserDropdownContentFunction · 0.90
CopyableValueFunction · 0.90
CopyButtonFunction · 0.90
CliAuthPageViewFunction · 0.90
CopyPromptButtonFunction · 0.90
CopySSHMenuItemFunction · 0.90
useDesktopConnectionFunction · 0.90
ButtonPreviewFunction · 0.90
renderUseClipboardFunction · 0.90

Calls 2

markSuccessFunction · 0.85
simulateClipboardWriteFunction · 0.85

Tested by 1

renderUseClipboardFunction · 0.72