mirasim's picture
Add the tasks, judges, harness, app under test, docs and report; merge the repository README into the card (part 4)
714ed7b verified
Raw History Blame Contribute Delete
4.96 kB
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { commentsApi } from "../../api/comments";
import { useSession } from "../../store/SessionContext";
import { useTeam } from "../../store/TeamContext";
import { useToast } from "../../store/ToastContext";
import type { Comment, Member } from "../../types";
import { formatDateTime, initials } from "../../utils/dates";
import { MentionTextarea } from "./MentionTextarea";
/** Highlights "@Full Name" for people on the team. */
function withMentions(body: string, members: Member[]): ReactNode[] {
const names = members.map((m) => m.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
if (!names.length) return [body];
return body.split(new RegExp(`(@(?:${names.join("|")}))`, "g")).map((part, i) =>
i % 2 ? (
<span key={i} className="mention">
{part}
</span>
) : (
part
),
);
}
const draftKey = (taskId: number) => `team-tasks.comment-draft.${taskId}`;
function readDraft(taskId: number): string {
try {
return localStorage.getItem(draftKey(taskId)) ?? "";
} catch {
return "";
}
}
function writeDraft(taskId: number, text: string): void {
try {
if (text) localStorage.setItem(draftKey(taskId), text);
else localStorage.removeItem(draftKey(taskId));
} catch {
// not kept, still usable
}
}
/**
* A task's comments, oldest first, in their own scroll area that starts at the newest. An unsent
* comment is kept per task in this browser, so it survives switching tasks and reloading.
*/
export function CommentThread({ taskId }: { taskId: number }) {
const { members } = useTeam();
const { canEdit } = useSession();
const toast = useToast();
const [comments, setComments] = useState<Comment[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [draft, setDraftState] = useState(() => readDraft(taskId));
const [posting, setPosting] = useState(false);
const list = useRef<HTMLOListElement>(null);
const setDraft = (text: string) => {
setDraftState(text);
writeDraft(taskId, text);
};
// Another task in the same place: show its draft.
useEffect(() => setDraftState(readDraft(taskId)), [taskId]);
useEffect(() => {
let live = true;
commentsApi.list(taskId).then(
(cs) => live && setComments(cs),
(e) => live && setError((e as Error).message),
);
return () => {
live = false;
};
}, [taskId]);
// Show the latest comment: start scrolled to the bottom, and go there again after posting.
useLayoutEffect(() => {
if (list.current) list.current.scrollTop = list.current.scrollHeight;
}, [comments]);
const post = async () => {
if (!draft.trim() || posting) return;
setPosting(true);
try {
const c = await commentsApi.post(taskId, draft.trim());
setComments((cs) => [...(cs ?? []), c]);
setDraft("");
} catch (e) {
toast((e as Error).message, "error");
} finally {
setPosting(false);
}
};
const author = (id: string) => members.find((m) => m.id === id)?.name ?? "Former member";
return (
<section className="thread" aria-labelledby={`thread-${taskId}`}>
<h3 id={`thread-${taskId}`}>
Comments {comments && <span className="count">{comments.length}</span>}
</h3>
{error && <p className="page-error">Couldn't load comments: {error}</p>}
{!comments && !error && <p className="loading">Loading…</p>}
{comments && (
<ol className="thread-list" ref={list} aria-label="Comments" tabIndex={0}>
{comments.map((c) => (
<li key={c.id} className="thread-item">
<span className="avatar small" aria-hidden="true">
{initials(author(c.authorId))}
</span>
<div className="thread-text">
<div className="thread-meta">
<strong>{author(c.authorId)}</strong> <time dateTime={c.createdAt}>{formatDateTime(c.createdAt)}</time>
</div>
<p className="thread-body">{withMentions(c.body, members)}</p>
</div>
</li>
))}
{comments.length === 0 && <li className="empty">No comments yet.</li>}
</ol>
)}
{canEdit && (
<form
className="composer"
onSubmit={(e) => {
e.preventDefault();
void post();
}}
>
<label className="field" htmlFor={`comment-${taskId}`}>
Add a comment
</label>
<MentionTextarea id={`comment-${taskId}`} value={draft} onChange={setDraft} members={members} onSubmit={() => void post()} />
<div className="actions start">
<button type="submit" className="primary" disabled={!draft.trim() || posting}>
{posting ? "Posting…" : "Post comment"}
</button>
</div>
</form>
)}
</section>
);
}