SurfSense/surfsense_web/hooks/use-api-key.ts

101 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-07-27 10:44:27 -07:00
import { useCallback, useEffect, useState } from "react";
2025-07-27 10:05:37 -07:00
import { toast } from "sonner";
import { getBearerToken } from "@/lib/auth-utils";
2025-04-07 23:47:06 -07:00
interface UseApiKeyReturn {
2025-07-27 10:05:37 -07:00
apiKey: string | null;
isLoading: boolean;
copied: boolean;
copyToClipboard: () => Promise<void>;
2025-04-07 23:47:06 -07:00
}
export function useApiKey(): UseApiKeyReturn {
2025-07-27 10:05:37 -07:00
const [apiKey, setApiKey] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
// Load API key from localStorage
const loadApiKey = () => {
try {
const token = getBearerToken();
2025-07-27 10:05:37 -07:00
setApiKey(token);
} catch (error) {
console.error("Error loading API key:", error);
toast.error("Failed to load API key");
} finally {
setIsLoading(false);
}
};
// Add a small delay to simulate loading
const timer = setTimeout(loadApiKey, 500);
return () => clearTimeout(timer);
}, []);
const fallbackCopyTextToClipboard = (text: string) => {
const textArea = document.createElement("textarea");
textArea.value = text;
2025-12-05 00:17:31 -08:00
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
textArea.style.opacity = "0";
2025-12-05 00:17:31 -08:00
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
2025-12-05 00:17:31 -08:00
try {
2025-12-05 00:17:31 -08:00
const successful = document.execCommand("copy");
document.body.removeChild(textArea);
2025-12-05 00:17:31 -08:00
if (successful) {
setCopied(true);
toast.success("API key copied to clipboard");
2025-12-05 00:17:31 -08:00
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");
}
};
2025-07-27 10:05:37 -07:00
const copyToClipboard = useCallback(async () => {
if (!apiKey) return;
try {
if (navigator.clipboard && window.isSecureContext) {
// Use Clipboard API if available and in secure context
await navigator.clipboard.writeText(apiKey);
setCopied(true);
toast.success("API key copied to clipboard");
2025-12-05 00:17:31 -08:00
setTimeout(() => {
setCopied(false);
}, 2000);
} else {
// Fallback for non-secure contexts or browsers without clipboard API
fallbackCopyTextToClipboard(apiKey);
}
2025-07-27 10:05:37 -07:00
} catch (err) {
console.error("Failed to copy:", err);
toast.error("Failed to copy API key");
}
}, [apiKey]);
return {
apiKey,
isLoading,
copied,
copyToClipboard,
};
2025-12-05 00:17:31 -08:00
}