@jant/core 0.8.1 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/{app--uxnaIRV.js → app-B3P2N2vM.js} +1346 -310
  2. package/dist/client/.vite/manifest.json +2 -2
  3. package/dist/client/_assets/{client-auth-begiT1tq.js → client-auth-CeGBe0qG.js} +1 -1
  4. package/dist/client/_assets/{client-BT6kpcuG.js → client-nByuF0Ct.js} +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/node.js +2 -2
  7. package/package.json +1 -1
  8. package/src/__tests__/helpers/cursor-walk.ts +37 -7
  9. package/src/app.tsx +4 -0
  10. package/src/lib/__tests__/discover.test.ts +24 -0
  11. package/src/lib/__tests__/thread-fold.test.ts +43 -0
  12. package/src/lib/api-posts.ts +110 -2
  13. package/src/lib/api-public-posts.ts +263 -0
  14. package/src/lib/api-threads.ts +207 -0
  15. package/src/lib/discover.ts +34 -0
  16. package/src/lib/thread-fold.ts +83 -41
  17. package/src/lib/thread-query.ts +143 -0
  18. package/src/middleware/cors.ts +8 -1
  19. package/src/middleware/deprecation.ts +48 -0
  20. package/src/routes/api/__tests__/mcp.test.ts +143 -0
  21. package/src/routes/api/__tests__/posts.test.ts +78 -0
  22. package/src/routes/api/__tests__/public-access.test.ts +5 -0
  23. package/src/routes/api/__tests__/search.test.ts +104 -0
  24. package/src/routes/api/__tests__/threads.test.ts +115 -0
  25. package/src/routes/api/posts.ts +15 -104
  26. package/src/routes/api/public/__tests__/threads.test.ts +363 -0
  27. package/src/routes/api/public/archive.ts +82 -81
  28. package/src/routes/api/public/posts.ts +97 -298
  29. package/src/routes/api/public/threads.ts +141 -0
  30. package/src/routes/api/search.ts +31 -2
  31. package/src/routes/api/threads.ts +128 -0
  32. package/src/routes/auth/__tests__/setup-discover.test.ts +29 -1
  33. package/src/routes/auth/__tests__/setup-page.test.tsx +59 -1
  34. package/src/routes/auth/setup.tsx +48 -9
  35. package/src/routes/pages/__tests__/search.test.ts +58 -0
  36. package/src/routes/pages/search.tsx +3 -1
  37. package/src/services/__tests__/search.test.ts +211 -0
  38. package/src/services/__tests__/thread.test.ts +495 -0
  39. package/src/services/index.ts +4 -0
  40. package/src/services/mcp.ts +217 -57
  41. package/src/services/post.ts +222 -43
  42. package/src/services/search.ts +77 -66
  43. package/src/services/thread.ts +392 -0
  44. package/src/types/constants.ts +25 -0
  45. package/src/ui/feed/ThreadPreview.tsx +9 -14
  46. package/src/ui/feed/__tests__/thread-preview.test.ts +18 -22
  47. package/src/ui/feed/thread-preview-state.ts +0 -35
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Public API Post responses
3
+ *
4
+ * The reading view of a Post that `/api/public/*` returns: rendered body or
5
+ * Markdown, public permalink, and public collection references.
6
+ */
7
+
8
+ import type { Services } from "../services/index.js";
9
+ import type { AppConfig } from "../types/config.js";
10
+ import type { Collection, Media, Post } from "../types.js";
11
+ import { getCollectionPagePath } from "./collection-paths.js";
12
+ import { toApiAttachment } from "./api-posts.js";
13
+ import { tiptapJsonToMarkdown } from "./tiptap-to-markdown.js";
14
+ import { toPublicPath } from "./url.js";
15
+ import { getImageUrl, getMediaUrl, getPublicUrlForProvider } from "./image.js";
16
+
17
+ export type PublicPostBaseResponse = {
18
+ id: string;
19
+ format: Post["format"];
20
+ status: "published";
21
+ visibility: Post["visibility"];
22
+ slug: string;
23
+ permalink: string;
24
+ title?: string | null;
25
+ url?: string | null;
26
+ sourceName?: string | null;
27
+ sourceUrl?: string | null;
28
+ quoteText: string | null;
29
+ summary: string | null;
30
+ rating: number | null;
31
+ previewKind: string | null;
32
+ previewProvider: string | null;
33
+ previewImageUrl: string | null;
34
+ replyToId: string | null;
35
+ threadId: string;
36
+ /**
37
+ * BCP 47 content language, or null on a post written before the site
38
+ * enabled multilingual content.
39
+ */
40
+ language: string | null;
41
+ /**
42
+ * Shared by every translation of this Thread. Null when the Thread has no
43
+ * translations.
44
+ */
45
+ translationGroupId: string | null;
46
+ /** Reply published without announcing its Thread. Always false on roots. */
47
+ quietReply: boolean;
48
+ pinnedAt: number | null;
49
+ featuredAt: number | null;
50
+ publishedAt: number | null;
51
+ /** Root only: newest post in the Thread, quiet replies excluded. */
52
+ lastActivityAt: number;
53
+ /** Root only: newest post in the Thread, quiet replies included. */
54
+ threadUpdatedAt: number;
55
+ /**
56
+ * Published Posts in this Post's Thread, its root included: 1 for a Post on
57
+ * its own.
58
+ */
59
+ threadPostCount: number;
60
+ createdAt: number;
61
+ updatedAt: number;
62
+ attachments: ReturnType<typeof toApiAttachment>[];
63
+ collections: {
64
+ id: string;
65
+ slug: string;
66
+ title: string;
67
+ url: string;
68
+ }[];
69
+ };
70
+
71
+ export type PublicPostRenderedResponse = PublicPostBaseResponse & {
72
+ bodyHtml: string | null;
73
+ bodyText: string | null;
74
+ };
75
+
76
+ export type PublicPostMarkdownResponse = PublicPostBaseResponse & {
77
+ bodyMarkdown: string | null;
78
+ };
79
+
80
+ export type PublicPostResponse =
81
+ PublicPostRenderedResponse | PublicPostMarkdownResponse;
82
+
83
+ /**
84
+ * The public Markdown for a post, or null for a historical body that isn't
85
+ * TipTap JSON. One unreadable row answers null and is logged, rather than
86
+ * failing the whole listing; `bodyHtml` still falls back to stored HTML.
87
+ */
88
+ function toPublicBodyMarkdown(postId: string, body: string): string | null {
89
+ try {
90
+ return tiptapJsonToMarkdown(body);
91
+ } catch (error) {
92
+ // eslint-disable-next-line no-console -- A skipped body must leave a trace
93
+ console.error(
94
+ `Couldn't convert the body of post ${postId} to Markdown`,
95
+ error,
96
+ );
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * One Post's reading view, from its attachments, its Thread's collections, and
103
+ * its Thread's Post count.
104
+ *
105
+ * @param post - The Post
106
+ * @param related - What was read about it in the same batch as its page
107
+ * @param appConfig - Media URLs and the site path prefix
108
+ * @param options - `content: "markdown"` returns `bodyMarkdown` instead of the
109
+ * rendered body
110
+ * @returns The public response
111
+ * @example
112
+ * toPublicPost(post, { media: [], collections: [], threadPostCount: 1 }, config);
113
+ */
114
+ export function toPublicPost(
115
+ post: Post,
116
+ related: {
117
+ media: Media[];
118
+ collections: Collection[];
119
+ threadPostCount: number;
120
+ },
121
+ appConfig: AppConfig,
122
+ options?: { content?: "markdown" },
123
+ ): PublicPostResponse {
124
+ const {
125
+ r2PublicUrl,
126
+ imageTransformUrl,
127
+ s3PublicUrl,
128
+ localPublicUrl,
129
+ sitePathPrefix,
130
+ storageDriver,
131
+ } = appConfig;
132
+
133
+ const previewImagePublicUrl = getPublicUrlForProvider(
134
+ storageDriver,
135
+ r2PublicUrl,
136
+ s3PublicUrl,
137
+ localPublicUrl,
138
+ );
139
+ const previewImageUrl = post.previewImageKey
140
+ ? getImageUrl(
141
+ getMediaUrl(
142
+ post.previewImageKey,
143
+ previewImagePublicUrl,
144
+ sitePathPrefix,
145
+ ),
146
+ imageTransformUrl,
147
+ { width: 1280, quality: 80, format: "auto", fit: "scale-down" },
148
+ )
149
+ : null;
150
+
151
+ const base = {
152
+ id: post.id,
153
+ format: post.format,
154
+ status: "published" as const,
155
+ visibility: post.visibility,
156
+ slug: post.slug,
157
+ permalink: toPublicPath(`/${post.slug}`, sitePathPrefix),
158
+ quoteText: post.quoteText,
159
+ summary: post.summary,
160
+ rating: post.rating,
161
+ previewKind: post.previewKind,
162
+ previewProvider: post.previewProvider,
163
+ previewImageUrl,
164
+ replyToId: post.replyToId,
165
+ threadId: post.threadId,
166
+ language: post.language,
167
+ translationGroupId: post.translationGroupId,
168
+ quietReply: post.quietReply,
169
+ pinnedAt: post.pinnedAt,
170
+ featuredAt: post.featuredAt,
171
+ publishedAt: post.publishedAt,
172
+ lastActivityAt: post.lastActivityAt,
173
+ threadUpdatedAt: post.threadUpdatedAt,
174
+ threadPostCount: related.threadPostCount,
175
+ createdAt: post.createdAt,
176
+ updatedAt: post.updatedAt,
177
+ attachments: related.media.map((media) =>
178
+ toApiAttachment(
179
+ media,
180
+ r2PublicUrl,
181
+ imageTransformUrl,
182
+ s3PublicUrl,
183
+ localPublicUrl,
184
+ sitePathPrefix,
185
+ ),
186
+ ),
187
+ collections: related.collections.map((collection) => ({
188
+ id: collection.id,
189
+ slug: collection.slug,
190
+ title: collection.title,
191
+ url: toPublicPath(getCollectionPagePath(collection.slug), sitePathPrefix),
192
+ })),
193
+ };
194
+ const contentFields =
195
+ options?.content === "markdown"
196
+ ? {
197
+ bodyMarkdown: post.body
198
+ ? toPublicBodyMarkdown(post.id, post.body)
199
+ : null,
200
+ }
201
+ : {
202
+ bodyHtml: post.bodyHtml,
203
+ bodyText: post.bodyText,
204
+ };
205
+
206
+ if (post.format === "quote") {
207
+ return {
208
+ ...base,
209
+ ...contentFields,
210
+ sourceName: post.title,
211
+ sourceUrl: post.url,
212
+ };
213
+ }
214
+
215
+ return {
216
+ ...base,
217
+ ...contentFields,
218
+ title: post.title,
219
+ url: post.url,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * Reading-view responses for Posts already loaded. Attachments, Thread
225
+ * collections, and Thread Post counts are each read in one batch.
226
+ *
227
+ * @param deps - Services and app config; a request's `c.var`
228
+ * @param posts - Posts to respond with, in order
229
+ * @param options - `content: "markdown"` returns `bodyMarkdown`
230
+ * @returns One response per Post, in the same order
231
+ * @example
232
+ * const responses = await loadPublicPostResponses(c.var, page.posts, {});
233
+ */
234
+ export async function loadPublicPostResponses(
235
+ deps: {
236
+ services: Pick<Services, "media" | "posts" | "collections">;
237
+ appConfig: AppConfig;
238
+ },
239
+ posts: Post[],
240
+ options: { content?: "markdown" } = {},
241
+ ): Promise<PublicPostResponse[]> {
242
+ if (posts.length === 0) return [];
243
+ const { services, appConfig } = deps;
244
+ const postIds = posts.map((post) => post.id);
245
+ const [mediaMap, collectionsMap, threadPostCounts] = await Promise.all([
246
+ services.media.getByPostIds(postIds),
247
+ services.collections.getCollectionsByPostIds(postIds),
248
+ services.posts.countThreadPosts(posts.map((post) => post.threadId)),
249
+ ]);
250
+
251
+ return posts.map((post) =>
252
+ toPublicPost(
253
+ post,
254
+ {
255
+ media: mediaMap.get(post.id) ?? [],
256
+ collections: collectionsMap.get(post.id) ?? [],
257
+ threadPostCount: threadPostCounts.get(post.threadId) ?? 0,
258
+ },
259
+ appConfig,
260
+ options,
261
+ ),
262
+ );
263
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * API Thread responses
3
+ *
4
+ * The Thread object the author API, the public API, and MCP return. One shape
5
+ * for all three, parameterized by how each surface renders a Post and how it
6
+ * names one: the author API's Post is the editing view, the public API's the
7
+ * reading view.
8
+ */
9
+
10
+ import type { ThreadSummary } from "../services/thread.js";
11
+ import type { Post } from "../types.js";
12
+ import {
13
+ loadApiPostResponses,
14
+ type ApiPostResponse,
15
+ type ApiPostResponseDeps,
16
+ } from "./api-posts.js";
17
+ import {
18
+ loadPublicPostResponses,
19
+ type PublicPostResponse,
20
+ } from "./api-public-posts.js";
21
+ import { toPublicPath } from "./url.js";
22
+
23
+ /**
24
+ * The homepage fold of one Thread: what it shows either side of the gap, and
25
+ * how much it hides. Which replies it keeps is the site's choice
26
+ * (`lib/thread-fold.ts`) and may change; `hidden` always says how many it left
27
+ * out, so a caller never has to work it out.
28
+ */
29
+ export interface ApiThreadFold<P, G> {
30
+ /** The earliest replies, as context. */
31
+ leading: P[];
32
+ /** How many replies the fold leaves out, between `leading` and `trailing`. */
33
+ hidden: number;
34
+ /** The first reply left out, where a link to the rest opens; null if none. */
35
+ gap: G | null;
36
+ /** The latest replies, oldest first; the newest reply is the last. */
37
+ trailing: P[];
38
+ }
39
+
40
+ /** One Thread, as a Thread list or lookup returns it. */
41
+ export interface ApiThreadResponse<P, G> {
42
+ /** The Thread's ID, which is its root Post's ID. */
43
+ id: string;
44
+ /** Published Posts in the Thread, the root included. */
45
+ postCount: number;
46
+ /** Newest post in the Thread, quiet replies excluded. */
47
+ lastActivityAt: number;
48
+ /** Newest post in the Thread, quiet replies included. */
49
+ threadUpdatedAt: number;
50
+ root: P;
51
+ /** Present when the request asked for it. */
52
+ fold?: ApiThreadFold<P, G>;
53
+ }
54
+
55
+ /** How the author API and MCP name a Post a fold leaves out. */
56
+ export interface ApiThreadGap {
57
+ id: string;
58
+ slug: string;
59
+ }
60
+
61
+ /** The author API's and MCP's Thread object. */
62
+ export type ApiAuthorThreadResponse = ApiThreadResponse<
63
+ ApiPostResponse,
64
+ ApiThreadGap
65
+ >;
66
+
67
+ /** How the public API names a Post a fold leaves out: with its address. */
68
+ export interface PublicThreadGap extends ApiThreadGap {
69
+ permalink: string;
70
+ }
71
+
72
+ /** The public API's Thread object. */
73
+ export type PublicThreadResponse = ApiThreadResponse<
74
+ PublicPostResponse,
75
+ PublicThreadGap
76
+ >;
77
+
78
+ /**
79
+ * Every Post a set of Thread responses renders, so their attachments and
80
+ * counts can be read in one batch: each root, then the replies its fold shows.
81
+ *
82
+ * @param summaries - Threads to respond with
83
+ * @returns The Posts, each once
84
+ * @example
85
+ * const responses = await render(collectThreadResponsePosts(summaries));
86
+ */
87
+ export function collectThreadResponsePosts(summaries: ThreadSummary[]): Post[] {
88
+ const seen = new Map<string, Post>();
89
+ for (const { root, fold } of summaries) {
90
+ seen.set(root.id, root);
91
+ if (!fold) continue;
92
+ for (const post of [
93
+ ...fold.leadingReplies,
94
+ ...fold.trailingReplies,
95
+ fold.latestReply,
96
+ ]) {
97
+ seen.set(post.id, post);
98
+ }
99
+ }
100
+ return [...seen.values()];
101
+ }
102
+
103
+ /**
104
+ * One Thread's response, from Post responses already rendered.
105
+ *
106
+ * @param summary - The Thread
107
+ * @param respond - The rendered response for a Post in it
108
+ * @param reference - How the surface names the Post a fold leaves out
109
+ * @returns The Thread object
110
+ * @example
111
+ * toApiThreadResponse(summary, (post) => byId.get(post.id)!, toGap);
112
+ */
113
+ export function toApiThreadResponse<P, G>(
114
+ summary: ThreadSummary,
115
+ respond: (post: Post) => P,
116
+ reference: (post: Post) => G,
117
+ ): ApiThreadResponse<P, G> {
118
+ const { root, fold } = summary;
119
+ const response: ApiThreadResponse<P, G> = {
120
+ id: root.id,
121
+ postCount: summary.postCount,
122
+ lastActivityAt: root.lastActivityAt,
123
+ threadUpdatedAt: root.threadUpdatedAt,
124
+ root: respond(root),
125
+ };
126
+ if (fold === null) {
127
+ response.fold = { leading: [], hidden: 0, gap: null, trailing: [] };
128
+ } else if (fold) {
129
+ response.fold = {
130
+ leading: fold.leadingReplies.map(respond),
131
+ hidden: fold.hiddenCount,
132
+ gap: fold.firstHiddenReply ? reference(fold.firstHiddenReply) : null,
133
+ trailing: [...fold.trailingReplies, fold.latestReply].map(respond),
134
+ };
135
+ }
136
+ return response;
137
+ }
138
+
139
+ /**
140
+ * The author API's and MCP's Thread objects for Threads already listed.
141
+ *
142
+ * @param deps - Services and app config
143
+ * @param summaries - Threads to respond with, in order
144
+ * @returns One Thread object per summary, in the same order
145
+ * @example
146
+ * const threads = await loadApiThreadResponses(c.var, page.threads);
147
+ */
148
+ export async function loadApiThreadResponses(
149
+ deps: ApiPostResponseDeps,
150
+ summaries: ThreadSummary[],
151
+ ): Promise<ApiAuthorThreadResponse[]> {
152
+ return buildThreadResponses(
153
+ summaries,
154
+ (posts) => loadApiPostResponses(deps, posts),
155
+ (post) => ({ id: post.id, slug: post.slug }),
156
+ );
157
+ }
158
+
159
+ /**
160
+ * The public API's Thread objects for Threads already listed.
161
+ *
162
+ * @param deps - Services and app config
163
+ * @param summaries - Threads to respond with, in order
164
+ * @param options - `content: "markdown"` returns `bodyMarkdown` on every Post
165
+ * @returns One Thread object per summary, in the same order
166
+ * @example
167
+ * const threads = await loadPublicThreadResponses(c.var, page.threads, {});
168
+ */
169
+ export async function loadPublicThreadResponses(
170
+ deps: ApiPostResponseDeps,
171
+ summaries: ThreadSummary[],
172
+ options: { content?: "markdown" } = {},
173
+ ): Promise<PublicThreadResponse[]> {
174
+ return buildThreadResponses(
175
+ summaries,
176
+ (posts) => loadPublicPostResponses(deps, posts, options),
177
+ (post) => ({
178
+ id: post.id,
179
+ slug: post.slug,
180
+ permalink: toPublicPath(`/${post.slug}`, deps.appConfig.sitePathPrefix),
181
+ }),
182
+ );
183
+ }
184
+
185
+ /** Render every Post the Threads show in one batch, then assemble them. */
186
+ async function buildThreadResponses<P, G>(
187
+ summaries: ThreadSummary[],
188
+ render: (posts: Post[]) => Promise<P[]>,
189
+ reference: (post: Post) => G,
190
+ ): Promise<ApiThreadResponse<P, G>[]> {
191
+ const posts = collectThreadResponsePosts(summaries);
192
+ const responses = await render(posts);
193
+ const byId = new Map(
194
+ posts.map((post, index) => [post.id, responses[index]] as const),
195
+ );
196
+ return summaries.map((summary) =>
197
+ toApiThreadResponse(
198
+ summary,
199
+ (post) => {
200
+ const response = byId.get(post.id);
201
+ if (!response) throw new Error(`No response built for post ${post.id}`);
202
+ return response;
203
+ },
204
+ reference,
205
+ ),
206
+ );
207
+ }
@@ -200,6 +200,40 @@ export const DISCOVER_FIRST_READ_MAX_HOURS = 6;
200
200
  */
201
201
  export const DISCOVER_PUBLIC_DELAY_HOURS = 24;
202
202
 
203
+ /**
204
+ * Languages the jant.me directory lists, as primary language subtags.
205
+ *
206
+ * The directory's rule — its `accepted_languages` — stated here for the same
207
+ * reason as `DISCOVER_MIN_PUBLIC_POSTS`, and read by setup alone: the Discover
208
+ * question is asked there only when the answer can lead somewhere. An author
209
+ * writing in a language the directory does not list would be handed a promise
210
+ * nobody keeps, ticked in advance on hosted Jant.
211
+ *
212
+ * Nothing else reads it. The settings checkbox records consent rather than
213
+ * applying for a listing, and a site can take on a listed language later
214
+ * through multilingual content, so it stays for everyone.
215
+ *
216
+ * Simplified and Traditional Chinese are one list there, which is why the
217
+ * match is on the primary subtag rather than on the script.
218
+ */
219
+ export const DISCOVER_LANGUAGES: readonly string[] = ["zh"];
220
+
221
+ /**
222
+ * Whether the jant.me directory lists posts written in a language.
223
+ *
224
+ * @param tag - A BCP 47 language tag, as the content language is stored
225
+ * @returns True when the tag's primary subtag is in `DISCOVER_LANGUAGES`
226
+ * @example
227
+ * ```ts
228
+ * isDiscoverLanguage("zh-Hant"); // true
229
+ * isDiscoverLanguage("en"); // false
230
+ * ```
231
+ */
232
+ export function isDiscoverLanguage(tag: string): boolean {
233
+ const primary = tag.split("-")[0]?.toLowerCase() ?? "";
234
+ return DISCOVER_LANGUAGES.includes(primary);
235
+ }
236
+
203
237
  /**
204
238
  * The directory's names for its two format lists.
205
239
  *
@@ -3,15 +3,17 @@
3
3
  *
4
4
  * How much of a thread the timeline shows, and how much it folds away.
5
5
  *
6
- * A thread appears in two places that cannot select its posts the same way.
7
- * The site paints a page of timeline items and must not load whole threads to
8
- * do it, so `getThreadTimelineContext` ranks replies in SQL and hands the
9
- * buckets down. The feed already holds every reply — `<content>` carries the
10
- * whole chain — so it slices the array it has. Two access paths, one rule.
6
+ * A thread is folded in three places that cannot all select its posts the same
7
+ * way. The site paints a page of timeline items and must not load whole
8
+ * threads to do it, so `getThreadTimelineContext` ranks replies in SQL and
9
+ * hands the windows down; the Threads API's `include=fold` reads the same
10
+ * windows. The feed already holds every reply — `<content>` carries the whole
11
+ * chain — so it slices the array it has. Two access paths, one rule.
11
12
  *
12
- * This module owns what they share: the thresholds, and the arithmetic that
13
- * turns a selection into a hidden count. Whoever changes the shape of the fold
14
- * changes it here, and both surfaces move together.
13
+ * This module owns what they share: the thresholds, how overlapping windows
14
+ * become the replies shown ({@link foldReplyWindows}), and the arithmetic that
15
+ * turns them into a hidden count. Whoever changes the shape of the fold changes
16
+ * it here, and every surface moves together.
15
17
  *
16
18
  * ## The fold
17
19
  *
@@ -101,6 +103,73 @@ export interface ThreadFold<T> {
101
103
  hiddenCount: number;
102
104
  }
103
105
 
106
+ /**
107
+ * Fold a thread from its ranked windows: the replies each end of the fold
108
+ * keeps, before any overlap between them is removed.
109
+ *
110
+ * Both access paths arrive here. The feed slices the windows out of the whole
111
+ * chain; the site and the API rank them in SQL (`getThreadTimelineContext`),
112
+ * which hands them over overlapping on purpose. A short thread's windows
113
+ * overlap, and the hero is inside both of them on the shortest ones: with a
114
+ * single reply, that reply is the newest *and* the whole leading window. Each
115
+ * list therefore drops whatever an earlier one already shows, hero first.
116
+ *
117
+ * @param buckets.leadingReplies - The first `THREAD_LEADING_REPLIES` replies
118
+ * @param buckets.trailingReplies - The replies just before the newest, oldest
119
+ * first
120
+ * @param buckets.latestReply - The newest reply
121
+ * @param buckets.nextReply - The reply right after the leading window, the
122
+ * only candidate for the gap; `null` when the thread has no such reply
123
+ * @param buckets.totalReplyCount - Every published reply in the thread
124
+ * @returns The fold
125
+ * @example
126
+ * foldReplyWindows({ leadingReplies: [r1, r2], trailingReplies: [r6, r7],
127
+ * latestReply: r8, nextReply: r3, totalReplyCount: 8 });
128
+ * // leading [r1, r2], trailing [r6, r7], latest r8, firstHidden r3, hidden 3
129
+ */
130
+ export function foldReplyWindows<T extends Identified>({
131
+ leadingReplies: leadingWindow,
132
+ trailingReplies: trailingWindow,
133
+ latestReply,
134
+ nextReply,
135
+ totalReplyCount,
136
+ }: {
137
+ leadingReplies: T[];
138
+ trailingReplies: T[];
139
+ latestReply: T;
140
+ nextReply: T | null;
141
+ totalReplyCount: number;
142
+ }): ThreadFold<T> {
143
+ const shown = new Set([latestReply.id]);
144
+ const keepUnshown = (replies: T[]) =>
145
+ replies.filter((reply) => {
146
+ if (shown.has(reply.id)) return false;
147
+ shown.add(reply.id);
148
+ return true;
149
+ });
150
+ const leadingReplies = keepUnshown(leadingWindow);
151
+ const trailingReplies = keepUnshown(trailingWindow);
152
+ const hiddenCount = getThreadHiddenCount({
153
+ leadingReplies,
154
+ trailingReplies,
155
+ latestReply,
156
+ totalReplyCount,
157
+ });
158
+
159
+ return {
160
+ leadingReplies,
161
+ trailingReplies,
162
+ latestReply,
163
+ // The reply after the leading window is hidden exactly when anything is:
164
+ // the trailing window starts at or before it otherwise.
165
+ firstHiddenReply:
166
+ hiddenCount > 0 && nextReply && !shown.has(nextReply.id)
167
+ ? nextReply
168
+ : null,
169
+ hiddenCount,
170
+ };
171
+ }
172
+
104
173
  /**
105
174
  * Fold a thread whose replies are already in hand.
106
175
  *
@@ -122,40 +191,13 @@ export function foldThreadReplies<T extends Identified>(
122
191
  const latestReply = replies.at(-1);
123
192
  if (!latestReply) return null;
124
193
 
125
- // A short thread's windows overlap, and the hero is inside both of them on
126
- // the shortest ones: with a single reply, that reply is the newest *and* the
127
- // whole leading window. Each list therefore drops whatever an earlier one
128
- // already shows, hero first — the same order `ThreadPreview` dedupes in when
129
- // it walks the buckets the SQL path hands it.
130
- const leadingReplies = replies
131
- .slice(0, THREAD_LEADING_REPLIES)
132
- .filter((reply) => reply.id !== latestReply.id);
133
-
134
- const leadingIds = new Set(leadingReplies.map((reply) => reply.id));
135
- const trailingReplies = replies
136
- .slice(-THREAD_TRAILING_REPLIES, -1)
137
- .filter(
138
- (reply) => reply.id !== latestReply.id && !leadingIds.has(reply.id),
139
- );
140
-
141
- const shown = new Set([
142
- ...leadingIds,
143
- ...trailingReplies.map((reply) => reply.id),
144
- latestReply.id,
145
- ]);
146
-
147
- return {
148
- leadingReplies,
149
- trailingReplies,
194
+ return foldReplyWindows({
195
+ leadingReplies: replies.slice(0, THREAD_LEADING_REPLIES),
196
+ trailingReplies: replies.slice(-THREAD_TRAILING_REPLIES, -1),
150
197
  latestReply,
151
198
  // In thread order, so the gap link lands on the earliest post it stands
152
199
  // for rather than somewhere in the middle of the run it hides.
153
- firstHiddenReply: replies.find((reply) => !shown.has(reply.id)) ?? null,
154
- hiddenCount: getThreadHiddenCount({
155
- leadingReplies,
156
- trailingReplies,
157
- latestReply,
158
- totalReplyCount: replies.length,
159
- }),
160
- };
200
+ nextReply: replies[THREAD_LEADING_REPLIES] ?? null,
201
+ totalReplyCount: replies.length,
202
+ });
161
203
  }