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 54074ea51..000000000 Binary files a/apps/web/content/docs/content-engine/threads-frontend-tree.webp and /dev/null differ 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 0c6cd2aca..440681439 100644 --- a/apps/web/content/docs/guides/forum.mdx +++ b/apps/web/content/docs/guides/forum.mdx @@ -1,20 +1,20 @@ --- 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"; +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. - 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,21 +96,82 @@ deep, and you can drag them to reorder. A forum's **Icon** accepts the same ## Pages members get -| 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/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 | - -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. +| 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. 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 | +| ------ | ------------------ | ------------------------------------------------------------ | +| 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 | + +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 - 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: + +```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. + +## 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 + +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** 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/plugins/forum/src/pages/forum-permissions.ts b/plugins/forum/src/pages/forum-permissions.ts index 4a8e69b9b..5e345909a 100644 --- a/plugins/forum/src/pages/forum-permissions.ts +++ b/plugins/forum/src/pages/forum-permissions.ts @@ -21,22 +21,3 @@ export const useTopicPermissions = (ids: readonly number[]) => return await res.json(); }, }); - -/** What the visitor may do with each comment on screen: `canEdit`, `canReport`. */ -export const useCommentPermissions = (ids: readonly number[]) => - useContentPermissions({ - ids, - queryKey: [manifest.id, "comments"], - fetch: async request => { - const res = await fetcher({ - plugin: manifest.id, - method: "get", - module: "content/comments", - path: "/permissions", - args: { query: { ids: request.join(",") } }, - }); - if (res.status !== 200) throw new Error("Loading permissions failed."); - - return await res.json(); - }, - }); diff --git a/plugins/forum/src/pages/forum-queries.test.ts b/plugins/forum/src/pages/forum-queries.test.ts index 9409150bf..dabfd90cb 100644 --- a/plugins/forum/src/pages/forum-queries.test.ts +++ b/plugins/forum/src/pages/forum-queries.test.ts @@ -2,12 +2,18 @@ import { createVitNodeQueryClient } from "@vitnode/core/lib/query-client"; import { describe, expect, it, vi } from "vitest"; import { + forumQueryKeys, forumStatsQueryOptions, invalidateForumComments, isSharedResponse, - threadQueryOptions, } from "./forum-queries"; +// The key `ContentComments` caches a topic's thread under. +const threadKey = (topicId: number) => [ + ...forumQueryKeys.thread(topicId), + "thread", +]; + describe("isSharedResponse", () => { it.each<[null | string, boolean]>([ [null, true], @@ -30,10 +36,15 @@ describe("invalidateForumComments", () => { const otherThread = vi.fn(async () => await Promise.resolve(null)); const stats = vi.fn(async () => await Promise.resolve([])); const load = async () => { - await queryClient.query({ ...threadQueryOptions(7), queryFn: thread }); await queryClient.query({ - ...threadQueryOptions(8), + queryFn: thread, + queryKey: threadKey(7), + staleTime: Number.POSITIVE_INFINITY, + }); + await queryClient.query({ queryFn: otherThread, + queryKey: threadKey(8), + staleTime: Number.POSITIVE_INFINITY, }); await queryClient.query({ ...forumStatsQueryOptions(), queryFn: stats }); }; diff --git a/plugins/forum/src/pages/forum-queries.ts b/plugins/forum/src/pages/forum-queries.ts index 657cfa1f2..ee546b832 100644 --- a/plugins/forum/src/pages/forum-queries.ts +++ b/plugins/forum/src/pages/forum-queries.ts @@ -7,13 +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 { fetchThreadPage } from "./thread-data"; +import { fetchForums, fetchForumStats, zodFeedTopic } from "./forum-data"; const FORUM_TREE_STALE_TIME = RECORD_STALE_TIME; @@ -43,14 +47,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, @@ -126,23 +163,24 @@ export const queryForum = async ( return data; }; -export const threadQueryOptions = (topicId: number) => - queryOptions({ - meta: LOADER_DATA_QUERY_META, - queryFn: async () => await fetchThreadPage({ topicId }), - queryKey: forumQueryKeys.thread(topicId), - staleTime: FORUM_ACTIVITY_STALE_TIME, - }); +/** Expires what a comment write changes outside its thread: counts, lists, pending posts. */ +export const invalidateForumCounts = async ( + queryClient: QueryClient, +): Promise => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: forumQueryKeys.submissions() }), + queryClient.invalidateQueries({ queryKey: forumQueryKeys.topicLists() }), + queryClient.invalidateQueries({ queryKey: forumQueryKeys.forumStats() }), + ]); +}; export const invalidateForumComments = async ( queryClient: QueryClient, topicId: number, ): Promise => { await Promise.all([ - queryClient.invalidateQueries({ queryKey: forumQueryKeys.submissions() }), + invalidateForumCounts(queryClient), queryClient.invalidateQueries({ queryKey: forumQueryKeys.thread(topicId) }), - queryClient.invalidateQueries({ queryKey: forumQueryKeys.topicLists() }), - queryClient.invalidateQueries({ queryKey: forumQueryKeys.forumStats() }), ]); }; 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..225dd1379 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,80 @@ 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/thread-data.ts b/plugins/forum/src/pages/thread-data.ts deleted file mode 100644 index 4588c6469..000000000 --- a/plugins/forum/src/pages/thread-data.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { zodRichTextDocument } from "@vitnode/core/content"; -import { fetcher } from "@vitnode/core/tanstack/fetcher"; -import { z } from "zod"; - -import { manifest } from "@/manifest.gen"; - -import { zodPerson } from "./forum-data"; - -export const THREAD_PAGE_SIZE = 20; - -/** `CONTENT_PUBLIC_MAX_PAGE_SIZE` - the most top-level comments one read carries. */ -export const THREAD_MAX_PAGE_SIZE = 50; - -/** A to-one relation as the public API projects it: `{ id }`, read as the bare id. */ -export const zodRelationId = z - .object({ id: z.number() }) - .transform(relation => relation.id); - -const zodComment = z.object({ - author: zodPerson, - body: zodRichTextDocument, - createdAt: z.string(), - id: z.number(), - parent: zodRelationId.nullable(), - publishedAt: z.string().nullable(), - slug: z.string(), - topic: zodRelationId, - updatedAt: z.string(), -}); - -export type ThreadComment = z.infer; - -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(), - }), - ), - pageInfo: z.object({ - endCursor: z.string().nullable(), - hasNextPage: z.boolean(), - totalCount: z.number(), - }), - replyCount: z.number(), - truncated: z.boolean(), - }) - .transform(({ replyCount, ...page }) => ({ - ...page, - commentCount: replyCount, - })); - -export type ThreadPage = z.infer; - -export type ThreadNode = ThreadPage["items"][number]; - -export const fetchThreadPage = async ({ - after, - first = THREAD_PAGE_SIZE, - topicId, -}: { - after?: string; - first?: number; - topicId: number; -}): Promise => { - const res = await fetcher({ - plugin: manifest.id, - method: "get", - module: "content/comments", - path: "/thread", - args: { - query: { - root: String(topicId), - first: Math.min(Math.max(first, 1), THREAD_MAX_PAGE_SIZE), - ...(after ? { after } : {}), - }, - }, - }); - - if (res.status === 404) return null; - if (res.status !== 200) throw new Error("Loading the comments failed."); - - return zodThreadPage.parse(await res.json()); -}; - -export interface ThreadTreeNode extends ThreadNode { - children: ThreadTreeNode[]; -} - -/** The flat, depth-first page as the tree it describes. */ -export const buildThreadTree = ( - items: readonly ThreadNode[], -): ThreadTreeNode[] => { - const nodes = new Map(); - const roots: ThreadTreeNode[] = []; - - for (const item of items) { - const node: ThreadTreeNode = { ...item, children: [] }; - nodes.set(item.id, node); - - const parent = - item.parentId === null ? undefined : nodes.get(item.parentId); - if (parent) parent.children.push(node); - else roots.push(node); - } - - return roots; -}; - -/** - * Every node's descendant count, keyed by id, in one walk of the tree - a - * recount per node would make a deep thread quadratic. - */ -export const countDescendants = ( - roots: readonly ThreadTreeNode[], -): ReadonlyMap => { - const counts = new Map(); - const visit = (node: ThreadTreeNode): number => { - let total = 0; - for (const child of node.children) total += 1 + visit(child); - counts.set(node.id, total); - - return total; - }; - - for (const root of roots) visit(root); - - return counts; -}; diff --git a/plugins/forum/src/pages/thread.tsx b/plugins/forum/src/pages/thread.tsx deleted file mode 100644 index e8e9c888d..000000000 --- a/plugins/forum/src/pages/thread.tsx +++ /dev/null @@ -1,611 +0,0 @@ -import type { ContentPermissions } from "@vitnode/core/tanstack/content"; - -import { useQueryClient } from "@tanstack/react-query"; -import { RichTextContent } from "@vitnode/core/components/rich-text"; -import { Button, buttonVariants } from "@vitnode/core/components/ui/button"; -import { - Empty, - EmptyDescription, - EmptyHeader, - EmptyMedia, - EmptyTitle, -} from "@vitnode/core/components/ui/empty"; -import { contentTarget, zodRichTextDocument } from "@vitnode/core/content"; -import { useRevealHashTarget } from "@vitnode/core/hooks/use-reveal-hash-target"; -import { useSessionQuery } from "@vitnode/core/tanstack/auth"; -import { - AutoTranslateNote, - useAutoTranslation, -} from "@vitnode/core/tanstack/auto-translate"; -import { ContentAccessRequired } from "@vitnode/core/tanstack/content"; -import { fetcher } from "@vitnode/core/tanstack/fetcher"; -import { HrefLink } from "@vitnode/core/tanstack/link"; -import { ReportButton } from "@vitnode/core/tanstack/moderation"; -import { ReactionBar } from "@vitnode/core/tanstack/reactions"; -import { cn } from "cn"; -import { - ChevronDownIcon, - ChevronRightIcon, - MessageSquareIcon, - PencilIcon, - ReplyIcon, -} from "lucide-react"; -import { - Activity, - lazy, - memo, - Suspense, - useCallback, - useMemo, - useState, -} from "react"; -import { toast } from "sonner"; -import { useTranslations } from "use-intl"; -import { z } from "zod"; - -import { commentContentType, FORUM_COMMENT_MAX_DEPTH } from "@/content/comment"; -import { manifest } from "@/manifest.gen"; - -import type { CommentComposerProps } from "./comment-composer"; -import type { ThreadComment, ThreadPage, ThreadTreeNode } from "./thread-data"; - -import { useForumRejection } from "./forum-errors"; -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 { - buildThreadTree, - countDescendants, - fetchThreadPage, - THREAD_MAX_PAGE_SIZE, - THREAD_PAGE_SIZE, -} from "./thread-data"; - -const loadCommentComposer = async () => await import("./comment-composer"); - -const CommentComposer = lazy(loadCommentComposer); - -/** Starts the editor chunk on intent, so a click rarely waits for it. */ -const preloadCommentComposer = () => { - void loadCommentComposer(); -}; - -const ComposerFallback = () => ( - ); diff --git a/plugins/forum/src/routes.ts b/plugins/forum/src/routes.ts index f25aea8f1..f29b65f4a 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", { @@ -66,7 +67,7 @@ export const routes = definePluginRoutes([ messages: [ "@vitnode/forum.forums", "@vitnode/forum.topics", - "@vitnode/forum.comments", + "core.comments", ], pendingComponent: RoutePendingSkeleton, search: topicSearch,