65 lines
2.2 KiB
TypeScript
65 lines
2.2 KiB
TypeScript
import { useState } from 'react';
|
|
import { useStartConversationMutation } from './conversation-queries.js';
|
|
|
|
interface StartConversationFormProps {
|
|
onStarted(conversationId: string): void;
|
|
}
|
|
|
|
export function StartConversationForm({ onStarted }: StartConversationFormProps) {
|
|
const [username, setUsername] = useState('');
|
|
const [message, setMessage] = useState('');
|
|
const [successUsername, setSuccessUsername] = useState<string | null>(null);
|
|
const mutation = useStartConversationMutation();
|
|
const canSubmit = username.trim().length > 0 && message.trim().length > 0 && !mutation.isPending;
|
|
|
|
function submit(event: React.FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
if (!canSubmit) return;
|
|
mutation.mutate(
|
|
{ username, message },
|
|
{
|
|
onSuccess(chat) {
|
|
setSuccessUsername(chat.username);
|
|
setUsername('');
|
|
setMessage('');
|
|
onStarted(chat.roomId ?? chat.username);
|
|
},
|
|
},
|
|
);
|
|
}
|
|
|
|
return (
|
|
<form className="start-conversation-form" onSubmit={submit}>
|
|
<div className="conversation-field">
|
|
<label htmlFor="new-conversation-username">Reddit username</label>
|
|
<input
|
|
autoComplete="off"
|
|
id="new-conversation-username"
|
|
onChange={(event) => setUsername(event.target.value)}
|
|
placeholder="username"
|
|
value={username}
|
|
/>
|
|
</div>
|
|
<div className="conversation-field">
|
|
<label htmlFor="new-conversation-message">Opening message</label>
|
|
<textarea
|
|
id="new-conversation-message"
|
|
onChange={(event) => setMessage(event.target.value)}
|
|
placeholder="Write a personal opening message"
|
|
rows={4}
|
|
value={message}
|
|
/>
|
|
</div>
|
|
{mutation.isError ? <div className="conversation-inline-error" role="alert">{mutation.error.message}</div> : null}
|
|
{successUsername ? (
|
|
<div aria-label="Conversation started" className="conversation-inline-success" role="status">
|
|
Conversation started with u/{successUsername}
|
|
</div>
|
|
) : null}
|
|
<button className="conversation-primary" disabled={!canSubmit} type="submit">
|
|
{mutation.isPending ? 'Starting…' : 'Start conversation'}
|
|
</button>
|
|
</form>
|
|
);
|
|
}
|