cg / hackerproducts

63 files · 5,740 lines · 159.1 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / components / CommentsSection.tsx

src/components/CommentsSection.tsx · 160 lines · 5.0 KB← back to folder
1"use client";
2
3import { useState } from "react";
4import Link from "next/link";
5import { formatDisplayDate } from "@/lib/format";
6import type { ProductComment } from "@/lib/comments";
7
8export function CommentsSection({
9 slug,
10 productOwnerId,
11 initialComments,
12 viewer,
13}: {
14 slug: string;
15 productOwnerId: string;
16 initialComments: ProductComment[];
17 viewer: { id: string; username: string; is_admin: boolean } | null;
18}) {
19 const [comments, setComments] = useState<ProductComment[]>(initialComments);
20 const [body, setBody] = useState("");
21 const [submitting, setSubmitting] = useState(false);
22 const [deletingId, setDeletingId] = useState<string | null>(null);
23 const [error, setError] = useState<string | null>(null);
24
25 async function handleSubmit(e: React.FormEvent) {
26 e.preventDefault();
27 if (!body.trim() || submitting) return;
28
29 setSubmitting(true);
30 setError(null);
31 try {
32 const res = await fetch(`/api/products/${encodeURIComponent(slug)}/comments`, {
33 method: "POST",
34 headers: { "Content-Type": "application/json" },
35 body: JSON.stringify({ body }),
36 });
37 const data = (await res.json().catch(() => ({}))) as {
38 comment?: ProductComment;
39 error?: string;
40 };
41 if (!res.ok || !data.comment) {
42 setError(data.error || "Could not post comment.");
43 return;
44 }
45 setComments((prev) => [...prev, data.comment!]);
46 setBody("");
47 window.minilytics?.("goal", "comment_posted", { slug });
48 } catch {
49 setError("Network error while posting comment.");
50 } finally {
51 setSubmitting(false);
52 }
53 }
54
55 async function handleDelete(id: string) {
56 if (!window.confirm("Delete this comment?")) return;
57 setDeletingId(id);
58 setError(null);
59 try {
60 const res = await fetch(
61 `/api/products/${encodeURIComponent(slug)}/comments/${encodeURIComponent(id)}`,
62 { method: "DELETE" }
63 );
64 if (!res.ok) {
65 const data = (await res.json().catch(() => ({}))) as { error?: string };
66 setError(data.error || "Could not delete comment.");
67 return;
68 }
69 setComments((prev) => prev.filter((c) => c.id !== id));
70 } catch {
71 setError("Network error while deleting comment.");
72 } finally {
73 setDeletingId(null);
74 }
75 }
76
77 return (
78 <section className="comments-section" id="comments" aria-labelledby="comments-heading">
79 <h2 id="comments-heading">
80 Comments {comments.length > 0 ? `(${comments.length})` : ""}
81 </h2>
82
83 {comments.length === 0 ? (
84 <p className="muted" style={{ marginTop: 0 }}>
85 No comments yet.
86 </p>
87 ) : (
88 <ol className="comment-list">
89 {comments.map((comment) => {
90 const isMaker = comment.user_id === productOwnerId;
91 const canDelete = Boolean(
92 viewer &&
93 (viewer.is_admin ||
94 viewer.id === comment.user_id ||
95 viewer.id === productOwnerId)
96 );
97 return (
98 <li key={comment.id} className="comment-item">
99 <p className="comment-meta">
100 <Link href={`/${comment.username}`} style={{ fontWeight: 600 }}>
101 {comment.username}
102 </Link>
103 {isMaker && <span className="muted"> (maker)</span>}
104 <span className="muted"> · {formatDisplayDate(comment.created_at)}</span>
105 {canDelete && (
106 <>
107 <span className="muted"> · </span>
108 <button
109 type="button"
110 className="link-button"
111 disabled={deletingId === comment.id}
112 onClick={() => void handleDelete(comment.id)}
113 >
114 delete
115 </button>
116 </>
117 )}
118 </p>
119 <p className="comment-body">{comment.body}</p>
120 </li>
121 );
122 })}
123 </ol>
124 )}
125
126 {error && (
127 <div className="form-error" role="alert">
128 {error}
129 </div>
130 )}
131
132 {viewer ? (
133 <form onSubmit={handleSubmit} className="plain-form" style={{ marginTop: 20 }}>
134 <div className="form-field">
135 <label htmlFor="comment-body">Add a comment</label>
136 <textarea
137 id="comment-body"
138 rows={3}
139 maxLength={2000}
140 required
141 value={body}
142 onChange={(e) => setBody(e.target.value)}
143 placeholder="Write a comment..."
144 />
145 </div>
146 <button type="submit" className="btn-secondary" disabled={submitting || !body.trim()}>
147 {submitting ? "Posting..." : "Post comment"}
148 </button>
149 </form>
150 ) : (
151 <p style={{ marginTop: 18 }}>
152 <Link href={`/login?next=${encodeURIComponent(`/${slug}#comments`)}`}>
153 Sign in to leave a comment
154 </Link>
155 </p>
156 )}
157 </section>
158 );
159}
160
cg / hackerproducts — hacker products