import React, { useState } from 'react'; import { Plus, Trash2, Copy, KeyRound } from 'lucide-react'; import { useCreateApiKey } from '../../utils/queries/apikey-queries'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from '../ui/dialog'; import { Button } from '../ui/button'; import { Input, Label } from '../ui/input'; const AVAILABLE_ROLES = ['guest', 'creator', 'admin']; const SELECT_CLASS = "flex h-9 w-full rounded-md border border-input bg-background/60 px-3 py-1 text-sm text-foreground transition-colors focus-visible:outline-none focus-visible:border-primary/60 focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50"; const ApiKeyCreationModal = ({ isOpen, onClose }) => { const [name, setName] = useState(''); const [roles, setRoles] = useState(['guest']); const [generatedKey, setGeneratedKey] = useState(null); const createApiKeyMutation = useCreateApiKey(); const handleAddRole = () => { const availableRoles = AVAILABLE_ROLES.filter(role => !roles.includes(role)); if (availableRoles.length > 0) { setRoles([...roles, availableRoles[0]]); } }; const handleRoleChange = (index, value) => { if (roles.includes(value) && roles.findIndex(r => r === value) !== index) { return; } const newRoles = [...roles]; newRoles[index] = value; setRoles(newRoles); }; const handleRemoveRole = (index) => { const newRoles = roles.filter((_, i) => i !== index); setRoles(newRoles); }; const handleGenerate = async () => { if (!name.trim()) { alert('API key name is required'); return; } try { const result = await createApiKeyMutation.mutateAsync({ name: name.trim(), roles: roles }); setGeneratedKey(result); } catch (error) { console.error('failed to create api key', error); alert('failed to create api key'); } }; const handleCopy = () => { navigator.clipboard.writeText(generatedKey) .then(() => alert('API key copied to clipboard')) .catch(err => console.error('failed to copy api key:', err)); }; const getRemainingRoles = (currentIndex) => { return AVAILABLE_ROLES.filter(role => !roles.find((r, i) => r === role && i !== currentIndex) ); }; return ( { if (!o) onClose(); }}> Create API Key {!generatedKey ? (
setName(e.target.value)} />
{roles.map((role, index) => (
))}
) : (
Please copy your API key immediately! It will only be displayed once!
)} {!generatedKey && ( )}
); }; export default ApiKeyCreationModal;