Open History to see the last commit
1"use client";
2import { useCallback, useMemo, useState } from "react";
3import { useCachedLiveQuery, useSession } from "../live-session";
4import type { SealedComments, SealedStory } from "@/lib/queries";
5import { sortStories, type Story } from "@/lib/types";
6import { sortComments, THREAD_LIMIT, type Comment } from "@/lib/comments";
7import { commentContent } from "@/lib/comment-content";
8import { age, HN, itemLink, userLink } from "@/lib/links";
9import { Header, useLiveControls } from "../live-ui";
10import { StoryRow } from "../story-row";
11import { useLiveList } from "../use-live-list";
12import { EventTimeline } from "../event-timeline";
13import type { HnEvent } from "@/lib/events";
14const storyFields = ["score", "comments", "title", "body"] as const;
15const commentFields = ["text", "deleted", "dead"] as const;
16type Queries = { story: SealedStory; comments: SealedComments };
17const emptyEvents: HnEvent[] = [];
18type Props = {
19 initialStories: Story[];
20 initialComments: Comment[];
21 queries: Queries | null;
22 initialNow: number;
23 fixtureEvents?: readonly HnEvent[];
24};
25export function CommentsClient(props: Props) {
26 if (!props.queries)
27 return (
28 <Discussion
29 {...props}
30 stories={props.initialStories}
31 comments={props.initialComments}
32 connection="fixture"
33 />
34 );
35 return <LiveDiscussion {...props} queries={props.queries} />;
36}
37function LiveDiscussion(props: Props & { queries: Queries }) {
38 const id = props.initialStories[0].item_id;
39 const session = useSession();
40 const renew = useCallback(async () => {
41 return session.json<Queries>(`/api/thread/live?id=${id}`);
42 }, [id, session]);
43 const refreshStory = useCallback(async () => (await renew()).story, [renew]);
44 const refreshComments = useCallback(
45 async () => (await renew()).comments,
46 [renew],
47 );
48 const story = useCachedLiveQuery(
49 `story:${id}`,
50 props.queries.story,
51 props.initialStories,
52 refreshStory,
53 );
54 const comments = useCachedLiveQuery(
55 `comments:${id}`,
56 props.queries.comments,
57 props.initialComments,
58 refreshComments,
59 );
60 const connection = [story.status, comments.status].includes("error")
61 ? "error"
62 : [story.status, comments.status].includes("stale")
63 ? "stale"
64 : story.status === "live" && comments.status === "live"
65 ? "live"
66 : "connecting";
67 return (
68 <Discussion
69 {...props}
70 initialStories={
71 story.data?.length ? [...story.data] : props.initialStories
72 }
73 initialComments={
74 comments.data ? [...comments.data] : props.initialComments
75 }
76 stories={story.data ?? props.initialStories}
77 comments={comments.data ?? props.initialComments}
78 connection={connection}
79 error={story.error?.message ?? comments.error?.message}
80 />
81 );
82}
83export function Discussion({
84 initialStories,
85 initialComments,
86 stories,
87 comments,
88 connection,
89 error,
90 initialNow,
91 fixtureEvents,
92}: Props & {
93 stories: readonly Story[];
94 comments: readonly Comment[];
95 connection: string;
96 error?: string;
97}) {
98 const id = initialStories[0].item_id;
99 const controls = useLiveControls(
100 initialNow,
101 connection,
102 `/api/thread/watch?id=${id}`,
103 "POST",
104 );
105 const liveStory = useLiveList(
106 initialStories,
107 stories,
108 sortStories,
109 storyFields,
110 controls.paused,
111 controls.highlight,
112 initialNow,
113 );
114 const list = useLiveList(
115 initialComments,
116 comments,
117 sortComments,
118 commentFields,
119 controls.paused,
120 controls.highlight,
121 initialNow,
122 );
123 const story = liveStory.rows[0] ?? initialStories[0];
124 const [collapsed, setCollapsed] = useState<Set<number>>(() => new Set());
125 const visible = useMemo(() => {
126 const hidden: string[] = [];
127 return list.rows.filter((row) => {
128 if (hidden.some((path) => row.path.startsWith(`${path}.`))) return false;
129 if (collapsed.has(row.item_id)) hidden.push(row.path);
130 return true;
131 });
132 }, [list.rows, collapsed]);
133 const toggle = (id: number) =>
134 setCollapsed((previous) => {
135 const next = new Set(previous);
136 if (next.has(id)) next.delete(id);
137 else next.add(id);
138 return next;
139 });
140 const limited =
141 controls.health &&
142 "truncated" in controls.health &&
143 controls.health.truncated === true;
144 return (
145 <main className="hn-page">
146 <Header controls={controls} connection={connection} error={error} />
147 <article
148 className="thread-story"
149 data-item-id={story.item_id}
150 ref={(node) => liveStory.register(story.item_id, node)}
151 >
152 <StoryRow
153 story={story}
154 change={liveStory.changes.get(story.item_id)}
155 now={controls.now}
156 thread
157 />
158 {story.body && (
159 <div
160 key={liveStory.changes.get(story.item_id)?.fields.body ?? 0}
161 className={`story-body comment-text ${liveStory.changes.get(story.item_id)?.fields.body ? "changed-value" : ""}`}
162 >
163 {commentContent(story.body)}
164 </div>
165 )}
166 </article>
167 <p className="discussion-actions">
168 <a href={itemLink(id)}>Comment on Hacker News</a>
169 </p>
170 <ol id="comments" className="comments" aria-label="Story comments">
171 {visible.map((comment) => {
172 const change = list.changes.get(comment.item_id);
173 const closed = collapsed.has(comment.item_id);
174 const edited =
175 change?.fields.text ||
176 change?.fields.deleted ||
177 change?.fields.dead;
178 return (
179 <li
180 key={comment.item_id}
181 id={`comment-${comment.item_id}`}
182 data-item-id={comment.item_id}
183 data-committed-at={comment.committed_at}
184 data-applied-at={list.appliedAt}
185 className={`comment ${change?.entered || change?.moved ? "changed-row" : ""}`}
186 style={
187 {
188 "--depth": Math.min(comment.depth, 12),
189 } as React.CSSProperties
190 }
191 ref={(node) => list.register(comment.item_id, node)}
192 >
193 <div className="comment-meta">
194 <a
195 className={`vote ${comment.deleted || comment.dead ? "no-vote" : ""}`}
196 href={itemLink(comment.item_id)}
197 aria-label="Vote on this comment at Hacker News"
198 >
199 <span />
200 </a>
201 {comment.author && (
202 <>
203 <a href={userLink(comment.author)}>{comment.author}</a>{" "}
204 </>
205 )}
206 <a href={itemLink(comment.item_id)}>
207 {age(comment.created, controls.now)}
208 </a>{" "}
209 <button
210 type="button"
211 onClick={() => toggle(comment.item_id)}
212 aria-expanded={!closed}
213 aria-label={`${closed ? "Expand" : "Collapse"} comment by ${comment.author ?? "unknown"}`}
214 >
215 {closed ? "[+]" : "[–]"}
216 </button>
217 </div>
218 {!closed && (
219 <div className="comment-content">
220 <div
221 key={edited ?? 0}
222 data-change={edited ? "text" : undefined}
223 className={`comment-text ${edited ? "changed-value" : ""} ${comment.dead ? "dead-comment" : ""}`}
224 >
225 {comment.deleted
226 ? "[deleted]"
227 : comment.dead
228 ? "[dead]"
229 : commentContent(comment.text)}
230 </div>
231 {!comment.deleted && !comment.dead && (
232 <a
233 className="reply"
234 href={`${HN}/reply?id=${comment.item_id}&goto=item%3Fid%3D${id}`}
235 >
236 reply
237 </a>
238 )}
239 </div>
240 )}
241 </li>
242 );
243 })}
244 </ol>
245 {!list.rows.length && (
246 <p className="discussion-empty" role="status">
247 {story.comments === 0
248 ? "No comments yet."
249 : controls.health?.state === "degraded"
250 ? "Comments are temporarily unavailable."
251 : "Loading comments…"}{" "}
252 <a href={itemLink(id)}>View on Hacker News</a>
253 </p>
254 )}
255 {limited && (
256 <p className="thread-limit">
257 Showing up to {THREAD_LIMIT} comments.{" "}
258 <a href={itemLink(id)}>Read the full discussion on Hacker News</a>.
259 </p>
260 )}
261 {controls.health?.state === "starting" && list.rows.length > 0 && (
262 <p className="thread-limit" role="status">
263 Loading remaining comments…
264 </p>
265 )}
266 {connection === "fixture" && (
267 <EventTimeline
268 paused={controls.paused}
269 fixtureEvents={fixtureEvents ?? emptyEvents}
270 />
271 )}
272 </main>
273 );
274}