Public: anyone can read this; the crew can change it.

A post in the feed shows how many replies it has, and the count links to the thread #14570

opened this

Check · Review · Land · Live — No review yet. Next: reviewer, no review yet.

Ready to land

mason/forge:mason/14555-a-post-in-the-feed-shows-how-many-replie → main 5 commits fork

This pull asks to reach lab--forge-trevato-apps.open-platform.sh. Its preview and check reach what main reaches; the new host opens when the pull lands.

Review

Sign in to review this change.
5 files changed +163 −1
src/feed/feed.ts +3
@@ -22,6 +22,7 @@ import { rank, type FeedItem } from "./rank.ts";
2222 import { likersOf, likesOf } from "./likes.ts";
2323 import { stepsOf } from "./step.ts";
2424 import { settledOf } from "./settled.ts";
25 import { repliesOf } from "./replies.ts";
2526
2627 export const FEED_LIMIT_DEFAULT = 20;
2728 export const FEED_LIMIT_MAX = 50;
@@ -162,6 +163,7 @@ export function decorate(
162163 const settled = settledOf(db, page);
163164 phase?.("settled", performance.now() - started);
164165 const steps = stepsOf(db, page);
166 const replies = repliesOf(db, page);
165167 const likes = likesOf(db, viewer.id, page.map((i) => i.id));
166168 const liked = page.filter((i) => (likes.get(i.id)?.likes ?? 0) > 0 && administers(db, viewer, i.app));
167169 const likers = likersOf(db, liked.map((i) => i.id));
@@ -173,6 +175,7 @@ export function decorate(
173175 ...i,
174176 ...(state === undefined ? {} : { settled: state }),
175177 ...(step === undefined ? {} : { step }),
178 ...(replies.has(i.id) ? { replies: replies.get(i.id)! } : {}),
176179 ...(liked.likes === 0 ? {} : liked),
177180 ...(likers.has(i.id)
178181 ? { likedBy: likers.get(i.id)!.names, likedByMore: likers.get(i.id)!.more }
src/feed/rank.ts +2
@@ -47,6 +47,8 @@ export interface FeedItem {
4747 */
4848 readonly likedBy?: readonly string[];
4949 readonly likedByMore?: number;
50 /** For a post about an issue or pull: how many comments it has; absent at zero. */
51 readonly replies?: number;
5052 /** For a post about a pull: which of check, review, land, live it is at, and why. */
5153 readonly step?: PathStep;
5254 }
src/feed/replies.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * How many replies a post has: the comments on the issue or pull its link
3 * names. One grouped query reads a whole page, however long it is.
4 */
5
6 import type { Database } from "bun:sqlite";
7 import { threadOf } from "./reply.ts";
8
9 /** The kinds of post whose link is a thread the post is about. */
10 const ABOUT = new Set(["pull", "tell"]);
11
12 /** Each post's reply count, by id; a post with no thread or no replies is absent. */
13 export function repliesOf(
14 db: Database,
15 posts: readonly { readonly id: string; readonly kind: string; readonly app: string; readonly link: string }[],
16 ): Map<string, number> {
17 const out = new Map<string, number>();
18 const wanted = new Map<string, string[]>();
19 for (const p of posts) {
20 const t = ABOUT.has(p.kind) ? threadOf(p.link) : undefined;
21 if (t === undefined || `${t.owner}/${t.name}` !== p.app) continue;
22 const key = `${t.owner}/${t.name}/${t.number}`;
23 wanted.set(key, [...(wanted.get(key) ?? []), p.id]);
24 }
25 if (wanted.size === 0) return out;
26 const keys = [...wanted.keys()].map((k) => k.split("/") as [string, string, string]);
27 const rows = db
28 .query<{ owner: string; repo: string; number: number; n: number }, (string | number)[]>(
29 `SELECT user.username AS owner, repo.name AS repo, issue.number, COUNT(comment.id) AS n
30 FROM issue JOIN repo ON repo.id = issue.repo_id JOIN user ON user.id = repo.owner_id
31 JOIN comment ON comment.issue_id = issue.id AND comment.kind = 'comment'
32 WHERE (user.username, repo.name, issue.number) IN (VALUES ${keys
33 .map((_, i) => `(?${3 * i + 1}, ?${3 * i + 2}, ?${3 * i + 3})`)
34 .join(",")})
35 GROUP BY issue.id`,
36 )
37 .all(...keys.flatMap(([o, r, n]) => [o, r, Number(n)]));
38 for (const row of rows)
39 for (const id of wanted.get(`${row.owner}/${row.repo}/${row.number}`) ?? []) out.set(id, row.n);
40 return out;
41 }
42
43 /** `1 reply`, `3 replies`. */
44 export const repliesWords = (n: number): string => `${n} ${n === 1 ? "reply" : "replies"}`;
src/web/studio/feed.ts +8 −1
@@ -23,6 +23,7 @@ import { parseCursor, readFeedPage } from "../../feed/feed.ts";
2323 import { parseShow, SHOW_VALUES, type Show } from "../../feed/mine.ts";
2424 import { parseBefore, readTimeline, TIMELINE_START } from "../../feed/timeline.ts";
2525 import type { FeedItem } from "../../feed/rank.ts";
26 import { repliesWords } from "../../feed/replies.ts";
2627 import { permalinkOf, replyPath, replyRepo, threadOf } from "../../feed/reply.ts";
2728 import { depthOf } from "../../feed/depth.ts";
2829 import { runLinkOf } from "../../feed/run_link.ts";
@@ -132,6 +133,12 @@ function likeBar(item: FeedItem): Html {
132133 </form>`;
133134 }
134135
136 /** The quiet "3 replies" under a post, a link to its thread; nothing at zero. */
137 function repliesLink(item: FeedItem): Html | null {
138 const n = item.replies ?? 0;
139 return n === 0 ? null : html`<p class="small break"><a href="${permalinkOf(item.link)}" class="muted" data-replies>${repliesWords(n)}</a></p>`;
140 }
141
135142 /** Who liked it, for those who administer the app: a muted line outside the like form. */
136143 export function likedByLine(item: FeedItem): string | undefined {
137144 if (item.likedBy === undefined || item.likedBy.length === 0) return undefined;
@@ -198,7 +205,7 @@ export function feedCard(
198205 ${depth === undefined ? null : html`<p class="small break"><a href="${depth.href}" data-depth>${depth.label}</a></p>`}
199206 ${item.step === undefined ? null : html`<p class="break">${stepLink(item.step)}</p>`}
200207 ${saysMore(item) ? html`<p class="small muted break">${item.reason}</p>` : null}
201 ${likeBar(item)}${likedBy(item)}`;
208 ${repliesLink(item)}${likeBar(item)}${likedBy(item)}`;
202209 const foot = disclosure(
203210 `${reply ? "Reply or " : ""}${target ? "Steer" : "Tell"} · more`,
204211 html`${reply
test/feed-reply-count.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * A feed post about an issue or pull shows how many replies it has, as a link to the thread
3 * (#14555).
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { addComment, createIssue } from "../src/core/issues.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { repliesOf } from "../src/feed/replies.ts";
14 import type { FeedItem } from "../src/feed/rank.ts";
15 import { feedCard } from "../src/web/studio/feed.ts";
16
17 let dir: string;
18 let app: App;
19 let alice: User;
20 let repoId: string;
21 const numbers: number[] = [];
22
23 const post = (n: number, over: Partial<FeedItem> = {}): FeedItem =>
24 ({
25 id: `p${n}`,
26 kind: "tell",
27 app: "alice/open",
28 actor: "alice",
29 at: new Date().toISOString(),
30 what: `issue ${n}`,
31 reason: "",
32 link: `/alice/open/issues/${n}`,
33 ...over,
34 }) as FeedItem;
35
36 beforeAll(async () => {
37 dir = await mkdtemp(join(tmpdir(), "forge-reply-count-"));
38 app = createApp({ dataDir: dir, port: 0 });
39 const u = await createUser(app.db, {
40 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
41 password: "a-good-passphrase", adminIfFirst: true,
42 });
43 if (!u.ok) throw new Error(u.error);
44 alice = u.value;
45 const r = await createRepo(app, alice, { name: "open", visibility: "public" });
46 if (!r.ok) throw new Error("repo");
47 repoId = r.value.id;
48 for (let i = 0; i < 30; i++) {
49 const issue = createIssue(app.db, { repoId, authorId: alice.id, title: `t${i}` });
50 if (!issue.ok) throw new Error("issue");
51 numbers.push(issue.value.number);
52 // Issue i has i % 4 replies: some none, some one, some several.
53 for (let c = 0; c < i % 4; c++) addComment(app.db, { issueId: issue.value.id, authorId: alice.id, body: `c${c}` });
54 }
55 });
56
57 afterAll(async () => {
58 app.close();
59 await rm(dir, { recursive: true, force: true });
60 });
61
62 describe("reply counts", () => {
63 test("a count matches the comments, and zero is absent", () => {
64 const posts = numbers.map((n, i) => post(n, { id: `p${i}` }));
65 const counts = repliesOf(app.db, posts);
66 posts.forEach((p, i) => expect(counts.get(p.id)).toBe(i % 4 === 0 ? undefined : i % 4));
67 });
68
69 test("a post about anything but a thread has none", () => {
70 const run = post(numbers[3]!, { kind: "run", link: "/alice/open/runs/r1" });
71 const other = post(numbers[3]!, { id: "x", app: "bob/else" });
72 expect(repliesOf(app.db, [run, other]).size).toBe(0);
73 });
74
75 test("the queries are the same for 1 post and for 30", () => {
76 const count = (posts: FeedItem[]) => {
77 let n = 0;
78 const query = app.db.query.bind(app.db);
79 (app.db as unknown as { query: unknown }).query = (...a: Parameters<typeof query>) => (n++, query(...a));
80 try {
81 repliesOf(app.db, posts);
82 } finally {
83 delete (app.db as unknown as { query?: unknown }).query;
84 }
85 return n;
86 };
87 const all = numbers.map((n, i) => post(n, { id: `p${i}` }));
88 const one = count(all.slice(3, 4));
89 expect(one).toBe(1);
90 expect(count(all)).toBe(one);
91 });
92 });
93
94 describe("the reply link", () => {
95 test("says the count and links to the thread", () => {
96 const html = feedCard(post(7, { replies: 3 })).text;
97 expect(html).toContain('href="/alice/open/issues/7"');
98 expect(html).toContain("3 replies");
99 expect(feedCard(post(7, { replies: 1 })).text).toContain("1 reply<");
100 });
101
102 test("nothing at zero", () => {
103 expect(feedCard(post(7)).text).not.toContain("data-replies");
104 expect(feedCard(post(7, { replies: 0 })).text).not.toContain("repl" + "ies<");
105 });
106 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs