mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-06-06 20:15:17 +02:00
Merge pull request #526 from waychan23/main
fix: copying api key to the clipboard fails in http context
This commit is contained in:
commit
264532b3cf
1 changed files with 49 additions and 8 deletions
|
|
@ -33,17 +33,58 @@ export function useApiKey(): UseApiKeyReturn {
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const fallbackCopyTextToClipboard = (text: string) => {
|
||||||
|
const textArea = document.createElement("textarea");
|
||||||
|
textArea.value = text;
|
||||||
|
|
||||||
|
// Avoid scrolling to bottom
|
||||||
|
textArea.style.top = "0";
|
||||||
|
textArea.style.left = "0";
|
||||||
|
textArea.style.position = "fixed";
|
||||||
|
textArea.style.opacity = "0";
|
||||||
|
|
||||||
|
document.body.appendChild(textArea);
|
||||||
|
textArea.focus();
|
||||||
|
textArea.select();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const successful = document.execCommand('copy');
|
||||||
|
document.body.removeChild(textArea);
|
||||||
|
|
||||||
|
if (successful) {
|
||||||
|
setCopied(true);
|
||||||
|
toast.success("API key copied to clipboard");
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
setCopied(false);
|
||||||
|
}, 2000);
|
||||||
|
} else {
|
||||||
|
toast.error("Failed to copy API key");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Fallback: Oops, unable to copy", err);
|
||||||
|
document.body.removeChild(textArea);
|
||||||
|
toast.error("Failed to copy API key");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const copyToClipboard = useCallback(async () => {
|
const copyToClipboard = useCallback(async () => {
|
||||||
if (!apiKey) return;
|
if (!apiKey) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(apiKey);
|
if (navigator.clipboard && window.isSecureContext) {
|
||||||
setCopied(true);
|
// Use Clipboard API if available and in secure context
|
||||||
toast.success("API key copied to clipboard");
|
await navigator.clipboard.writeText(apiKey);
|
||||||
|
setCopied(true);
|
||||||
setTimeout(() => {
|
toast.success("API key copied to clipboard");
|
||||||
setCopied(false);
|
|
||||||
}, 2000);
|
setTimeout(() => {
|
||||||
|
setCopied(false);
|
||||||
|
}, 2000);
|
||||||
|
} else {
|
||||||
|
// Fallback for non-secure contexts or browsers without clipboard API
|
||||||
|
fallbackCopyTextToClipboard(apiKey);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to copy:", err);
|
console.error("Failed to copy:", err);
|
||||||
toast.error("Failed to copy API key");
|
toast.error("Failed to copy API key");
|
||||||
|
|
@ -56,4 +97,4 @@ export function useApiKey(): UseApiKeyReturn {
|
||||||
copied,
|
copied,
|
||||||
copyToClipboard,
|
copyToClipboard,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue