File size: 4,963 Bytes
714ed7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | 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>
);
}
|