From 90e0abd84ab0762e68001f6455d94a534741a563 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 10:42:53 +0000 Subject: [PATCH 01/10] =?UTF-8?q?feat(forum):=20=E2=9C=A8=20Reddit-style?= =?UTF-8?q?=20topic=20feed=20with=20Hot,=20New,=20Active=20and=20Top=20sor?= =?UTF-8?q?ting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `/forum` is now a feed of topics from every readable forum, with the forum tree in a sidebar (forum chips on phones) - Forum pages use the same sortable feed instead of newest-first cursor pages - New `GET /forum/feed` route: ranks by reactions (negative-point reactions count down), comments and age; shared one-minute ranking cache, filtered per viewer's forum access - Topic cards show forum, author, age, excerpt, points and comments - Document sorting in the forum guide Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- apps/web/content/docs/guides/forum.mdx | 47 ++- .../src/api/modules/forum/forum.module.ts | 9 +- .../forum/src/api/modules/forum/lib/feed.ts | 207 ++++++++++++ .../modules/forum/routes/list-feed.route.ts | 189 +++++++++++ plugins/forum/src/feed-sorts.ts | 46 +++ plugins/forum/src/locales/en.json | 30 +- plugins/forum/src/pages/forum-data.ts | 9 +- plugins/forum/src/pages/forum-links.ts | 63 +++- plugins/forum/src/pages/forum-page.tsx | 196 ++--------- plugins/forum/src/pages/forum-queries.ts | 44 ++- plugins/forum/src/pages/forum-ui.tsx | 10 +- plugins/forum/src/pages/forums-page.tsx | 191 +++++++++-- plugins/forum/src/pages/topic-feed.tsx | 313 ++++++++++++++++++ plugins/forum/src/routes.ts | 3 +- 14 files changed, 1135 insertions(+), 222 deletions(-) create mode 100644 plugins/forum/src/api/modules/forum/lib/feed.ts create mode 100644 plugins/forum/src/api/modules/forum/routes/list-feed.route.ts create mode 100644 plugins/forum/src/feed-sorts.ts create mode 100644 plugins/forum/src/pages/topic-feed.tsx diff --git a/apps/web/content/docs/guides/forum.mdx b/apps/web/content/docs/guides/forum.mdx index 0c6cd2aca..80171e275 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -98,14 +98,57 @@ deep, and you can drag them to reorder. A forum's **Icon** accepts the same | Page | What it does | | ------------------------ | ---------------------------------------------------------------------- | -| `/forum` | Every forum with its topic and comment counts and its newest topic | -| `/forum/:slug` | Subforums and the topics of one forum, newest first | +| `/forum` | A feed of topics from every forum you can read, with the forum list | +| `/forum/:slug` | Subforums and the topics of one forum, in the same sortable feed | | `/forum/create/topic` | Start a topic (signed-in members) | | `/forum/topics/:slug` | The topic, its nested comments, and a comment box | | `/forum/topics/:id/edit` | Edit your own topic | | `/forum/comments/:slug` | Permalink of one comment - redirects to its place in the topic | | `/forum/me/pending` | Your posts a moderator approved, declined, or has not looked at yet | +## Sort the feed + +`/forum` works like a Reddit front page: one feed of topics from every forum +the visitor may read, with the forum tree beside it (a row of forum chips on +phones). Each forum page shows its own topics the same way. Every topic card +has its forum, author, age, title, a short excerpt, its points and comments. + +| Sort | URL | Shows first | +| ------ | ------------------ | ------------------------------------------------------------ | +| Hot | `/forum` | Busy topics that are still fresh - the default | +| New | `?sort=new` | The newest topics | +| Active | `?sort=active` | Topics with the latest comment, like a classic forum | +| Top | `?sort=top&t=week` | The most points today, this week, month or year, or all time | + +**Points** are a topic's reactions: every reaction adds one, and a reaction +worth negative points in **AdminCP → Reactions** (like "Disagree") takes one +away. **Hot** adds comments to the points and weighs them on a log scale +against age, so ten times the engagement buys a topic about 12.5 hours of +freshness. A brilliant topic from last month politely makes room for today's. + +Pages go `?page=2` and on, up to page 40. The ranking is shared by everyone and +cached for a minute; a new topic or comment refreshes it at once, a new +reaction within a minute. Topics in forums the visitor cannot read never make +it into their feed. + +Need the feed in your own component? Call the same route: + +```ts +import { fetcher } from "@vitnode/core/tanstack/fetcher"; + +const res = await fetcher({ + plugin: "@vitnode/forum", + method: "get", + module: "forum", + path: "/feed", + args: { query: { page: 1, sort: "top", t: "month" } }, +}); +``` + +Add `forumId` to the query for one forum's topics only. + +## Comments + Comments nest up to six levels - hit **Reply** under any comment to answer it. On small screens deep comments stop indenting, so the text keeps its width, and every branch can be collapsed. A comment removed by a moderator stays as "This diff --git a/plugins/forum/src/api/modules/forum/forum.module.ts b/plugins/forum/src/api/modules/forum/forum.module.ts index 541d01505..48d12890d 100644 --- a/plugins/forum/src/api/modules/forum/forum.module.ts +++ b/plugins/forum/src/api/modules/forum/forum.module.ts @@ -1,6 +1,7 @@ import { buildModule } from "@/api/builders"; import { forumStatsEventListeners } from "@/api/lib/events"; +import { forumFeedRoute } from "./routes/list-feed.route"; import { forumStatsRoute } from "./routes/list-forum-stats.route"; import { topicStatsRoute } from "./routes/list-topic-stats.route"; import { forumTopicsRoute } from "./routes/list-topics.route"; @@ -8,6 +9,12 @@ import { topicSlugRoute } from "./routes/show-topic-slug.route"; export const forumModule = buildModule({ name: "forum", - routes: [forumStatsRoute, topicStatsRoute, topicSlugRoute, forumTopicsRoute], + routes: [ + forumFeedRoute, + forumStatsRoute, + topicStatsRoute, + topicSlugRoute, + forumTopicsRoute, + ], events: forumStatsEventListeners, }); diff --git a/plugins/forum/src/api/modules/forum/lib/feed.ts b/plugins/forum/src/api/modules/forum/lib/feed.ts new file mode 100644 index 000000000..97930994d --- /dev/null +++ b/plugins/forum/src/api/modules/forum/lib/feed.ts @@ -0,0 +1,207 @@ +import type { SQL } from "drizzle-orm"; +import type { Context } from "hono"; + +import { + core_reactions, + core_reactions_counts, +} from "@vitnode/api/database/reactions"; +import { and, count, desc, eq, gte, max, sql } from "drizzle-orm"; +import { z } from "zod"; + +import type { ForumFeedSort, ForumFeedTopWindow } from "@/feed-sorts"; + +import { defineCacheEntry } from "@/api/builders"; +import { readForumStatsGeneration } from "@/api/lib/stats-cache"; +import { topicContentType } from "@/content/topic"; +import { commentContent } from "@/database/comments"; +import { topicContent } from "@/database/topics"; +import { FORUM_FEED_MAX_PAGES, FORUM_FEED_PAGE_SIZE } from "@/feed-sorts"; +import { manifest } from "@/manifest.gen"; + +import { publicComment, publicTopic } from "./public-condition"; +import { iso } from "./stats"; + +export const FORUM_FEED_MAX_RANKED = + FORUM_FEED_MAX_PAGES * FORUM_FEED_PAGE_SIZE; + +/** + * Reactions are not forum writes, so they do not move the stats generation. + * Rankings are cut into one-minute buckets instead: a new reaction (and the + * `hot` decay) reaches the feed within a minute, a new topic or comment at once. + */ +const FEED_BUCKET_SECONDS = 60; + +/** Reddit's hot decay: ten times the engagement is worth 12.5 hours of age. */ +const HOT_DECAY_SECONDS = 45_000; + +const TOP_WINDOW_INTERVALS: Record< + Exclude, + string +> = { + day: "1 day", + week: "7 days", + month: "1 month", + year: "1 year", +}; + +const zodRankedTopic = z.object({ + commentCount: z.number().int(), + forum: z.number().int(), + id: z.number().int(), + lastActivityAt: z.iso.datetime().nullable(), + score: z.number().int(), +}); + +export type RankedTopic = z.infer; + +/** + * Every public topic of one feed in rank order, for everybody: the route keeps + * only the forums the viewer may read, so a restricted forum's topics never + * leave the server. + */ +const feedRankingCache = defineCacheEntry({ + name: "feed.ranking", + version: 1, + key: ( + generation: string, + bucket: number, + sort: ForumFeedSort, + window: ForumFeedTopWindow, + forumId: null | number, + ) => [generation, bucket, sort, window, forumId ?? "all"], + schema: z.array(zodRankedTopic), + ttlSeconds: FEED_BUCKET_SECONDS * 2, +}); + +const rankTopics = async ( + c: Context, + { + forumId, + sort, + window, + }: { + forumId: null | number; + sort: ForumFeedSort; + window: ForumFeedTopWindow; + }, +): Promise => { + const db = c.get("db"); + const topics = topicContent.table; + const comments = commentContent.table; + + const commentStats = db + .select({ + commentCount: count().as("comment_count"), + lastCommentAt: max(comments.publishedAt).as("last_comment_at"), + topicId: comments.topic, + }) + .from(comments) + .where(publicComment()) + .groupBy(comments.topic) + .as("forum_feed_comment_stats"); + + // A reaction worth negative points (a dislike) pulls the score down; every + // other reaction counts as one point up. + const reactionStats = db + .select({ + score: + sql`coalesce(sum(case when ${core_reactions.points} < 0 then -${core_reactions_counts.count} else ${core_reactions_counts.count} end), 0)::int`.as( + "score", + ), + targetId: core_reactions_counts.targetId, + }) + .from(core_reactions_counts) + .innerJoin( + core_reactions, + eq(core_reactions_counts.reactionId, core_reactions.id), + ) + .where( + and( + eq(core_reactions_counts.pluginId, manifest.id), + eq(core_reactions_counts.targetType, topicContentType.id), + ), + ) + .groupBy(core_reactions_counts.targetId) + .as("forum_feed_reaction_stats"); + + const commentCount = sql`coalesce(${commentStats.commentCount}, 0)::int`; + const score = sql`coalesce(${reactionStats.score}, 0)::int`; + // `greatest` skips nulls: a topic without comments was last active when it + // was published. + const lastActivityAt = sql< + Date | null | string + >`greatest(${topics.publishedAt}, ${commentStats.lastCommentAt})`; + const engagement = sql`(${score} + ${commentCount})`; + const hot = sql`sign(${engagement}) * log(greatest(abs(${engagement}), 1)) + extract(epoch from ${topics.publishedAt}) / ${HOT_DECAY_SECONDS}`; + + const order: SQL[] = { + active: [desc(lastActivityAt)], + hot: [desc(hot)], + new: [desc(topics.publishedAt)], + top: [desc(score), desc(commentCount), desc(topics.publishedAt)], + }[sort]; + + const rows = await db + .select({ + commentCount, + forum: topics.forum, + id: topics.id, + lastActivityAt, + score, + }) + .from(topics) + .leftJoin(commentStats, eq(commentStats.topicId, topics.id)) + .leftJoin( + reactionStats, + eq(reactionStats.targetId, sql`cast(${topics.id} as varchar)`), + ) + .where( + and( + publicTopic(), + forumId === null ? undefined : eq(topics.forum, forumId), + sort === "top" && window !== "all" + ? gte( + topics.publishedAt, + sql`now() - cast(${TOP_WINDOW_INTERVALS[window]} as interval)`, + ) + : undefined, + ), + ) + .orderBy(...order, desc(topics.id)) + .limit(FORUM_FEED_MAX_RANKED); + + return rows.map(row => ({ + commentCount: row.commentCount, + forum: row.forum, + id: row.id, + lastActivityAt: iso(row.lastActivityAt), + score: row.score, + })); +}; + +/** The ranked topics of one feed, cached for everybody (see {@link feedRankingCache}). */ +export const loadFeedRanking = async ( + c: Context, + options: { + forumId: null | number; + sort: ForumFeedSort; + window: ForumFeedTopWindow; + }, +): Promise => { + const generation = await readForumStatsGeneration(c); + const bucket = Math.floor(Date.now() / 1000 / FEED_BUCKET_SECONDS); + // `window` only shapes `top`; folding it away keeps one entry per sort. + const window = options.sort === "top" ? options.window : "all"; + + return await c + .get("cache") + .entry( + feedRankingCache, + generation, + bucket, + options.sort, + window, + options.forumId, + ) + .remember(async () => await rankTopics(c, { ...options, window })); +}; diff --git a/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts b/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts new file mode 100644 index 000000000..31df502a6 --- /dev/null +++ b/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts @@ -0,0 +1,189 @@ +import { z } from "@hono/zod-openapi"; +import { + CONTENT_ACCESS_REQUIRED_CODE, + zodContentPublicPerson, +} from "@vitnode/api/content"; +import { richTextToPlainText } from "@vitnode/api/content/rich-text"; +import { createContentAccess } from "@vitnode/api/content/server"; +import { HTTPException } from "hono/http-exception"; + +import { buildRoute } from "@/api/builders"; +import { forumContainers } from "@/content/forums"; +import { topicContent } from "@/database/topics"; +import { + FORUM_FEED_DEFAULT_SORT, + FORUM_FEED_DEFAULT_TOP_WINDOW, + FORUM_FEED_MAX_PAGES, + FORUM_FEED_PAGE_SIZE, + FORUM_FEED_SORTS, + FORUM_FEED_TOP_WINDOWS, +} from "@/feed-sorts"; + +import { loadFeedRanking } from "../lib/feed"; +import { forumStatsHeaders, iso } from "../lib/stats"; +import { readableForumIds } from "./list-forum-stats.route"; + +const EXCERPT_LENGTH = 280; + +const excerptOf = (body: unknown): string => { + const text = richTextToPlainText( + body as Parameters[0], + ) + .replaceAll(/\s+/g, " ") + .trim(); + if (text.length <= EXCERPT_LENGTH) return text; + + const cut = text.slice(0, EXCERPT_LENGTH); + const lastSpace = cut.lastIndexOf(" "); + + return `${(lastSpace > EXCERPT_LENGTH / 2 ? cut.slice(0, lastSpace) : cut).trimEnd()}…`; +}; + +/** + * One page of a topic feed - every forum the viewer may read, or one forum - + * ranked `hot`, `new`, `active` or `top`. Each topic comes with a plain-text + * excerpt of its body, its reaction score and its public comment stats. + */ +export const forumFeedRoute = buildRoute({ + route: { + method: "get", + path: "/feed", + description: + "One page of public topics across every readable forum, or one forum, ranked hot, new, active or top", + request: { + query: z.object({ + forumId: z.coerce.number().int().positive().optional().openapi({ + description: "Only this forum's topics. Omit for every forum.", + example: 1, + }), + page: z.coerce + .number() + .int() + .min(1) + .max(FORUM_FEED_MAX_PAGES) + .default(1), + sort: z.enum(FORUM_FEED_SORTS).default(FORUM_FEED_DEFAULT_SORT), + t: z + .enum(FORUM_FEED_TOP_WINDOWS) + .default(FORUM_FEED_DEFAULT_TOP_WINDOW) + .openapi({ description: "How far back `top` looks." }), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + items: z.array( + z.object({ + author: zodContentPublicPerson.nullable(), + commentCount: z.number(), + excerpt: z.string(), + forum: z.number(), + id: z.number(), + lastActivityAt: z.string().nullable(), + publishedAt: z.string().nullable(), + score: z.number(), + slug: z.string(), + title: z.string(), + }), + ), + pageInfo: z.object({ + hasNextPage: z.boolean(), + page: z.number(), + }), + }), + }, + }, + description: "A page of ranked topics", + }, + 400: { description: "Invalid query parameters" }, + 403: { + content: { + "application/json": { + schema: z.object({ + accessRequired: z.literal(true), + code: z.literal(CONTENT_ACCESS_REQUIRED_CODE), + }), + }, + }, + description: "The viewer may see the forum but not read its topics", + }, + 404: { description: "No forum the viewer may see" }, + }, + }, + handler: async c => { + const { forumId, page, sort, t } = c.req.valid("query"); + const service = topicContent.publicService?.(c); + if (!service?.findManyByIds) { + throw new HTTPException(500, { message: "Topics have no public API." }); + } + + if (forumId !== undefined) { + const access = createContentAccess(c); + if (!(await access.canScope(forumContainers.id, forumId, "view"))) { + throw new HTTPException(404, { message: "Forum not found." }); + } + if (!(await access.canScope(forumContainers.id, forumId, "read"))) { + return c.json( + { + accessRequired: true as const, + code: CONTENT_ACCESS_REQUIRED_CODE, + }, + 403, + { "Cache-Control": "private, no-store" }, + ); + } + } + + const [ranked, readable, headers] = await Promise.all([ + loadFeedRanking(c, { forumId: forumId ?? null, sort, window: t }), + readableForumIds(c), + forumStatsHeaders(c), + ]); + const visible = readable + ? ranked.filter(item => readable.has(item.forum)) + : ranked; + const start = (page - 1) * FORUM_FEED_PAGE_SIZE; + const slice = visible.slice(start, start + FORUM_FEED_PAGE_SIZE); + + // The ranking is a minute old at most; the rows are read now, with the + // viewer's access, so a topic hidden since then simply drops out. + const rows = new Map( + (await service.findManyByIds(slice.map(item => item.id))).map(row => [ + row.id, + row, + ]), + ); + + return c.json( + { + items: slice.flatMap(item => { + const row = rows.get(item.id); + if (!row) return []; + + return [ + { + author: row.author, + commentCount: item.commentCount, + excerpt: excerptOf(row.body), + forum: row.forum, + id: row.id, + lastActivityAt: item.lastActivityAt, + publishedAt: iso(row.publishedAt), + score: item.score, + slug: row.slug, + title: row.title, + }, + ]; + }), + pageInfo: { + hasNextPage: visible.length > start + FORUM_FEED_PAGE_SIZE, + page, + }, + }, + 200, + headers, + ); + }, +}); diff --git a/plugins/forum/src/feed-sorts.ts b/plugins/forum/src/feed-sorts.ts new file mode 100644 index 000000000..05a672232 --- /dev/null +++ b/plugins/forum/src/feed-sorts.ts @@ -0,0 +1,46 @@ +/** + * How a topic feed is ordered - the forum home and every forum page. + * + * - `hot`: engagement (reaction score plus comments) on a log scale, with newer + * topics ahead, so a busy topic from this morning beats a busier one from + * last month. + * - `new`: newest first. + * - `active`: the latest comment (or the topic itself) first. + * - `top`: the highest reaction score within {@link ForumFeedTopWindow}. + */ +export const FORUM_FEED_SORTS = ["hot", "new", "active", "top"] as const; + +export type ForumFeedSort = (typeof FORUM_FEED_SORTS)[number]; + +export const FORUM_FEED_DEFAULT_SORT: ForumFeedSort = "hot"; + +/** How far back `top` looks, by publication time. */ +export const FORUM_FEED_TOP_WINDOWS = [ + "day", + "week", + "month", + "year", + "all", +] as const; + +export type ForumFeedTopWindow = (typeof FORUM_FEED_TOP_WINDOWS)[number]; + +export const FORUM_FEED_DEFAULT_TOP_WINDOW: ForumFeedTopWindow = "week"; + +export const FORUM_FEED_PAGE_SIZE = 25; + +/** + * A feed ranks at most this many pages of topics. Past it, readers reach older + * topics through search or the `new` sort of a single forum. + */ +export const FORUM_FEED_MAX_PAGES = 40; + +export const isForumFeedSort = (value: unknown): value is ForumFeedSort => + typeof value === "string" && + (FORUM_FEED_SORTS as readonly string[]).includes(value); + +export const isForumFeedTopWindow = ( + value: unknown, +): value is ForumFeedTopWindow => + typeof value === "string" && + (FORUM_FEED_TOP_WINDOWS as readonly string[]).includes(value); diff --git a/plugins/forum/src/locales/en.json b/plugins/forum/src/locales/en.json index d351b0d1b..7707008d9 100644 --- a/plugins/forum/src/locales/en.json +++ b/plugins/forum/src/locales/en.json @@ -74,8 +74,6 @@ "desc": "Nobody has started a topic in this forum yet. Break the ice!" }, "pagination": "Topic pages", - "newest": "Newest topics", - "older": "Older topics", "comment_count": "{count, plural, =0 {No comments} one {# comment} other {# comments}}", "last_comment": "Last comment", "errors": { @@ -97,7 +95,33 @@ } }, "access_required": "Members only", - "members_only": "Restricted" + "members_only": "Restricted", + "feed": { + "title": "Topic feed", + "sort": { + "label": "Sort topics", + "hot": "Hot", + "new": "New", + "active": "Active", + "top": "Top" + }, + "window": { + "label": "Top topics from", + "day": "Today", + "week": "This week", + "month": "This month", + "year": "This year", + "all": "All time" + }, + "score": "{count, plural, one {# point} other {# points}}", + "empty_top": { + "title": "Nothing at the top yet", + "desc": "No topics were posted in this time range. Pick a longer one, or post something worth climbing the charts." + }, + "previous": "Previous", + "next": "Next", + "page": "Page {page}" + } }, "topics": { "form": { diff --git a/plugins/forum/src/pages/forum-data.ts b/plugins/forum/src/pages/forum-data.ts index f7473fc0d..539e5ea14 100644 --- a/plugins/forum/src/pages/forum-data.ts +++ b/plugins/forum/src/pages/forum-data.ts @@ -53,17 +53,20 @@ export const zodPerson = zodContentPublicPerson.nullable().catch(null); export type ForumPerson = z.infer; -export const zodTopicListRow = z.object({ +export const zodFeedTopic = z.object({ author: zodPerson, commentCount: z.number(), + excerpt: z.string(), + forum: z.number(), id: z.number(), - lastCommentAt: z.string().nullable(), + lastActivityAt: z.string().nullable(), publishedAt: z.string().nullable(), + score: z.number(), slug: z.string(), title: z.string(), }); -export type TopicListRowData = z.infer; +export type FeedTopic = z.infer; export const indexBy = ( items: readonly TItem[], diff --git a/plugins/forum/src/pages/forum-links.ts b/plugins/forum/src/pages/forum-links.ts index 5a9aa7f6c..3252c5b26 100644 --- a/plugins/forum/src/pages/forum-links.ts +++ b/plugins/forum/src/pages/forum-links.ts @@ -1,8 +1,16 @@ +import type { ForumFeedSort, ForumFeedTopWindow } from "@/feed-sorts"; + +import { + FORUM_FEED_DEFAULT_SORT, + FORUM_FEED_DEFAULT_TOP_WINDOW, + FORUM_FEED_MAX_PAGES, + isForumFeedSort, + isForumFeedTopWindow, +} from "@/feed-sorts"; + export const FORUM_HREF = "/forum"; export const FORUM_PENDING_HREF = "/forum/me/pending"; -const CURSOR = /^[A-Za-z0-9_-]{1,512}$/; - const positiveId = (raw: unknown): number | undefined => { const value = typeof raw === "number" @@ -17,17 +25,54 @@ const positiveId = (raw: unknown): number | undefined => { const isTrue = (raw: unknown): boolean => raw === true || raw === "true" || raw === 1 || raw === "1"; +/** + * The feed's place in the URL: `/forum` and `/forum/:slug` both take + * `?sort=top&t=month&page=2`. Defaults stay out of the URL, so the plain + * address is the canonical one. + */ export interface ForumSearch { - cursor?: string; + page?: number; + sort?: ForumFeedSort; + t?: ForumFeedTopWindow; } -export const forumSearch = (input: Record): ForumSearch => - typeof input.cursor === "string" && CURSOR.test(input.cursor) - ? { cursor: input.cursor } - : {}; +export const forumSearch = (input: Record): ForumSearch => { + const search: ForumSearch = {}; + const sort = isForumFeedSort(input.sort) ? input.sort : undefined; + if (sort && sort !== FORUM_FEED_DEFAULT_SORT) search.sort = sort; + if ( + sort === "top" && + isForumFeedTopWindow(input.t) && + input.t !== FORUM_FEED_DEFAULT_TOP_WINDOW + ) { + search.t = input.t; + } + const page = positiveId(input.page); + if (page !== undefined && page > 1 && page <= FORUM_FEED_MAX_PAGES) { + search.page = page; + } + + return search; +}; + +const feedQueryString = ({ page, sort, t }: ForumSearch): string => { + const params = new URLSearchParams(); + if (sort && sort !== FORUM_FEED_DEFAULT_SORT) params.set("sort", sort); + if (sort === "top" && t && t !== FORUM_FEED_DEFAULT_TOP_WINDOW) { + params.set("t", t); + } + if (page && page > 1) params.set("page", String(page)); + const query = params.toString(); + + return query ? `?${query}` : ""; +}; + +/** The forum home feed, sorted and paged as `search` says. */ +export const feedHref = (search: ForumSearch = {}): string => + `${FORUM_HREF}${feedQueryString(search)}`; -export const forumHref = (slug: string, { cursor }: ForumSearch = {}): string => - `${FORUM_HREF}/${encodeURIComponent(slug)}${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`; +export const forumHref = (slug: string, search: ForumSearch = {}): string => + `${FORUM_HREF}/${encodeURIComponent(slug)}${feedQueryString(search)}`; export interface TopicSearch { created?: true; diff --git a/plugins/forum/src/pages/forum-page.tsx b/plugins/forum/src/pages/forum-page.tsx index 6e5d509f5..078ecea30 100644 --- a/plugins/forum/src/pages/forum-page.tsx +++ b/plugins/forum/src/pages/forum-page.tsx @@ -1,7 +1,6 @@ import type { QueryClient } from "@tanstack/react-query"; import type { PluginRoutePageProps } from "@vitnode/core/routing"; -import { queryOptions } from "@tanstack/react-query"; import { BreadcrumbItem, BreadcrumbLink, @@ -17,83 +16,34 @@ import { EmptyMedia, EmptyTitle, } from "@vitnode/core/components/ui/empty"; -import { LOADER_DATA_QUERY_META } from "@vitnode/core/lib/query-client"; import { ContentAccessRequired, contentPageItem, } from "@vitnode/core/tanstack/content"; -import { fetcher } from "@vitnode/core/tanstack/fetcher"; import { HrefLink } from "@vitnode/core/tanstack/link"; import { defineRoute } from "@vitnode/core/tanstack/plugin-routes"; -import { - MessageSquareIcon, - MessagesSquareIcon, - PenSquareIcon, - SearchXIcon, -} from "lucide-react"; +import { PenSquareIcon, SearchXIcon } from "lucide-react"; import { Fragment } from "react"; import { useTranslations } from "use-intl"; -import { z } from "zod"; - -import { manifest } from "@/manifest.gen"; -import type { TopicListRowData } from "./forum-data"; import type { ForumSearch } from "./forum-links"; +import type { FeedHref } from "./topic-feed"; -import { indexBy, zodTopicListRow } from "./forum-data"; -import { FORUM_HREF, forumHref, topicHref, topicNewHref } from "./forum-links"; +import { indexBy } from "./forum-data"; +import { FORUM_HREF, forumHref, topicNewHref } from "./forum-links"; import { ForumList } from "./forum-list"; import { - FORUM_ACTIVITY_STALE_TIME, - forumQueryKeys, + feedQueryOptions, forumStatsQueryOptions, queryForum, } from "./forum-queries"; -import { - ForumIcon, - ForumShell, - PersonAvatar, - PersonName, - TimeAgo, -} from "./forum-ui"; - -const PAGE_SIZE = 25; - -const forumTopicsQueryOptions = (request: ForumSearch & { forumId: number }) => - queryOptions({ - meta: LOADER_DATA_QUERY_META, - queryFn: async () => { - const list = await fetcher({ - plugin: manifest.id, - method: "get", - module: "forum", - path: "/topics", - args: { - query: { - first: String(PAGE_SIZE), - forumId: request.forumId, - ...(request.cursor ? { cursor: request.cursor } : {}), - }, - }, - }); - - if (list.status !== 200) throw new Error("Loading the topics failed."); - - const { edges, pageInfo } = await list.json(); - - return { - nextCursor: pageInfo.hasNextPage ? pageInfo.endCursor : null, - topics: z.array(zodTopicListRow).parse(edges), - }; - }, - queryKey: forumQueryKeys.topicList(request), - staleTime: FORUM_ACTIVITY_STALE_TIME, - }); +import { ForumIcon, ForumShell } from "./forum-ui"; +import { FeedPagination, FeedSortNav, TopicFeed } from "./topic-feed"; const loadForum = async ( queryClient: QueryClient, { locale, slug }: { locale: string; slug: string }, - { cursor }: ForumSearch, + search: ForumSearch, ) => { const { ancestors, children, container } = contentPageItem( await queryForum(queryClient, slug, locale), @@ -102,15 +52,12 @@ const loadForum = async ( // A forum the viewer may see but not read lists nothing - not even how // many topics it holds. const canRead = container.access.canRead; - const [{ nextCursor, topics }, forumStats] = await Promise.all([ + const [feed, forumStats] = await Promise.all([ canRead ? queryClient.query( - forumTopicsQueryOptions({ - forumId: container.id, - ...(cursor ? { cursor } : {}), - }), + feedQueryOptions({ ...search, forumId: container.id }), ) - : Promise.resolve({ nextCursor: null, topics: [] }), + : Promise.resolve(null), children.length > 0 ? queryClient.query(forumStatsQueryOptions()) : Promise.resolve([]), @@ -121,10 +68,9 @@ const loadForum = async ( canRead, children, container, + feed, forumStats, - isFirstPage: cursor === undefined, - nextCursor, - topics, + search, }; }; @@ -210,62 +156,12 @@ export const route = defineRoute({ notFound: ForumNotFound, }); -const TopicListRow = ({ topic }: { topic: TopicListRowData }) => { - const t = useTranslations("@vitnode/forum.forums"); - - return ( -
  • - -
    -
    - - {topic.title} - -

    - - {topic.publishedAt ? ( - <> - - - - ) : null} -

    -
    - -

    - - - {topic.lastCommentAt ? ( - - {t("last_comment")} - - ) : null} -

    -
    -
  • - ); -}; - const ForumPage = ({ loaderData, }: PluginRoutePageProps) => { const t = useTranslations("@vitnode/forum.forums"); - const { - canRead, - children, - container, - forumStats, - isFirstPage, - nextCursor, - topics, - } = loaderData; + const { canRead, children, container, feed, forumStats, search } = loaderData; + const hrefFor: FeedHref = next => forumHref(container.slug, next); return ( - {!canRead ? ( + {!canRead || !feed ? ( - ) : topics.length === 0 ? ( - - - - - }>{t("empty_forum.title")} - {t("empty_forum.desc")} - - - - {t("new_topic")} - - - ) : ( -
      - {topics.map(topic => ( - - ))} -
    - )} - - {isFirstPage && nextCursor === null ? null : ( - + <> + + + + )}
    diff --git a/plugins/forum/src/pages/forum-queries.ts b/plugins/forum/src/pages/forum-queries.ts index 657cfa1f2..23f3b5077 100644 --- a/plugins/forum/src/pages/forum-queries.ts +++ b/plugins/forum/src/pages/forum-queries.ts @@ -7,12 +7,17 @@ import { RECORD_STALE_TIME, } from "@vitnode/core/lib/query-freshness"; import { fetcher } from "@vitnode/core/tanstack/fetcher"; +import { z } from "zod"; +import { + FORUM_FEED_DEFAULT_SORT, + FORUM_FEED_DEFAULT_TOP_WINDOW, +} from "@/feed-sorts"; import { manifest } from "@/manifest.gen"; import type { ForumSearch } from "./forum-links"; -import { fetchForums, fetchForumStats } from "./forum-data"; +import { fetchForums, fetchForumStats, zodFeedTopic } from "./forum-data"; import { fetchThreadPage } from "./thread-data"; const FORUM_TREE_STALE_TIME = RECORD_STALE_TIME; @@ -43,14 +48,47 @@ export const forumQueryKeys = { thread: (topicId: number) => [...all, "thread", topicId] as const, topic: (slug: string) => [...topicDetails, slug] as const, topicDetails: () => topicDetails, - topicList: (request: ForumSearch & { forumId: number }) => - [...topicLists, request] as const, + topicList: (request: FeedRequest) => [...topicLists, request] as const, topicLists: () => topicLists, }; export const isSharedResponse = (res: Response): boolean => !/\b(?:no-store|private)\b/i.test(res.headers.get("cache-control") ?? ""); +/** One page of a feed: every readable forum, or `forumId` alone. */ +export type FeedRequest = ForumSearch & { forumId?: number }; + +export const feedQueryOptions = (request: FeedRequest) => + queryOptions({ + meta: LOADER_DATA_QUERY_META, + queryFn: async () => { + const res = await fetcher({ + plugin: manifest.id, + method: "get", + module: "forum", + path: "/feed", + args: { + query: { + ...(request.forumId === undefined + ? {} + : { forumId: request.forumId }), + page: request.page ?? 1, + sort: request.sort ?? FORUM_FEED_DEFAULT_SORT, + t: request.t ?? FORUM_FEED_DEFAULT_TOP_WINDOW, + }, + }, + }); + + if (res.status !== 200) throw new Error("Loading the topics failed."); + + const { items, pageInfo } = await res.json(); + + return { pageInfo, topics: z.array(zodFeedTopic).parse(items) }; + }, + queryKey: forumQueryKeys.topicList(request), + staleTime: FORUM_ACTIVITY_STALE_TIME, + }); + export const forumsQueryOptions = (locale: string) => queryOptions({ meta: LOADER_DATA_QUERY_META, diff --git a/plugins/forum/src/pages/forum-ui.tsx b/plugins/forum/src/pages/forum-ui.tsx index c5f43c962..5c26382f5 100644 --- a/plugins/forum/src/pages/forum-ui.tsx +++ b/plugins/forum/src/pages/forum-ui.tsx @@ -23,13 +23,21 @@ export const ForumShell = ({ children, description, title, + wide, }: { actions?: React.ReactNode; children: React.ReactNode; description?: null | string; title: React.ReactNode; + /** Room for a sidebar next to the content on large screens. */ + wide?: boolean; }) => ( -
    +

    diff --git a/plugins/forum/src/pages/forums-page.tsx b/plugins/forum/src/pages/forums-page.tsx index 7ec68152d..fad8f4e68 100644 --- a/plugins/forum/src/pages/forums-page.tsx +++ b/plugins/forum/src/pages/forums-page.tsx @@ -1,4 +1,5 @@ import type { QueryClient } from "@tanstack/react-query"; +import type { ContentContainerTreeNode } from "@vitnode/core/content"; import type { PluginRoutePageProps } from "@vitnode/core/routing"; import { buttonVariants } from "@vitnode/core/components/ui/button"; @@ -13,22 +14,40 @@ import { import { contentContainerTree } from "@vitnode/core/content"; import { HrefLink } from "@vitnode/core/tanstack/link"; import { defineRoute } from "@vitnode/core/tanstack/plugin-routes"; -import { MessagesSquareIcon, PenSquareIcon } from "lucide-react"; -import { useTranslations } from "use-intl"; +import { LockIcon, MessagesSquareIcon, PenSquareIcon } from "lucide-react"; +import { useFormatter, useTranslations } from "use-intl"; + +import type { Forum, ForumStats } from "./forum-data"; +import type { ForumSearch } from "./forum-links"; import { indexBy } from "./forum-data"; -import { topicNewHref } from "./forum-links"; -import { ForumList } from "./forum-list"; -import { forumsQueryOptions, forumStatsQueryOptions } from "./forum-queries"; -import { ForumShell } from "./forum-ui"; +import { feedHref, forumHref, topicNewHref } from "./forum-links"; +import { + feedQueryOptions, + forumsQueryOptions, + forumStatsQueryOptions, +} from "./forum-queries"; +import { ForumIcon, ForumShell } from "./forum-ui"; +import { FeedPagination, FeedSortNav, TopicFeed } from "./topic-feed"; -const loadForums = async (queryClient: QueryClient, locale: string) => { - const [forums, stats] = await Promise.all([ +const loadForums = async ( + queryClient: QueryClient, + locale: string, + search: ForumSearch, +) => { + const [forums, stats, feed] = await Promise.all([ queryClient.query(forumsQueryOptions(locale)), queryClient.query(forumStatsQueryOptions()), + queryClient.query(feedQueryOptions(search)), ]); - return { stats, tree: contentContainerTree(forums) }; + return { + feed, + forums, + search, + stats, + tree: contentContainerTree(forums), + }; }; type ForumsPageData = Awaited>; @@ -39,9 +58,9 @@ const ForumsBreadcrumb = () => { return {t("title")}; }; -export const route = defineRoute({ - load: async ({ context }) => - await loadForums(context.queryClient, context.locale), +export const route = defineRoute({ + load: async ({ context, search }) => + await loadForums(context.queryClient, context.locale, search), head: ({ t }) => ({ description: t("@vitnode/forum.forums.desc"), @@ -51,24 +70,72 @@ export const route = defineRoute({ breadcrumb: ForumsBreadcrumb, }); -const ForumsPage = ({ loaderData }: PluginRoutePageProps) => { +const SidebarForums = ({ + depth = 0, + nodes, + stats, +}: { + depth?: number; + nodes: ContentContainerTreeNode[]; + stats: ReadonlyMap; +}) => { const t = useTranslations("@vitnode/forum.forums"); - const stats = indexBy(loaderData.stats, item => item.forumId); + const format = useFormatter(); return ( - 0 ? ( - - - ) : ( -
    -

    - {t("tree")} + + ); + } + + return ( + + ); }; diff --git a/plugins/forum/src/pages/topic-feed.tsx b/plugins/forum/src/pages/topic-feed.tsx new file mode 100644 index 000000000..42139d294 --- /dev/null +++ b/plugins/forum/src/pages/topic-feed.tsx @@ -0,0 +1,313 @@ +import { buttonVariants } from "@vitnode/core/components/ui/button"; +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from "@vitnode/core/components/ui/empty"; +import { HrefLink } from "@vitnode/core/tanstack/link"; +import { + ActivityIcon, + ArrowBigUpIcon, + ChevronLeftIcon, + ChevronRightIcon, + FlameIcon, + MessageSquareIcon, + MessagesSquareIcon, + PenSquareIcon, + SparklesIcon, + TrophyIcon, +} from "lucide-react"; +import { useTranslations } from "use-intl"; + +import type { ForumFeedSort } from "@/feed-sorts"; + +import { + FORUM_FEED_DEFAULT_SORT, + FORUM_FEED_DEFAULT_TOP_WINDOW, + FORUM_FEED_SORTS, + FORUM_FEED_TOP_WINDOWS, +} from "@/feed-sorts"; + +import type { FeedTopic, Forum } from "./forum-data"; +import type { ForumSearch } from "./forum-links"; + +import { forumHref, topicHref, topicNewHref } from "./forum-links"; +import { ForumIcon, PersonAvatar, PersonName, TimeAgo } from "./forum-ui"; + +const SORT_ICONS: Record = { + active: ActivityIcon, + hot: FlameIcon, + new: SparklesIcon, + top: TrophyIcon, +}; + +/** Builds the URL of the same feed with another sort, window or page. */ +export type FeedHref = (search: ForumSearch) => string; + +export const FeedSortNav = ({ + hrefFor, + search, +}: { + hrefFor: FeedHref; + search: ForumSearch; +}) => { + const t = useTranslations("@vitnode/forum.forums.feed"); + const sort = search.sort ?? FORUM_FEED_DEFAULT_SORT; + const window = search.t ?? FORUM_FEED_DEFAULT_TOP_WINDOW; + + return ( + + ); +}; + +const FeedCard = ({ + forum, + topic, +}: { + /** The topic's forum, shown above the title; omit on the forum's own page. */ + forum?: Forum; + topic: FeedTopic; +}) => { + const t = useTranslations("@vitnode/forum.forums"); + const titleId = `feed-topic-${topic.id}`; + + return ( +
  • +
    +

    + {forum ? ( + <> + + + {forum.name} + + + + ) : null} + + + + + {topic.publishedAt ? ( + <> + + + + ) : null} +

    + +

    + + {topic.title} + +

    + + {topic.excerpt ? ( +

    + {topic.excerpt} +

    + ) : null} + +
      +
    • +
    • +
    • +
    • + {topic.commentCount > 0 && topic.lastActivityAt ? ( +
    • +
    • + ) : null} +
    +
    +
  • + ); +}; + +/** + * A ranked page of topics, Reddit-style: forum, author and age on top, the + * title, a short excerpt, then the score and the conversation around it. + */ +export const TopicFeed = ({ + forumId, + forums, + search, + topics, +}: { + /** The forum the feed belongs to; its "new topic" link starts there. */ + forumId?: number; + /** Forums by id, to label each topic. Omit when the feed is one forum's. */ + forums?: ReadonlyMap; + search: ForumSearch; + topics: FeedTopic[]; +}) => { + const t = useTranslations("@vitnode/forum.forums"); + + if (topics.length === 0) { + const isTopWindow = + search.sort === "top" && + (search.t ?? FORUM_FEED_DEFAULT_TOP_WINDOW) !== "all"; + + return ( + + + + + }> + {isTopWindow ? t("feed.empty_top.title") : t("empty_forum.title")} + + + {isTopWindow ? t("feed.empty_top.desc") : t("empty_forum.desc")} + + + + + + + + ); + } + + return ( +
      + {topics.map(topic => ( + + ))} +
    + ); +}; + +export const FeedPagination = ({ + hasNextPage, + hrefFor, + search, +}: { + hasNextPage: boolean; + hrefFor: FeedHref; + search: ForumSearch; +}) => { + const t = useTranslations("@vitnode/forum.forums"); + const page = search.page ?? 1; + + if (page === 1 && !hasNextPage) return null; + + return ( + + ); +}; diff --git a/plugins/forum/src/routes.ts b/plugins/forum/src/routes.ts index f25aea8f1..9127747d0 100644 --- a/plugins/forum/src/routes.ts +++ b/plugins/forum/src/routes.ts @@ -27,7 +27,8 @@ export const routes = definePluginRoutes([ cache: PUBLIC_CACHE, component: lazy(() => import("./pages/forums-page")), messages: ["@vitnode/forum.forums"], - pendingComponent: RoutePendingSkeleton, + pendingComponent: FeedPendingSkeleton, + search: forumSearch, }), page("/forum/me/pending", { From f0c9db56e5c4ddd68f01a95795875555f503be3b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 10:44:53 +0000 Subject: [PATCH 02/10] =?UTF-8?q?docs(plans):=20=F0=9F=93=9D=20Plan=20up/d?= =?UTF-8?q?own=20votes=20and=20ranked=20threads?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- plans/forum-voting.md | 236 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 plans/forum-voting.md diff --git a/plans/forum-voting.md b/plans/forum-voting.md new file mode 100644 index 000000000..df47d01d0 --- /dev/null +++ b/plans/forum-voting.md @@ -0,0 +1,236 @@ +# Votes (up/down) and ranked threads + +Status: planned, not started. Owner: core (`@vitnode/api` + `@vitnode/core`), +first consumer `@vitnode/forum`. + +The forum feed (`GET /forum/feed`, Hot/New/Active/Top) ranks topics by +**points**, and today points are borrowed from reactions: every reaction is +`+1`, a negative-point reaction is `-1`. That was a stand-in. Reactions say how +someone _feels_ ("haha", "thanks"); a vote says whether something _belongs +higher up_. This plan adds votes as their own core feature and switches the +forum's ranking to them. + +## Goals + +1. **Reddit-style voting** on anything: ▲ / ▼, one vote per member per item, + click again to take it back, switch in one click. +2. **Opt in with one line**: `votes: true` on `defineContentType`, the same way + `reactions: true` and `reports: true` work. Custom targets register with + `defineVoteTarget`, like `defineReactionTarget`. +3. **Ranking source.** The forum feed, and later any "top" list, sorts by the + vote score instead of reactions. +4. **Ranked comments.** Thread roots sort by Best (default), Top, New, Old or + Controversial. +5. **Karma.** Votes feed the author's reputation, with weights an admin sets. +6. **Live.** Scores update on screen over the WebSocket when it's available, + plain HTTP otherwise - the same as reactions. + +Non-goals (first version): vote fuzzing, public lists of who voted, awards, +voting on AdminCP-only records, per-forum karma leaderboards. + +## Votes and reactions side by side + +Both stay. They answer different questions and read differently on screen. + +| | Reactions | Votes | +| -------------- | --------------------------------- | ---------------------------------------- | +| Meaning | Emotion, thanks | "Show this higher / lower" | +| Per user | Role cap, several kinds | Exactly one: `+1`, `-1` or none | +| Shown | Pills with counts, who reacted | Net score only, voters private | +| Ranking | No (after this plan) | Yes - feed, Top, Best comments | +| Reputation | Per-reaction points | Per-vote weights (default `+1` / `-1`) | + +After phase 3 the forum's points are **votes only**. Reactions remain on topics +and comments for emotion and no longer move the ranking. (Open question 1.) + +## The pattern we copy: reactions + +| Reactions | Votes | +| ---------------------------------------------------------- | ----------------------------------------------------------- | +| `defineReactionTarget` in `lib/reactions/targets.ts` | `defineVoteTarget` in `lib/votes/targets.ts` | +| `reactions: true` → `contentReactionTarget(model)` | `votes: true` → `contentVoteTarget(model)` | +| `resolveReactions` in `content/define-reactions.ts` | `resolveVotes` in `content/define-votes.ts` | +| `core_reactions_entries` / `core_reactions_counts` | `core_votes_entries` / `core_votes_counts` | +| `canReact` in `ContentViewerPermissions` | `canVote`, `canDownvote` next to it | +| `` | `` | +| WebSocket channel `reactions/live` | `votes/live` (same room per target, same `seq` rule) | +| Role tab **Reactions** | Role tab **Votes** | +| Events `reaction.added/removed/changed` | `vote.added`, `vote.removed`, `vote.changed` | + +A target is the same triple `{ pluginId, type, id }`. + +## Decisions + +| Topic | Decision | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Values | `1` or `-1`, stored; "no vote" is no row. `PUT` with `0` deletes. | +| Own content | Never. No self-votes, no automatic author upvote: every score starts at `0`. | +| Who votes | Role column `allowVote` (default `true`, `false` for guests). Downvoting is a separate `allowDownvote` (default `true`), so an install can keep fresh members to upvotes only. Most generous role wins. | +| Daily limit | Role column `votesPerDay` (`null` = unlimited, the default). Votes given today that still exist count, as with reactions. Toggle spam is the per-minute rate limit's job. | +| Public numbers | Net score only (`score = up - down`). Up and down counts stay on the server for ranking (Controversial, Best) and for moderators. | +| Voter privacy | Nobody sees who voted, except moderators with a new `can_view_votes` permission in ModCP (abuse checks). No timeline entries. | +| Reputation | Two settings in **AdminCP → Votes**: points per upvote (default `1`) and per downvote (default `-1`), `-10..10`, `0` turns it off. Changing them queues a recount, like reaction points. Target opt-out `votes: { reputation: false }`. | +| Hidden / locked | Unreadable or hidden targets can't be voted on; scores are kept and come back on unhide. | +| Deleted target/user | Same as reactions: target deletion effects remove votes and their reputation; a deleted user cascades and a task recounts the targets and authors. | +| Concurrency | One write path in a transaction with an advisory lock per target, like reactions, so `seq` follows commit order and counts never drift. | +| Per-forum switch | A container policy `votes: "updown" \| "up" \| "off"` (default `updown`, inherits from the parent forum), next to `publish` and `edits`. "Ask the experts" forums can go up-only; announcements can turn it off. | + +## Data model + +`packages/api/src/database/votes.ts` + +```ts +/** One member's vote on one target. */ +export const core_votes_entries = camelCase.table.withRLS( + "core_votes_entries", + t => ({ + pluginId: t.varchar({ length: 100 }).notNull(), + targetType: t.varchar({ length: 100 }).notNull(), + targetId: t.varchar({ length: CONTENT_ID_KEY_LENGTH }).notNull(), + userId: t + .integer() + .notNull() + .references(() => core_users.id, { onDelete: "cascade" }), + value: t.smallint().notNull(), // 1 | -1 + // Who collects the reputation; null with `reputation: false`. + targetAuthorId: t + .integer() + .references(() => core_users.id, { onDelete: "set null" }), + createdAt: t.timestamp().notNull().defaultNow(), + updatedAt: t.timestamp().notNull().defaultNow(), + }), + t => [ + primaryKey({ + columns: [t.pluginId, t.targetType, t.targetId, t.userId], + }), + index("core_votes_entries_user_day_idx").on(t.userId, t.createdAt), + index("core_votes_entries_author_idx").on(t.targetAuthorId), + check("core_votes_entries_value", sql`${t.value} in (-1, 1)`), + ], +); + +/** Denormalized totals, written in the same transaction as the entry. */ +export const core_votes_counts = camelCase.table.withRLS( + "core_votes_counts", + t => ({ + pluginId: t.varchar({ length: 100 }).notNull(), + targetType: t.varchar({ length: 100 }).notNull(), + targetId: t.varchar({ length: CONTENT_ID_KEY_LENGTH }).notNull(), + upvotes: t.integer().notNull().default(0), + downvotes: t.integer().notNull().default(0), + score: t.integer().notNull().default(0), // upvotes - downvotes + version: t.bigint({ mode: "number" }).notNull().default(0), + }), + t => [ + primaryKey({ columns: [t.pluginId, t.targetType, t.targetId] }), + // "Top" without scanning every target of a type. + index("core_votes_counts_score_idx").on(t.pluginId, t.targetType, t.score), + ], +); +``` + +Role columns (`core_roles`): `allowVote`, `allowDownvote`, `votesPerDay`. +Settings (`core_site` or the existing settings store): `votes.upvotePoints`, +`votes.downvotePoints`. Migration: guest role gets `allowVote = false`. + +## API (core module `votes`) + +| Route | What | +| --------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `PUT /votes` | `{ target, value: 1 \| -1 \| 0 }` → new public summary. `401` guest, `403` role/policy/own content, `404` unreadable target, `429` daily limit. | +| `GET /votes/summaries?pluginId&type&ids` | Public `{ id, score, seq }[]` for up to 100 ids. Cacheable; unreadable ids answer as score `0`. | +| `GET /votes/me?pluginId&type&ids` | The viewer's own `{ id, value }[]`, `private, no-store` - asked in the browser, like `/permissions`. | +| `GET /admin/votes/settings`, `PUT` | Reputation weights. Staff permission. | +| `GET /moderation/votes/{target}` | Voters of one target for moderators with `can_view_votes`. | + +Every write emits `vote.added` / `vote.changed` / `vote.removed` and, when +reputation moves, the existing `reputation.changed`. Documented in +`apps/web/content/docs/dev/events/built-in-events.mdx`. + +## UI (`@vitnode/core/components/votes`) + +- ``: ▲ score ▼. + Buttons with `aria-pressed` and labels ("Upvote", "Remove upvote"…), score + in `ShortNumber` with a polite live region. Optimistic update, rolled back + with a `sonner` toast on error; `isLoading` on the pressed button while + sending. Disabled ▼ with a tooltip when the role or forum is up-only. +- Guests see the score; a click opens the sign-in prompt. +- Own content: score shown, buttons disabled with "You can't vote on your own post". +- Colors from tokens only (`text-primary` up, `text-destructive` down), the + direction also given by the icon fill, never color alone. +- Batched reads: one `summaries` + one `me` request per page, shared through + TanStack Query keys per target type, like reaction summaries. + +## Forum changes + +1. `votes: true` on `forum.topic` and `forum.comment`. +2. **Feed ranking** (`plugins/forum/src/api/modules/forum/lib/feed.ts`): + points = `core_votes_counts.score` instead of the reactions join. + - Hot: `sign(s) * log10(max(|s|, 1)) + epoch / 45000` with `s = score` + (comments no longer inflate it - a flame war is not "hot" by itself). + - Top: `score`, then `upvotes`. + - New sort **Controversial**: `(up + down) ^ (min(up, down) / max(up, down))` + for items with both, like Reddit. + - The ranking cache keeps its one-minute bucket; a vote moves a score within + a minute, which is fine for a feed. +3. **Feed card**: `VoteControl` vertical on the left from `md`, horizontal in + the footer on phones; the "points" text goes away. +4. **Topic page**: `VoteControl` next to the title. +5. **Comments**: `VoteControl` in each comment's action row. + +## Comment sorting (Content Engine `thread`) + +Today thread roots are paged by `createdAt asc` +(`packages/api/src/content/server/thread.ts`). Add a `sort` to the thread +read: `best` (default when the type has votes), `top`, `new`, `old`, +`controversial`. + +- **Best** is the Wilson score lower bound (95%) of `up / (up + down)`, so one + lone upvote doesn't beat 40 up and 2 down. A pure function + `wilsonLowerBound(up, down)` in `@vitnode/api/lib/votes/rank.ts`, mirrored in + SQL for ordering. +- Only **roots** are reordered and paged; replies keep chronological order + under their parent (readable conversations), as Reddit does for deep levels. +- The cursor encodes the sort key + id, so pages stay stable while scores move. +- The topic page gets a "Sort comments" select; the choice lives in the URL + (`?comments=top`), the default isn't written. + +## Phases + +| Phase | Scope | Done when | +| ----- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | +| 1 | Tables, migration, `lib/votes` service (write, limits, reputation, deletion), targets registry, `votes: true` in the Content Engine, API routes, events | `PUT /votes` works for a forum topic from curl; reputation moves; deleting the topic cleans up | +| 2 | Role **Votes** tab, AdminCP **Votes** settings Sheet, per-forum `votes` policy | An up-only forum refuses `-1` with `403`; a role without votes sees disabled buttons | +| 3 | `VoteControl`, live channel `votes/live`, forum feed on votes, feed card + topic page + comments | Two browsers see each other's votes live; the feed reorders within a minute | +| 4 | Thread `sort` (Best/Top/New/Old/Controversial), Controversial in the feed | A 40↑/2↓ comment sits above a 1↑/0↓ one under Best | +| 5 | ModCP voters list (`can_view_votes`), docs | Docs pages below are live | + +Each phase ends with `pnpm lint:fix`, typecheck, the existing tests and a run of +the app with seeded data. + +## Docs + +- `content-engine/votes.mdx`: `votes: true`, options, `canVote`, `VoteControl`. +- `dev/votes/*`: `defineVoteTarget` for custom targets, the API, the events. +- `guides/forum.mdx`: points are votes, the per-forum switch, comment sorting. +- `dev/events/built-in-events.mdx`: `vote.*`. + +## Tests (a separate session, after it works) + +- `lib/votes/rank.test.ts`: `wilsonLowerBound`, controversy - one `it.each`. +- Service: add/switch/remove, no self-vote, `allowDownvote`, daily limit, + reputation deltas, concurrent writes keep counts exact (postgres test). +- `votes` routes: `401`/`403`/`404`/`429`, summaries hide unreadable targets. +- Content Engine: deletion effects remove votes (extend the reactions effects test). +- Forum feed: ordering per sort on a postgres fixture. +- `VoteControl`: pressed state, rollback on error, guest prompt. + +## Open questions + +1. **Reactions in the ranking.** Votes only (proposed), or keep reactions as a + small bonus to Hot? +2. **Karma.** One reputation for reactions and votes (proposed), or a separate + "karma" number next to it? +3. **Downvotes.** Everyone by default (proposed), or off until a role allows them? +4. **Default sort.** Hot for the home feed and Best for comments (proposed), or + per forum (Active for support forums, like Invision)? From f9b5dd457a11cc2fd35c9863f8550ed964508390 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 10:46:16 +0000 Subject: [PATCH 03/10] =?UTF-8?q?docs(plans):=20=F0=9F=93=9D=20Replace=20t?= =?UTF-8?q?he=20votes=20plan=20with=20points=20from=20reactions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- plans/forum-reaction-points.md | 145 ++++++++++++++++++++ plans/forum-voting.md | 236 --------------------------------- 2 files changed, 145 insertions(+), 236 deletions(-) create mode 100644 plans/forum-reaction-points.md delete mode 100644 plans/forum-voting.md diff --git a/plans/forum-reaction-points.md b/plans/forum-reaction-points.md new file mode 100644 index 000000000..ae9f472f4 --- /dev/null +++ b/plans/forum-reaction-points.md @@ -0,0 +1,145 @@ +# Forum: points from reactions + +Status: planned, not started. Owner: `@vitnode/forum` (no core changes). + +No up/down voting and no Reddit-style rating. Members keep reacting the way +they do today, and each reaction is worth the **points** an admin gave it in +**AdminCP → Reactions** (`like` +1, `thanks` +2, `sad` 0, `disagree` -1 …). +A topic's or comment's points are the sum of its reactions' points - the same +number its author earned as reputation from it. Points rank the feed and the +comments. + +## What changes from today + +The feed (`GET /forum/feed`, Hot/New/Active/Top) already ranks by "points", +but they are a stand-in: every reaction counts `+1`, a negative reaction `-1`, +whatever its configured value, and reactions to one's own post count too. + +| Today | After | +| --------------------------------------------- | ------------------------------------------------------------- | +| `thanks` (+2) counts +1, `sad` (0) counts +1 | Each reaction counts its own `points` | +| Self reactions count | Ignored, like reputation | +| Read from `core_reactions_counts` | Read from `core_reactions_entries` (`targetAuthorId` set) | +| Card shows "N points" only | Card shows the reaction bar and a points badge | +| Topic page and comments show no points | Points next to the reaction bar | +| Comments in posting order only | Sort comments: Oldest (default), Newest, Most points | + +## Decisions + +| Topic | Decision | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Formula | `points = sum(core_reactions.points)` over the target's entries with `targetAuthorId is not null` - the exact rule of `lib/reactions/reputation.ts`, so a topic's points and its author's reputation never disagree. | +| Self reactions | Don't count (`targetAuthorId` is null for them). | +| Deleted author | `targetAuthorId` becomes null, so the topic drops to 0 points - the same as the reputation it no longer gives anyone. Accepted. | +| Disabled reaction | Still counts, as it does for reputation. Deleting the reaction removes its rows and its points. | +| Changing a reaction's points in AdminCP | Retroactive at once - points are summed on read, nothing to recount. The feed catches up within its one-minute cache bucket. | +| Hot | `engagement = points + comments`, log scale against age (unchanged formula, new points). | +| Top | Points, then comments, then newest. | +| Negative points | Allowed: a topic full of `disagree` sinks in Hot and Top. Shown with its sign (`-3`). | +| Who sees points | Anyone who can read the topic - they already see every reaction count it is made of. | +| Configuration | None new. Points per reaction and who may react stay in AdminCP → Reactions and the role's **Reactions** tab. | +| Core changes | None. Everything lives in the forum plugin; core already exposes the tables, `ReactionBar` and live counts. | + +## API + +### Shared helper + +`plugins/forum/src/api/modules/forum/lib/reaction-points.ts` + +- `reactionPointsSubquery(db, targetType)` - `{ targetId, points }` grouped per + target, `pluginId = manifest.id`, joined with `core_reactions`, filtered on + `targetAuthorId is not null`. Used by the feed ranking (topics) and the thread + (comments). Served by `core_reactions_entries_target_idx`. +- `loadReactionPoints(c, targetType, ids)` - points for one page of ids, for + routes that don't rank. + +### Feed (`lib/feed.ts`) + +Swap the `core_reactions_counts` join for `reactionPointsSubquery`. The response +field `score` is renamed `points`. Ranking cache key version goes to `2` so no +old entry is read back. + +### Topic points + +`GET /forum/stats/topics` (exists, cached per id set) gains `points` next to +`commentCount`, so the topic page and any list get them in the request they +already make. Its cache stays on the stats generation **plus** the one-minute +bucket the feed uses, since reactions don't move the generation. + +### Comment points and sorting + +`GET /forum/topics/{id}/comments/points?ids=…` → `{ id, points }[]` for the +comments on screen, `private` only when access rules apply (same headers helper +as the stats routes). + +Sorting by points ranks **root comments** only; replies stay in order under +their parent so a conversation reads top to bottom. The thread is read through +the Content Engine (`content/server/thread.ts`), which pages roots by +`createdAt asc`. Two options: + +1. **Plugin-side (proposed first):** for `?comments=points`, the forum asks + for the ranked root ids (`reactionPointsSubquery` over `forum_comments` + where `parent is null`), then reads those roots and their replies through + the thread service by ids. No core change; pages are numbered, not cursors. +2. **Core option (later, if blog wants it too):** a `sort` on `thread` reads in + the Content Engine, with the sort key in the cursor. + +## UI + +- **Feed card** (`topic-feed.tsx`): + - `ReactionBar` in the card footer, so members react straight from the feed. + Bars on one page share a single `GET /reactions?ids=…` (core batches per + type), and counts update live over the WebSocket. + - A **points badge** before the reactions: `+12` / `-3` / `0`, tinted with the + same tokens as the reputation badge (`--success` above zero, `--destructive` + below, muted at zero), the sign always written so color isn't the only cue. + `sr-only` text "12 points"; tooltip "Points from reactions". + - The "N points" text and the arrow icon go away. +- **Topic page**: the same badge next to the topic's `ReactionBar`. +- **Comments**: the badge in each comment's action row, before `ReactionBar`. +- **Sort comments**: a small select above the thread - "Oldest first" + (default), "Newest first", "Most points". In the URL as `?comments=new` / + `?comments=points`; the default isn't written. Loading a new order keeps the + current comments dimmed (`aria-busy`, `opacity-60`) until the new page lands. +- Live points: the badge recomputes from the live reaction counts the bar + already receives (`count × points` of each reaction in the catalog, minus + nothing - self reactions can't be told apart in the browser, so the live + number may be off by the author's own reactions until the next load). + Open question 2. + +## Phases + +| Phase | Scope | Done when | +| ----- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| 1 | `reaction-points.ts`, feed on real points, `score` → `points` | A topic with one `thanks` (+2) outranks one with a `like` (+1) in Top; `sad` adds nothing | +| 2 | `ReactionBar` + points badge on feed cards, badge on the topic page | Reacting from the feed updates the bar live and the badge on the next load | +| 3 | Comment points route, badge on comments | Each comment shows the points its author earned from it | +| 4 | Sort comments (Oldest / Newest / Most points) | `?comments=points` puts the most-thanked root comment first; replies keep their order | +| 5 | Docs | `guides/forum.mdx` explains points, sorting and where to set reaction points | + +Each phase ends with `pnpm lint:fix`, typecheck, the existing tests and a run +of the app with seeded reactions of different points. + +## Docs + +- `guides/forum.mdx`: "Sort the feed" says points come from reactions and links + to AdminCP → Reactions; new "Sort comments" section. +- `content-engine/reactions` (or `dev/reactions`): one line that the forum uses + reaction points for ranking, as an example of reading them. + +## Tests (a separate session, after it works) + +- Feed ranking on a postgres fixture: reaction points weigh in, self reactions + don't, negative points sink a topic, `top` windows. +- Comment points route: hidden comments and unreadable forums answer nothing. +- Comment sort: roots by points, replies in order. +- Points badge: sign and the sr-only label (DOM output only). + +## Open questions + +1. **Hot**: keep comments in Hot's engagement (`points + comments`, proposed), + or points only? +2. **Live badge**: accept that the live number may count the author's own + reactions until reload (proposed), or show the badge only from the server? +3. **Default comment order**: Oldest first (proposed, classic forum), or Most + points? diff --git a/plans/forum-voting.md b/plans/forum-voting.md deleted file mode 100644 index df47d01d0..000000000 --- a/plans/forum-voting.md +++ /dev/null @@ -1,236 +0,0 @@ -# Votes (up/down) and ranked threads - -Status: planned, not started. Owner: core (`@vitnode/api` + `@vitnode/core`), -first consumer `@vitnode/forum`. - -The forum feed (`GET /forum/feed`, Hot/New/Active/Top) ranks topics by -**points**, and today points are borrowed from reactions: every reaction is -`+1`, a negative-point reaction is `-1`. That was a stand-in. Reactions say how -someone _feels_ ("haha", "thanks"); a vote says whether something _belongs -higher up_. This plan adds votes as their own core feature and switches the -forum's ranking to them. - -## Goals - -1. **Reddit-style voting** on anything: ▲ / ▼, one vote per member per item, - click again to take it back, switch in one click. -2. **Opt in with one line**: `votes: true` on `defineContentType`, the same way - `reactions: true` and `reports: true` work. Custom targets register with - `defineVoteTarget`, like `defineReactionTarget`. -3. **Ranking source.** The forum feed, and later any "top" list, sorts by the - vote score instead of reactions. -4. **Ranked comments.** Thread roots sort by Best (default), Top, New, Old or - Controversial. -5. **Karma.** Votes feed the author's reputation, with weights an admin sets. -6. **Live.** Scores update on screen over the WebSocket when it's available, - plain HTTP otherwise - the same as reactions. - -Non-goals (first version): vote fuzzing, public lists of who voted, awards, -voting on AdminCP-only records, per-forum karma leaderboards. - -## Votes and reactions side by side - -Both stay. They answer different questions and read differently on screen. - -| | Reactions | Votes | -| -------------- | --------------------------------- | ---------------------------------------- | -| Meaning | Emotion, thanks | "Show this higher / lower" | -| Per user | Role cap, several kinds | Exactly one: `+1`, `-1` or none | -| Shown | Pills with counts, who reacted | Net score only, voters private | -| Ranking | No (after this plan) | Yes - feed, Top, Best comments | -| Reputation | Per-reaction points | Per-vote weights (default `+1` / `-1`) | - -After phase 3 the forum's points are **votes only**. Reactions remain on topics -and comments for emotion and no longer move the ranking. (Open question 1.) - -## The pattern we copy: reactions - -| Reactions | Votes | -| ---------------------------------------------------------- | ----------------------------------------------------------- | -| `defineReactionTarget` in `lib/reactions/targets.ts` | `defineVoteTarget` in `lib/votes/targets.ts` | -| `reactions: true` → `contentReactionTarget(model)` | `votes: true` → `contentVoteTarget(model)` | -| `resolveReactions` in `content/define-reactions.ts` | `resolveVotes` in `content/define-votes.ts` | -| `core_reactions_entries` / `core_reactions_counts` | `core_votes_entries` / `core_votes_counts` | -| `canReact` in `ContentViewerPermissions` | `canVote`, `canDownvote` next to it | -| `` | `` | -| WebSocket channel `reactions/live` | `votes/live` (same room per target, same `seq` rule) | -| Role tab **Reactions** | Role tab **Votes** | -| Events `reaction.added/removed/changed` | `vote.added`, `vote.removed`, `vote.changed` | - -A target is the same triple `{ pluginId, type, id }`. - -## Decisions - -| Topic | Decision | -| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Values | `1` or `-1`, stored; "no vote" is no row. `PUT` with `0` deletes. | -| Own content | Never. No self-votes, no automatic author upvote: every score starts at `0`. | -| Who votes | Role column `allowVote` (default `true`, `false` for guests). Downvoting is a separate `allowDownvote` (default `true`), so an install can keep fresh members to upvotes only. Most generous role wins. | -| Daily limit | Role column `votesPerDay` (`null` = unlimited, the default). Votes given today that still exist count, as with reactions. Toggle spam is the per-minute rate limit's job. | -| Public numbers | Net score only (`score = up - down`). Up and down counts stay on the server for ranking (Controversial, Best) and for moderators. | -| Voter privacy | Nobody sees who voted, except moderators with a new `can_view_votes` permission in ModCP (abuse checks). No timeline entries. | -| Reputation | Two settings in **AdminCP → Votes**: points per upvote (default `1`) and per downvote (default `-1`), `-10..10`, `0` turns it off. Changing them queues a recount, like reaction points. Target opt-out `votes: { reputation: false }`. | -| Hidden / locked | Unreadable or hidden targets can't be voted on; scores are kept and come back on unhide. | -| Deleted target/user | Same as reactions: target deletion effects remove votes and their reputation; a deleted user cascades and a task recounts the targets and authors. | -| Concurrency | One write path in a transaction with an advisory lock per target, like reactions, so `seq` follows commit order and counts never drift. | -| Per-forum switch | A container policy `votes: "updown" \| "up" \| "off"` (default `updown`, inherits from the parent forum), next to `publish` and `edits`. "Ask the experts" forums can go up-only; announcements can turn it off. | - -## Data model - -`packages/api/src/database/votes.ts` - -```ts -/** One member's vote on one target. */ -export const core_votes_entries = camelCase.table.withRLS( - "core_votes_entries", - t => ({ - pluginId: t.varchar({ length: 100 }).notNull(), - targetType: t.varchar({ length: 100 }).notNull(), - targetId: t.varchar({ length: CONTENT_ID_KEY_LENGTH }).notNull(), - userId: t - .integer() - .notNull() - .references(() => core_users.id, { onDelete: "cascade" }), - value: t.smallint().notNull(), // 1 | -1 - // Who collects the reputation; null with `reputation: false`. - targetAuthorId: t - .integer() - .references(() => core_users.id, { onDelete: "set null" }), - createdAt: t.timestamp().notNull().defaultNow(), - updatedAt: t.timestamp().notNull().defaultNow(), - }), - t => [ - primaryKey({ - columns: [t.pluginId, t.targetType, t.targetId, t.userId], - }), - index("core_votes_entries_user_day_idx").on(t.userId, t.createdAt), - index("core_votes_entries_author_idx").on(t.targetAuthorId), - check("core_votes_entries_value", sql`${t.value} in (-1, 1)`), - ], -); - -/** Denormalized totals, written in the same transaction as the entry. */ -export const core_votes_counts = camelCase.table.withRLS( - "core_votes_counts", - t => ({ - pluginId: t.varchar({ length: 100 }).notNull(), - targetType: t.varchar({ length: 100 }).notNull(), - targetId: t.varchar({ length: CONTENT_ID_KEY_LENGTH }).notNull(), - upvotes: t.integer().notNull().default(0), - downvotes: t.integer().notNull().default(0), - score: t.integer().notNull().default(0), // upvotes - downvotes - version: t.bigint({ mode: "number" }).notNull().default(0), - }), - t => [ - primaryKey({ columns: [t.pluginId, t.targetType, t.targetId] }), - // "Top" without scanning every target of a type. - index("core_votes_counts_score_idx").on(t.pluginId, t.targetType, t.score), - ], -); -``` - -Role columns (`core_roles`): `allowVote`, `allowDownvote`, `votesPerDay`. -Settings (`core_site` or the existing settings store): `votes.upvotePoints`, -`votes.downvotePoints`. Migration: guest role gets `allowVote = false`. - -## API (core module `votes`) - -| Route | What | -| --------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `PUT /votes` | `{ target, value: 1 \| -1 \| 0 }` → new public summary. `401` guest, `403` role/policy/own content, `404` unreadable target, `429` daily limit. | -| `GET /votes/summaries?pluginId&type&ids` | Public `{ id, score, seq }[]` for up to 100 ids. Cacheable; unreadable ids answer as score `0`. | -| `GET /votes/me?pluginId&type&ids` | The viewer's own `{ id, value }[]`, `private, no-store` - asked in the browser, like `/permissions`. | -| `GET /admin/votes/settings`, `PUT` | Reputation weights. Staff permission. | -| `GET /moderation/votes/{target}` | Voters of one target for moderators with `can_view_votes`. | - -Every write emits `vote.added` / `vote.changed` / `vote.removed` and, when -reputation moves, the existing `reputation.changed`. Documented in -`apps/web/content/docs/dev/events/built-in-events.mdx`. - -## UI (`@vitnode/core/components/votes`) - -- ``: ▲ score ▼. - Buttons with `aria-pressed` and labels ("Upvote", "Remove upvote"…), score - in `ShortNumber` with a polite live region. Optimistic update, rolled back - with a `sonner` toast on error; `isLoading` on the pressed button while - sending. Disabled ▼ with a tooltip when the role or forum is up-only. -- Guests see the score; a click opens the sign-in prompt. -- Own content: score shown, buttons disabled with "You can't vote on your own post". -- Colors from tokens only (`text-primary` up, `text-destructive` down), the - direction also given by the icon fill, never color alone. -- Batched reads: one `summaries` + one `me` request per page, shared through - TanStack Query keys per target type, like reaction summaries. - -## Forum changes - -1. `votes: true` on `forum.topic` and `forum.comment`. -2. **Feed ranking** (`plugins/forum/src/api/modules/forum/lib/feed.ts`): - points = `core_votes_counts.score` instead of the reactions join. - - Hot: `sign(s) * log10(max(|s|, 1)) + epoch / 45000` with `s = score` - (comments no longer inflate it - a flame war is not "hot" by itself). - - Top: `score`, then `upvotes`. - - New sort **Controversial**: `(up + down) ^ (min(up, down) / max(up, down))` - for items with both, like Reddit. - - The ranking cache keeps its one-minute bucket; a vote moves a score within - a minute, which is fine for a feed. -3. **Feed card**: `VoteControl` vertical on the left from `md`, horizontal in - the footer on phones; the "points" text goes away. -4. **Topic page**: `VoteControl` next to the title. -5. **Comments**: `VoteControl` in each comment's action row. - -## Comment sorting (Content Engine `thread`) - -Today thread roots are paged by `createdAt asc` -(`packages/api/src/content/server/thread.ts`). Add a `sort` to the thread -read: `best` (default when the type has votes), `top`, `new`, `old`, -`controversial`. - -- **Best** is the Wilson score lower bound (95%) of `up / (up + down)`, so one - lone upvote doesn't beat 40 up and 2 down. A pure function - `wilsonLowerBound(up, down)` in `@vitnode/api/lib/votes/rank.ts`, mirrored in - SQL for ordering. -- Only **roots** are reordered and paged; replies keep chronological order - under their parent (readable conversations), as Reddit does for deep levels. -- The cursor encodes the sort key + id, so pages stay stable while scores move. -- The topic page gets a "Sort comments" select; the choice lives in the URL - (`?comments=top`), the default isn't written. - -## Phases - -| Phase | Scope | Done when | -| ----- | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | -| 1 | Tables, migration, `lib/votes` service (write, limits, reputation, deletion), targets registry, `votes: true` in the Content Engine, API routes, events | `PUT /votes` works for a forum topic from curl; reputation moves; deleting the topic cleans up | -| 2 | Role **Votes** tab, AdminCP **Votes** settings Sheet, per-forum `votes` policy | An up-only forum refuses `-1` with `403`; a role without votes sees disabled buttons | -| 3 | `VoteControl`, live channel `votes/live`, forum feed on votes, feed card + topic page + comments | Two browsers see each other's votes live; the feed reorders within a minute | -| 4 | Thread `sort` (Best/Top/New/Old/Controversial), Controversial in the feed | A 40↑/2↓ comment sits above a 1↑/0↓ one under Best | -| 5 | ModCP voters list (`can_view_votes`), docs | Docs pages below are live | - -Each phase ends with `pnpm lint:fix`, typecheck, the existing tests and a run of -the app with seeded data. - -## Docs - -- `content-engine/votes.mdx`: `votes: true`, options, `canVote`, `VoteControl`. -- `dev/votes/*`: `defineVoteTarget` for custom targets, the API, the events. -- `guides/forum.mdx`: points are votes, the per-forum switch, comment sorting. -- `dev/events/built-in-events.mdx`: `vote.*`. - -## Tests (a separate session, after it works) - -- `lib/votes/rank.test.ts`: `wilsonLowerBound`, controversy - one `it.each`. -- Service: add/switch/remove, no self-vote, `allowDownvote`, daily limit, - reputation deltas, concurrent writes keep counts exact (postgres test). -- `votes` routes: `401`/`403`/`404`/`429`, summaries hide unreadable targets. -- Content Engine: deletion effects remove votes (extend the reactions effects test). -- Forum feed: ordering per sort on a postgres fixture. -- `VoteControl`: pressed state, rollback on error, guest prompt. - -## Open questions - -1. **Reactions in the ranking.** Votes only (proposed), or keep reactions as a - small bonus to Hot? -2. **Karma.** One reputation for reactions and votes (proposed), or a separate - "karma" number next to it? -3. **Downvotes.** Everyone by default (proposed), or off until a role allows them? -4. **Default sort.** Hot for the home feed and Best for comments (proposed), or - per forum (Active for support forums, like Invision)? From 5ade7586f85bbb8d195235f383ebf6834240cd08 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 10:58:44 +0000 Subject: [PATCH 04/10] =?UTF-8?q?feat(forum):=20=E2=9C=A8=20Points=20from?= =?UTF-8?q?=20reactions,=20reactions=20on=20feed=20cards=20and=20comment?= =?UTF-8?q?=20sorting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Points are each reaction's count times its points from AdminCP → Reactions (enabled reactions), the same sum the reaction pills show; the feed ranks by them (Hot still adds comments) - Feed cards get the reaction bar and a live points badge; the topic page and every comment show the badge too - Comments sort by Oldest (default), Newest or Most points; only top-level comments move, replies stay under their parent - New `GET /forum/topics/{id}/comments/order` route; branches are read through the Content Engine's `/thread/branches` - Document points and comment sorting in the forum guide Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- apps/web/content/docs/guides/forum.mdx | 32 ++-- plans/forum-reaction-points.md | 22 ++- .../src/api/modules/forum/forum.module.ts | 2 + .../forum/src/api/modules/forum/lib/feed.ts | 52 ++---- .../api/modules/forum/lib/reaction-points.ts | 45 ++++++ .../forum/routes/list-comment-order.route.ts | 149 ++++++++++++++++++ .../modules/forum/routes/list-feed.route.ts | 6 +- plugins/forum/src/feed-sorts.ts | 23 ++- plugins/forum/src/locales/en.json | 13 +- plugins/forum/src/pages/forum-data.ts | 2 +- plugins/forum/src/pages/forum-links.ts | 32 +++- plugins/forum/src/pages/forum-queries.ts | 19 ++- plugins/forum/src/pages/reaction-points.tsx | 114 ++++++++++++++ plugins/forum/src/pages/thread-data.ts | 133 ++++++++++++++-- plugins/forum/src/pages/thread.tsx | 112 +++++++++++-- plugins/forum/src/pages/topic-feed.tsx | 48 +++--- plugins/forum/src/pages/topic-page.tsx | 27 +++- 17 files changed, 717 insertions(+), 114 deletions(-) create mode 100644 plugins/forum/src/api/modules/forum/lib/reaction-points.ts create mode 100644 plugins/forum/src/api/modules/forum/routes/list-comment-order.route.ts create mode 100644 plugins/forum/src/pages/reaction-points.tsx diff --git a/apps/web/content/docs/guides/forum.mdx b/apps/web/content/docs/guides/forum.mdx index 80171e275..ad6f74611 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -111,7 +111,8 @@ deep, and you can drag them to reorder. A forum's **Icon** accepts the same `/forum` works like a Reddit front page: one feed of topics from every forum the visitor may read, with the forum tree beside it (a row of forum chips on phones). Each forum page shows its own topics the same way. Every topic card -has its forum, author, age, title, a short excerpt, its points and comments. +has its forum, author, age, title, a short excerpt, its points, its reactions - +members react right from the feed - and its comments. | Sort | URL | Shows first | | ------ | ------------------ | ------------------------------------------------------------ | @@ -120,16 +121,10 @@ has its forum, author, age, title, a short excerpt, its points and comments. | Active | `?sort=active` | Topics with the latest comment, like a classic forum | | Top | `?sort=top&t=week` | The most points today, this week, month or year, or all time | -**Points** are a topic's reactions: every reaction adds one, and a reaction -worth negative points in **AdminCP → Reactions** (like "Disagree") takes one -away. **Hot** adds comments to the points and weighs them on a log scale -against age, so ten times the engagement buys a topic about 12.5 hours of -freshness. A brilliant topic from last month politely makes room for today's. - Pages go `?page=2` and on, up to page 40. The ranking is shared by everyone and cached for a minute; a new topic or comment refreshes it at once, a new -reaction within a minute. Topics in forums the visitor cannot read never make -it into their feed. +reaction - or a new value for a reaction in AdminCP - within a minute. Topics +in forums the visitor cannot read never make it into their feed. Need the feed in your own component? Call the same route: @@ -147,8 +142,27 @@ const res = await fetcher({ Add `forumId` to the query for one forum's topics only. +## Points come from reactions + +There is no up/down voting. A topic's or comment's **points** are its +reactions, each worth what you set in **AdminCP → Reactions**. Say `like` is +worth 1, `thanks` 2, `sad` 0 and `disagree` -1: a topic with three likes and +one thanks has 5 points. In other words, points are exactly what the +reaction pills under a post add up to, and they update live as people react. +Disabled reactions don't count. + +**Hot** adds the comment count to the points and weighs the sum on a log scale +against age, so ten times the engagement buys a topic about 12.5 hours of +freshness. A brilliant topic from last month politely makes room for today's. + ## Comments +Comments come in posting order, like a classic forum. Above them, readers can +switch to **Newest** (`?comments=new`) or **Most points** +(`?comments=points`). Only top-level comments move; replies stay under their +parent in the order they were written, so a conversation still reads top to +bottom. Every comment shows its points next to its reactions. + Comments nest up to six levels - hit **Reply** under any comment to answer it. On small screens deep comments stop indenting, so the text keeps its width, and every branch can be collapsed. A comment removed by a moderator stays as "This diff --git a/plans/forum-reaction-points.md b/plans/forum-reaction-points.md index ae9f472f4..ef5de62ef 100644 --- a/plans/forum-reaction-points.md +++ b/plans/forum-reaction-points.md @@ -1,6 +1,26 @@ # Forum: points from reactions -Status: planned, not started. Owner: `@vitnode/forum` (no core changes). +Status: implemented (phases 1-5); tests still to write in a separate session. +Owner: `@vitnode/forum` (no core changes). + +## Implemented differently from this plan + +- **Points are what the pills add up to**, read from `core_reactions_counts` + (`count × points`, enabled reactions only) - not from the entries with a + `targetAuthorId`. The reputation rule (no self reactions) can't be followed + in the browser, so the live badge and the ranking disagreed whenever an + author reacted to their own post (only possible when a role allows it). + Counting what readers see keeps both the same. +- **No topic or comment points route.** The badge (`ReactionPoints`) reads the + reaction summary and catalog `ReactionBar` already loads, read-only + (`enabled: false`): fetching them itself made the bar hydrate with data the + server never rendered. Feed cards pass the ranking's number as `initial`. +- **Comment order**: `GET /forum/topics/{id}/comments/order?sort=new|points` + returns root ids with an offset cursor; the browser reads them through + `/content/comments/thread/branches`, ten per request. Hidden roots are left + out of the sorted views, also for moderators. +- Decisions taken: Hot keeps comments in its engagement; comments default to + oldest first. No up/down voting and no Reddit-style rating. Members keep reacting the way they do today, and each reaction is worth the **points** an admin gave it in diff --git a/plugins/forum/src/api/modules/forum/forum.module.ts b/plugins/forum/src/api/modules/forum/forum.module.ts index 48d12890d..204e4b4e7 100644 --- a/plugins/forum/src/api/modules/forum/forum.module.ts +++ b/plugins/forum/src/api/modules/forum/forum.module.ts @@ -1,6 +1,7 @@ import { buildModule } from "@/api/builders"; import { forumStatsEventListeners } from "@/api/lib/events"; +import { commentOrderRoute } from "./routes/list-comment-order.route"; import { forumFeedRoute } from "./routes/list-feed.route"; import { forumStatsRoute } from "./routes/list-forum-stats.route"; import { topicStatsRoute } from "./routes/list-topic-stats.route"; @@ -10,6 +11,7 @@ import { topicSlugRoute } from "./routes/show-topic-slug.route"; export const forumModule = buildModule({ name: "forum", routes: [ + commentOrderRoute, forumFeedRoute, forumStatsRoute, topicStatsRoute, diff --git a/plugins/forum/src/api/modules/forum/lib/feed.ts b/plugins/forum/src/api/modules/forum/lib/feed.ts index 97930994d..d99dfbbad 100644 --- a/plugins/forum/src/api/modules/forum/lib/feed.ts +++ b/plugins/forum/src/api/modules/forum/lib/feed.ts @@ -1,10 +1,6 @@ import type { SQL } from "drizzle-orm"; import type { Context } from "hono"; -import { - core_reactions, - core_reactions_counts, -} from "@vitnode/api/database/reactions"; import { and, count, desc, eq, gte, max, sql } from "drizzle-orm"; import { z } from "zod"; @@ -16,9 +12,9 @@ import { topicContentType } from "@/content/topic"; import { commentContent } from "@/database/comments"; import { topicContent } from "@/database/topics"; import { FORUM_FEED_MAX_PAGES, FORUM_FEED_PAGE_SIZE } from "@/feed-sorts"; -import { manifest } from "@/manifest.gen"; import { publicComment, publicTopic } from "./public-condition"; +import { reactionPointsSubquery } from "./reaction-points"; import { iso } from "./stats"; export const FORUM_FEED_MAX_RANKED = @@ -49,7 +45,7 @@ const zodRankedTopic = z.object({ forum: z.number().int(), id: z.number().int(), lastActivityAt: z.iso.datetime().nullable(), - score: z.number().int(), + points: z.number().int(), }); export type RankedTopic = z.infer; @@ -61,7 +57,7 @@ export type RankedTopic = z.infer; */ const feedRankingCache = defineCacheEntry({ name: "feed.ranking", - version: 1, + version: 2, key: ( generation: string, bucket: number, @@ -100,45 +96,27 @@ const rankTopics = async ( .groupBy(comments.topic) .as("forum_feed_comment_stats"); - // A reaction worth negative points (a dislike) pulls the score down; every - // other reaction counts as one point up. - const reactionStats = db - .select({ - score: - sql`coalesce(sum(case when ${core_reactions.points} < 0 then -${core_reactions_counts.count} else ${core_reactions_counts.count} end), 0)::int`.as( - "score", - ), - targetId: core_reactions_counts.targetId, - }) - .from(core_reactions_counts) - .innerJoin( - core_reactions, - eq(core_reactions_counts.reactionId, core_reactions.id), - ) - .where( - and( - eq(core_reactions_counts.pluginId, manifest.id), - eq(core_reactions_counts.targetType, topicContentType.id), - ), - ) - .groupBy(core_reactions_counts.targetId) - .as("forum_feed_reaction_stats"); + const reactionPoints = reactionPointsSubquery( + c, + topicContentType.id, + "forum_feed_reaction_points", + ); const commentCount = sql`coalesce(${commentStats.commentCount}, 0)::int`; - const score = sql`coalesce(${reactionStats.score}, 0)::int`; + const points = sql`coalesce(${reactionPoints.points}, 0)::int`; // `greatest` skips nulls: a topic without comments was last active when it // was published. const lastActivityAt = sql< Date | null | string >`greatest(${topics.publishedAt}, ${commentStats.lastCommentAt})`; - const engagement = sql`(${score} + ${commentCount})`; + const engagement = sql`(${points} + ${commentCount})`; const hot = sql`sign(${engagement}) * log(greatest(abs(${engagement}), 1)) + extract(epoch from ${topics.publishedAt}) / ${HOT_DECAY_SECONDS}`; const order: SQL[] = { active: [desc(lastActivityAt)], hot: [desc(hot)], new: [desc(topics.publishedAt)], - top: [desc(score), desc(commentCount), desc(topics.publishedAt)], + top: [desc(points), desc(commentCount), desc(topics.publishedAt)], }[sort]; const rows = await db @@ -147,13 +125,13 @@ const rankTopics = async ( forum: topics.forum, id: topics.id, lastActivityAt, - score, + points, }) .from(topics) .leftJoin(commentStats, eq(commentStats.topicId, topics.id)) .leftJoin( - reactionStats, - eq(reactionStats.targetId, sql`cast(${topics.id} as varchar)`), + reactionPoints, + eq(reactionPoints.targetId, sql`cast(${topics.id} as varchar)`), ) .where( and( @@ -175,7 +153,7 @@ const rankTopics = async ( forum: row.forum, id: row.id, lastActivityAt: iso(row.lastActivityAt), - score: row.score, + points: row.points, })); }; diff --git a/plugins/forum/src/api/modules/forum/lib/reaction-points.ts b/plugins/forum/src/api/modules/forum/lib/reaction-points.ts new file mode 100644 index 000000000..3ba14aa46 --- /dev/null +++ b/plugins/forum/src/api/modules/forum/lib/reaction-points.ts @@ -0,0 +1,45 @@ +import type { Context } from "hono"; + +import { + core_reactions, + core_reactions_counts, +} from "@vitnode/api/database/reactions"; +import { and, eq, sql } from "drizzle-orm"; + +import { manifest } from "@/manifest.gen"; + +/** + * Points per target of one forum content type: each reaction's count times + * its points, as set in AdminCP → Reactions - exactly what the reaction pills + * under the item add up to, so the number a reader sees and the one the feed + * ranks by never disagree. Disabled reactions are left out, as the pills leave + * them out. Read from the denormalized counts. + */ +export const reactionPointsSubquery = ( + c: Context, + targetType: string, + alias: string, +) => + c + .get("db") + .select({ + points: + sql`coalesce(sum(${core_reactions_counts.count} * ${core_reactions.points}), 0)::int`.as( + "points", + ), + targetId: core_reactions_counts.targetId, + }) + .from(core_reactions_counts) + .innerJoin( + core_reactions, + eq(core_reactions_counts.reactionId, core_reactions.id), + ) + .where( + and( + eq(core_reactions_counts.pluginId, manifest.id), + eq(core_reactions_counts.targetType, targetType), + eq(core_reactions.enabled, true), + ), + ) + .groupBy(core_reactions_counts.targetId) + .as(alias); diff --git a/plugins/forum/src/api/modules/forum/routes/list-comment-order.route.ts b/plugins/forum/src/api/modules/forum/routes/list-comment-order.route.ts new file mode 100644 index 000000000..ef1f01e6b --- /dev/null +++ b/plugins/forum/src/api/modules/forum/routes/list-comment-order.route.ts @@ -0,0 +1,149 @@ +import type { PgColumn } from "drizzle-orm/pg-core"; + +import { z } from "@hono/zod-openapi"; +import { CONTENT_PUBLIC_MAX_PAGE_SIZE } from "@vitnode/api/content"; +import { + and, + asc, + count, + desc, + eq, + isNotNull, + isNull, + lte, + sql, +} from "drizzle-orm"; +import { HTTPException } from "hono/http-exception"; + +import { buildRoute } from "@/api/builders"; +import { commentContentType } from "@/content/comment"; +import { commentContent } from "@/database/comments"; +import { topicContent } from "@/database/topics"; + +import { json } from "../lib/json-response"; +import { reactionPointsSubquery } from "../lib/reaction-points"; + +/** + * Top-level comments a reader can find in the thread: published, not hidden. + * Deleted ones stay in - the thread keeps them as "removed" placeholders while + * they have replies, and drops the rest itself. + */ +const rootCondition = (topicId: number) => { + const columns = commentContent.columns as Record; + const comments = commentContent.table; + + return and( + eq(comments.topic, topicId), + isNull(comments.parent), + eq(columns.status, "published"), + isNotNull(columns.publishedAt), + lte(columns.publishedAt, sql`now()`), + isNull(columns.hiddenAt), + ); +}; + +/** + * The ids of one page of a topic's top-level comments, newest first or by + * points from reactions. The thread's own `/thread` route reads the default + * posting order; this one only decides the order - the browser reads the + * branches themselves through `/content/comments/thread/branches`, which + * applies every visibility rule again. + */ +export const commentOrderRoute = buildRoute({ + route: { + method: "get", + path: "/topics/{id}/comments/order", + description: + "The ids of one page of a topic's top-level comments, newest first or with the most points from reactions first", + request: { + params: z.object({ + id: z.coerce.number().int().positive().openapi({ example: 1 }), + }), + query: z.object({ + after: z.coerce + .number() + .int() + .min(0) + .max(100_000) + .default(0) + .openapi({ description: "How many top-level comments to skip." }), + first: z.coerce + .number() + .int() + .min(1) + .max(CONTENT_PUBLIC_MAX_PAGE_SIZE) + .default(20), + sort: z.enum(["new", "points"]), + }), + }, + responses: { + 200: json( + z.object({ + ids: z.array(z.number()), + pageInfo: z.object({ + endCursor: z.string().nullable(), + hasNextPage: z.boolean(), + totalCount: z.number(), + }), + }), + "Top-level comment ids in order", + ), + 404: { description: "No topic the viewer may read" }, + }, + }, + handler: async c => { + const { id } = c.req.valid("param"); + const { after, first, sort } = c.req.valid("query"); + + // The public service applies publication and the forum's access rules. + const topic = await topicContent.publicService?.(c).findById(id); + if (!topic) throw new HTTPException(404, { message: "Topic not found." }); + + const db = c.get("db"); + const comments = commentContent.table; + const columns = commentContent.columns as Record; + const where = rootCondition(id); + + const reactionPoints = reactionPointsSubquery( + c, + commentContentType.id, + "forum_comment_reaction_points", + ); + const points = sql`coalesce(${reactionPoints.points}, 0)`; + + const [rows, [total]] = await Promise.all([ + db + .select({ id: comments.id }) + .from(comments) + .leftJoin( + reactionPoints, + eq(reactionPoints.targetId, sql`cast(${comments.id} as varchar)`), + ) + .where(where) + .orderBy( + ...(sort === "points" + ? [desc(points), asc(columns.publishedAt), asc(comments.id)] + : [desc(columns.publishedAt), desc(comments.id)]), + ) + .limit(first + 1) + .offset(after), + db.select({ value: count() }).from(comments).where(where), + ]); + + const hasNextPage = rows.length > first; + + return c.json( + { + ids: rows.slice(0, first).map(row => row.id), + pageInfo: { + endCursor: hasNextPage ? String(after + first) : null, + hasNextPage, + totalCount: total?.value ?? 0, + }, + }, + 200, + // Reactions move the order without expiring any cache tag. + { "Cache-Control": "private, no-store" }, + ); + }, +}); diff --git a/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts b/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts index 31df502a6..1c19159ac 100644 --- a/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts +++ b/plugins/forum/src/api/modules/forum/routes/list-feed.route.ts @@ -42,7 +42,7 @@ const excerptOf = (body: unknown): string => { /** * One page of a topic feed - every forum the viewer may read, or one forum - * ranked `hot`, `new`, `active` or `top`. Each topic comes with a plain-text - * excerpt of its body, its reaction score and its public comment stats. + * excerpt of its body, its points from reactions and its public comment stats. */ export const forumFeedRoute = buildRoute({ route: { @@ -82,8 +82,8 @@ export const forumFeedRoute = buildRoute({ forum: z.number(), id: z.number(), lastActivityAt: z.string().nullable(), + points: z.number(), publishedAt: z.string().nullable(), - score: z.number(), slug: z.string(), title: z.string(), }), @@ -170,8 +170,8 @@ export const forumFeedRoute = buildRoute({ forum: row.forum, id: row.id, lastActivityAt: item.lastActivityAt, + points: item.points, publishedAt: iso(row.publishedAt), - score: item.score, slug: row.slug, title: row.title, }, diff --git a/plugins/forum/src/feed-sorts.ts b/plugins/forum/src/feed-sorts.ts index 05a672232..ed1a8f712 100644 --- a/plugins/forum/src/feed-sorts.ts +++ b/plugins/forum/src/feed-sorts.ts @@ -1,12 +1,12 @@ /** * How a topic feed is ordered - the forum home and every forum page. * - * - `hot`: engagement (reaction score plus comments) on a log scale, with newer + * - `hot`: engagement (points from reactions plus comments) on a log scale, with newer * topics ahead, so a busy topic from this morning beats a busier one from * last month. * - `new`: newest first. * - `active`: the latest comment (or the topic itself) first. - * - `top`: the highest reaction score within {@link ForumFeedTopWindow}. + * - `top`: the most points from reactions within {@link ForumFeedTopWindow}. */ export const FORUM_FEED_SORTS = ["hot", "new", "active", "top"] as const; @@ -44,3 +44,22 @@ export const isForumFeedTopWindow = ( ): value is ForumFeedTopWindow => typeof value === "string" && (FORUM_FEED_TOP_WINDOWS as readonly string[]).includes(value); + +/** + * How a topic's comments are ordered. Only top-level comments move; replies + * stay in posting order under their parent, so a conversation reads top to + * bottom. + * + * - `old`: posting order, like a classic forum - the default. + * - `new`: newest first. + * - `points`: most points from reactions first. + */ +export const FORUM_COMMENT_SORTS = ["old", "new", "points"] as const; + +export type ForumCommentSort = (typeof FORUM_COMMENT_SORTS)[number]; + +export const FORUM_COMMENT_DEFAULT_SORT: ForumCommentSort = "old"; + +export const isForumCommentSort = (value: unknown): value is ForumCommentSort => + typeof value === "string" && + (FORUM_COMMENT_SORTS as readonly string[]).includes(value); diff --git a/plugins/forum/src/locales/en.json b/plugins/forum/src/locales/en.json index 7707008d9..53878b58c 100644 --- a/plugins/forum/src/locales/en.json +++ b/plugins/forum/src/locales/en.json @@ -113,7 +113,6 @@ "year": "This year", "all": "All time" }, - "score": "{count, plural, one {# point} other {# points}}", "empty_top": { "title": "Nothing at the top yet", "desc": "No topics were posted in this time range. Pick a longer one, or post something worth climbing the charts." @@ -121,6 +120,10 @@ "previous": "Previous", "next": "Next", "page": "Page {page}" + }, + "points": { + "unit": "{count, plural, one {point} other {points}}", + "hint": "Points from reactions to this post" } }, "topics": { @@ -269,7 +272,13 @@ "someone": "this comment", "removed": "This comment was removed.", "show_answers": "{count, plural, one {Show # reply} other {Show # replies}}", - "hide_answers": "{count, plural, one {Hide # reply} other {Hide # replies}}" + "hide_answers": "{count, plural, one {Hide # reply} other {Hide # replies}}", + "sort": { + "label": "Sort comments", + "old": "Oldest", + "new": "Newest", + "points": "Most points" + } }, "pending": { "title": "My posts awaiting approval", diff --git a/plugins/forum/src/pages/forum-data.ts b/plugins/forum/src/pages/forum-data.ts index 539e5ea14..366902404 100644 --- a/plugins/forum/src/pages/forum-data.ts +++ b/plugins/forum/src/pages/forum-data.ts @@ -60,8 +60,8 @@ export const zodFeedTopic = z.object({ forum: z.number(), id: z.number(), lastActivityAt: z.string().nullable(), + points: z.number(), publishedAt: z.string().nullable(), - score: z.number(), slug: z.string(), title: z.string(), }); diff --git a/plugins/forum/src/pages/forum-links.ts b/plugins/forum/src/pages/forum-links.ts index 3252c5b26..256cbf8be 100644 --- a/plugins/forum/src/pages/forum-links.ts +++ b/plugins/forum/src/pages/forum-links.ts @@ -1,9 +1,14 @@ -import type { ForumFeedSort, ForumFeedTopWindow } from "@/feed-sorts"; +import type { + ForumCommentSort, + ForumFeedSort, + ForumFeedTopWindow, +} from "@/feed-sorts"; import { FORUM_FEED_DEFAULT_SORT, FORUM_FEED_DEFAULT_TOP_WINDOW, FORUM_FEED_MAX_PAGES, + isForumCommentSort, isForumFeedSort, isForumFeedTopWindow, } from "@/feed-sorts"; @@ -75,17 +80,32 @@ export const forumHref = (slug: string, search: ForumSearch = {}): string => `${FORUM_HREF}/${encodeURIComponent(slug)}${feedQueryString(search)}`; export interface TopicSearch { + /** How the top-level comments are ordered; posting order without it. */ + comments?: Exclude; created?: true; } -export const topicSearch = (input: Record): TopicSearch => - isTrue(input.created) ? { created: true } : {}; +export const topicSearch = (input: Record): TopicSearch => { + const search: TopicSearch = {}; + if (isTrue(input.created)) search.created = true; + if (isForumCommentSort(input.comments) && input.comments !== "old") { + search.comments = input.comments; + } + + return search; +}; export const topicHref = ( slug: string, - { created }: TopicSearch = {}, -): string => - `${FORUM_HREF}/topics/${encodeURIComponent(slug)}${created ? "?created=true" : ""}`; + { comments, created }: TopicSearch = {}, +): string => { + const params = new URLSearchParams(); + if (comments) params.set("comments", comments); + if (created) params.set("created", "true"); + const query = params.toString(); + + return `${FORUM_HREF}/topics/${encodeURIComponent(slug)}${query ? `?${query}` : ""}`; +}; export const commentAnchorId = (commentSlug: string): string => `comment-${commentSlug}`; diff --git a/plugins/forum/src/pages/forum-queries.ts b/plugins/forum/src/pages/forum-queries.ts index 23f3b5077..be829e5d2 100644 --- a/plugins/forum/src/pages/forum-queries.ts +++ b/plugins/forum/src/pages/forum-queries.ts @@ -9,7 +9,10 @@ import { import { fetcher } from "@vitnode/core/tanstack/fetcher"; import { z } from "zod"; +import type { ForumCommentSort } from "@/feed-sorts"; + import { + FORUM_COMMENT_DEFAULT_SORT, FORUM_FEED_DEFAULT_SORT, FORUM_FEED_DEFAULT_TOP_WINDOW, } from "@/feed-sorts"; @@ -18,7 +21,7 @@ import { manifest } from "@/manifest.gen"; import type { ForumSearch } from "./forum-links"; import { fetchForums, fetchForumStats, zodFeedTopic } from "./forum-data"; -import { fetchThreadPage } from "./thread-data"; +import { fetchSortedThreadPage } from "./thread-data"; const FORUM_TREE_STALE_TIME = RECORD_STALE_TIME; @@ -45,7 +48,10 @@ export const forumQueryKeys = { pending: (userId: number, page: number) => [...submissions, userId, { page }] as const, submissions: () => submissions, - thread: (topicId: number) => [...all, "thread", topicId] as const, + thread: (topicId: number, sort?: ForumCommentSort) => + sort === undefined + ? ([...all, "thread", topicId] as const) + : ([...all, "thread", topicId, sort] as const), topic: (slug: string) => [...topicDetails, slug] as const, topicDetails: () => topicDetails, topicList: (request: FeedRequest) => [...topicLists, request] as const, @@ -164,11 +170,14 @@ export const queryForum = async ( return data; }; -export const threadQueryOptions = (topicId: number) => +export const threadQueryOptions = ( + topicId: number, + sort: ForumCommentSort = FORUM_COMMENT_DEFAULT_SORT, +) => queryOptions({ meta: LOADER_DATA_QUERY_META, - queryFn: async () => await fetchThreadPage({ topicId }), - queryKey: forumQueryKeys.thread(topicId), + queryFn: async () => await fetchSortedThreadPage({ sort, topicId }), + queryKey: forumQueryKeys.thread(topicId, sort), staleTime: FORUM_ACTIVITY_STALE_TIME, }); diff --git a/plugins/forum/src/pages/reaction-points.tsx b/plugins/forum/src/pages/reaction-points.tsx new file mode 100644 index 000000000..10ef31b67 --- /dev/null +++ b/plugins/forum/src/pages/reaction-points.tsx @@ -0,0 +1,114 @@ +import type { ContentTarget } from "@vitnode/core/content"; +import type { + ReactionsCatalog, + ReactionSummary, +} from "@vitnode/core/tanstack/reactions"; + +import { useQuery } from "@tanstack/react-query"; +import { FEEDBACK_TONE_TEXT } from "@vitnode/core/components/ui/feedback-tone"; +import { ShortNumber } from "@vitnode/core/components/ui/short-number"; +import { Skeleton } from "@vitnode/core/components/ui/skeleton"; +import { useSessionQuery } from "@vitnode/core/tanstack/auth"; +import { + reactionsCatalogQueryOptions, + reactionSummaryQueryOptions, +} from "@vitnode/core/tanstack/reactions"; +import { cn } from "cn"; +import { useTranslations } from "use-intl"; + +/** + * Points from the reactions on screen: each reaction's count times its points + * from the catalog - the same sum the server ranks by. + */ +export const pointsFromSummary = ( + summary: Pick, + catalog: Pick, +): number => { + const pointsOf = new Map(catalog.items.map(item => [item.code, item.points])); + + return summary.counts.reduce( + (sum, { code, count }) => sum + count * (pointsOf.get(code) ?? 0), + 0, + ); +}; + +export const PointsBadge = ({ + className, + value, +}: { + className?: string; + value: number; +}) => { + const t = useTranslations("@vitnode/forum.forums.points"); + + return ( + 0 && [ + FEEDBACK_TONE_TEXT.success, + "bg-success/10 dark:bg-success/20", + ], + value < 0 && [ + FEEDBACK_TONE_TEXT.destructive, + "bg-destructive/10 dark:bg-destructive/20", + ], + value === 0 && "bg-muted text-muted-foreground", + className, + )} + title={t("hint")} + > + + {t("unit", { count: value })} + + ); +}; + +/** + * The points of one topic or comment, live. Render it next to the item's + * `ReactionBar`: it reads the summary and catalog the bar loads (it never + * fetches them itself) and follows the bar's live counts. Until they load it + * shows `initial`, the server's number, or a placeholder of the same size. + */ +export const ReactionPoints = ({ + className, + initial, + target, +}: { + className?: string; + initial?: number; + target: ContentTarget; +}) => { + const session = useSessionQuery(); + const viewerId = session.data?.user?.id ?? null; + // Read-only: the `ReactionBar` next to it fetches both, after hydration. A + // fetch started here could land before the bar hydrates and make it render + // something the server did not. + const summary = useQuery({ + ...reactionSummaryQueryOptions(target, viewerId), + enabled: false, + }); + const catalog = useQuery({ + ...reactionsCatalogQueryOptions(viewerId), + enabled: false, + }); + + if (summary.data && catalog.data) { + return ( + + ); + } + + if (initial !== undefined) { + return ; + } + + return ; +}; diff --git a/plugins/forum/src/pages/thread-data.ts b/plugins/forum/src/pages/thread-data.ts index 4588c6469..63d4abd5a 100644 --- a/plugins/forum/src/pages/thread-data.ts +++ b/plugins/forum/src/pages/thread-data.ts @@ -2,6 +2,9 @@ import { zodRichTextDocument } from "@vitnode/core/content"; import { fetcher } from "@vitnode/core/tanstack/fetcher"; import { z } from "zod"; +import type { ForumCommentSort } from "@/feed-sorts"; + +import { FORUM_COMMENT_DEFAULT_SORT } from "@/feed-sorts"; import { manifest } from "@/manifest.gen"; import { zodPerson } from "./forum-data"; @@ -30,17 +33,17 @@ const zodComment = z.object({ export type ThreadComment = z.infer; +const zodThreadNode = z.object({ + depth: z.number(), + id: z.number(), + parentId: z.number().nullable(), + record: zodComment.nullable(), + removed: z.boolean(), +}); + const zodThreadPage = z .object({ - items: z.array( - z.object({ - depth: z.number(), - id: z.number(), - parentId: z.number().nullable(), - record: zodComment.nullable(), - removed: z.boolean(), - }), - ), + items: z.array(zodThreadNode), pageInfo: z.object({ endCursor: z.string().nullable(), hasNextPage: z.boolean(), @@ -87,6 +90,118 @@ export const fetchThreadPage = async ({ return zodThreadPage.parse(await res.json()); }; +/** `CONTENT_THREAD_BRANCHES_MAX` - the most branches one `/thread/branches` read takes. */ +const THREAD_BRANCHES_PER_READ = 10; + +const zodBranches = z.object({ + branches: z.array( + z.discriminatedUnion("status", [ + z.object({ + id: z.number(), + items: z.array(zodThreadNode), + status: z.literal("ok"), + }), + z.object({ id: z.number(), status: z.literal("gone") }), + ]), + ), + replyCount: z.number(), + truncated: z.boolean(), +}); + +const fetchBranches = async (topicId: number, ids: readonly number[]) => { + const res = await fetcher({ + plugin: manifest.id, + method: "get", + module: "content/comments", + path: "/thread/branches", + args: { + query: { + root: String(topicId), + ...(ids.length > 0 ? { ids: ids.join(",") } : {}), + }, + }, + }); + + if (res.status === 404) return null; + if (res.status !== 200) throw new Error("Loading the comments failed."); + + return zodBranches.parse(await res.json()); +}; + +/** + * One page of a thread with its top-level comments in `sort` order: the forum + * ranks the ids, then the Content Engine reads those branches with every + * visibility rule, ten at a time. Same shape as {@link fetchThreadPage}; the + * cursor is an offset. + */ +const fetchOrderedThreadPage = async ({ + after, + first = THREAD_PAGE_SIZE, + sort, + topicId, +}: { + after?: string; + first?: number; + sort: Exclude; + topicId: number; +}): Promise => { + const res = await fetcher({ + plugin: manifest.id, + method: "get", + module: "forum", + path: "/topics/{id}/comments/order", + args: { + params: { id: topicId }, + query: { + after: after ? Number(after) : 0, + first: Math.min(Math.max(first, 1), THREAD_MAX_PAGE_SIZE), + sort, + }, + }, + }); + + if (res.status === 404) return null; + if (res.status !== 200) throw new Error("Loading the comments failed."); + + const { ids, pageInfo } = await res.json(); + const chunks: number[][] = []; + for (let index = 0; index < ids.length; index += THREAD_BRANCHES_PER_READ) { + chunks.push(ids.slice(index, index + THREAD_BRANCHES_PER_READ)); + } + const reads = await Promise.all( + (chunks.length > 0 ? chunks : [[]]).map( + async chunk => await fetchBranches(topicId, chunk), + ), + ); + if (reads.some(read => read === null)) return null; + const answered = reads.filter(read => read !== null); + + return { + commentCount: answered[0]?.replyCount ?? 0, + items: answered.flatMap(read => + read.branches.flatMap(branch => + branch.status === "ok" ? branch.items : [], + ), + ), + pageInfo, + truncated: answered.some(read => read.truncated), + }; +}; + +/** One page of a topic's thread in `sort` order (`old` is posting order). */ +export const fetchSortedThreadPage = async ({ + sort = FORUM_COMMENT_DEFAULT_SORT, + ...request +}: { + after?: string; + first?: number; + sort?: ForumCommentSort; + topicId: number; +}): Promise => + sort === "old" + ? await fetchThreadPage(request) + : await fetchOrderedThreadPage({ ...request, sort }); + export interface ThreadTreeNode extends ThreadNode { children: ThreadTreeNode[]; } diff --git a/plugins/forum/src/pages/thread.tsx b/plugins/forum/src/pages/thread.tsx index e8e9c888d..42d0acff6 100644 --- a/plugins/forum/src/pages/thread.tsx +++ b/plugins/forum/src/pages/thread.tsx @@ -26,9 +26,12 @@ import { cn } from "cn"; import { ChevronDownIcon, ChevronRightIcon, + ClockIcon, MessageSquareIcon, PencilIcon, ReplyIcon, + SmilePlusIcon, + SparklesIcon, } from "lucide-react"; import { Activity, @@ -43,7 +46,10 @@ import { toast } from "sonner"; import { useTranslations } from "use-intl"; import { z } from "zod"; +import type { ForumCommentSort } from "@/feed-sorts"; + import { commentContentType, FORUM_COMMENT_MAX_DEPTH } from "@/content/comment"; +import { FORUM_COMMENT_DEFAULT_SORT, FORUM_COMMENT_SORTS } from "@/feed-sorts"; import { manifest } from "@/manifest.gen"; import type { CommentComposerProps } from "./comment-composer"; @@ -54,10 +60,11 @@ import { commentAnchorId, loginHref, topicHref } from "./forum-links"; import { useCommentPermissions } from "./forum-permissions"; import { invalidateForumComments } from "./forum-queries"; import { PersonAvatar, PersonName, TimeAgo } from "./forum-ui"; +import { ReactionPoints } from "./reaction-points"; import { buildThreadTree, countDescendants, - fetchThreadPage, + fetchSortedThreadPage, THREAD_MAX_PAGE_SIZE, THREAD_PAGE_SIZE, } from "./thread-data"; @@ -218,6 +225,10 @@ const CommentBody = ({ {editing ? null : (
    + = { + new: SparklesIcon, + old: ClockIcon, + points: SmilePlusIcon, +}; + +const CommentSortControl = ({ + onChange, + pending, + sort, +}: { + onChange: (sort: ForumCommentSort) => void; + pending: ForumCommentSort | null; + sort: ForumCommentSort; +}) => { + const t = useTranslations("@vitnode/forum.comments.sort"); + + return ( +
    + {FORUM_COMMENT_SORTS.map(item => { + const Icon = SORT_ICONS[item]; + + return ( + + ); + })} +
    + ); +}; + export const ForumThread = ({ canReply = true, initial, + onSortChange, + sort = FORUM_COMMENT_DEFAULT_SORT, topicId, topicSlug, }: { @@ -392,6 +452,10 @@ export const ForumThread = ({ */ canReply?: boolean; initial: ThreadPage; + /** Shows the sort control; called with the order the reader picked. */ + onSortChange?: (sort: ForumCommentSort) => Promise; + /** The order `initial` was read in. */ + sort?: ForumCommentSort; topicId: number; topicSlug: string; }) => { @@ -401,6 +465,8 @@ export const ForumThread = ({ const currentUserId = session?.user?.id ?? null; const [pages, setPages] = useState([initial]); const [isLoadingMore, setIsLoadingMore] = useState(false); + // The current order stays on screen, dimmed, until the new one arrives. + const [pendingSort, setPendingSort] = useState(null); const [composerKey, setComposerKey] = useState(0); const [composer, setComposer] = useState<"closed" | "open" | "opening">( "closed", @@ -419,8 +485,9 @@ export const ForumThread = ({ if (!last.pageInfo.endCursor) return; setIsLoadingMore(true); try { - const next = await fetchThreadPage({ + const next = await fetchSortedThreadPage({ after: last.pageInfo.endCursor, + sort, topicId, }); if (next) setPages([...pages, next]); @@ -436,7 +503,8 @@ export const ForumThread = ({ const refresh = useCallback(async () => { const loaded = items.filter(item => item.depth === 1).length; try { - const fresh = await fetchThreadPage({ + const fresh = await fetchSortedThreadPage({ + sort, // One more than is on screen, so a new top-level comment at the end of // the conversation shows up without another click. first: Math.min( @@ -451,7 +519,7 @@ export const ForumThread = ({ description: t("load_failed.desc"), }); } - }, [items, t, topicId]); + }, [items, sort, t, topicId]); const onChanged = useCallback( ({ pending }: { pending: boolean }) => { @@ -494,13 +562,27 @@ export const ForumThread = ({ return (
    -

    -

    +
    +

    +

    + {onSortChange && last.pageInfo.totalCount > 1 ? ( + { + setPendingSort(next); + void onSortChange(next).finally(() => { + setPendingSort(null); + }); + }} + pending={pendingSort} + sort={sort} + /> + ) : null} +
    {tree.length === 0 ? ( @@ -513,7 +595,13 @@ export const ForumThread = ({ ) : ( -
      +
        {tree.map(node => ( = { active: ActivityIcon, @@ -122,6 +126,7 @@ const FeedCard = ({ }) => { const t = useTranslations("@vitnode/forum.forums"); const titleId = `feed-topic-${topic.id}`; + const target = contentTarget(manifest.id, topicContentType, topic.id); return (
      1. @@ -172,28 +177,28 @@ const FeedCard = ({

        ) : null} -
          -
        • -
        • -
        • -
        • - {topic.commentCount > 0 && topic.lastActivityAt ? ( +
          +
          + + +
          +
          • -
          • - ) : null} -
          + {topic.commentCount > 0 && topic.lastActivityAt ? ( +
        • +
        • + ) : null} +
        +
    ); @@ -201,7 +206,8 @@ const FeedCard = ({ /** * A ranked page of topics, Reddit-style: forum, author and age on top, the - * title, a short excerpt, then the score and the conversation around it. + * title, a short excerpt, then its points and reactions - react right from the + * feed - and the conversation around it. */ export const TopicFeed = ({ forumId, diff --git a/plugins/forum/src/pages/topic-page.tsx b/plugins/forum/src/pages/topic-page.tsx index 06352a597..67fafef8f 100644 --- a/plugins/forum/src/pages/topic-page.tsx +++ b/plugins/forum/src/pages/topic-page.tsx @@ -43,6 +43,7 @@ import { z } from "zod"; import { commentContentType } from "@/content/comment"; import { topicContentType } from "@/content/topic"; +import { FORUM_COMMENT_DEFAULT_SORT } from "@/feed-sorts"; import { manifest } from "@/manifest.gen"; import type { ForumPerson } from "./forum-data"; @@ -65,6 +66,7 @@ import { TOPIC_STALE_TIME, } from "./forum-queries"; import { PersonAvatar, PersonName, TimeAgo } from "./forum-ui"; +import { ReactionPoints } from "./reaction-points"; import { ForumThread } from "./thread"; const DESCRIPTION_MAX_LENGTH = 160; @@ -149,6 +151,7 @@ const topicOgImageQueryOptions = (id: number) => const loadTopic = async ( queryClient: QueryClient, { locale, slug }: { locale: string; slug: string }, + { comments }: TopicSearch, ) => { const loaded = await queryClient.query(topicQueryOptions(slug)); if ("accessRequired" in loaded) return { accessRequired: true as const }; @@ -156,7 +159,7 @@ const loadTopic = async ( const [forum, thread, ogImage] = await Promise.all([ queryForum(queryClient, String(topic.forum), locale).catch(() => null), - queryClient.query(threadQueryOptions(topic.id)), + queryClient.query(threadQueryOptions(topic.id, comments)), queryClient.query(topicOgImageQueryOptions(topic.id)).catch(() => null), ]); @@ -219,11 +222,12 @@ const ForumsCrumb = () => { }; export const route = defineRoute({ - load: async ({ context, params }) => - await loadTopic(context.queryClient, { - locale: context.locale, - slug: params.slug, - }), + load: async ({ context, params, search }) => + await loadTopic( + context.queryClient, + { locale: context.locale, slug: params.slug }, + search, + ), head: ({ loaderData, t }) => !loaderData || loaderData.accessRequired @@ -312,6 +316,9 @@ const TopicViewerActions = ({ typeLabel={t("report_type")} /> ) : null} + @@ -530,6 +537,14 @@ const TopicViewInner = ({ loaderData, navigate, search }: TopicViewProps) => { { + await navigate({ + resetScroll: false, + search: sort === "old" ? {} : { comments: sort }, + }); + }} + sort={search.comments ?? FORUM_COMMENT_DEFAULT_SORT} topicId={topic.id} topicSlug={topic.slug} /> From 2f9727755dafbc036856c8d45bea61bf694a877c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 11:11:37 +0000 Subject: [PATCH 05/10] =?UTF-8?q?feat(content):=20=E2=9C=A8=20One=20commen?= =?UTF-8?q?t=20look=20for=20every=20module,=20from=20the=20blog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `ContentComments` now draws the blog's design for every plugin: a card per conversation, replies inside it in writing order naming whom they answer, Quote, Share, an Author badge, a hidden-comment gate, sorting by Oldest, Newest or Most points and folding of long threads - New `history` option on `useContentComments`: an "edited" link opens the edit history and the before/after of each edit - New display options: `authorIds`, `shareTitle`, `points` - `ReactionPoints` and `reactionPoints` move to `@vitnode/core/tanstack/reactions` - Blog drops its own thread, Newsroom gets the new look, and forum topics use the shared section (live updates and edit history included); the forum's own thread, composer and comment-order route are gone - Docs: Comments API, Replies, Blog and Forum guides Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- .../docs/content-engine/comments-api.mdx | 28 +- .../content-engine/threads-frontend-tree.webp | Bin 41656 -> 0 bytes .../docs/content-engine/threads-frontend.mdx | 24 +- apps/web/content/docs/guides/blog.mdx | 7 +- apps/web/content/docs/guides/forum.mdx | 26 +- packages/vitnode/src/locales/en.json | 58 +- .../src/tanstack/comments/card-thread.tsx | 477 +++++++----- .../tanstack/comments/content-comments.tsx | 637 ++++++++++++---- .../src/tanstack/comments/edit-history.tsx | 137 ++-- .../tanstack/comments/use-content-comments.ts | 26 + .../vitnode/src/tanstack/reactions/index.ts | 1 + .../tanstack/reactions}/reaction-points.tsx | 77 +- plans/forum-reaction-points.md | 9 +- plugins/blog/src/locales/en.json | 54 -- plugins/blog/src/pages/post-comments-data.ts | 23 +- plugins/blog/src/pages/post-comments.tsx | 559 +------------- plugins/blog/src/routes.ts | 2 +- .../src/api/modules/forum/forum.module.ts | 2 - .../forum/routes/list-comment-order.route.ts | 149 ---- plugins/forum/src/feed-sorts.ts | 19 - plugins/forum/src/locales/en.json | 65 +- plugins/forum/src/pages/comment-composer.tsx | 172 ----- .../forum/src/pages/comment-redirect-page.tsx | 2 +- plugins/forum/src/pages/forum-links.ts | 32 +- plugins/forum/src/pages/forum-permissions.ts | 19 - plugins/forum/src/pages/forum-queries.test.ts | 17 +- plugins/forum/src/pages/forum-queries.ts | 33 +- plugins/forum/src/pages/thread-data.ts | 248 ------- plugins/forum/src/pages/thread.tsx | 699 ------------------ plugins/forum/src/pages/topic-comments.tsx | 222 ++++++ plugins/forum/src/pages/topic-feed.tsx | 3 +- plugins/forum/src/pages/topic-page.tsx | 76 +- plugins/forum/src/routes.ts | 2 +- 33 files changed, 1369 insertions(+), 2536 deletions(-) delete mode 100644 apps/web/content/docs/content-engine/threads-frontend-tree.webp rename plugins/blog/src/pages/post-comment-thread.tsx => packages/vitnode/src/tanstack/comments/card-thread.tsx (59%) rename plugins/blog/src/pages/post-comment-edits.tsx => packages/vitnode/src/tanstack/comments/edit-history.tsx (80%) rename {plugins/forum/src/pages => packages/vitnode/src/tanstack/reactions}/reaction-points.tsx (54%) delete mode 100644 plugins/forum/src/api/modules/forum/routes/list-comment-order.route.ts delete mode 100644 plugins/forum/src/pages/comment-composer.tsx delete mode 100644 plugins/forum/src/pages/thread-data.ts delete mode 100644 plugins/forum/src/pages/thread.tsx create mode 100644 plugins/forum/src/pages/topic-comments.tsx diff --git a/apps/web/content/docs/content-engine/comments-api.mdx b/apps/web/content/docs/content-engine/comments-api.mdx index fb539352f..bd5ef2265 100644 --- a/apps/web/content/docs/content-engine/comments-api.mdx +++ b/apps/web/content/docs/content-engine/comments-api.mdx @@ -35,6 +35,7 @@ const comments = useContentComments({ queryKey, thread, ...actions }) | `onChanged` | `(queryClient) => void \| Promise` | No | Refreshes your other queries after a successful write, such as a comment count elsewhere on the page | | `branches` | `(ids) => Promise` | No | [`GET /thread/branches`](#get-threadbranches) with `root`, plus `ids` joined by commas only when there are any. Writes then re-read only the branch they touched instead of every loaded page. `live` needs it | | `live` | `{ contentTypeId, rootId }` | No | The comment content type's `id` and the root record's id. Keeps the thread current over the WebSocket while it is mounted; ignored without `branches`. See [Live comments](/docs/content-engine/threads-live) | +| `history` | `{ list(id), entry(id, revisionId) }` | No | `GET /{id}/history` and `GET /{id}/history/{revisionId}`, which every type with `editorial` revisions has. An **edited** link next to the date then opens who edited the comment and what changed. Signed-in members only | ### Callback contract @@ -95,10 +96,24 @@ Its `queryFn` throws when the thread route answers anything but `2xx`. ## `ContentComments` -The complete section: the count, the thread, **Load more comments**, the composer (hidden from guests), the actions menu, the delete confirmation and the report dialog. It scrolls to and rings the comment a `#comment-...` link points to, loading more pages until it appears. +The complete section, and the look every comment section in VitNode shares - Blog, Newsroom and Forum use it as is: + +- Each top-level comment is a **card**: avatar, author, date and actions menu on a tinted header, then the text, its reactions, **Quote** and **Share**. +- Its replies sit inside the card in the order they were written, joined by a thin line. A reply to a reply says whom it answers ("In reply to Ada"), so deep conversations stay readable without indenting. +- A **Write a reply** field closes each card for members who can answer. +- Readers sort conversations by **Oldest**, **Newest** or **Most points** (each conversation's reaction points). A thread with more than ten conversations folds the middle ones behind a **Load more…** gap. +- Hidden comments fold behind a notice their author and moderators can open. + +Below the conversations come **Load more comments**, the live status and the composer (hidden from guests). It scrolls to and rings the comment a `#comment-...` link points to, loading more pages until it appears. ```tsx - + comment.slug} + authorIds={[article.author.id]} + comments={comments} + permalink={anchorId => `/blog/article/${article.slug}#${anchorId}`} + shareTitle={article.title} +/> ``` | Prop | Description | @@ -107,11 +122,14 @@ The complete section: the count, the thread, **Load more comments**, the compose | `className` | Classes for the `
    ` | | `title` | Replaces the "N comments" heading | | `anchorKey(record)` | What follows `comment-` in each comment's element id. Defaults to the id; return the slug to match slug permalinks | -| `permalink(anchorId)` | The link on each comment's date. Defaults to `#comment-...` on the same page | +| `permalink(anchorId)` | The link on each comment's date, and what **Share** shares. Defaults to `#comment-...` on the same page | +| `shareTitle` | The title **Share** sends along, usually the commented record's | +| `authorIds` | Users whose comments get an **Author** badge, such as the article's authors or the topic's starter | +| `points` | Shows each comment's points from reactions next to its reaction bar. Off by default | | `render.author(record)` | Replaces the author's name | | `render.body(record)` | Replaces the text | | `render.meta(record)` | Adds details after the date, such as a badge | -| `render.actions(record)` | Adds buttons next to **Reply** | +| `render.actions(record)` | Adds buttons next to **Quote** and **Share** | The section's element id is `comments`, so `#comments` links scroll to it. Its messages live in the `core.comments` namespace; add it to the page's route `messages` to load them with the page. @@ -176,7 +194,7 @@ const MyComment = ({ node }) => { | `contentCommentAuthor(record)`, `contentCommentAuthorName(person)` | Read the `author` person and the name to show | | `useContentCommentErrorToast()` | Shows the section's message for a failed action's status | -The Blog plugin's `plugins/blog/src/pages/post-comments.tsx` is a complete custom layout: rail connectors, collapsible branches, share buttons and slug permalinks, with every action from these components. +Reach for these only when the shared look really doesn't fit: a comment section that looks different from every other one in the app is one more thing for readers to learn. ## Outcomes and errors diff --git a/apps/web/content/docs/content-engine/threads-frontend-tree.webp b/apps/web/content/docs/content-engine/threads-frontend-tree.webp deleted file mode 100644 index 54074ea517ef89ac8a6057d9d41e556e574a8dc2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 41656 zcmc$_WpJEbk~Ju1W@cuVEM{hAu$Y;dC5xGv$zo<^mTWPzWHD2H?&;~Cw`bh5yFYff zqAH@|MnyeO<~@1x5`ls>wfYghLZsbgr-QW#u;>Tsfp!3lKT_UDP7gM&!2Q&G0=9vVH1>Lv{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Nf#bLy&|6nUH9F*Edzvfg##*CkX($Zz5(9cg*(EmXOm)Bj02Owx*OHJ#Vny7$L;wH)0000000000000000012> BZ^{4w diff --git a/apps/web/content/docs/content-engine/threads-frontend.mdx b/apps/web/content/docs/content-engine/threads-frontend.mdx index 5d6df24c9..e8de5ad50 100644 --- a/apps/web/content/docs/content-engine/threads-frontend.mdx +++ b/apps/web/content/docs/content-engine/threads-frontend.mdx @@ -22,10 +22,7 @@ implementation: import { Tab, Tabs } from "fumadocs-ui/components/tabs"; -import { ImgDocs } from "@/components/fumadocs/img"; -import tree from "./threads-frontend-tree.webp"; - -Replies let a comment answer another comment, so a conversation can branch. The thread route already returns each top-level comment followed by every answer below it, and the shared section draws them as a tree. This page raises the depth limit and tells the section about it, which turns on **Reply**. +Replies let a comment answer another comment, so a conversation can branch. The thread route already returns each top-level comment followed by every answer below it, and the shared section draws each conversation as a card. This page raises the depth limit and tells the section about it, which turns on **Reply**. This continues the comment section from [Comments](/docs/content-engine/threads). Replies work with or without [Comment actions](/docs/content-engine/threads-editing). @@ -82,7 +79,7 @@ import { COMMENT_MAX_DEPTH } from "@/content/comment"; // [!code ++] maxDepth: COMMENT_MAX_DEPTH, // [!code ++] ``` -That is the whole change. `create` already sends `parent: parentId`, which is now the comment being answered instead of `null`. The section shows **Reply** under every comment above the limit, opens a composer under it, and draws replies indented below their parent. Below three levels it stops indenting, so deep branches stay readable on a phone. +That is the whole change. `create` already sends `parent: parentId`, which is now the comment being answered instead of `null`. The section shows **Reply** under every comment above the limit and a **Write a reply** field at the bottom of each conversation. Replies sit inside their conversation's card in the order they were written, and a reply to a reply names whom it answers - no indenting, so deep conversations stay readable on a phone. @@ -92,16 +89,11 @@ That is the whole change. `create` already sends `parent: parentId`, which is no Open an article with a comment and sign in as a member: -1. Click **Reply** under the comment, write an answer and click **Post comment**. **Comment posted** appears and the answer shows indented below the comment. -2. Reply to the reply, and again, until a reply sits at depth 4. That reply has no **Reply** button. +1. Click **Write a reply** under the comment, write an answer and click **Post comment**. **Comment posted** appears and the answer shows inside the comment's card. +2. Reply to the reply with its **Reply** button, and again, until a reply sits at depth 4. That reply has no **Reply** button, and each answer says "In reply to" whom. 3. Reload. The tree comes back the same way. - +{/* Image prompt: A VitNode article's comment section in light theme: a card for Ada Lovelace's comment with a tinted header, her text, a reaction pill and Quote/Share icons, then inside the same card a reply by Grace Hopper and a reply to that reply marked "In reply to Grace Hopper", joined by a thin vertical line, and a "Write a reply" field at the bottom of the card. Oldest / Newest / Most points toggle above. 1440x900. */} ## Long conversations @@ -112,8 +104,8 @@ Open an article with a comment and sign in as a member: ## Removed and hidden comments in a tree -- **Deleted with replies.** A comment deleted while it has replies stays as a **[deleted]** placeholder with no text and no author. It reads "Comment deleted by user" or "Comment removed by a moderator". Its replies keep their place, and you can still answer them. -- **Hidden with replies.** Readers who can't see a hidden comment get the same placeholder, so the branch below it stays readable. Its author and moderators see the real comment, marked **Hidden**. The section offers no **Reply** on a hidden comment. +- **Deleted with replies.** A top-level comment deleted while it has replies keeps its card, with a note instead of its text and author: "Comment deleted by user" or "Comment removed by a moderator". Its replies keep their place, and you can still answer them. +- **Hidden with replies.** Readers who can't see a hidden comment get the same note, so the conversation below it stays readable. Its author and moderators see the real comment folded behind "This comment was hidden." with **Show comment**. The section offers no **Reply** on a hidden comment. - **Removed without replies.** The comment disappears. There's no branch below it to hold up. The server keeps the tree valid on every write, in the AdminCP too: the parent must exist, be public and belong to the same article, a comment never answers itself or one of its own answers, and nothing nests deeper than `maxDepth`. A reply that breaks a rule answers `400`, and the composer keeps its text. @@ -121,5 +113,5 @@ The server keeps the tree valid on every write, in the AdminCP too: the parent m ## Related - [Notifications](/docs/content-engine/notifications): optional. Tell members about replies to their comments, sent by the server with no change to the section. -- [Comments API](/docs/content-engine/comments-api): build your own tree layout with `ContentCommentsRoot`, as the Blog plugin does with its connectors and collapsible branches. +- [Comments API](/docs/content-engine/comments-api): every `ContentComments` option, and the building blocks for a layout of your own. - [thread reference](/docs/content-engine/reference#thread): every `thread` option. diff --git a/apps/web/content/docs/guides/blog.mdx b/apps/web/content/docs/guides/blog.mdx index 60ae3a838..ffe7ece77 100644 --- a/apps/web/content/docs/guides/blog.mdx +++ b/apps/web/content/docs/guides/blog.mdx @@ -216,13 +216,16 @@ An edited comment shows **edited ▾** next to its date. It lists who wrote the Above the conversation, **Oldest** (the default) reads them in the order they started, **Newest** puts the conversations with the latest activity first, and -**Top** puts the most-reacted comments first, then the ones with the most -replies. The order holds while you read: a new reply shows up live but doesn't +**Most points** puts the comments whose reactions are worth the most points +(set in **AdminCP → Reactions**) first, then the ones with the most replies. The order holds while you read: a new reply shows up live but doesn't move its conversation, and a new conversation joins at the top (Newest) or the bottom. Pick a sort again to re-sort. A busy article doesn't turn into a wall: past 10 conversations, the middle folds into a **12 hidden conversations** box between the first five and the last two. **Load more…** brings back ten at a time, and a link to one comment always shows them all. +This is the Content Engine's shared [comment section](/docs/content-engine/comments-api#contentcomments), +so forum topics and news articles look and behave the same way. + Comments are a Content Engine [thread](/docs/content-engine/threads): the `blog.comment` content type, stored in `blog_comments`, with the article as the thread's root. One conversation is shared by every translation of an article, diff --git a/apps/web/content/docs/guides/forum.mdx b/apps/web/content/docs/guides/forum.mdx index ad6f74611..9fff5dd67 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -1,13 +1,13 @@ --- title: Run a Community Forum -description: Enable the @vitnode/forum plugin, create forums in AdminCP, choose who publishes straight away, and let members post topics and nested comments. +description: Enable the @vitnode/forum plugin, create forums in AdminCP, choose who publishes straight away, and let members post topics and threaded comments. icon: MessagesSquare --- import { Tab, Tabs } from "fumadocs-ui/components/tabs"; `@vitnode/forum` adds a community forum to a VitNode app: a tree of forums, -topics inside them and Reddit-style nested comments. It is built only from +topics inside them and threaded comments. It is built only from Content Engine pieces - a [container](/docs/content-engine/containers) for the forums, two content types and a [thread](/docs/content-engine/threads) - so everything you learn here works the same way in your own plugins. @@ -101,7 +101,7 @@ deep, and you can drag them to reorder. A forum's **Icon** accepts the same | `/forum` | A feed of topics from every forum you can read, with the forum list | | `/forum/:slug` | Subforums and the topics of one forum, in the same sortable feed | | `/forum/create/topic` | Start a topic (signed-in members) | -| `/forum/topics/:slug` | The topic, its nested comments, and a comment box | +| `/forum/topics/:slug` | The topic, its comments, and a comment box | | `/forum/topics/:id/edit` | Edit your own topic | | `/forum/comments/:slug` | Permalink of one comment - redirects to its place in the topic | | `/forum/me/pending` | Your posts a moderator approved, declined, or has not looked at yet | @@ -157,17 +157,17 @@ freshness. A brilliant topic from last month politely makes room for today's. ## Comments +Topic comments look exactly like blog and news comments - they all use the +Content Engine's shared [comment section](/docs/content-engine/comments-api#contentcomments). +Each top-level comment is a card, and its replies sit inside it in the order +they were written, each naming whom it answers. Replies go up to six levels +deep. Every comment shows its points next to its reactions, and comments by +the topic's starter carry an **Author** badge. + Comments come in posting order, like a classic forum. Above them, readers can -switch to **Newest** (`?comments=new`) or **Most points** -(`?comments=points`). Only top-level comments move; replies stay under their -parent in the order they were written, so a conversation still reads top to -bottom. Every comment shows its points next to its reactions. - -Comments nest up to six levels - hit **Reply** under any comment to answer it. -On small screens deep comments stop indenting, so the text keeps its width, and -every branch can be collapsed. A comment removed by a moderator stays as "This -comment was removed." when it has public replies, so the conversation keeps its -shape. +switch to **Newest** or **Most points**; only whole conversations move. Edited +comments get an **edited** link with the edit history, and new comments show up +live while the topic is open. The forum index, forum and topic pages are cached for a minute and refreshed in the background. Edit buttons and the comment box load in the browser, so every diff --git a/packages/vitnode/src/locales/en.json b/packages/vitnode/src/locales/en.json index 6c157031a..a6155275e 100644 --- a/packages/vitnode/src/locales/en.json +++ b/packages/vitnode/src/locales/en.json @@ -1957,7 +1957,59 @@ "retry": "Try again", "edit_removed": "This comment was removed while you were editing it. Your text is still here, but it can no longer be saved.", "reply_removed": "The comment you are replying to was removed. Your text is still here, but it can no longer be posted." - } + }, + "share": { + "label": "Share", + "description": "Comment by {name}" + }, + "in_reply_to": "In reply to ", + "reply_count": "{count} {count, plural, one {reply} other {replies}}", + "write_reply": "Write a reply", + "hidden": { + "notice": "This comment was hidden.", + "show": "Show comment", + "hide": "Hide comment" + }, + "sort": { + "label": "Sort comments", + "newest": "Newest", + "oldest": "Oldest", + "top": "Most points" + }, + "gap": { + "hidden": "{count, plural, one {# hidden conversation} other {# hidden conversations}}", + "load": "Load more…" + }, + "edits": { + "trigger": "edited", + "trigger_label": "Edited {count, plural, one {# time} other {# times}}. Show the edit history", + "title": "Edited {count, plural, one {# time} other {# times}}", + "edited": " edited ", + "created": " created ", + "most_recent": "(most recent)", + "incomplete": "Older edits are no longer kept.", + "loading": "Loading the edit history", + "retry": "Try again", + "added": "Added", + "removed": "Removed", + "formatting_only": "Only the formatting changed in this edit.", + "load_error": { + "title": "History didn't load", + "desc": "Try again in a moment." + }, + "entry_error": { + "title": "This edit didn't load", + "desc": "Try again in a moment." + }, + "dialog": { + "edited_title": "{name}'s edit", + "created_title": "{name}'s first version", + "edited_desc": "Edited ", + "created_desc": "Written " + } + }, + "quote_reply": "Quote reply", + "author_badge": "Author" }, "content": { "empty": { @@ -3889,6 +3941,10 @@ "reacted": " reacted to {title}", "reacted_in": " reacted to {kind, select, comment {{count, plural, one {# comment} other {# comments}}} topic {{count, plural, one {# topic} other {# topics}}} other {{count, plural, one {# item} other {# items}}}} in {title}", "more": "and {count} more" + }, + "points": { + "unit": "{count, plural, one {point} other {points}}", + "hint": "Points from reactions to this post" } }, "site_offline": { diff --git a/plugins/blog/src/pages/post-comment-thread.tsx b/packages/vitnode/src/tanstack/comments/card-thread.tsx similarity index 59% rename from plugins/blog/src/pages/post-comment-thread.tsx rename to packages/vitnode/src/tanstack/comments/card-thread.tsx index 70db747d6..c53d79b5f 100644 --- a/plugins/blog/src/pages/post-comment-thread.tsx +++ b/packages/vitnode/src/tanstack/comments/card-thread.tsx @@ -1,35 +1,7 @@ -import type { RichTextDocument } from "@vitnode/core/content/rich-text"; - -import { Avatar } from "@vitnode/core/components/avatar"; -import { DateFormat } from "@vitnode/core/components/date-format"; -import { RichTextContent } from "@vitnode/core/components/rich-text"; -import { SharePopover } from "@vitnode/core/components/share-popover"; -import { Badge } from "@vitnode/core/components/ui/badge"; -import { Button } from "@vitnode/core/components/ui/button"; -import { - Collapsible, - CollapsibleContent, -} from "@vitnode/core/components/ui/collapsible"; -import { SlidingNumber } from "@vitnode/core/components/ui/sliding-number"; -import { - TooltipGroup, - TooltipGroupTrigger, -} from "@vitnode/core/components/ui/tooltip"; -import { UserFormat } from "@vitnode/core/components/user-format"; -import { UserPreview } from "@vitnode/core/components/user-preview"; -import { - AutoTranslateNote, - useAutoTranslation, -} from "@vitnode/core/tanstack/auto-translate"; -import { - ContentCommentActions, - contentCommentAuthorName, - ContentCommentComposer, - type ContentCommentTreeNode, - preloadContentCommentComposer, - useContentCommentItem, -} from "@vitnode/core/tanstack/comments"; -import { ReactionBar } from "@vitnode/core/tanstack/reactions"; +import type { ContentId } from "@vitnode/api/content/ids"; +import type { RichTextDocument } from "@vitnode/api/content/rich-text"; + +import { zodRichTextDocument } from "@vitnode/api/content/rich-text"; import { cn } from "cn"; import { ChevronsDownUpIcon, @@ -42,33 +14,94 @@ import { import React from "react"; import { useTranslations } from "use-intl"; -import { blogCommentContentType } from "@/content/comment"; - -import type { PostComment } from "./post-comments-data"; +import { Avatar } from "@/components/avatar"; +import { DateFormat } from "@/components/date-format"; +import { RichTextContent } from "@/components/rich-text/rich-text-content"; +import { SharePopover } from "@/components/share-popover"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Collapsible, CollapsibleContent } from "@/components/ui/collapsible"; +import { SlidingNumber } from "@/components/ui/sliding-number"; +import { TooltipGroup, TooltipGroupTrigger } from "@/components/ui/tooltip"; +import { UserFormat } from "@/components/user-format"; +import { UserPreview } from "@/components/user-preview"; +import { ReactionBar } from "@/tanstack/reactions/reaction-bar"; +import { ReactionPoints } from "@/tanstack/reactions/reaction-points"; + +import type { ContentCommentNode, ContentCommentTreeNode } from "./thread"; + +import { contentCommentAuthor, contentCommentAuthorName } from "./author"; +import { ContentCommentEditHistory } from "./edit-history"; +import { + ContentCommentActions, + ContentCommentComposer, + preloadContentCommentComposer, + useContentCommentItem, +} from "./item"; +import { useContentCommentsContext } from "./root"; +import { CONTENT_COMMENT_ANCHOR_PREFIX } from "./thread"; + +/** How the default comments section links, labels and renders comments. */ +export interface ContentCommentsDisplay { + /** + * What follows `comment-` in a comment's element id, for links such as + * `#comment-42`. Defaults to the comment's id; return its slug to match + * permalinks built from slugs. + */ + anchorKey?: (record: TRecord) => string; + /** + * Users marked with an **Author** badge on their comments - the people who + * wrote the commented record, such as an article's authors or a topic's + * starter. + */ + authorIds?: readonly number[]; + /** + * The link on a comment's date, and what **Share** shares. Gets the element + * id, e.g. `comment-42`. Defaults to `#comment-42` on the current page. + */ + permalink?: (anchorId: string) => string; + /** + * A points pill (`ReactionPoints`) next to each comment's reactions: the sum + * of its reactions' points from AdminCP → Reactions. Off by default. + */ + points?: boolean; + /** Replaces parts of a comment. Each gets the comment's public record. */ + render?: { + /** Extra buttons in the row under the comment, next to **Reply**. */ + actions?: (record: TRecord) => React.ReactNode; + /** The author's name; defaults to the `author` field's person. */ + author?: (record: TRecord) => React.ReactNode; + /** The text; defaults to the rich-text `field`. */ + body?: (record: TRecord) => React.ReactNode; + /** Extra details after the date, such as a badge. */ + meta?: (record: TRecord) => React.ReactNode; + }; + /** The title **Share** sends along, usually the commented record's. */ + shareTitle?: string; +} -import { CommentEdits } from "./post-comment-edits"; -import { commentAnchorId } from "./post-comments-data"; +export type AnyCommentsDisplay = ContentCommentsDisplay; -export type CommentTreeNode = ContentCommentTreeNode; +export type CommentTreeNode = ContentCommentTreeNode; -export interface ThreadContextValue { +export interface CardThreadContextValue { animateEntries: boolean; - articleAuthorIds: ReadonlySet; - articleHref: string; - articleTitle: string; + authorIds: ReadonlySet; + display: AnyCommentsDisplay; highlightedId: null | string; - postedReplyId: null | number; - setPostedReplyId: (id: null | number) => void; + postedReplyId: ContentId | null; + setPostedReplyId: (id: ContentId | null) => void; signedIn: boolean; } -export const ThreadContext = React.createContext( - null, -); +export const CardThreadContext = + React.createContext(null); -const useThread = () => { - const thread = React.use(ThreadContext); - if (!thread) throw new Error("useThread must be used inside ThreadContext"); +const useCardThread = () => { + const thread = React.use(CardThreadContext); + if (!thread) { + throw new Error("Comment cards render inside CardThreadContext."); + } return thread; }; @@ -79,12 +112,41 @@ const ENTER_CLASS = const COLLAPSIBLE_PANEL_CLASS = "ease-fluid h-(--collapsible-panel-height) overflow-hidden transition-[height,opacity] duration-200 data-ending-style:h-0 data-ending-style:opacity-0 data-starting-style:h-0 data-starting-style:opacity-0 motion-reduce:transition-[opacity]"; -export const nodeTime = (node: CommentTreeNode) => +const recordField = (record: unknown, name: string): unknown => + typeof record === "object" && record !== null && name in record + ? (record as Record)[name] + : undefined; + +const readDate = (record: unknown, name: string): null | string => { + const value = recordField(record, name); + + return typeof value === "string" ? value : null; +}; + +/** When a comment was published, or created before that. */ +export const commentDate = (record: unknown): null | string => + readDate(record, "publishedAt") ?? readDate(record, "createdAt"); + +export const nodeTime = (node: ContentCommentNode): number => { + const date = node.record ? commentDate(node.record) : null; + + return date ? new Date(date).getTime() : 0; +}; + +/** The element id of a comment, e.g. `comment-42`. */ +export const commentAnchorIdOf = ( + node: ContentCommentNode, + display: AnyCommentsDisplay, +): null | string => node.record - ? new Date(node.record.publishedAt ?? node.record.createdAt).getTime() - : 0; + ? `${CONTENT_COMMENT_ANCHOR_PREFIX}${display.anchorKey ? display.anchorKey(node.record) : String(node.id)}` + : null; + +const permalinkOf = (display: AnyCommentsDisplay, anchorId: string) => + display.permalink ? display.permalink(anchorId) : `#${anchorId}`; -export const flattenReplies = ( +/** Every reply below `node`, at any depth, each with the comment it answers. */ +const flattenReplies = ( node: CommentTreeNode, ): { node: CommentTreeNode; parent: CommentTreeNode }[] => node.children.flatMap(child => [ @@ -93,24 +155,28 @@ export const flattenReplies = ( ]); const useEntry = (node: CommentTreeNode) => { - const thread = useThread(); - const tc = useTranslations("core.comments"); + const thread = useCardThread(); + const { comments } = useContentCommentsContext(); + const t = useTranslations("core.comments"); const item = useContentCommentItem(node); - const comment = node.record; - const anchorId = comment ? commentAnchorId(comment.slug) : null; + const record = node.record; + const anchorId = commentAnchorIdOf(node, thread.display); + const author = record ? contentCommentAuthor(record) : null; + const body = record + ? zodRichTextDocument.safeParse(recordField(record, comments.field)) + : null; return { anchorId, + author, authorId: anchorId ? `${anchorId}-author` : undefined, - authorName: comment - ? (contentCommentAuthorName(comment.author) ?? tc("deleted_user")) - : tc("deleted_user"), - comment, - isArticleAuthor: - !!comment?.author && thread.articleAuthorIds.has(comment.author.id), + authorName: contentCommentAuthorName(author) ?? t("deleted_user"), + body: body?.success ? body.data : null, + isRecordAuthor: !!author && thread.authorIds.has(author.id), isHighlighted: anchorId !== null && anchorId === thread.highlightedId, item, node, + record, thread, }; }; @@ -118,8 +184,8 @@ const useEntry = (node: CommentTreeNode) => { type Entry = ReturnType; const usePostedReplyRef = (entry: Entry) => { - const { comment, thread } = entry; - const posted = comment !== null && comment.id === thread.postedReplyId; + const { node, thread } = entry; + const posted = node.record !== null && node.id === thread.postedReplyId; return React.useCallback( (element: HTMLLIElement | null) => { @@ -138,20 +204,20 @@ const usePostedReplyRef = (entry: Entry) => { ); }; -const anchorProps = (node: CommentTreeNode, className?: string) => ({ +const anchorProps = (entry: Entry, className?: string) => ({ className: cn("scroll-mt-24 outline-none", className), - id: node.record ? commentAnchorId(node.record.slug) : undefined, - tabIndex: node.record ? -1 : undefined, + id: entry.anchorId ?? undefined, + tabIndex: entry.anchorId ? -1 : undefined, }); -const CommentAvatar = ({ node }: { node: CommentTreeNode }) => - node.record?.author ? ( +const CommentAvatar = ({ entry }: { entry: Entry }) => + entry.author ? ( - + ) : ( { content: [{ text: line, type: "text" }], type: "paragraph", })) - : (entry.comment?.body.content ?? []); + : (entry.body?.content ?? []); return { content: [{ content: quoted, type: "blockquote" }, { type: "paragraph" }], @@ -226,8 +292,8 @@ const QuoteButton = ({ entry: Entry; onQuote: () => void; }) => { - const t = useTranslations("@vitnode/blog.comments"); - if (!entry.item.canReply || entry.node.hidden) return null; + const t = useTranslations("core.comments"); + if (!entry.item.canReply || entry.node.hidden || !entry.body) return null; return ( { - const t = useTranslations("@vitnode/blog.comments"); - const tc = useTranslations("core.comments"); - const { comment } = entry; - if (!comment) return null; - const date = comment.publishedAt ?? comment.createdAt; + const t = useTranslations("core.comments"); + const { comments } = useContentCommentsContext(); + const { record } = entry; + if (!record) return null; + const date = commentDate(record); + const { render } = entry.thread.display; return (
    - {comment.author ? ( - - ) : ( - + {render?.author ? ( + render.author(record) + ) : entry.author ? ( + + ) : ( + + {t("deleted_user")} + + )} + + {date && entry.anchorId ? ( + - {tc("deleted_user")} - - )} - - - {tc("permalink")} - + + {t("permalink")} + + ) : null} {entry.node.editCount ? ( - entry.thread.signedIn ? ( - ) : ( @@ -303,17 +372,18 @@ const CommentHeader = ({ entry }: { entry: Entry }) => { {entry.node.hidden ? ( · ) : null} + {render?.meta?.(record)}
    - {entry.isArticleAuthor ? ( + {entry.isRecordAuthor ? ( - {t("article_author")} + {t("author_badge")} ) : null} @@ -322,42 +392,30 @@ const CommentHeader = ({ entry }: { entry: Entry }) => { ); }; -const CommentBody = ({ entry }: { entry: Entry }) => - entry.comment ? ( - - ) : null; - -const CommentBodyContent = ({ - comment, - entry, -}: { - comment: PostComment; - entry: Entry; -}) => { - const tc = useTranslations("core.comments"); - const { elementRef, ...translation } = useAutoTranslation({ - contentTypeId: blogCommentContentType.id, - fields: { body: comment.body }, - id: comment.id, - }); +const CommentBody = ({ entry }: { entry: Entry }) => { + const t = useTranslations("core.comments"); + const { record } = entry; + if (!record) return null; + const custom = entry.thread.display.render?.body; return ( <> -
    - +
    + {custom ? ( + custom(record) + ) : entry.body ? ( + + ) : null}
    - {entry.node.hidden && entry.node.hiddenReason ? (

    - {tc("visibility.hidden_reason", { - reason: entry.node.hiddenReason, - })} + {t("visibility.hidden_reason", { reason: entry.node.hiddenReason })}

    ) : null} @@ -365,14 +423,14 @@ const CommentBodyContent = ({ }; const ShareButton = ({ entry }: { entry: Entry }) => { - const t = useTranslations("@vitnode/blog.comments"); - if (entry.node.hidden || !entry.comment) return null; + const t = useTranslations("core.comments"); + if (entry.node.hidden || !entry.record || !entry.anchorId) return null; return ( { ); }; -const Reactions = ({ entry }: { entry: Entry }) => - entry.item.reactionTarget && !entry.node.hidden ? ( - - ) : null; +const Reactions = ({ entry }: { entry: Entry }) => { + const target = entry.item.reactionTarget; + if (!target || entry.node.hidden) return null; + + return ( +
    + {entry.thread.display.points ? : null} + +
    + ); +}; + +const ExtraActions = ({ entry }: { entry: Entry }) => { + const actions = entry.thread.display.render?.actions; + if (!entry.record || !actions) return null; + + return <>{actions(entry.record)}; +}; const ReplyComposer = ({ className, @@ -408,8 +480,8 @@ const ReplyComposer = ({ onClose: () => void; quote: null | Quote; }) => { - const tc = useTranslations("core.comments"); - if (!entry.comment || !entry.item.isReplying) return null; + const t = useTranslations("core.comments"); + if (!entry.record || !entry.item.isReplying) return null; const close = () => { entry.item.setIsReplying(false); onClose(); @@ -421,37 +493,35 @@ const ReplyComposer = ({ autoFocus initialBody={quote?.body} key={quote?.key ?? "reply"} - label={tc("form.answer_label", { name: entry.authorName })} + label={t("form.answer_label", { name: entry.authorName })} mode="create" onCancel={close} onDone={(_outcome, id) => { close(); - if (typeof id === "number") entry.thread.setPostedReplyId(id); + if (id !== null) entry.thread.setPostedReplyId(id); }} - parentId={entry.comment.id} - unavailable={ - entry.item.isRemoved ? tc("live.reply_removed") : undefined - } + parentId={entry.node.id} + unavailable={entry.item.isRemoved ? t("live.reply_removed") : undefined} />
    ); }; const EditComposer = ({ entry }: { entry: Entry }) => { - const tc = useTranslations("core.comments"); - if (!entry.comment || !entry.item.editing) return null; + const t = useTranslations("core.comments"); + if (!entry.record || !entry.item.editing) return null; return ( ); }; @@ -465,7 +535,7 @@ const Notice = ({ expanded?: boolean; onToggle?: () => void; }) => { - const t = useTranslations("@vitnode/blog.comments"); + const t = useTranslations("core.comments"); return (
    { - const t = useTranslations("@vitnode/blog.comments"); + const t = useTranslations("core.comments"); const [shown, setShown] = React.useState(false); const [wasHighlighted, setWasHighlighted] = React.useState(false); if (entry.isHighlighted !== wasHighlighted) { @@ -552,18 +622,20 @@ const ReplyRow = ({ node: CommentTreeNode; replyingTo: CommentTreeNode | null; }) => { - const t = useTranslations("@vitnode/blog.comments"); - const tc = useTranslations("core.comments"); + const t = useTranslations("core.comments"); const entry = useEntry(node); const { clearQuote, quote, startQuote } = useQuoteReply(entry); const postedReplyRef = usePostedReplyRef(entry); + const replyingToAuthor = replyingTo?.record + ? contentCommentAuthor(replyingTo.record) + : null; return (
  • - {entry.comment ? ( + {entry.record ? (
    - +
  • { entry.isHighlighted && "ring-primary/50 ring-2", )} > - {entry.comment ? ( + {entry.record ? ( {entry.item.editing ? (
    @@ -739,7 +820,7 @@ export const CommentThread = ({ node }: { node: CommentTreeNode }) => { <>
    - +
    @@ -759,6 +840,7 @@ export const CommentThread = ({ node }: { node: CommentTreeNode }) => { ) : null}
    + @@ -770,12 +852,14 @@ export const CommentThread = ({ node }: { node: CommentTreeNode }) => { )} - ) : null} - {replies.length > 0 || entry.comment ? ( + ) : ( + + )} + {replies.length > 0 || entry.record ? (
    0) && "border-t", )} > {replies.length > 0 ? ( @@ -784,7 +868,7 @@ export const CommentThread = ({ node }: { node: CommentTreeNode }) => { @@ -804,3 +888,22 @@ export const CommentThread = ({ node }: { node: CommentTreeNode }) => {
  • ); }; + +/** + * The header of a conversation whose first comment was deleted or hidden from + * this reader while it still had replies: no text, no author. + */ +const RemovedHeader = ({ node }: { node: CommentTreeNode }) => { + const t = useTranslations("core.comments"); + const { deleted } = node; + + return ( + + {deleted + ? deleted.byAuthor + ? t("placeholder.by_author") + : t("placeholder.by_moderator") + : t("removed")} + + ); +}; diff --git a/packages/vitnode/src/tanstack/comments/content-comments.tsx b/packages/vitnode/src/tanstack/comments/content-comments.tsx index 317513d16..6db28cc72 100644 --- a/packages/vitnode/src/tanstack/comments/content-comments.tsx +++ b/packages/vitnode/src/tanstack/comments/content-comments.tsx @@ -1,8 +1,11 @@ import type { ContentId } from "@vitnode/api/content/ids"; +import { useQueryClient } from "@tanstack/react-query"; import { zodRichTextDocument } from "@vitnode/api/content/rich-text"; import { cn } from "cn"; import { + ArrowDownWideNarrowIcon, + ArrowUpNarrowWideIcon, ChevronDownIcon, EyeOffIcon, MessageSquareIcon, @@ -10,8 +13,10 @@ import { PencilIcon, ReplyIcon, RotateCwIcon, + TrendingUpIcon, } from "lucide-react"; import React from "react"; +import { flushSync } from "react-dom"; import { toast } from "sonner"; import { useTranslations } from "use-intl"; @@ -28,16 +33,34 @@ import { EmptyTitle, } from "@/components/ui/empty"; import { Skeleton } from "@/components/ui/skeleton"; +import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { UserFormat } from "@/components/user-format"; import { UserPreview } from "@/components/user-preview"; import { useRevealHashTarget } from "@/hooks/use-reveal-hash-target"; +import { + reactionsCatalogQueryOptions, + reactionSummaryQueryOptions, +} from "@/tanstack/reactions/query"; import { ReactionBar } from "@/tanstack/reactions/reaction-bar"; +import { reactionPoints } from "@/tanstack/reactions/reaction-points"; -import type { ContentCommentNode, ContentCommentTreeNode } from "./thread"; +import type { + AnyCommentsDisplay, + CardThreadContextValue, + CommentTreeNode, + ContentCommentsDisplay, +} from "./card-thread"; +import type { ContentCommentNode } from "./thread"; import type { ContentCommentsController } from "./use-content-comments"; import { ContentAccessRequired } from "../content/access-required"; import { contentCommentAuthor, contentCommentAuthorName } from "./author"; +import { + CardThreadContext, + commentAnchorIdOf, + ContentCommentCard, + nodeTime, +} from "./card-thread"; import { ContentCommentActions, ContentCommentComposer, @@ -51,33 +74,9 @@ const EDITED_AFTER_MS = 60_000; export { CONTENT_COMMENT_ANCHOR_PREFIX }; -/** How the default comments section links, labels and renders comments. */ -export interface ContentCommentsDisplay { - /** - * What follows `comment-` in a comment's element id, for links such as - * `#comment-42`. Defaults to the comment's id; return its slug to match - * permalinks built from slugs. - */ - anchorKey?: (record: TRecord) => string; - /** - * The link on a comment's date. Gets the element id, e.g. `comment-42`. - * Defaults to `#comment-42` on the current page. - */ - permalink?: (anchorId: string) => string; - /** Replaces parts of a comment. Each gets the comment's public record. */ - render?: { - /** Extra buttons in the row under the comment, next to **Reply**. */ - actions?: (record: TRecord) => React.ReactNode; - /** The author's name; defaults to the `author` field's person. */ - author?: (record: TRecord) => React.ReactNode; - /** The text; defaults to the rich-text `field`. */ - body?: (record: TRecord) => React.ReactNode; - /** Extra details after the date, such as a badge. */ - meta?: (record: TRecord) => React.ReactNode; - }; -} +export type { ContentCommentsDisplay }; -type AnyDisplay = ContentCommentsDisplay; +type AnyDisplay = AnyCommentsDisplay; const recordField = (record: unknown, name: string): unknown => typeof record === "object" && record !== null && name in record @@ -341,66 +340,25 @@ export const ContentCommentItem = ({ ); }; -/** Deeper replies stop indenting here, so narrow screens keep their width. */ -const INDENT_UNTIL_DEPTH = 3; - -const CommentBranch = ({ - display, - highlightedId, - node, -}: { - display: AnyDisplay; - highlightedId: null | string; - node: ContentCommentTreeNode; -}) => { - const anchorId = anchorIdOf(node, display); - - return ( -
  • - - {node.children.length > 0 ? ( -
      - {node.children.map(child => ( - - ))} -
    - ) : null} -
  • - ); -}; - const COMMENT_SKELETON_KEYS = ["first", "second", "third"]; const CommentsSkeleton = ({ label }: { label: string }) => ( -
    +
    {label} {COMMENT_SKELETON_KEYS.map(key => ( -

    diff --git a/apps/web/src/proto/forum-home/score.tsx b/apps/web/src/proto/forum-home/score.tsx index c55a988ac..ded2ff036 100644 --- a/apps/web/src/proto/forum-home/score.tsx +++ b/apps/web/src/proto/forum-home/score.tsx @@ -18,7 +18,7 @@ import { useFormatter, useTranslations } from 'use-intl' import type { VariantProps } from './data' -import { CardsLayout, MetaItem } from './layout' +import { CardsLayout, MetaItem, MetaLine } from './layout' import { useLivePoints } from './parts' const ScoreColumn = ({ topic }: { topic: FeedTopic }) => { @@ -67,9 +67,9 @@ const ScoreCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => {
    -

    + {forum ? ( - + { ) : null} - - + + @@ -89,7 +89,7 @@ const ScoreCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { ) : null} -

    +

    { ) : null}
    -

    + {forum ? ( - + { ) : null} - + - + @@ -69,7 +69,7 @@ const SoftCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { ) : null} -

    +

    { ) : null}
    - +
    Date: Tue, 24 Nov 2026 13:50:13 +0000 Subject: [PATCH 10/10] =?UTF-8?q?feat(forum):=20=E2=9C=A8=20Topic=20cards?= =?UTF-8?q?=20on=20the=20forum=20feed,=20sidebar=20with=20an=20about=20car?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every topic in the feed is its own card - forum icon, meta line, title, excerpt and a footer with points, reactions and comments - on /forum and every forum page. The /forum sidebar sticks and opens with the description, totals and the New topic button. The forum home prototype is removed; the decision and rejected directions are in plans/forum-home-layout.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CnAiFY7Jx5zhRmwMYfnFKU --- apps/web/content/docs/guides/forum.mdx | 58 +++-- apps/web/src/page-cache.gen.ts | 1 - apps/web/src/proto/forum-home/cards.tsx | 122 --------- apps/web/src/proto/forum-home/data.tsx | 45 ---- apps/web/src/proto/forum-home/grid.tsx | 110 -------- apps/web/src/proto/forum-home/harness.tsx | 238 ------------------ apps/web/src/proto/forum-home/layout.tsx | 165 ------------ apps/web/src/proto/forum-home/parts.tsx | 128 ---------- apps/web/src/proto/forum-home/people.tsx | 161 ------------ apps/web/src/proto/forum-home/score.tsx | 141 ----------- apps/web/src/proto/forum-home/soft.tsx | 124 --------- apps/web/src/routeTree.gen.ts | 21 -- .../web/src/routes/_main/proto.forum-home.tsx | 20 -- plans/forum-home-layout.md | 57 +++++ plugins/forum/src/locales/en.json | 1 - plugins/forum/src/pages/forums-page.tsx | 67 ++++- plugins/forum/src/pages/topic-feed.tsx | 146 ++++++----- 17 files changed, 229 insertions(+), 1376 deletions(-) delete mode 100644 apps/web/src/proto/forum-home/cards.tsx delete mode 100644 apps/web/src/proto/forum-home/data.tsx delete mode 100644 apps/web/src/proto/forum-home/grid.tsx delete mode 100644 apps/web/src/proto/forum-home/harness.tsx delete mode 100644 apps/web/src/proto/forum-home/layout.tsx delete mode 100644 apps/web/src/proto/forum-home/parts.tsx delete mode 100644 apps/web/src/proto/forum-home/people.tsx delete mode 100644 apps/web/src/proto/forum-home/score.tsx delete mode 100644 apps/web/src/proto/forum-home/soft.tsx delete mode 100644 apps/web/src/routes/_main/proto.forum-home.tsx create mode 100644 plans/forum-home-layout.md diff --git a/apps/web/content/docs/guides/forum.mdx b/apps/web/content/docs/guides/forum.mdx index 9fff5dd67..440681439 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -4,7 +4,7 @@ description: Enable the @vitnode/forum plugin, create forums in AdminCP, choose icon: MessagesSquare --- -import { Tab, Tabs } from "fumadocs-ui/components/tabs"; +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' `@vitnode/forum` adds a community forum to a VitNode app: a tree of forums, topics inside them and threaded comments. It is built only from @@ -13,8 +13,8 @@ forums, two content types and a [thread](/docs/content-engine/threads) - so everything you learn here works the same way in your own plugins. - The plugin is `private: true` and ships with the VitNode repository, like - the `newsroom` plugin. It is not published to npm yet. + The plugin is `private: true` and ships with the VitNode repository, like the + `newsroom` plugin. It is not published to npm yet. @@ -26,13 +26,13 @@ Add the API factory to `vitnode.api.config.ts` - in `apps/web` for a single app, and in `apps/api` too for a split deployment. ```ts title="apps/web/src/vitnode.api.config.ts" -import { forumApiPlugin } from "@vitnode/forum/config.api"; // [!code ++] +import { forumApiPlugin } from '@vitnode/forum/config.api' // [!code ++] export const vitNodeApiConfig = buildApiConfig({ plugins: [ forumApiPlugin(), // [!code ++] ], -}); +}) ``` @@ -44,13 +44,13 @@ The web factory brings the pages, the AdminCP **Forums** screen and the translations. ```ts title="apps/web/src/vitnode.config.ts" -import { forumPlugin } from "@vitnode/forum/config"; // [!code ++] +import { forumPlugin } from '@vitnode/forum/config' // [!code ++] export const vitNodeConfig = buildConfig({ plugins: [ forumPlugin(), // [!code ++] ], -}); +}) ``` @@ -96,23 +96,27 @@ deep, and you can drag them to reorder. A forum's **Icon** accepts the same ## Pages members get -| Page | What it does | -| ------------------------ | ---------------------------------------------------------------------- | -| `/forum` | A feed of topics from every forum you can read, with the forum list | -| `/forum/:slug` | Subforums and the topics of one forum, in the same sortable feed | -| `/forum/create/topic` | Start a topic (signed-in members) | -| `/forum/topics/:slug` | The topic, its comments, and a comment box | -| `/forum/topics/:id/edit` | Edit your own topic | -| `/forum/comments/:slug` | Permalink of one comment - redirects to its place in the topic | -| `/forum/me/pending` | Your posts a moderator approved, declined, or has not looked at yet | +| Page | What it does | +| ------------------------ | ------------------------------------------------------------------- | +| `/forum` | A feed of topics from every forum you can read, with the forum list | +| `/forum/:slug` | Subforums and the topics of one forum, in the same sortable feed | +| `/forum/create/topic` | Start a topic (signed-in members) | +| `/forum/topics/:slug` | The topic, its comments, and a comment box | +| `/forum/topics/:id/edit` | Edit your own topic | +| `/forum/comments/:slug` | Permalink of one comment - redirects to its place in the topic | +| `/forum/me/pending` | Your posts a moderator approved, declined, or has not looked at yet | ## Sort the feed `/forum` works like a Reddit front page: one feed of topics from every forum -the visitor may read, with the forum tree beside it (a row of forum chips on -phones). Each forum page shows its own topics the same way. Every topic card -has its forum, author, age, title, a short excerpt, its points, its reactions - -members react right from the feed - and its comments. +the visitor may read. Beside it sits a sidebar that follows you down the page: +the forum's description, how many topics and comments it holds, a **New topic** +button and the forum tree (on phones, a row of forum chips instead). Each forum +page shows its own topics the same way. + +Every topic is a card: the forum's icon, then its forum, author and age, the +title and a short excerpt. The card's footer holds its points and reactions - +members react right from the feed - and a link straight to its comments. | Sort | URL | Shows first | | ------ | ------------------ | ------------------------------------------------------------ | @@ -129,15 +133,15 @@ in forums the visitor cannot read never make it into their feed. Need the feed in your own component? Call the same route: ```ts -import { fetcher } from "@vitnode/core/tanstack/fetcher"; +import { fetcher } from '@vitnode/core/tanstack/fetcher' const res = await fetcher({ - plugin: "@vitnode/forum", - method: "get", - module: "forum", - path: "/feed", - args: { query: { page: 1, sort: "top", t: "month" } }, -}); + plugin: '@vitnode/forum', + method: 'get', + module: 'forum', + path: '/feed', + args: { query: { page: 1, sort: 'top', t: 'month' } }, +}) ``` Add `forumId` to the query for one forum's topics only. diff --git a/apps/web/src/page-cache.gen.ts b/apps/web/src/page-cache.gen.ts index 26d81c72b..8e67c777f 100644 --- a/apps/web/src/page-cache.gen.ts +++ b/apps/web/src/page-cache.gen.ts @@ -88,7 +88,6 @@ export const pageCacheRoutes: PageCacheRouteTable = [ { path: '/settings/standing' }, { path: '/admin/core' }, { path: '/docs/search' }, - { path: '/proto/forum-home' }, { path: '/letters/:id/edit' }, { path: '/news/:id/edit' }, { path: '/blog/:slug' }, diff --git a/apps/web/src/proto/forum-home/cards.tsx b/apps/web/src/proto/forum-home/cards.tsx deleted file mode 100644 index f5130c8bb..000000000 --- a/apps/web/src/proto/forum-home/cards.tsx +++ /dev/null @@ -1,122 +0,0 @@ -// Prototype - riff anchor "Cards" (picked last round): every topic is its own -// card, the forum's icon anchors it on the left, and points, reactions and -// comments sit in a footer bar. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { buttonVariants } from '@vitnode/core/components/ui/button' -import { contentTarget } from '@vitnode/core/content' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { ReactionBar, ReactionPoints } from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref, topicHref } from '@vitnode/forum/pages/forum-links' -import { - ForumIcon, - PersonAvatar, - PersonName, - TimeAgo, -} from '@vitnode/forum/pages/forum-ui' -import { MessageSquareIcon } from 'lucide-react' -import { useTranslations } from 'use-intl' - -import type { VariantProps } from './data' - -import { CardsLayout, MetaItem, MetaLine } from './layout' - -const TopicCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { - const t = useTranslations('@vitnode/forum.forums') - const titleId = `card-${topic.id}` - const target = contentTarget('@vitnode/forum', topicContentType, topic.id) - - return ( -
  • -
    -
    - {forum ? ( - - ) : null} -
    - - {forum ? ( - - - {forum.name} - - - ) : null} - - - - - - - {topic.publishedAt ? ( - - - - ) : null} - -

    - - {topic.title} - -

    - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} -
    -
    -
    -
    - - -
    - - -
    -
    -
  • - ) -} - -export const Cards = (props: VariantProps) => ( - ( -
      - {topics.map((topic) => ( - - ))} -
    - )} - /> -) diff --git a/apps/web/src/proto/forum-home/data.tsx b/apps/web/src/proto/forum-home/data.tsx deleted file mode 100644 index 4fbaef799..000000000 --- a/apps/web/src/proto/forum-home/data.tsx +++ /dev/null @@ -1,45 +0,0 @@ -// Prototype - deleted after the decision. Not imported by production code. -import type { ForumSearch } from '@vitnode/forum/pages/forum-links' - -import { - keepPreviousData, - useQuery, - useSuspenseQuery, -} from '@tanstack/react-query' -import { contentContainerTree } from '@vitnode/core/content' -import { useLocale } from '@vitnode/core/tanstack/i18n' -import { - feedQueryOptions, - forumsQueryOptions, - forumStatsQueryOptions, -} from '@vitnode/forum/pages/forum-queries' - -export const useHomeData = () => { - const locale = useLocale() - const forums = useSuspenseQuery(forumsQueryOptions(locale)).data - const stats = useSuspenseQuery(forumStatsQueryOptions()).data - - return { - forums, - forumsById: new Map(forums.map((forum) => [forum.id, forum])), - stats: new Map(stats.map((item) => [item.forumId, item])), - totals: stats.reduce( - (sum, item) => ({ - comments: sum.comments + item.commentCount, - topics: sum.topics + item.topicCount, - }), - { comments: 0, topics: 0 }, - ), - tree: contentContainerTree(forums), - } -} - -/** A feed that keeps the previous page on screen while the next one loads. */ -export const useFeed = (search: ForumSearch) => - useQuery({ ...feedQueryOptions(search), placeholderData: keepPreviousData }) - -/** Props every variant gets: the URL's feed search and links that keep `?v`. */ -export interface VariantProps { - hrefFor: (search: ForumSearch) => string - search: ForumSearch -} diff --git a/apps/web/src/proto/forum-home/grid.tsx b/apps/web/src/proto/forum-home/grid.tsx deleted file mode 100644 index 16402ed34..000000000 --- a/apps/web/src/proto/forum-home/grid.tsx +++ /dev/null @@ -1,110 +0,0 @@ -// Prototype - riff 4 "Grid": the same cards, laid out as a two-column board -// on tablets and up - twice the topics above the fold. Each card is a fixed -// shape: forum on top, title, a clamped excerpt, author, then points, -// reactions and comments pinned to the bottom so rows line up. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { contentTarget } from '@vitnode/core/content' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { ReactionBar, ReactionPoints } from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref, topicHref } from '@vitnode/forum/pages/forum-links' -import { - ForumIcon, - PersonAvatar, - PersonName, - TimeAgo, -} from '@vitnode/forum/pages/forum-ui' -import { MessageSquareIcon } from 'lucide-react' -import { useFormatter } from 'use-intl' - -import type { VariantProps } from './data' - -import { CardsLayout, MetaItem, MetaLine } from './layout' - -const GridCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { - const format = useFormatter() - const titleId = `grid-${topic.id}` - const target = contentTarget('@vitnode/forum', topicContentType, topic.id) - - return ( -
  • -
    - {forum ? ( - - - {forum.name} - - ) : null} -

    - - {topic.title} - -

    - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} -
    - - - - - - - - {topic.publishedAt ? ( - - - - ) : null} - -
    -
    - - - - -
    -
    -
  • - ) -} - -export const Grid = (props: VariantProps) => ( - ( -
      - {topics.map((topic) => ( - - ))} -
    - )} - maxWidth="max-w-7xl" - /> -) diff --git a/apps/web/src/proto/forum-home/harness.tsx b/apps/web/src/proto/forum-home/harness.tsx deleted file mode 100644 index 17e5558cf..000000000 --- a/apps/web/src/proto/forum-home/harness.tsx +++ /dev/null @@ -1,238 +0,0 @@ -import type { ForumSearch } from '@vitnode/forum/pages/forum-links' - -// Prototype harness - deleted after the decision. Picker per PICKER.md. -import { RouteMessages } from '@vitnode/core/tanstack/i18n' -import { FeedPendingSkeleton } from '@vitnode/core/tanstack/pending' -import React from 'react' - -import { Cards } from './cards' -import { Grid } from './grid' -import { People } from './people' -import { Score } from './score' -import { Soft } from './soft' - -const VARIANTS = [ - { component: Cards, name: 'Cards' }, - { component: Score, name: 'Score' }, - { component: People, name: 'People' }, - { component: Grid, name: 'Grid' }, - { component: Soft, name: 'Soft' }, -] as const - -/** The feed URL inside the prototype, keeping the picked variant. */ -const protoHref = (variant: number, search: ForumSearch) => { - const params = new URLSearchParams({ v: String(variant + 1) }) - if (search.sort && search.sort !== 'hot') params.set('sort', search.sort) - if (search.sort === 'top' && search.t) params.set('t', search.t) - if (search.page && search.page > 1) params.set('page', String(search.page)) - - return `/proto/forum-home?${params.toString()}` -} - -const PICKER_CSS = ` -.proto-picker { - position: fixed; - bottom: 24px; - left: 50%; - transform: translateX(-50%); - z-index: 2147483647; - display: flex; - align-items: center; - gap: 2px; - padding: 4px; - border-radius: 999px; - background: rgba(10, 10, 10, 0.82); - -webkit-backdrop-filter: blur(12px) saturate(1.4); - backdrop-filter: blur(12px) saturate(1.4); - box-shadow: - 0 0 0 1px rgba(255, 255, 255, 0.08) inset, - 0 8px 24px rgba(0, 0, 0, 0.24), - 0 2px 6px rgba(0, 0, 0, 0.12); - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; - font-size: 13px; - line-height: 1; - -webkit-font-smoothing: antialiased; - user-select: none; - -webkit-user-select: none; -} -.proto-picker-highlight { - position: absolute; - top: 4px; - left: 0; - height: 28px; - border-radius: 999px; - background: rgba(255, 255, 255, 0.12); - will-change: transform; -} -.proto-picker[data-ready] .proto-picker-highlight { - transition: - transform 250ms cubic-bezier(0.23, 1, 0.32, 1), - width 250ms cubic-bezier(0.23, 1, 0.32, 1); -} -@media (prefers-reduced-motion: reduce) { - .proto-picker[data-ready] .proto-picker-highlight { transition: none; } -} -.proto-picker-item { - position: relative; - display: flex; - align-items: center; - height: 28px; - padding: 0 12px; - border: 0; - border-radius: 999px; - background: transparent; - color: rgba(255, 255, 255, 0.55); - font: inherit; - cursor: pointer; - transition: color 150ms ease-out; -} -.proto-picker-item:hover { color: rgba(255, 255, 255, 0.85); } -.proto-picker-item:active { transform: scale(0.97); } -.proto-picker-item:focus-visible { - outline: 2px solid rgba(255, 255, 255, 0.4); - outline-offset: 2px; -} -.proto-picker-item[data-active] { color: #fff; } -.proto-picker[data-position="top"] { - bottom: auto; - top: 24px; -} -` - -const Picker = ({ - current, - onSelect, -}: { - current: number - onSelect: (index: number) => void -}) => { - const navRef = React.useRef(null) - const highlightRef = React.useRef(null) - const itemRefs = React.useRef<(HTMLButtonElement | null)[]>([]) - - React.useLayoutEffect(() => { - const move = () => { - const item = itemRefs.current[current] - const highlight = highlightRef.current - if (!item || !highlight) return - highlight.style.width = `${item.offsetWidth}px` - highlight.style.transform = `translateX(${item.offsetLeft}px)` - } - move() - window.addEventListener('resize', move) - - return () => { - window.removeEventListener('resize', move) - } - }, [current]) - - React.useEffect(() => { - const frame = requestAnimationFrame(() => - requestAnimationFrame(() => { - navRef.current?.setAttribute('data-ready', '') - }), - ) - - return () => { - cancelAnimationFrame(frame) - } - }, []) - - return ( - // The app's bottom bar sits at the bottom center on phones. - - ) -} - -export const ForumHomeProto = ({ - initial, - search, -}: { - initial: number - search: ForumSearch -}) => { - const [current, setCurrent] = React.useState( - initial >= 0 && initial < VARIANTS.length ? initial : 0, - ) - - const select = React.useCallback((index: number) => { - if (index < 0 || index >= VARIANTS.length) return - setCurrent(index) - const url = new URL(window.location.href) - url.searchParams.set('v', String(index + 1)) - window.history.replaceState(window.history.state, '', url) - }, []) - - React.useEffect(() => { - const onKey = (event: KeyboardEvent) => { - const target = event.target as HTMLElement - if ( - /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || - target.isContentEditable - ) { - return - } - if (event.metaKey || event.ctrlKey || event.altKey) return - const number = Number.parseInt(event.key, 10) - if (number >= 1 && number <= VARIANTS.length) select(number - 1) - else if (event.key === 'ArrowRight') { - select((current + 1) % VARIANTS.length) - } else if (event.key === 'ArrowLeft') { - select((current - 1 + VARIANTS.length) % VARIANTS.length) - } - } - document.addEventListener('keydown', onKey) - - return () => { - document.removeEventListener('keydown', onKey) - } - }, [current, select]) - - const Variant = VARIANTS[current].component - - return ( - <> - - - }> - protoHref(current, next)} - key={current} - search={search} - /> - - - - - ) -} diff --git a/apps/web/src/proto/forum-home/layout.tsx b/apps/web/src/proto/forum-home/layout.tsx deleted file mode 100644 index fc5c8d5cd..000000000 --- a/apps/web/src/proto/forum-home/layout.tsx +++ /dev/null @@ -1,165 +0,0 @@ -// Prototype - the page around the card riffs: header, sort, feed, pages and -// a sticky sidebar. Each variant brings its own list. Deleted after the -// decision. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { buttonVariants } from '@vitnode/core/components/ui/button' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { FeedPendingSkeleton } from '@vitnode/core/tanstack/pending' -import { topicNewHref } from '@vitnode/forum/pages/forum-links' -import { FeedPagination, FeedSortNav } from '@vitnode/forum/pages/topic-feed' -import { cn } from 'cn' -import { PenSquareIcon } from 'lucide-react' -import React from 'react' -import { useFormatter, useTranslations } from 'use-intl' - -import type { VariantProps } from './data' - -import { useFeed, useHomeData } from './data' -import { ForumChips, ForumTree } from './parts' - -/** A wrapping line of meta items with a dot between them. Every item carries - * a leading dot, and the line is shifted left by one dot and clipped, so the - * dot that would start a line - the first, or one after a wrap - is hidden. */ -export const MetaLine = ({ children }: { children: React.ReactNode }) => ( -
    -

    {children}

    -
    -) - -export const MetaItem = ({ children }: { children: React.ReactNode }) => ( - - {children} - -) - -const About = ({ surface }: { surface: string }) => { - const t = useTranslations('@vitnode/forum.forums') - const format = useFormatter() - const { totals } = useHomeData() - - return ( -
    -

    - {t('desc')} -

    -
    -
    -
    {t('stats.topics')}
    -
    - {format.number(totals.topics)} -
    -
    -
    -
    - {t('stats.comments')} -
    -
    - {format.number(totals.comments)} -
    -
    -
    - - -
    - ) -} - -export const CardsLayout = ({ - hrefFor, - list, - maxWidth = 'max-w-6xl', - search, - surface = 'bg-card rounded-xl border shadow-xs', -}: VariantProps & { - list: ( - topics: FeedTopic[], - forums: ReadonlyMap, - ) => React.ReactNode - maxWidth?: string - /** Classes of the sidebar's boxes, so they match the variant's cards. */ - surface?: string -}) => { - const t = useTranslations('@vitnode/forum.forums') - const { forumsById, stats, tree } = useHomeData() - const feed = useFeed(search) - - return ( -
    -
    -

    - {t('title')} -

    - - -
    - -
    -
    -

    - {t('feed.title')} -

    - - - {feed.data ? ( -
    - {list(feed.data.topics, forumsById)} - -
    - ) : ( - - )} -
    - - -
    -
    - ) -} diff --git a/apps/web/src/proto/forum-home/parts.tsx b/apps/web/src/proto/forum-home/parts.tsx deleted file mode 100644 index f023439ee..000000000 --- a/apps/web/src/proto/forum-home/parts.tsx +++ /dev/null @@ -1,128 +0,0 @@ -// Prototype - shared pieces of the riff variants. Deleted after the decision. -import type { ContentContainerTreeNode } from '@vitnode/core/content' -import type { Forum, ForumStats } from '@vitnode/forum/pages/forum-data' - -import { useQuery } from '@tanstack/react-query' -import { buttonVariants } from '@vitnode/core/components/ui/button' -import { contentTarget } from '@vitnode/core/content' -import { useSessionQuery } from '@vitnode/core/tanstack/auth' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { - reactionPoints, - reactionsCatalogQueryOptions, - reactionSummaryQueryOptions, -} from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref } from '@vitnode/forum/pages/forum-links' -import { ForumIcon } from '@vitnode/forum/pages/forum-ui' -import { cn } from 'cn' -import { LockIcon } from 'lucide-react' -import { useFormatter, useTranslations } from 'use-intl' - -export const ForumTree = ({ - depth = 0, - nodes, - stats, -}: { - depth?: number - nodes: ContentContainerTreeNode[] - stats: ReadonlyMap -}) => { - const t = useTranslations('@vitnode/forum.forums') - const format = useFormatter() - - return ( -
      - {nodes.map((node) => ( -
    • - - - - {node.name} - - {node.access.canRead ? ( - - {t('stats.topics')}: - {format.number(stats.get(node.id)?.topicCount ?? 0)} - - ) : ( - - )} - - {node.children.length > 0 ? ( -
      - -
      - ) : null} -
    • - ))} -
    - ) -} - -/** The forum chips the baseline shows on phones instead of the sidebar. */ -export const ForumChips = ({ - className, - nodes, -}: { - className?: string - nodes: ContentContainerTreeNode[] -}) => { - const t = useTranslations('@vitnode/forum.forums') - - return ( - - ) -} - -/** The topic's live points: what the card's `ReactionBar` loaded, or the - * server's ranking number until then. Read-only, like `ReactionPoints`. */ -export const useLivePoints = (topicId: number, initial: number) => { - const session = useSessionQuery() - const viewerId = session.data?.user?.id ?? null - const target = contentTarget('@vitnode/forum', topicContentType, topicId) - const summary = useQuery({ - ...reactionSummaryQueryOptions(target, viewerId), - enabled: false, - }) - const catalog = useQuery({ - ...reactionsCatalogQueryOptions(viewerId), - enabled: false, - }) - - return summary.data && catalog.data - ? reactionPoints(summary.data, catalog.data) - : initial -} diff --git a/apps/web/src/proto/forum-home/people.tsx b/apps/web/src/proto/forum-home/people.tsx deleted file mode 100644 index 7a26988dc..000000000 --- a/apps/web/src/proto/forum-home/people.tsx +++ /dev/null @@ -1,161 +0,0 @@ -// Prototype - riff 3 "People": a card reads like a post from someone, not an -// entry in a forum. The author leads - big avatar, name, "in Forum · 6h" - -// and the footer is a row of actions: react, comment, share. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { Button, buttonVariants } from '@vitnode/core/components/ui/button' -import { contentTarget } from '@vitnode/core/content' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { ReactionBar, ReactionPoints } from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref, topicHref } from '@vitnode/forum/pages/forum-links' -import { - PersonAvatar, - PersonName, - TimeAgo, -} from '@vitnode/forum/pages/forum-ui' -import { MessageSquareIcon, Share2Icon } from 'lucide-react' -import { toast } from 'sonner' -import { useTranslations } from 'use-intl' - -import type { VariantProps } from './data' - -import { CardsLayout, MetaItem, MetaLine } from './layout' - -const ShareButton = ({ topic }: { topic: FeedTopic }) => { - const share = async () => { - const url = new URL(topicHref(topic.slug), window.location.origin).href - if (typeof navigator.share === 'function') { - try { - await navigator.share({ title: topic.title, url }) - } catch { - // Closed the share sheet - nothing to do. - } - - return - } - try { - await navigator.clipboard.writeText(url) - toast.success('Link copied', { description: topic.title }) - } catch { - toast.error('Could not copy the link', { description: url }) - } - } - - return ( - - ) -} - -const PostCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { - const t = useTranslations('@vitnode/forum.forums') - const titleId = `post-${topic.id}` - const target = contentTarget('@vitnode/forum', topicContentType, topic.id) - - return ( -
  • -
    -
    - -
    - - - - - {forum ? ( - - - in{' '} - - {forum.name} - - - - ) : null} - {topic.publishedAt ? ( - - - - ) : null} - -
    -
    - -
    -

    - - {topic.title} - -

    - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} -
    - -
    - - {topic.commentCount > 0 && topic.lastActivityAt ? ( - - {t('last_comment')} - - ) : null} -
    - -
    - -
    - - - -
    -
    -
    -
  • - ) -} - -export const People = (props: VariantProps) => ( - ( -
      - {topics.map((topic) => ( - - ))} -
    - )} - /> -) diff --git a/apps/web/src/proto/forum-home/score.tsx b/apps/web/src/proto/forum-home/score.tsx deleted file mode 100644 index ded2ff036..000000000 --- a/apps/web/src/proto/forum-home/score.tsx +++ /dev/null @@ -1,141 +0,0 @@ -// Prototype - riff 2 "Score": the card's left edge is its points. A tall -// column holds the number - big, tinted by sign, ticking live as people -// react - so scanning the feed reads like a scoreboard. The forum icon moves -// into the meta line; the footer keeps reactions and comments. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { buttonVariants } from '@vitnode/core/components/ui/button' -import { FEEDBACK_TONE_TEXT } from '@vitnode/core/components/ui/feedback-tone' -import { contentTarget } from '@vitnode/core/content' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { ReactionBar } from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref, topicHref } from '@vitnode/forum/pages/forum-links' -import { ForumIcon, PersonName, TimeAgo } from '@vitnode/forum/pages/forum-ui' -import { cn } from 'cn' -import { MessageSquareIcon } from 'lucide-react' -import { useFormatter, useTranslations } from 'use-intl' - -import type { VariantProps } from './data' - -import { CardsLayout, MetaItem, MetaLine } from './layout' -import { useLivePoints } from './parts' - -const ScoreColumn = ({ topic }: { topic: FeedTopic }) => { - const format = useFormatter() - const points = useLivePoints(topic.id, topic.points) - - return ( -
    0 && 'bg-success/5 dark:bg-success/10', - points < 0 && 'bg-destructive/5 dark:bg-destructive/10', - points === 0 && 'bg-muted/40', - )} - > - 0 && FEEDBACK_TONE_TEXT.success, - points < 0 && FEEDBACK_TONE_TEXT.destructive, - points === 0 && 'text-muted-foreground', - )} - > - {format.number(points, { - notation: 'compact', - signDisplay: 'exceptZero', - })} - - pts - points -
    - ) -} - -const ScoreCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { - const t = useTranslations('@vitnode/forum.forums') - const titleId = `score-${topic.id}` - const target = contentTarget('@vitnode/forum', topicContentType, topic.id) - - return ( -
  • -
    - -
    -
    - - {forum ? ( - - - - {forum.name} - - - ) : null} - - - - - - {topic.publishedAt ? ( - - - - ) : null} - -

    - - {topic.title} - -

    - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} -
    -
    - - - -
    -
    -
    -
  • - ) -} - -export const Score = (props: VariantProps) => ( - ( -
      - {topics.map((topic) => ( - - ))} -
    - )} - /> -) diff --git a/apps/web/src/proto/forum-home/soft.tsx b/apps/web/src/proto/forum-home/soft.tsx deleted file mode 100644 index 101442546..000000000 --- a/apps/web/src/proto/forum-home/soft.tsx +++ /dev/null @@ -1,124 +0,0 @@ -// Prototype - riff 5 "Soft": the Cards layout with a calmer surface. No -// borders or shadows - each card is a softly tinted block with more air, the -// footer bar dissolves into the card, and the sidebar matches. Hover deepens -// the tint instead of drawing an edge. -import type { FeedTopic, Forum } from '@vitnode/forum/pages/forum-data' - -import { buttonVariants } from '@vitnode/core/components/ui/button' -import { contentTarget } from '@vitnode/core/content' -import { HrefLink } from '@vitnode/core/tanstack/link' -import { ReactionBar, ReactionPoints } from '@vitnode/core/tanstack/reactions' -import { topicContentType } from '@vitnode/forum/content/topic' -import { forumHref, topicHref } from '@vitnode/forum/pages/forum-links' -import { - ForumIcon, - PersonAvatar, - PersonName, - TimeAgo, -} from '@vitnode/forum/pages/forum-ui' -import { MessageSquareIcon } from 'lucide-react' -import { useTranslations } from 'use-intl' - -import type { VariantProps } from './data' - -import { CardsLayout, MetaItem, MetaLine } from './layout' - -const SURFACE = 'bg-muted/50 rounded-2xl' - -const SoftCard = ({ forum, topic }: { forum?: Forum; topic: FeedTopic }) => { - const t = useTranslations('@vitnode/forum.forums') - const titleId = `soft-${topic.id}` - const target = contentTarget('@vitnode/forum', topicContentType, topic.id) - - return ( -
  • -
    - {forum ? ( - - ) : null} -
    - - {forum ? ( - - - {forum.name} - - - ) : null} - - - - - - - {topic.publishedAt ? ( - - - - ) : null} - -

    - - {topic.title} - -

    - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} -
    -
    - - -
    - - -
    -
    -
    -
  • - ) -} - -export const Soft = (props: VariantProps) => ( - ( -
      - {topics.map((topic) => ( - - ))} -
    - )} - surface={SURFACE} - /> -) diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 130c2baf4..4aade3421 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -21,7 +21,6 @@ import { Route as DocsSearchRouteImport } from './routes/docs.search' import { Route as DocsChar123Char125DotmdRouteImport } from './routes/docs.{$}[.]md' import { Route as DocsDocsIndexRouteImport } from './routes/_docs/docs.index' import { Route as DocsDocsSplatRouteImport } from './routes/_docs/docs.$' -import { Route as MainProtoForumHomeRouteImport } from './routes/_main/proto.forum-home' import { Route as MainSolutionsIndexRouteImport } from './routes/_main/solutions/index' import { Route as MainSolutionsSlugRouteImport } from './routes/_main/solutions/$slug' import { Route as AdminAdminCoreIndexRouteImport } from './routes/_admin/admin.core.index' @@ -83,11 +82,6 @@ const DocsDocsSplatRoute = DocsDocsSplatRouteImport.update({ path: '/docs/$', getParentRoute: () => DocsRoute, } as any) -const MainProtoForumHomeRoute = MainProtoForumHomeRouteImport.update({ - id: '/proto/forum-home', - path: '/proto/forum-home', - getParentRoute: () => MainRoute, -} as any) const MainSolutionsIndexRoute = MainSolutionsIndexRouteImport.update({ id: '/solutions/', path: '/solutions/', @@ -113,7 +107,6 @@ export interface FileRoutesByFullPath { '/docs/search': typeof DocsSearchRoute '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute '/docs/$': typeof DocsDocsSplatRoute - '/proto/forum-home': typeof MainProtoForumHomeRoute '/solutions/$slug': typeof MainSolutionsSlugRoute '/docs/': typeof DocsDocsIndexRoute '/solutions/': typeof MainSolutionsIndexRoute @@ -128,7 +121,6 @@ export interface FileRoutesByTo { '/docs/search': typeof DocsSearchRoute '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute '/docs/$': typeof DocsDocsSplatRoute - '/proto/forum-home': typeof MainProtoForumHomeRoute '/solutions/$slug': typeof MainSolutionsSlugRoute '/docs': typeof DocsDocsIndexRoute '/solutions': typeof MainSolutionsIndexRoute @@ -147,7 +139,6 @@ export interface FileRoutesById { '/docs/{$}.md': typeof DocsChar123Char125DotmdRoute '/_main/': typeof MainIndexRoute '/_docs/docs/$': typeof DocsDocsSplatRoute - '/_main/proto/forum-home': typeof MainProtoForumHomeRoute '/_main/solutions/$slug': typeof MainSolutionsSlugRoute '/_docs/docs/': typeof DocsDocsIndexRoute '/_main/solutions/': typeof MainSolutionsIndexRoute @@ -164,7 +155,6 @@ export interface FileRouteTypes { | '/docs/search' | '/docs/{$}.md' | '/docs/$' - | '/proto/forum-home' | '/solutions/$slug' | '/docs/' | '/solutions/' @@ -179,7 +169,6 @@ export interface FileRouteTypes { | '/docs/search' | '/docs/{$}.md' | '/docs/$' - | '/proto/forum-home' | '/solutions/$slug' | '/docs' | '/solutions' @@ -197,7 +186,6 @@ export interface FileRouteTypes { | '/docs/{$}.md' | '/_main/' | '/_docs/docs/$' - | '/_main/proto/forum-home' | '/_main/solutions/$slug' | '/_docs/docs/' | '/_main/solutions/' @@ -301,13 +289,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DocsDocsSplatRouteImport parentRoute: typeof DocsRoute } - '/_main/proto/forum-home': { - id: '/_main/proto/forum-home' - path: '/proto/forum-home' - fullPath: '/proto/forum-home' - preLoaderRoute: typeof MainProtoForumHomeRouteImport - parentRoute: typeof MainRoute - } '/_main/solutions/': { id: '/_main/solutions/' path: '/solutions' @@ -357,7 +338,6 @@ const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) interface MainRouteChildren { MainPluginsRoute: typeof MainPluginsRoute MainIndexRoute: typeof MainIndexRoute - MainProtoForumHomeRoute: typeof MainProtoForumHomeRoute MainSolutionsSlugRoute: typeof MainSolutionsSlugRoute MainSolutionsIndexRoute: typeof MainSolutionsIndexRoute } @@ -365,7 +345,6 @@ interface MainRouteChildren { const MainRouteChildren: MainRouteChildren = { MainPluginsRoute: MainPluginsRoute, MainIndexRoute: MainIndexRoute, - MainProtoForumHomeRoute: MainProtoForumHomeRoute, MainSolutionsSlugRoute: MainSolutionsSlugRoute, MainSolutionsIndexRoute: MainSolutionsIndexRoute, } diff --git a/apps/web/src/routes/_main/proto.forum-home.tsx b/apps/web/src/routes/_main/proto.forum-home.tsx deleted file mode 100644 index 68b3b1d39..000000000 --- a/apps/web/src/routes/_main/proto.forum-home.tsx +++ /dev/null @@ -1,20 +0,0 @@ -// Prototype route - deleted after the decision. -import { createFileRoute } from '@tanstack/react-router' -import { forumSearch } from '@vitnode/forum/pages/forum-links' - -import { ForumHomeProto } from '@/proto/forum-home/harness' - -const ProtoPage = () => { - const { v, ...search } = Route.useSearch() - - return -} - -export const Route = createFileRoute('/_main/proto/forum-home')({ - validateSearch: (search: Record) => ({ - v: Number(search.v) || 1, - ...forumSearch(search), - }), - head: () => ({ meta: [{ title: 'Forum home - prototype' }] }), - component: ProtoPage, -}) diff --git a/plans/forum-home-layout.md b/plans/forum-home-layout.md new file mode 100644 index 000000000..31a84b123 --- /dev/null +++ b/plans/forum-home-layout.md @@ -0,0 +1,57 @@ +# Forum home layout - decided from /proto/forum-home + +Two prototype rounds behind a picker, then the pick. The prototype is deleted; +this note is what is left of it. + +## Decision: Cards + +- Every topic is its own card (`bg-card rounded-xl border shadow-xs`, 12px + apart) instead of rows in one bordered list. Shared by `/forum` and every + forum page (`TopicFeed`). +- The forum's icon sits on the card's left edge (from `sm`), the meta line on + top: forum (bold), author with avatar, age. +- Title `text-xl` semibold, excerpt clamped to three lines. +- A footer bar under a border: points pill and reactions on the left, a ghost + "N comments" link to `#comments` on the right. +- Meta dots belong to the item after them and the line is clipped by one dot, + so a wrapped line never starts with a stray "·". +- `/forum` sidebar sticks under the header (`lg:top-20`) and opens with an + "about" card: the forum description, topic and comment totals and the New + topic button. The forum tree follows in its own card. The page header keeps + only the title; New topic shows there below `lg`, where the sidebar is + hidden. +- Dropped: "Last comment … ago" on the card (the Active sort covers it). + +## Rejected + +Round 1 (whole-page directions): + +- **Board** (Invision index first, feed shrunk to three "trending" cards): + the feed - the reason for the redesign - fell below the fold. +- **Compact** (one row per topic, columns): no excerpt or reactions; titles cut + on phones. +- **Editorial** (lead story, story grid, "latest" column): long forum titles ate + the page, and the hierarchy is curated, not ranked. +- **Channels** (Discord-like list filtering in place): weaker URLs and SEO, no + forum pages to share. + +Round 2 (riffs on the then-current page, a feed in one bordered list): + +- **Rail** (sticky left tree, right rail with top of the week): the right rail + only fits from 1280px; below that its content disappears. +- **Density** (Cards/Compact switch): one more control for a choice few + readers make. +- **Focus** (one column, composer prompt, forum strip): flattens the forum + tree; subforums lose their place. +- **Cards** was picked here, then explored in round 3. + +Round 3 (riffs on Cards): + +- **Score** (points as a tall tinted column on the card's edge): a column of + "0" on fresh topics reads empty, and it costs width on phones. +- **People** (author-first post with a share button): the forum, the thing a + forum is organised by, became small print. +- **Grid** (two-column cards): titles clamp to three lines and short topics + next to long ones leave holes. +- **Soft** (borderless tinted cards): weak separation on bright screens; the + bordered card read clearer. diff --git a/plugins/forum/src/locales/en.json b/plugins/forum/src/locales/en.json index 161fd0453..5bd872cc0 100644 --- a/plugins/forum/src/locales/en.json +++ b/plugins/forum/src/locales/en.json @@ -75,7 +75,6 @@ }, "pagination": "Topic pages", "comment_count": "{count, plural, =0 {No comments} one {# comment} other {# comments}}", - "last_comment": "Last comment", "errors": { "title": "That did not go through", "unknown": "Something went wrong. Please try again in a moment.", diff --git a/plugins/forum/src/pages/forums-page.tsx b/plugins/forum/src/pages/forums-page.tsx index fad8f4e68..225dd1379 100644 --- a/plugins/forum/src/pages/forums-page.tsx +++ b/plugins/forum/src/pages/forums-page.tsx @@ -129,7 +129,15 @@ const ForumsPage = ({ loaderData, }: PluginRoutePageProps) => { const t = useTranslations("@vitnode/forum.forums"); + const format = useFormatter(); const { feed, forums, search, tree } = loaderData; + const totals = loaderData.stats.reduce( + (sum, item) => ({ + comments: sum.comments + item.commentCount, + topics: sum.topics + item.topicCount, + }), + { comments: 0, topics: 0 }, + ); const stats = indexBy(loaderData.stats, item => item.forumId); const forumsById = indexBy(forums, item => item.id); @@ -160,17 +168,22 @@ const ForumsPage = ({ return ( + } - description={t("desc")} title={t("title")} wide > -
    -
    +
    +

    {t("feed.title")}

    @@ -204,11 +217,45 @@ const ForumsPage = ({ />
    -
    diff --git a/plugins/forum/src/pages/topic-feed.tsx b/plugins/forum/src/pages/topic-feed.tsx index 4ff519e2d..f3c86d9e0 100644 --- a/plugins/forum/src/pages/topic-feed.tsx +++ b/plugins/forum/src/pages/topic-feed.tsx @@ -115,11 +115,28 @@ export const FeedSortNav = ({ ); }; +/** + * A wrapping line of meta items with a dot between them. Every item carries a + * leading dot and the line is shifted left by one dot and clipped, so no line - + * the first, or one after a wrap - starts with a stray dot. + */ +const MetaLine = ({ children }: { children: React.ReactNode }) => ( +
    +

    {children}

    +
    +); + +const MetaItem = ({ children }: { children: React.ReactNode }) => ( + + {children} + +); + const FeedCard = ({ forum, topic, }: { - /** The topic's forum, shown above the title; omit on the forum's own page. */ + /** The topic's forum, shown beside the title; omit on the forum's own page. */ forum?: Forum; topic: FeedTopic; }) => { @@ -128,85 +145,90 @@ const FeedCard = ({ const target = contentTarget(manifest.id, topicContentType, topic.id); return ( -
  • +
  • -

    +

    {forum ? ( - <> + + ) : null} +
    + + {forum ? ( + + + {forum.name} + + + ) : null} + + + + + + + {topic.publishedAt ? ( + + + + ) : null} + + +

    - - {forum.name} + {topic.title} - - - ) : null} - - - - - {topic.publishedAt ? ( - <> - - - - ) : null} -

    +

    -

    - - {topic.title} - -

    - - {topic.excerpt ? ( -

    - {topic.excerpt} -

    - ) : null} + {topic.excerpt ? ( +

    + {topic.excerpt} +

    + ) : null} +
    +
    -
    +
    -
      -
    • -
    • - {topic.commentCount > 0 && topic.lastActivityAt ? ( -
    • -
    • - ) : null} -
    -
    + + +
  • ); }; /** - * A ranked page of topics, Reddit-style: forum, author and age on top, the - * title, a short excerpt, then its points and reactions - react right from the - * feed - and the conversation around it. + * A ranked page of topics, one card each: the forum's icon beside it, forum, + * author and age on top, the title and a short excerpt, then a footer with its + * points and reactions - react right from the feed - and a link to its + * comments. */ export const TopicFeed = ({ forumId, @@ -255,7 +277,7 @@ export const TopicFeed = ({ } return ( -
      +
        {topics.map(topic => (