Files
sorsfonalak/services/frontend/src/components/forum/Composer.tsx
T

184 lines
5.6 KiB
TypeScript
Raw Normal View History

"use client";
import { useEffect, useRef, useState } from "react";
import { api } from "@/lib/api";
import { usePhotoUploads } from "@/lib/photos";
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
import type { ForumAuthor } from "@/lib/forum";
import { Avatar } from "./Avatar";
import { PhotoButton, PickedPhotos } from "./Photos";
/** "@Ho" right before the caret: what was typed after the "@", and where it starts. */
function mentionAt(text: string, caret: number): { query: string; start: number } | null {
const before = text.slice(0, caret);
const match = /(?:^|\s)@([^\s@]{1,24})$/.exec(before);
if (!match) return null;
return { query: match[1], start: caret - match[1].length - 1 };
}
/**
* The text box and the send button. Character smileys (`:)`, `<3`) turn into
* emoji as they are typed; phones bring their own emoji keyboard.
* `onTyping`: called on every keystroke (the "… gépel" notice).
* `mentions`: typing "@Ho" offers the members whose nickname starts so.
* `onChange`: the text as it is typed (to keep a draft when the box moves).
* `photos`: a "Fotó" button; the uploaded photos' ids go with the text.
*/
export function Composer({
id,
label,
placeholder,
initial = "",
submitLabel = "Küldés",
busy,
onSubmit,
onCancel,
onTyping,
onChange,
mentions = false,
photos = false,
rows = 3,
autoFocus = false,
}: {
id: string;
label: string;
placeholder?: string;
initial?: string;
submitLabel?: string;
busy: boolean;
onSubmit: (text: string, photos: string[]) => Promise<boolean>;
onCancel?: () => void;
onTyping?: () => void;
onChange?: (text: string) => void;
mentions?: boolean;
photos?: boolean;
rows?: number;
autoFocus?: boolean;
}) {
const [text, setText] = useState(initial);
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
const area = useRef<HTMLTextAreaElement>(null);
const picked = usePhotoUploads();
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
useEffect(() => {
onChange?.(text);
}, [text, onChange]);
function lookUp(value: string, caret: number) {
window.clearTimeout(timer.current);
const at = mentions ? mentionAt(value, caret) : null;
if (!at) {
setSuggest(null);
return;
}
timer.current = window.setTimeout(() => {
api<{ members: ForumAuthor[] }>(`/forum/members/search?q=${encodeURIComponent(at.query)}`)
.then((res) => setSuggest(res.members.length ? { ...at, members: res.members } : null))
.catch(() => setSuggest(null));
}, 200);
}
function pick(nickname: string) {
if (!suggest) return;
const el = area.current;
const caret = el?.selectionStart ?? text.length;
const inserted = `@${nickname} `;
const next = text.slice(0, suggest.start) + inserted + text.slice(caret);
setText(next);
setSuggest(null);
requestAnimationFrame(() => {
el?.focus();
const at = suggest.start + inserted.length;
el?.setSelectionRange(at, at);
});
}
async function submit() {
if (!text.trim() || busy || picked.busy) return;
const final = convertEmoticons(text, text.length, true).text;
if (await onSubmit(final, picked.ids)) {
setText("");
setSuggest(null);
picked.reset();
}
}
// Not a <form>: iOS Safari offers its card and address AutoFill for the text
// boxes of a form. The button sends; Ctrl/Cmd+Enter too.
return (
<div className="fc" data-kb-block>
<label htmlFor={id} className="sr-only">
{label}
</label>
<textarea
id={id}
ref={area}
className="fc-text"
rows={rows}
placeholder={placeholder}
value={text}
onChange={(e) => {
withEmoji(e, setText);
lookUp(e.target.value, e.target.selectionStart ?? e.target.value.length);
onTyping?.();
}}
onKeyDown={(e) => {
if (e.key === "Escape") setSuggest(null);
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void submit();
}
}}
maxLength={10000}
autoComplete="off"
autoFocus={autoFocus}
aria-autocomplete={mentions ? "list" : undefined}
/>
{suggest && (
<div className="fc-suggest" role="listbox" aria-label="Tagok">
{suggest.members.map((m) => (
<button
key={m.nickname}
type="button"
role="option"
aria-selected="false"
className="fc-suggest-item"
onClick={() => pick(m.nickname)}
>
<Avatar avatar={m.avatar} size={24} online={m.online} />
{m.nickname}
</button>
))}
</div>
)}
{photos && <PickedPhotos items={picked.items} onRemove={picked.remove} />}
{photos && picked.error && (
<p className="msg msg-error" role="alert">
{picked.error}
</p>
)}
<div className="fc-actions">
{photos && <PhotoButton onFiles={(files) => void picked.add(files)} disabled={picked.full} />}
<span className="fc-spacer" />
{onCancel && (
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
Mégse
</button>
)}
<button
type="button"
className="btn btn-primary btn-sm"
disabled={busy || picked.busy || !text.trim()}
onClick={() => void submit()}
>
{busy ? "Küldés…" : submitLabel}
</button>
</div>
</div>
);
}