Files
relay/client/src/components/chat/CreateGroupButton.tsx
2024-12-14 23:20:41 +01:00

101 lines
3.0 KiB
TypeScript

import LoadingWheel from './LoadingWheel.tsx';
import { useRef, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { axiosClient } from '../../App.tsx';
type Inputs = {
groupName: string;
};
function CreateGroupButton() {
const [isLoading, setIsLoading] = useState<boolean>(false);
const modalRef = useRef<HTMLDialogElement | null>(null);
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<Inputs>();
const onSubmit: SubmitHandler<Inputs> = async (data) => {
try {
setIsLoading(true);
const response = await axiosClient.post(`/api/chat/groups/create`, data);
console.log(response.data);
if (response.data.group_id) {
setIsLoading(false);
if (modalRef.current) {
modalRef.current.close();
}
}
reset();
} catch (e) {
console.error('Failed to create group: ', e);
setIsLoading(false);
}
};
return (
<>
<div>
<button
className="m-2 border p-1 rounded-md"
onClick={() =>
(
document.getElementById('createGroupModal') as HTMLDialogElement
).showModal()
}
>
Create group
</button>
<dialog id="createGroupModal" className="modal" ref={modalRef}>
<div className="modal-box bg-gray-800 text-center relative p-1">
<div className="absolute right-2 top-2">
<form method="dialog">
<button className="btn btn-sm btn-circle btn-ghost"></button>
</form>
</div>
<div className="flex flex-col items-center justify-center pb-1 mt-6">
<h3 className="text-lg mb-4">Enter room name</h3>
<form
onSubmit={handleSubmit(onSubmit)}
className="w-full max-w-xs relative"
>
<input
className="input input-bordered bg-green-50 w-full h-10 text-black rounded-md text-center"
{...register('groupName', {
required: true,
minLength: 4,
maxLength: 20,
})}
aria-invalid={errors.groupName ? 'true' : 'false'}
/>
{errors.groupName?.type === 'minLength' && (
<p className="text-gray-300">room name is too short</p>
)}
{errors.groupName?.type === 'maxLength' && (
<p className="text-gray-300">room name is too long</p>
)}
</form>
</div>
<div className="mt-4 flex justify-center">
<button
type="submit"
onClick={handleSubmit(onSubmit)}
className="btn btn-sm bg-green-500 text-black hover:bg-green-600"
>
{isLoading ? <LoadingWheel /> : 'Create'}
</button>
</div>
</div>
</dialog>
</div>
</>
);
}
export default CreateGroupButton;