|
| 1 | +import { AuthContext } from '@luna/contexts/api/auth/AuthContext'; |
| 2 | +import { newUninitializedRole, Role } from '@luna/contexts/api/auth/types'; |
| 3 | +import { CreateOrUpdateRolePayload } from '@luna/contexts/api/auth/types/CreateOrUpdateRolePayload'; |
| 4 | +import { |
| 5 | + Button, |
| 6 | + Input, |
| 7 | + Modal, |
| 8 | + ModalBody, |
| 9 | + ModalContent, |
| 10 | + ModalFooter, |
| 11 | + ModalHeader, |
| 12 | +} from '@heroui/react'; |
| 13 | +import { useCallback, useContext, useEffect, useState } from 'react'; |
| 14 | + |
| 15 | +export interface RoleAddModalProps { |
| 16 | + isOpen: boolean; |
| 17 | + setOpen: (show: boolean) => void; |
| 18 | +} |
| 19 | + |
| 20 | +export function RoleAddModal({ isOpen, setOpen }: RoleAddModalProps) { |
| 21 | + const [role, setRole] = useState<Role>(newUninitializedRole()); |
| 22 | + |
| 23 | + // initialize/reset modal state |
| 24 | + useEffect(() => { |
| 25 | + if (!isOpen) return; |
| 26 | + setRole(newUninitializedRole()); |
| 27 | + }, [isOpen]); |
| 28 | + |
| 29 | + const auth = useContext(AuthContext); |
| 30 | + |
| 31 | + const addRole = useCallback(async () => { |
| 32 | + const payload: CreateOrUpdateRolePayload = { |
| 33 | + name: role.name, |
| 34 | + }; |
| 35 | + const result = await auth.createRole(payload); |
| 36 | + if (result.ok) { |
| 37 | + console.log('added role:', payload); |
| 38 | + } else { |
| 39 | + console.log('failed to add role:', result.error); |
| 40 | + } |
| 41 | + // TODO: UI feedback from the request (success, error) |
| 42 | + setOpen(false); |
| 43 | + }, [setOpen, role, auth]); |
| 44 | + |
| 45 | + return ( |
| 46 | + <Modal isOpen={isOpen} onOpenChange={setOpen}> |
| 47 | + <ModalContent> |
| 48 | + {onClose => ( |
| 49 | + <> |
| 50 | + <ModalHeader>Add Role</ModalHeader> |
| 51 | + <ModalBody> |
| 52 | + <Input |
| 53 | + label="Name" |
| 54 | + value={role.name} |
| 55 | + onValueChange={name => { |
| 56 | + if (!role) return; |
| 57 | + setRole({ ...role, name }); |
| 58 | + }} |
| 59 | + /> |
| 60 | + </ModalBody> |
| 61 | + <ModalFooter> |
| 62 | + <Button color="success" onPress={addRole}> |
| 63 | + Add |
| 64 | + </Button> |
| 65 | + <Button onPress={onClose}>Cancel</Button> |
| 66 | + </ModalFooter> |
| 67 | + </> |
| 68 | + )} |
| 69 | + </ModalContent> |
| 70 | + </Modal> |
| 71 | + ); |
| 72 | +} |
0 commit comments