Files
WebDrop/web/src/features/channel/ChatPane.tsx
T

49 lines
2.8 KiB
TypeScript

import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
import { Button } from '@/ui/Button';
import { ChatMessage } from './ChatMessage';
import styles from './ChatPane.module.css';
interface Props { threadName: string; ids: string[]; enabled: boolean; onSend: (text: string) => Promise<void>; onDelete: (id: string) => void; onOpenFile: (id: string) => void; onFiles?: (files: File[]) => void }
export function ChatPane({ threadName, ids, enabled, onSend, onDelete, onOpenFile, onFiles }: Props) {
const [text, setText] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const messages = useRef<HTMLDivElement>(null);
const fileInput = useRef<HTMLInputElement>(null);
const chronological = ids.slice().reverse();
useEffect(() => { messages.current?.scrollTo({ top: messages.current.scrollHeight }); }, [chronological.length]);
async function submit() {
const value = text.trim();
if (!value || busy || !enabled) return;
setBusy(true);
setError('');
try { await onSend(value); setText(''); }
catch (cause) { setError(cause instanceof Error ? cause.message : '发送失败'); }
finally { setBusy(false); }
}
function keyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); void submit(); }
}
return (
<section className={styles.pane} aria-label={`${threadName} 聊天`}>
<div className={styles.head}><strong>{threadName}</strong><span>频道聊天</span></div>
<div className={styles.messages} ref={messages} aria-live="polite">
{chronological.length === 0 ? <p className={styles.empty}>在这里发送消息或文件,成员可以看到你的名称和头像。</p> : null}
{chronological.map((id) => <ChatMessage key={id} id={id} onOpenFile={onOpenFile} onDelete={onDelete} />)}
</div>
<form className={styles.composer} onSubmit={(event) => { event.preventDefault(); void submit(); }}>
{onFiles ? <><input ref={fileInput} type="file" multiple hidden onChange={(event) => { if (event.target.files?.length) onFiles([...event.target.files]); event.target.value = ''; }} />
<Button variant="ghost" icon="clip" label="上传文件到当前频道" disabled={!enabled} onClick={() => fileInput.current?.click()} /></> : null}
<textarea value={text} disabled={!enabled || busy} rows={2} placeholder={enabled ? '输入消息,Enter 发送,Shift+Enter 换行' : '先创建或加入一个频道'} onChange={(event) => setText(event.target.value)} onKeyDown={keyDown} />
<Button variant="primary" icon="send" label="发送消息" disabled={!enabled || busy || !text.trim()} onClick={() => void submit()} />
</form>
{error ? <p className={styles.error} role="alert">{error}</p> : null}
</section>
);
}