diff --git a/AGENTS.md b/AGENTS.md
index a166fed775..a67dd8b5e9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -28,7 +28,7 @@ import { Activity } from "react";
```
- Always use skeletons for loading feedback. Use `` only if its necessary.
-- Add a breadcrumb with the route's `staticData.breadcrumb`; a crumb that renders strings needs its own `RouteMessages`.
+- Breadcrumbs are optional on every page. Add one with the route's `staticData.breadcrumb` (or a plugin page's `route.breadcrumb`) only when the trail helps; leaving it out adds no crumb, and with no crumbs the breadcrumb bar is not rendered. A crumb that renders strings needs its own `RouteMessages`.
- Route files are topology only - `validateSearch`, `loaderDeps`, `loader`, `head`, `staticData`. The query, the permissions, the namespaces and the screen live in `@vitnode/core/tanstack/*`.
- Write `head` **after** `loader` in the same object literal: `loaderData` is inferred from `loader`, and TypeScript reads members in order.
- Name files `x.server.ts` when they must never reach the browser bundle.
diff --git a/apps/api/migrations/20261123121401_add_mentions/migration.sql b/apps/api/migrations/20261123121401_add_mentions/migration.sql
new file mode 100644
index 0000000000..a9a00fc529
--- /dev/null
+++ b/apps/api/migrations/20261123121401_add_mentions/migration.sql
@@ -0,0 +1,22 @@
+CREATE TABLE "core_mentions" (
+ "id" serial PRIMARY KEY,
+ "pluginId" varchar(100) NOT NULL,
+ "targetType" varchar(100) NOT NULL,
+ "targetId" varchar(100) NOT NULL,
+ "userId" integer NOT NULL,
+ "actorId" integer,
+ "eventId" bigint,
+ "notified" boolean DEFAULT false NOT NULL,
+ "createdAt" timestamp DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "core_mentions" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint
+ALTER TABLE "core_roles" ADD COLUMN "allowMentions" boolean DEFAULT true NOT NULL;--> statement-breakpoint
+ALTER TABLE "core_roles" ADD COLUMN "maxMentionsPerItem" integer DEFAULT 25;--> statement-breakpoint
+UPDATE "core_roles" SET "allowMentions" = false WHERE "guest" = true;--> statement-breakpoint
+CREATE UNIQUE INDEX "core_mentions_target_user_idx" ON "core_mentions" ("pluginId","targetType","targetId","userId");--> statement-breakpoint
+CREATE INDEX "core_mentions_user_id_idx" ON "core_mentions" ("userId","createdAt");--> statement-breakpoint
+CREATE INDEX "core_mentions_event_id_idx" ON "core_mentions" ("eventId");--> statement-breakpoint
+ALTER TABLE "core_mentions" ADD CONSTRAINT "core_mentions_userId_core_users_id_fkey" FOREIGN KEY ("userId") REFERENCES "core_users"("id") ON DELETE CASCADE;--> statement-breakpoint
+ALTER TABLE "core_mentions" ADD CONSTRAINT "core_mentions_actorId_core_users_id_fkey" FOREIGN KEY ("actorId") REFERENCES "core_users"("id") ON DELETE SET NULL;--> statement-breakpoint
+ALTER TABLE "core_mentions" ADD CONSTRAINT "core_mentions_eventId_core_notification_events_id_fkey" FOREIGN KEY ("eventId") REFERENCES "core_notification_events"("id") ON DELETE SET NULL;
\ No newline at end of file
diff --git a/apps/api/migrations/20261123121401_add_mentions/snapshot.json b/apps/api/migrations/20261123121401_add_mentions/snapshot.json
new file mode 100644
index 0000000000..e1d003d007
--- /dev/null
+++ b/apps/api/migrations/20261123121401_add_mentions/snapshot.json
@@ -0,0 +1,559 @@
+{
+ "type": "diff",
+ "version": "9",
+ "dialect": "postgres",
+ "id": "a15b8ebf-81b6-45d3-bc42-24cfbaaf11b5",
+ "prevIds": [
+ "d68f291f-7e91-4b91-b606-bca1ba71055c"
+ ],
+ "footprints": [
+ {
+ "statementType": "create_table",
+ "statementTarget": [
+ "table",
+ "public",
+ "core_mentions"
+ ],
+ "writes": [
+ "s|tbl|public.core_mentions",
+ "n|tbl|public.core_mentions",
+ "e|tbl|public.core_mentions",
+ "n|rel|public.core_mentions",
+ "n|type|public.core_mentions",
+ "n|rel|public.core_mentions_pkey"
+ ],
+ "reads": [
+ "n|sch|public"
+ ]
+ },
+ {
+ "statementType": "add_column",
+ "statementTarget": [
+ "column",
+ "public",
+ "core_roles",
+ "allowMentions"
+ ],
+ "writes": [
+ "s|col|public.core_roles.allowMentions",
+ "n|col|public.core_roles.allowMentions",
+ "e|col|public.core_roles.allowMentions"
+ ],
+ "reads": [
+ "n|tbl|public.core_roles",
+ "n|sch|public"
+ ]
+ },
+ {
+ "statementType": "add_column",
+ "statementTarget": [
+ "column",
+ "public",
+ "core_roles",
+ "maxMentionsPerItem"
+ ],
+ "writes": [
+ "s|col|public.core_roles.maxMentionsPerItem",
+ "n|col|public.core_roles.maxMentionsPerItem",
+ "e|col|public.core_roles.maxMentionsPerItem"
+ ],
+ "reads": [
+ "n|tbl|public.core_roles",
+ "n|sch|public"
+ ]
+ },
+ {
+ "statementType": "create_index",
+ "statementTarget": [
+ "index",
+ "public",
+ "core_mentions",
+ "core_mentions_target_user_idx"
+ ],
+ "writes": [
+ "s|idx|public.core_mentions_target_user_idx",
+ "n|idx|public.core_mentions_target_user_idx",
+ "e|idx|public.core_mentions_target_user_idx",
+ "n|rel|public.core_mentions_target_user_idx"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|col|public.core_mentions.pluginId",
+ "n|col|public.core_mentions.targetType",
+ "n|col|public.core_mentions.targetId",
+ "n|col|public.core_mentions.userId"
+ ]
+ },
+ {
+ "statementType": "create_index",
+ "statementTarget": [
+ "index",
+ "public",
+ "core_mentions",
+ "core_mentions_user_id_idx"
+ ],
+ "writes": [
+ "s|idx|public.core_mentions_user_id_idx",
+ "n|idx|public.core_mentions_user_id_idx",
+ "e|idx|public.core_mentions_user_id_idx",
+ "n|rel|public.core_mentions_user_id_idx"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|col|public.core_mentions.userId",
+ "n|col|public.core_mentions.createdAt"
+ ]
+ },
+ {
+ "statementType": "create_index",
+ "statementTarget": [
+ "index",
+ "public",
+ "core_mentions",
+ "core_mentions_event_id_idx"
+ ],
+ "writes": [
+ "s|idx|public.core_mentions_event_id_idx",
+ "n|idx|public.core_mentions_event_id_idx",
+ "e|idx|public.core_mentions_event_id_idx",
+ "n|rel|public.core_mentions_event_id_idx"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|col|public.core_mentions.eventId"
+ ]
+ },
+ {
+ "statementType": "create_fk",
+ "statementTarget": [
+ "table",
+ "public",
+ "core_mentions"
+ ],
+ "writes": [
+ "s|fk|public.core_mentions.core_mentions_userId_core_users_id_fkey",
+ "n|fk|public.core_mentions.core_mentions_userId_core_users_id_fkey",
+ "e|fk|public.core_mentions.core_mentions_userId_core_users_id_fkey",
+ "n|con|public.core_mentions.core_mentions_userId_core_users_id_fkey"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|tbl|public.core_users",
+ "n|sch|public",
+ "n|col|public.core_mentions.userId",
+ "n|col|public.core_users.id",
+ "e|uniqueness|public.core_users.id"
+ ]
+ },
+ {
+ "statementType": "create_fk",
+ "statementTarget": [
+ "table",
+ "public",
+ "core_mentions"
+ ],
+ "writes": [
+ "s|fk|public.core_mentions.core_mentions_actorId_core_users_id_fkey",
+ "n|fk|public.core_mentions.core_mentions_actorId_core_users_id_fkey",
+ "e|fk|public.core_mentions.core_mentions_actorId_core_users_id_fkey",
+ "n|con|public.core_mentions.core_mentions_actorId_core_users_id_fkey"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|tbl|public.core_users",
+ "n|sch|public",
+ "n|col|public.core_mentions.actorId",
+ "n|col|public.core_users.id",
+ "e|uniqueness|public.core_users.id"
+ ]
+ },
+ {
+ "statementType": "create_fk",
+ "statementTarget": [
+ "table",
+ "public",
+ "core_mentions"
+ ],
+ "writes": [
+ "s|fk|public.core_mentions.core_mentions_eventId_core_notification_events_id_fkey",
+ "n|fk|public.core_mentions.core_mentions_eventId_core_notification_events_id_fkey",
+ "e|fk|public.core_mentions.core_mentions_eventId_core_notification_events_id_fkey",
+ "n|con|public.core_mentions.core_mentions_eventId_core_notification_events_id_fkey"
+ ],
+ "reads": [
+ "n|tbl|public.core_mentions",
+ "n|sch|public",
+ "n|tbl|public.core_notification_events",
+ "n|sch|public",
+ "n|col|public.core_mentions.eventId",
+ "n|col|public.core_notification_events.id",
+ "e|uniqueness|public.core_notification_events.id"
+ ]
+ }
+ ],
+ "deltas": [
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "name": "core_mentions",
+ "isRlsEnabled": true,
+ "entityType": "tables"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "id",
+ "type": "serial",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "pluginId",
+ "type": "varchar(100)",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "targetType",
+ "type": "varchar(100)",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "targetId",
+ "type": "varchar(100)",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "userId",
+ "type": "integer",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "actorId",
+ "type": "integer",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "eventId",
+ "type": "bigint",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": null,
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "notified",
+ "type": "boolean",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "false",
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "createdAt",
+ "type": "timestamp",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "now()",
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_roles",
+ "name": "allowMentions",
+ "type": "boolean",
+ "typeSchema": null,
+ "notNull": true,
+ "dimensions": 0,
+ "default": "true",
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_roles",
+ "name": "maxMentionsPerItem",
+ "type": "integer",
+ "typeSchema": null,
+ "notNull": false,
+ "dimensions": 0,
+ "default": "25",
+ "generated": null,
+ "identity": null,
+ "entityType": "columns"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_target_user_idx",
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "pluginId",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ },
+ {
+ "value": "targetType",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ },
+ {
+ "value": "targetId",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ },
+ {
+ "value": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": true,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "entityType": "indexes"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_user_id_idx",
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ },
+ {
+ "value": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": false,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "entityType": "indexes"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_event_id_idx",
+ "nameExplicit": true,
+ "columns": [
+ {
+ "value": "eventId",
+ "isExpression": false,
+ "asc": true,
+ "nullsFirst": false,
+ "opclass": null
+ }
+ ],
+ "isUnique": false,
+ "where": null,
+ "with": "",
+ "method": "btree",
+ "concurrently": false,
+ "entityType": "indexes"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_userId_core_users_id_fkey",
+ "nameExplicit": false,
+ "columns": [
+ "userId"
+ ],
+ "schemaTo": "public",
+ "tableTo": "core_users",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "CASCADE",
+ "entityType": "fks"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_actorId_core_users_id_fkey",
+ "nameExplicit": false,
+ "columns": [
+ "actorId"
+ ],
+ "schemaTo": "public",
+ "tableTo": "core_users",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "SET NULL",
+ "entityType": "fks"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_eventId_core_notification_events_id_fkey",
+ "nameExplicit": false,
+ "columns": [
+ "eventId"
+ ],
+ "schemaTo": "public",
+ "tableTo": "core_notification_events",
+ "columnsTo": [
+ "id"
+ ],
+ "onUpdate": "NO ACTION",
+ "onDelete": "SET NULL",
+ "entityType": "fks"
+ }
+ },
+ {
+ "op": "create",
+ "row": {
+ "schema": "public",
+ "table": "core_mentions",
+ "name": "core_mentions_pkey",
+ "columns": [
+ "id"
+ ],
+ "nameExplicit": false,
+ "entityType": "pks"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/web/content/docs/content-engine/comments-api.mdx b/apps/web/content/docs/content-engine/comments-api.mdx
index cb39304771..fb539352f7 100644
--- a/apps/web/content/docs/content-engine/comments-api.mdx
+++ b/apps/web/content/docs/content-engine/comments-api.mdx
@@ -54,7 +54,7 @@ const comments = useContentComments({ queryKey, thread, ...actions })
| `hasMore`, `loadMore()`, `isLoadingMore` | The next page of top-level comments. `loadMore` resolves to `false` when it failed |
| `isRefreshing`, `retry()` | A refetch over data on screen (not **Load more**), and retrying a failed first load |
| `refreshError`, `retryRefresh()` | A background read of the comments on screen failed, and they stayed as they were. `retryRefresh()` asks again for what it missed and resolves when done |
-| `hasNewComments`, `showNewComments()` | With `live`: comments appeared after the last loaded one, at the end of the thread. `showNewComments()` reads only those and adds them below; it resolves to `false` when that failed |
+| `newCommentIds` | With `live`: top-level comments by other people that were added at the end of the thread while it was open, oldest first |
| `liveStatus` | `"off"` (no `live`, or no open WebSocket), `"joining"`, `"live"`, or `"denied"` when the server refused or revoked the subscription |
| `trackDraft(id, open)` | Call with `true` while an edit or reply form is open on `id` and `false` when it closes. A live update that removes that comment keeps it on screen with `removed: true` and its record until then. `useContentCommentItem` calls it for you |
| `replyCount`, `truncated` | Every public comment at any depth, and whether a page held more replies than one answer carries |
@@ -168,7 +168,8 @@ const MyComment = ({ node }) => {
| `useContentCommentItem(node)` | One comment's state: `permissions` (the server's answers limited to wired actions), `canReply`, `editing`, `startEditing()`, `stopEditing()`, `isReplying`, `setIsReplying`, `isBusy`, and `isRemoved` when a live update removed the comment under an open form |
| `ContentCommentActions` | The **More actions** menu with the hide-reason prompt. `children` adds your own menu items |
| `ContentCommentComposer` | The comment form, lazy-loaded: `mode="create"` with `parentId` and an optional `initialBody` (a quote, say), or `mode="edit"` with `id` and `editable`. `onDone(outcome, id)` gets what the comment became and its id. `hideLabel` keeps the editor's label for screen readers only. `unavailable` (a translated reason) keeps the text but hides the submit button |
-| `ContentCommentsLiveStatus` | **Show new comments** and the refresh-failed notice, with a polite screen reader announcement. Renders nothing while there is nothing to say |
+| `ContentCommentsNewSeparator` | The blue **N new comments** divider. Renders an `
`: put it in your thread's list right before the comment whose id is `newCommentIds[0]` |
+| `ContentCommentsLiveStatus` | The refresh-failed notice, plus a polite screen reader announcement when new comments arrive. Renders nothing visible while there is nothing to say |
| `ContentCommentItem` | One comment as the default section draws it |
| `ContentCommentPlaceholder` | The anonymous stand-in for a removed comment |
| `ContentCommentsComposer`, `ContentCommentsLoadMore` | The new-comment card and the load-more button. The card renders nothing for guests; `showTitle={false}` keeps its **Leave a comment** heading for screen readers only, and `hideLabel` does the same for the editor's label |
diff --git a/apps/web/content/docs/content-engine/notifications-api.mdx b/apps/web/content/docs/content-engine/notifications-api.mdx
index 58fe8f3ad6..a8fd8a89bc 100644
--- a/apps/web/content/docs/content-engine/notifications-api.mdx
+++ b/apps/web/content/docs/content-engine/notifications-api.mdx
@@ -197,7 +197,7 @@ Core checks a notification type's `access` before delivering it, before every im
| `"submission"` (`moderationDecision`) | The member is the submission's author, the submission still has that decision and the record exists. An approval also needs the record to be public; a rejection does not. The root must stay public |
| `"approval"` (`approvalPending`) | The submission is still pending, the record exists, and the member holds `can_approve` both for the container the queue lists the submission under and for the one the record is filed in now. The record does not have to be public |
-A notification that fails the check shows "This notification is no longer available", with no title, text or link, and its email is skipped. Content Engine reads are not role-based, so add `access` to `buildContentNotifications` when your plugin limits content to some members. An email that was already sent cannot be taken back.
+A notification that fails the check is deleted from the inbox, and its email is skipped. Content Engine reads are not role-based, so add `access` to `buildContentNotifications` when your plugin limits content to some members. An email that was already sent cannot be taken back.
## Delivery and retries
@@ -212,9 +212,9 @@ A failure retries with backoff up to 5 attempts, then the task is marked `failed
Deleting a record stores a cleanup intent in the same transaction. Once it runs, the record's notifications leave every inbox, and so do notifications about records in its thread when the record was the root, including replies a database cascade removed. A grouped item loses only the deleted contributions and points at the newest one left; it disappears when none is left. Pending emails for those notifications are dropped.
-A submission that stops waiting, because a moderator decided it, the author replaced it with a newer proposal or the record was deleted, stores a cleanup intent in the same transaction, and its `approvalPending` notifications leave the moderators' inboxes. Delivery that has not reached an inbox yet is stopped by the access check; in the rare case that delivery and cleanup cross, the item stays behind as "no longer available".
+A submission that stops waiting, because a moderator decided it, the author replaced it with a newer proposal or the record was deleted, stores a cleanup intent in the same transaction, and its `approvalPending` notifications leave the moderators' inboxes. Delivery that has not reached an inbox yet is stopped by the access check; in the rare case that delivery and cleanup cross, the item is deleted the next time the inbox loads.
-Hiding is not deleting. A hidden record's notifications are only unavailable until it is shown again. A delete that races with a notification being sent is safe either way, because the access check runs again at every step.
+Hiding a record deletes its notifications the next time each inbox loads, and showing it again does not bring them back. A delete that races with a notification being sent is safe either way, because the access check runs again at every step.
## `useRevealHashTarget()`
diff --git a/apps/web/content/docs/content-engine/notifications.mdx b/apps/web/content/docs/content-engine/notifications.mdx
index 2e95ff004a..f565d62e6b 100644
--- a/apps/web/content/docs/content-engine/notifications.mdx
+++ b/apps/web/content/docs/content-engine/notifications.mdx
@@ -294,11 +294,11 @@ A comment notifies **once, the first time it becomes public**. VitNode tells tha
| Waiting for approval, then approved | Sent once, at approval |
| Rejected | None about the comment. A [`moderationDecision` rule](#tell-authors-about-moderation-decisions) can tell its author |
| Edited, or an edit approved | No new one |
-| Hidden, then shown again | Shows "This notification is no longer available." while hidden, then comes back. A comment hidden before the notification went out is never announced |
-| Unpublished, then published again | Unavailable meanwhile, then back. No new one |
+| Hidden, then shown again | Deleted from the inbox while hidden, and not brought back. A comment hidden before the notification went out is never announced |
+| Unpublished, then published again | Deleted meanwhile. No new one |
| Deleted without replies | Removed from inboxes |
-| Deleted while it has replies | It stays as a placeholder in the thread, and its notification is unavailable. Notifications about its replies stay |
-| Its article unpublished, hidden or deleted | Unavailable while the article is not public; removed with a deleted article |
+| Deleted while it has replies | It stays as a placeholder in the thread, and its notification is deleted. Notifications about its replies stay |
+| Its article unpublished, hidden or deleted | Deleted from the inbox |
Comments that were already public before you added the rules never notify, so deploying them doesn't bury every author under a year of old news.
@@ -368,7 +368,7 @@ You need two members, Ada and Grace. For setup B, first make Ada the author of a
3. As Ada, reply to Grace's comment. Grace gets "replied to your comment" and Ada gets nothing. Open it as Grace, and the reply is highlighted below Grace's comment.
4. As Grace, open **Settings → Notifications**, expand **Comments and replies** and turn **Notification list** off. Have Ada reply again. Nothing new arrives. Turn it back on.
-5. As a moderator, hide Grace's comment. Ada's notification now says it is no longer available. Show the comment again and the notification comes back.
+5. As a moderator, hide Grace's comment. Ada's notification is gone the next time their inbox loads, and showing the comment again does not bring it back.
6. Delete the article. Both notifications disappear from the inboxes.
## Related
diff --git a/apps/web/content/docs/content-engine/threads-live.mdx b/apps/web/content/docs/content-engine/threads-live.mdx
index 69e3fda9f9..f397cb0bf3 100644
--- a/apps/web/content/docs/content-engine/threads-live.mdx
+++ b/apps/web/content/docs/content-engine/threads-live.mdx
@@ -22,7 +22,7 @@ implementation:
import { ImgDocs } from "@/components/fumadocs/img";
import newComments from "./threads-live-new-comments.webp";
-Live comments keep a comment section current while people read it. When someone replies, edits, hides or deletes a comment, every open copy of the article re-reads only the branch that changed. New top-level comments wait behind a **Show new comments** button, because nobody enjoys a page that rearranges itself mid-sentence. Loaded pages, open reply forms and the reading position stay where they were.
+Live comments keep a comment section current while people read it. When someone replies, edits, hides or deletes a comment, every open copy of the article re-reads only the branch that changed. New top-level comments show up at the end of the thread right away, under a blue **2 new comments** divider so you can tell what's fresh. Loaded pages, open reply forms and the reading position stay where they were, because nobody enjoys a page that rearranges itself mid-sentence.
## Before you begin
@@ -71,7 +71,7 @@ import { commentContentType } from "@/content/comment"; // [!code ++]
live: { contentTypeId: commentContentType.id, rootId: articleId }, // [!code ++]
```
-That's the whole change. `live` needs `branches` and is ignored without it. `ContentComments` shows **Show new comments** and refresh errors on its own. A custom layout renders `ContentCommentsLiveStatus` inside its `ContentCommentsRoot`, as the Blog plugin does; see [Comments API](/docs/content-engine/comments-api#your-own-layout).
+That's the whole change. `live` needs `branches` and is ignored without it. `ContentComments` shows the new-comments divider and refresh errors on its own. A custom layout renders `ContentCommentsNewSeparator` before the first id in `newCommentIds` and `ContentCommentsLiveStatus` inside its `ContentCommentsRoot`, as the Blog plugin does; see [Comments API](/docs/content-engine/comments-api#your-own-layout).
@@ -83,7 +83,7 @@ Use two browser windows, one of them private, so they hold different sessions. S
1. In window A, reply to a comment. Window B shows the reply within a second or two, without a reload.
2. In window B, click **Reply** under a comment and type a few words without sending. In window A, reply to the same comment. Window B shows the new reply and keeps your unsent text.
-3. In window A, post a new top-level comment. Window B shows **New comments were posted.** at the end of the thread. Click **Show new comments** to add it below the others.
+3. In window A, post a new top-level comment. Window B adds it at the end of the thread right away, under a **1 new comment** divider. Window A shows its own comment without the divider.
A signed-out window gets the same updates; it just can't reply.
@@ -91,7 +91,7 @@ A signed-out window gets the same updates; it just can't reply.
withoutBackground
className="*:max-w-full"
src={newComments}
- alt="Two Blog plugin conversation cards by Ada Lovelace and Grace Hopper, then a 'New comments were posted.' notice with a Show new comments button above the Write a comment field"
+ alt="Two Blog plugin conversation cards by Ada Lovelace and Grace Hopper, then a blue '1 new comment' divider above a comment that just arrived"
/>
## What arrives live
@@ -100,7 +100,7 @@ A signed-out window gets the same updates; it just can't reply.
| --- | --- |
| A reply, edit, hide, unhide or delete in a loaded branch | Re-reads that branch and puts it back in place |
| A burst of changes to one branch | Re-reads it once, 0.4 seconds after the last change and never more than 2 seconds after the first |
-| A new top-level comment, with every page loaded | Shows **Show new comments**; clicking it reads only what follows the last loaded comment |
+| A new top-level comment, with every page loaded | Reads only what follows the last loaded comment and adds it at the end, under the **new comments** divider. Your own comments never get the divider |
| A new top-level comment, with more pages on the server | Nothing yet. Comments are oldest first, so **Load more comments** reaches it |
| A change in a branch that isn't loaded | Nothing; it's read fresh when its page loads |
| A comment that is a draft or waits for a moderator | Nothing. It isn't public, so other readers aren't told |
diff --git a/apps/web/content/docs/dev/events/built-in-events.mdx b/apps/web/content/docs/dev/events/built-in-events.mdx
index 328381d397..2d1d7734b3 100644
--- a/apps/web/content/docs/dev/events/built-in-events.mdx
+++ b/apps/web/content/docs/dev/events/built-in-events.mdx
@@ -638,6 +638,24 @@ administrator for `reaction.catalog_changed`. See [Reactions](/docs/dev/reaction
`targetAuthorId` is `null` for a self reaction and for targets without reputation.
Deleting an item emits `reputation.changed` for its authors but no `reaction.removed`.
+## Mention events
+
+Two names, exported from `@vitnode/api/events/mentions`: `mentionCreatedEvent`
+and `mentionRemovedEvent`. Core emits them with `pluginId: "@vitnode/core"`
+after `syncMentions` commits, which for Content Engine records happens in the
+`content-mentions` queue task right after the write. See
+[Mentions](/docs/dev/mentions).
+
+| Event | Payload | Fires when |
+| ----------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------- |
+| `mention.created` | `{ pluginId, targetType, targetId, actorId, users }` | Members are `@mentioned` in a target for the first time |
+| `mention.removed` | `{ pluginId, targetType, targetId, actorId, userIds }` | An edit removed mentions; their notifications are already retracted |
+
+`users` is `{ id, notified }[]`. `notified` is `false` for a member who got no
+notification: they can't read the target, the author's role may not mention,
+or the role's per-post cap was reached. Deleting a target forgets its mentions
+without `mention.removed`.
+
## Moderation events
Twenty names, exported from `@vitnode/api/events/moderation` as
diff --git a/apps/web/content/docs/dev/mentions-editor-popup.webp b/apps/web/content/docs/dev/mentions-editor-popup.webp
new file mode 100644
index 0000000000..022e7993d2
Binary files /dev/null and b/apps/web/content/docs/dev/mentions-editor-popup.webp differ
diff --git a/apps/web/content/docs/dev/mentions-role-settings.webp b/apps/web/content/docs/dev/mentions-role-settings.webp
new file mode 100644
index 0000000000..86951cf36f
Binary files /dev/null and b/apps/web/content/docs/dev/mentions-role-settings.webp differ
diff --git a/apps/web/content/docs/dev/mentions.mdx b/apps/web/content/docs/dev/mentions.mdx
new file mode 100644
index 0000000000..c1c876be33
--- /dev/null
+++ b/apps/web/content/docs/dev/mentions.mdx
@@ -0,0 +1,178 @@
+---
+title: Mentions
+description: Let members @mention each other in VitNode rich text, notify them once they can read the post, and turn mentions off for a field or a role.
+icon: AtSign
+---
+
+import { ImgDocs } from '@/components/fumadocs/img'
+import popup from './mentions-editor-popup.webp'
+import roleSettings from './mentions-role-settings.webp'
+
+Mentions let members type `@` and the first three letters of a name in any rich-text editor, pick someone, and notify them. They are on by default: every `field.richText()` in the Content Engine and every `AutoFormEditor` supports them without any code. This page explains what notifies whom, how to turn mentions off, and how to use them in your own tables.
+
+## How mentions work
+
+Typing `@` and a few letters opens a list of members. Arrow keys move through it, **Enter** or **Tab** inserts the mention. Members only see the list when they are signed in and one of their roles may mention.
+
+
+
+The editor stores a `mention` node with the member's id and a snapshot of their name:
+
+```json
+{ "type": "mention", "attrs": { "id": 3, "label": "Bartek", "nameCode": "bartek" } }
+```
+
+`RichTextContent` renders it as a link to the member's profile with the user preview card. It looks up the member's current name by id, so a renamed member still gets the right link. A deleted member shows as plain `@name` text. Plain text, excerpts and search use `@name` too.
+
+A mention notifies the member with **Mentions** (`core.mention`) when all of these are true:
+
+- The record is public: published, not hidden, and its thread is public. A draft or a post waiting for approval notifies when it goes live.
+- The mentioned member can read the record under its access rules.
+- One of the author's roles allows mentioning, and the post hasn't reached that role's cap.
+- The member isn't the author, and isn't already told about the same reply by a thread notification (the topic author and the author of the comment being answered).
+
+Editing a post notifies only members who are newly mentioned. Removing a mention takes its notification out of the member's inbox, read or not. Every mention is its own item, so three comments that mention you show up as three notifications. The notification is in-app and sends an email right away by default; members change that in **Settings → Notifications**.
+
+## Turn mentions off for a field
+
+Set `mentions: false` on the field, and `mentions={false}` on the editor that edits it. The form can't read the server's field options, so both are needed:
+
+```ts title="plugins/newsroom/src/content/letter.ts"
+fields: {
+ body: field.richText({ required: true, mentions: false }), // [!code highlight]
+},
+```
+
+```tsx title="Your letter form"
+
+```
+
+The server option stops notifications. The editor option hides the `@` list. If you forget the editor side, members can still insert a mention, but it notifies nobody.
+
+## Set who can mention
+
+Open **AdminCP → Users → Roles**, edit a role and open the **Content** tab.
+
+
+
+- **Allow mentioning members** shows the `@` list and lets the role's posts notify. It is on for every role except guests.
+- **Members notified per post** caps how many members one post notifies, 25 by default, or **Unlimited**. More mentions still show as links, without a notification.
+
+A member with several roles gets the most generous setting of them all.
+
+## Mention from your own tables
+
+Content Engine records need nothing more. For rich text your plugin stores in its own table, register a mention target and call `syncMentions` after each write. The example below uses a `guestbook_entries` table with a rich-text `body` column, readable by everyone.
+
+
+
+
+
+### Define the target
+
+A target tells core who may read an item. Core asks before notifying, before each email and each time an inbox shows the notification:
+
+```ts title="src/api/lib/mentions.ts"
+import { defineMentionTarget } from '@vitnode/api/mentions'
+
+export const guestbookMentionTarget = defineMentionTarget({
+ type: 'guestbook.entry',
+ // Every member can read the guestbook.
+ access: async ({ userIds }) => userIds,
+})
+```
+
+`access` receives `{ c, id, rootId, userIds }` and returns the ids that may read item `id`. It runs once per batch, never once per member.
+
+
+
+
+
+### Register it
+
+Pass the target to `buildApiPlugin` in `src/config.api.ts`:
+
+```ts title="src/config.api.ts"
+import { guestbookMentionTarget } from '@/api/lib/mentions'
+
+export const guestbookApiPlugin = () =>
+ buildApiPlugin({
+ manifest,
+ mentions: { targets: [guestbookMentionTarget] }, // [!code ++]
+ // modules, permissions and the rest as before
+ })
+```
+
+
+
+
+
+### Sync after every write
+
+In the routes that create and edit an entry, call `syncMentions` after the write commits. It stores new mentions, notifies them, and retracts the ones the text no longer has. Calling it again with the same text changes nothing:
+
+```ts title="Your create and edit route handlers"
+import { syncMentions } from '@vitnode/api/mentions'
+
+await syncMentions({
+ c,
+ pluginId: manifest.id,
+ target: guestbookMentionTarget,
+ id: entry.id,
+ actorId: entry.authorId,
+ documents: [entry.body],
+ title: entry.title,
+ url: `/guestbook#entry-${entry.id}`,
+})
+```
+
+`actorId` is the author: their roles decide whether the post notifies. `documents` takes every rich-text value of the item.
+
+
+
+
+
+### Forget mentions on delete
+
+In the route that deletes an entry, after the delete commits:
+
+```ts title="Your delete route handler"
+import { deleteMentions } from '@vitnode/api/mentions'
+
+await deleteMentions({
+ c,
+ pluginId: manifest.id,
+ targetType: 'guestbook.entry',
+ id: entry.id,
+})
+```
+
+
+
+
+
+## Check the result
+
+Sign in as one member, post `Hi @` plus another member's name, and pick them from the list. Sign in as the other member: the bell shows that you were mentioned, with the post's title, like … mentioned you in "Welcome to the newsroom", and the notification opens the post. Edit the post to remove the mention, and the notification leaves their inbox.
+
+## Reference
+
+| Route | Who | Returns |
+| --- | --- | --- |
+| `GET /users/mentions?search=&limit=` | Signed-in members whose role may mention; `401` for guests, `403` without the role setting | Up to 10 members (6 by default) matching the start of their URL name or name, then names containing it. The member asking is left out. |
+| `GET /users/mentioned?ids=1,2,3` | Everyone | The current `name` and `nameCode` of up to 50 members. Deleted members are left out. |
+
+The session (`GET /users/session`) includes `canMention`. Mention events are listed in [Built-in events](/docs/dev/events/built-in-events#mention-events).
+
+## Related
+
+- [Notification types](/docs/dev/notifications/notification-types)
+- [Built-in events](/docs/dev/events/built-in-events#mention-events)
diff --git a/apps/web/content/docs/dev/meta.json b/apps/web/content/docs/dev/meta.json
index 5f5336e3b1..7d4d9f8978 100644
--- a/apps/web/content/docs/dev/meta.json
+++ b/apps/web/content/docs/dev/meta.json
@@ -33,6 +33,7 @@
"working-with-users",
"moderation",
"reactions",
+ "mentions",
"audit-logs",
"events",
"notifications",
diff --git a/apps/web/content/docs/dev/notifications/access.mdx b/apps/web/content/docs/dev/notifications/access.mdx
index 67c84dade5..fa40520de8 100644
--- a/apps/web/content/docs/dev/notifications/access.mdx
+++ b/apps/web/content/docs/dev/notifications/access.mdx
@@ -70,7 +70,7 @@ await c.get('notifications').remove({
})
```
-`remove()` keeps inboxes tidy, but it is not required for privacy. An item whose `access` check now says no already shows "This notification is no longer available." instead of its text.
+`remove()` cleans up right away, but it is not required for privacy. An item whose `access` check now says no is deleted from the inbox the next time it loads.
@@ -78,15 +78,15 @@ await c.get('notifications').remove({
If `access` throws while notifications are delivered, the whole batch fails
- and the queue retries it later. When the inbox loads, a throw turns that one
- item into the "no longer available" placeholder. Let real database errors
+ and the queue retries it later. When the inbox loads, a throw leaves that one
+ item out of the page but keeps it, so it shows again once the check works. Let real database errors
throw, but do not throw for "no access": return fewer ids instead.
## Check the result
1. Publish a reply in a private topic with two members and one non-member listed in `recipients`. Only the two members get an inbox item.
-2. Remove one member from the topic and reload their notifications. The item shows "This notification is no longer available." and no longer links to the topic.
+2. Remove one member from the topic and reload their notifications. The item is gone, and their unread count drops if it was unread.
3. Delete the topic. The item disappears from the remaining member's inbox, and their unread count drops at the same moment.
For the full `remove()` signature, see the [Notifications API reference](/docs/dev/notifications/reference#remove).
diff --git a/apps/web/content/docs/dev/notifications/inbox-and-realtime.mdx b/apps/web/content/docs/dev/notifications/inbox-and-realtime.mdx
index 02f8599183..5c0dbce600 100644
--- a/apps/web/content/docs/dev/notifications/inbox-and-realtime.mdx
+++ b/apps/web/content/docs/dev/notifications/inbox-and-realtime.mdx
@@ -30,9 +30,9 @@ Types with [`grouping`](/docs/dev/notifications/notification-types#grouping) mer
## Items that are no longer available
-Before returning a page of the inbox, core checks every item again: the type is still registered, its stored data still parses, `access` still allows the member and `present` still renders. If any check fails, the item comes back as a placeholder with the title "This notification is no longer available." and no link.
+Before returning a page of the inbox, core checks every item again: the type is still registered, its stored data still parses, `access` still allows the member and `present` still renders. If the type is gone, the data no longer parses or `access` says no, the item is deleted for good and the unread count drops with it. That covers deleted or hidden content, revoked access and uninstalled plugins. Showing the content again does not bring the item back.
-The placeholder keeps its read state, so members can still read or archive it, and the unread count never includes an item they cannot clear. This covers deleted content, revoked access and uninstalled plugins.
+If `access` throws or `present` fails, the item is left out of that page but kept, since the cause may be a passing error or a bug about to be fixed. The error is logged.
## The live unread count
@@ -48,6 +48,14 @@ WebSocket messages missed while a tab was offline are not replayed. Instead, the
When the count changes, open notification lists refresh once per burst: 1 second after the last change and at most 5 seconds after the first.
+## Toasts for new notifications
+
+When a new notification lands in a member's inbox while a tab is open, it also pops up as a toast: the sender's avatar with a small badge for the kind of notification (@ for a mention, an arrow for a reply, a smile for a reaction), their name, what happened and the text. The whole toast is one button. Clicking it opens the notification and marks it read, just like clicking it in the bell. The server adds the member's own `notificationId` to the `created` message, and the browser fetches that item and shows it if it is still unread.
+
+The same badge marks each item in the bell and on the notifications page. Admin messages skip it, because the AdminCP already sends them as a live toast of their own.
+
+Every open tab shows the toast. Without a socket there are no toasts; the count still catches up through `/state`.
+
With `REDIS_URL` set, realtime messages travel between API instances over
Redis, so delivery on instance A reaches a tab connected to instance B.
@@ -58,10 +66,10 @@ When the count changes, open notification lists refresh once per burst: 1 second
## What core ships in the UI
-| Piece | Where |
-| ---------------------- | ----------------------------------------------------------------------------------------- |
-| Bell with unread badge | Site header on every screen size. Loads the recent list only when opened |
-| Notifications page | `/notifications`, with **All** and **Unread** tabs, a category filter and infinite scroll |
-| Preferences | `/settings/notifications`, see [Preferences](/docs/dev/notifications/preferences) |
+| Piece | Where |
+| ---------------------- | -------------------------------------------------------------------------------------------------- |
+| Bell with unread badge | Site header on every screen size. Loads the recent list only when opened |
+| Notifications page | `/notifications`, a paged table you can sort by date or category and filter by status and category |
+| Preferences | `/settings/notifications`, see [Preferences](/docs/dev/notifications/preferences) |
A default theme needs no wiring. To build your own bell, call the [member endpoints](/docs/dev/notifications/reference#member-endpoints) and listen to the [realtime channel](/docs/dev/notifications/reference#realtime-channel).
diff --git a/apps/web/content/docs/dev/notifications/notification-types.mdx b/apps/web/content/docs/dev/notifications/notification-types.mdx
index a50d8683e2..13fe6f3cb1 100644
--- a/apps/web/content/docs/dev/notifications/notification-types.mdx
+++ b/apps/web/content/docs/dev/notifications/notification-types.mdx
@@ -154,7 +154,7 @@ Core cleans what `present` returns before anyone sees it:
- `title` and `body` are plain text. Markup is never rendered, whitespace is collapsed and each string is cut at 500 characters.
- `target` must be a path on the same site, such as `/forum/topics/42`. Absolute URLs, `//host`, `javascript:` and backslashes are dropped, and the item renders without a link.
-- If `present` throws or returns an empty title, the item shows "This notification is no longer available." and the error is logged.
+- If `present` throws or returns an empty title, the item is left out of the list and the error is logged.
## `access`
@@ -194,7 +194,7 @@ export const topicReplyNotification = buildNotificationType({
})
```
-Data that cannot be upgraded is never shown. That covers a missing `migrate`, a stored version newer than the code, a thrown error or a failed parse. A notification not yet delivered is marked failed, and inbox items show the "no longer available" placeholder.
+Data that cannot be upgraded is never shown. That covers a missing `migrate`, a stored version newer than the code, a thrown error or a failed parse. A notification not yet delivered is marked failed, and inbox items are deleted when they next load.
## `mandatory`
diff --git a/apps/web/content/docs/dev/notifications/reference.mdx b/apps/web/content/docs/dev/notifications/reference.mdx
index 867e8a70d3..9edbe07aa0 100644
--- a/apps/web/content/docs/dev/notifications/reference.mdx
+++ b/apps/web/content/docs/dev/notifications/reference.mdx
@@ -113,16 +113,17 @@ It also throws when two transactions publish the same key at the same moment and
Every route acts on the signed-in member and answers `401` to guests. Paths are relative to `/api/@vitnode/core/notifications`.
-| Method | Path | Behavior |
-| ------ | --------------- | ---------------------------------------------------------------------------------------------------------------------- |
-| `GET` | `/` | One page of items, newest activity first. Query: `limit` (1 to 50, default 20), `cursor`, `unread`, `category`, `type` |
-| `GET` | `/state` | `{ unread, revision }` |
-| `POST` | `/{id}/read` | Marks one item read. Optional body `{ throughSeq }` |
-| `POST` | `/{id}/unread` | Marks one item unread again |
-| `POST` | `/{id}/archive` | Hides one item from the inbox. New activity brings it back |
-| `POST` | `/read-all` | Marks everything read. Optional body `{ category }` |
-| `GET` | `/preferences` | Every type the member can see, with their channels |
-| `PUT` | `/preferences` | Saves `{ types: { [typeId]: { inApp?, push?, email? } } }`. Other types keep their choices |
+| Method | Path | Behavior |
+| ------ | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `GET` | `/` | One page of items, newest activity first. Query: `limit` (1 to 50, default 20), `cursor`, `unread`, `category`, `type` |
+| `GET` | `/inbox` | One numbered page for the notifications table, with `pageInfo` totals. Query: `page`, `first` (page size), `orderBy` (`lastActivityAt` or `category`), `order`, `status` (`unread` or `read`), `category` (comma-separated) |
+| `GET` | `/state` | `{ unread, revision }` |
+| `POST` | `/{id}/read` | Marks one item read. Optional body `{ throughSeq }` |
+| `POST` | `/{id}/unread` | Marks one item unread again |
+| `POST` | `/{id}/archive` | Hides one item from the inbox. New activity brings it back |
+| `POST` | `/read-all` | Marks everything read. Optional body `{ category }` |
+| `GET` | `/preferences` | Every type the member can see, with their channels |
+| `PUT` | `/preferences` | Saves `{ types: { [typeId]: { inApp?, push?, email? } } }`. Other types keep their choices |
The mark routes return the new `{ unread, revision }`. Another member's item id answers `404`, like a missing one. Call these routes with the [fetcher](/docs/dev/fetcher):
diff --git a/apps/web/content/docs/dev/notifications/troubleshooting.mdx b/apps/web/content/docs/dev/notifications/troubleshooting.mdx
index 09f709471d..42cd4f51ba 100644
--- a/apps/web/content/docs/dev/notifications/troubleshooting.mdx
+++ b/apps/web/content/docs/dev/notifications/troubleshooting.mdx
@@ -37,6 +37,8 @@ Digests follow the time zone the member set under **Region** on `/settings`, the
Every inbox change updates the count in the same transaction, so a wrong count is a bug worth reporting. To check and repair counts, call `POST /reconcile` from the [AdminCP endpoints](/docs/dev/notifications/reference#admincp-endpoints). It only reports mismatches unless you send `{ "dryRun": false }`, which also pushes the corrected badge to open tabs.
-## Items say "This notification is no longer available"
+## Items disappear from the inbox
-The item is a placeholder. The content was deleted, the member lost access, the plugin was uninstalled, or the stored data no longer matches the type's schema and `migrate` could not upgrade it. Members can still read or archive the item. Plugins can tidy these up with [`remove()`](/docs/dev/notifications/access#remove-notifications-when-content-goes-away).
+Core deletes an item when it loads and finds the content gone or hidden, the member without access, the plugin uninstalled, or stored data that no longer matches the type's schema and that `migrate` could not upgrade. See [Items that are no longer available](/docs/dev/notifications/inbox-and-realtime#items-that-are-no-longer-available). Plugins can clean up sooner with [`remove()`](/docs/dev/notifications/access#remove-notifications-when-content-goes-away).
+
+An item that stays in the unread count but never shows up has a `present` or `access` that fails. Check the server log for `[Notifications] "" failed to render`.
diff --git a/apps/web/content/docs/dev/routing/breadcrumbs.mdx b/apps/web/content/docs/dev/routing/breadcrumbs.mdx
index 1155f20613..f859e64fb1 100644
--- a/apps/web/content/docs/dev/routing/breadcrumbs.mdx
+++ b/apps/web/content/docs/dev/routing/breadcrumbs.mdx
@@ -53,7 +53,7 @@ Declare `breadcrumb` after `load`, so TypeScript types `loaderData` from the loa
## Leave a route out
-A route without `breadcrumb` adds nothing, and the crumbs above it stay. Write `breadcrumb: false` (or `null`) to make that explicit, for example on an `index()` page whose layout already names the screen. The trail then ends at the deepest route that declares a crumb, and that crumb gets `aria-current="page"`.
+Breadcrumbs are optional on every page. A route without `breadcrumb` adds nothing, and the crumbs above it stay. When no matched route declares one, the breadcrumb bar is not rendered at all. Write `breadcrumb: false` (or `null`) to make that explicit, for example on an `index()` page whose layout already names the screen. The trail then ends at the deepest route that declares a crumb, and that crumb gets `aria-current="page"`.
## Several crumbs from one route
diff --git a/apps/web/src/locales/@vitnode/core/pl.json b/apps/web/src/locales/@vitnode/core/pl.json
index c5cde2eb6c..4beddcafab 100644
--- a/apps/web/src/locales/@vitnode/core/pl.json
+++ b/apps/web/src/locales/@vitnode/core/pl.json
@@ -626,6 +626,15 @@
},
"in_unit": "kB"
},
+ "mentions": {
+ "allow": "Zezwalaj na wspominanie osób",
+ "allow_desc": "Wpisanie @ w edytorze podpowiada osoby do wspomnienia, a one dostają powiadomienie.",
+ "max_per_item": "Powiadomione osoby na wpis",
+ "max_per_item_desc": "Ile wspomnianych osób może powiadomić jeden wpis. Dalsze wzmianki nadal się wyświetlają, ale bez powiadomienia.",
+ "in_unit": "osób",
+ "or": "lub",
+ "unlimited": "Bez limitu"
+ },
"name": "Nazwa",
"personal_info": {
"allow_edit": "Zezwalaj na edycję informacji osobistych",
@@ -3568,6 +3577,15 @@
"uploading": "Przesyłanie…",
"open": "Otwórz {name}"
},
+ "mention": {
+ "label": "Osoby do wspomnienia",
+ "hint": "Wpisz nazwę, aby wspomnieć osobę.",
+ "loading": "Szukam osób…",
+ "empty": "Nie znaleziono osób.",
+ "load_error": "Nie udało się wczytać osób. Sprawdź połączenie i spróbuj ponownie.",
+ "forbidden": "Twoja rola nie może wspominać osób.",
+ "retry": "Spróbuj ponownie"
+ },
"uploads": {
"errors": {
"title": "Nie dodano pliku",
@@ -4242,15 +4260,19 @@
"notifications": {
"title": "Powiadomienia",
"desc": "Wszystko, co wydarzyło się pod Twoją nieobecność. Otwarcie tej strony niczego nie oznacza jako przeczytanego.",
- "list_label": "Powiadomienia",
- "filter_all": "Wszystkie",
"filter_unread": "Nieprzeczytane",
- "all_categories": "Wszystkie kategorie",
- "category_label": "Filtruj według kategorii",
"mark_all_read": "Oznacz wszystkie jako przeczytane",
- "settings": "Ustawienia powiadomień",
- "loading": "Wczytywanie…",
- "load_more": "Wczytaj więcej",
+ "settings_button": "Ustawienia",
+ "summary": "{total} {total, plural, one {powiadomienie} few {powiadomienia} many {powiadomień} other {powiadomienia}} · {unread} nieprzeczytane",
+ "column_status": "Status",
+ "column_notification": "Powiadomienie",
+ "column_category": "Kategoria",
+ "column_received": "Otrzymano",
+ "column_actions": "Akcje",
+ "filter_status": "Status",
+ "filter_status_all": "Dowolny status",
+ "filter_category": "Kategoria",
+ "status_read": "Przeczytane",
"load_error": {
"title": "Nie udało się wczytać powiadomień",
"desc": "Coś poszło nie tak podczas pobierania. Sprawdź połączenie i spróbuj ponownie."
@@ -4419,8 +4441,7 @@
"by_moderator": "Komentarz usunięty przez moderatora"
},
"live": {
- "new_comments": "Pojawiły się nowe komentarze.",
- "show_new": "Pokaż nowe komentarze",
+ "new_count": "{count, plural, one {# nowy komentarz} few {# nowe komentarze} many {# nowych komentarzy} other {# nowego komentarza}}",
"refresh_failed": "Nie udało się odświeżyć komentarzy, więc część z nich może być nieaktualna.",
"retry": "Spróbuj ponownie",
"edit_removed": "Ten komentarz został usunięty w trakcie edycji. Twój tekst nadal tu jest, ale nie da się go już zapisać.",
diff --git a/packages/api/scripts/prepare-database.ts b/packages/api/scripts/prepare-database.ts
index f603e20cca..0fca2c5446 100644
--- a/packages/api/scripts/prepare-database.ts
+++ b/packages/api/scripts/prepare-database.ts
@@ -664,6 +664,7 @@ export const initialDataForDatabase = async (given?: VitNodeApiConfig) => {
protected: true,
guest: true,
allowReact: false,
+ allowMentions: false,
},
{
// Member role
diff --git a/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts b/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts
index 33cf74bb60..864f1e2bfa 100644
--- a/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts
+++ b/packages/api/src/content/approvals/server/approval-notifications.postgres.test.ts
@@ -383,12 +383,6 @@ describe.skipIf(!POSTGRES_TEST_URL)(
(await listNotifications(await contextAs(userId), { limit: 50, userId }))
.items;
- const UNAVAILABLE = {
- available: false,
- target: null,
- title: "core.notifications.unavailable",
- };
-
const modelOf = (kind: "reply" | "topic") =>
kind === "topic" ? policyTopics : policyReplies;
@@ -711,19 +705,18 @@ describe.skipIf(!POSTGRES_TEST_URL)(
},
]),
);
- const delivered = (await inbox(USER.ROOT)).map(
- ({ available, target, title }) => ({ available, target, title }),
- );
+ const delivered = (await inbox(USER.ROOT)).map(({ target, title }) => ({
+ target,
+ title,
+ }));
expect(delivered).toHaveLength(2);
expect(delivered).toEqual(
expect.arrayContaining([
{
- available: true,
target: `/modcp/approvals/${reply}`,
title: "ptest.reply_pending.pending",
},
{
- available: true,
target: `/modcp/approvals/${topic}`,
title: "ptest.topic_pending.pending",
},
@@ -956,7 +949,7 @@ describe.skipIf(!POSTGRES_TEST_URL)(
{ data: { submissionId: second } },
]);
await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { available: true, target: `/modcp/approvals/${second}` },
+ { target: `/modcp/approvals/${second}` },
]);
});
});
@@ -1041,18 +1034,18 @@ describe.skipIf(!POSTGRES_TEST_URL)(
await drain();
await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { available: true, target: `/modcp/approvals/${second}` },
+ { target: `/modcp/approvals/${second}` },
]);
expect(
(await inbox(USER.MOD_A)).map(item => item.target),
).not.toContain(`/modcp/approvals/${first}`);
});
- it("shows a placeholder to a moderator who lost can_approve, whose link answers 404", async () => {
+ it("deletes the item of a moderator who lost can_approve, whose link answers 404", async () => {
const id = await open({ id: TOPIC.A });
await drain();
await expect(inbox(USER.MOD_A)).resolves.toMatchObject([
- { available: true, target: `/modcp/approvals/${id}` },
+ { target: `/modcp/approvals/${id}` },
]);
expect((await showSubmission(id, USER.MOD_A)).status).toBe(200);
@@ -1064,22 +1057,22 @@ describe.skipIf(!POSTGRES_TEST_URL)(
}),
]);
- await expect(inbox(USER.MOD_A)).resolves.toMatchObject([UNAVAILABLE]);
+ await expect(inbox(USER.MOD_A)).resolves.toEqual([]);
expect((await showSubmission(id, USER.MOD_A)).status).toBe(404);
await expect(inbox(USER.MOD_ALL)).resolves.toMatchObject([
- { available: true },
+ { type: TOPIC_PENDING },
]);
});
- it("shows a placeholder to a moderator of the old board once the record moves", async () => {
+ it("deletes the item of a moderator of the old board once the record moves", async () => {
await open({ id: TOPIC.A });
await drain();
await moveTopic(TOPIC.A, B);
- await expect(inbox(USER.MOD_A)).resolves.toMatchObject([UNAVAILABLE]);
+ await expect(inbox(USER.MOD_A)).resolves.toEqual([]);
await expect(inbox(USER.MOD_AB)).resolves.toMatchObject([
- { available: true },
+ { type: TOPIC_PENDING },
]);
});
});
diff --git a/packages/api/src/content/const.ts b/packages/api/src/content/const.ts
index f0433209c6..5d4926429c 100644
--- a/packages/api/src/content/const.ts
+++ b/packages/api/src/content/const.ts
@@ -383,6 +383,9 @@ export const CONTENT_QUEUE_TASK_SCHEDULE_EFFECTS = "content-schedule-effects";
/** Processes the notification intents content operations store in their transactions. */
export const CONTENT_QUEUE_TASK_NOTIFICATIONS = "content-notifications";
+/** Syncs a record's `@mentions` with its text after a committed write. */
+export const CONTENT_QUEUE_TASK_MENTIONS = "content-mentions";
+
/** Finishes a dependent reindex too big for the request that started it. */
export const CONTENT_QUEUE_TASK_SEARCH_DEPENDENTS = "content-search-dependents";
diff --git a/packages/api/src/content/fields.ts b/packages/api/src/content/fields.ts
index 3747705dae..bab6fb702e 100644
--- a/packages/api/src/content/fields.ts
+++ b/packages/api/src/content/fields.ts
@@ -134,6 +134,13 @@ const richText = <
SharedArgs & {
/** Largest serialised document accepted, in bytes. Defaults to 1 MiB. */
maxBytes?: number;
+ /**
+ * `@mentions` in this field notify the mentioned members once the record
+ * is public and they can read it. On by default; `false` turns it off -
+ * pass `mentions={false}` to the field's `AutoFormEditor` too, so the
+ * `@` popup doesn't open.
+ */
+ mentions?: boolean;
/**
* Lets the AdminCP editor accept dropped, pasted and inserted images,
* stored in `core_files`. Needs the staff permission `files:can_upload`.
diff --git a/packages/api/src/content/rich-text/elements.ts b/packages/api/src/content/rich-text/elements.ts
index 61a3b86302..37690274b7 100644
--- a/packages/api/src/content/rich-text/elements.ts
+++ b/packages/api/src/content/rich-text/elements.ts
@@ -11,6 +11,7 @@ import {
type RichTextMark,
type RichTextNode,
} from "./document";
+import { richTextMentionHref, richTextMentionOf } from "./mentions";
import { richTextToPlainText } from "./plain-text";
export const RICH_TEXT_SLOT = 0;
@@ -372,6 +373,32 @@ const attachmentElement = (node: RichTextNode): null | RichTextElement => {
};
};
+const mentionElement = (node: RichTextNode): null | RichTextElement => {
+ const mention = richTextMentionOf(node);
+ if (!mention) return null;
+
+ const attrs: Record = {
+ class: "mention",
+ "data-id": mention.id,
+ "data-label": mention.label,
+ "data-type": "mention",
+ };
+
+ if (mention.nameCode === null) {
+ return { attrs, children: [`@${mention.label}`], tag: "span" };
+ }
+
+ return {
+ attrs: {
+ ...attrs,
+ "data-name-code": mention.nameCode,
+ href: richTextMentionHref(mention.nameCode),
+ },
+ children: [`@${mention.label}`],
+ tag: "a",
+ };
+};
+
export const richTextNodeElement = (
node: RichTextNode,
): null | RichTextElement => {
@@ -441,6 +468,8 @@ export const richTextNodeElement = (
return imageElement(node);
case "listItem":
return { children: [RICH_TEXT_SLOT], tag: "li" };
+ case "mention":
+ return mentionElement(node);
case "orderedList": {
const start = positiveInteger(node.attrs?.start);
diff --git a/packages/api/src/content/rich-text/index.ts b/packages/api/src/content/rich-text/index.ts
index d8297583fd..72132ddad4 100644
--- a/packages/api/src/content/rich-text/index.ts
+++ b/packages/api/src/content/rich-text/index.ts
@@ -35,4 +35,12 @@ export type {
RichTextElementChild,
} from "./elements";
export { escapeRichTextHtml, richTextToHtml } from "./html";
+export {
+ RICH_TEXT_MENTION_LABEL_MAX,
+ RICH_TEXT_MENTION_NODE,
+ richTextMentionHref,
+ richTextMentionOf,
+ richTextMentionsOf,
+} from "./mentions";
+export type { RichTextMention } from "./mentions";
export { richTextToPlainText } from "./plain-text";
diff --git a/packages/api/src/content/rich-text/mentions.ts b/packages/api/src/content/rich-text/mentions.ts
new file mode 100644
index 0000000000..82fea6a82c
--- /dev/null
+++ b/packages/api/src/content/rich-text/mentions.ts
@@ -0,0 +1,103 @@
+import type { RichTextNode } from "./document";
+
+/** The node type of an `@mention` in a rich-text document. */
+export const RICH_TEXT_MENTION_NODE = "mention";
+
+/** Longest `label` a mention keeps; longer ones are cut. */
+export const RICH_TEXT_MENTION_LABEL_MAX = 255;
+
+const MENTIONS_MAX_DEPTH = 256;
+
+/**
+ * One `@mention` as stored: `id` is the member it points at, `label` (their
+ * name) and `nameCode` (their URL name) are a snapshot from when it was
+ * written, used until the current values load.
+ */
+export interface RichTextMention {
+ id: number;
+ label: string;
+ nameCode: null | string;
+}
+
+const mentionIdOf = (value: unknown): null | number => {
+ const id =
+ typeof value === "string" && /^\d{1,10}$/.test(value)
+ ? Number(value)
+ : value;
+
+ return typeof id === "number" &&
+ Number.isInteger(id) &&
+ id > 0 &&
+ id <= 2_147_483_647
+ ? id
+ : null;
+};
+
+/**
+ * Reads a mention node's attrs, or `null` when it is not a mention or points
+ * at no valid member id. Never trust stored attrs elsewhere - read them here.
+ */
+export const richTextMentionOf = (
+ node: null | RichTextNode | undefined,
+): null | RichTextMention => {
+ if (!node || node.type !== RICH_TEXT_MENTION_NODE) return null;
+
+ const id = mentionIdOf(node.attrs?.id);
+ if (id === null) return null;
+
+ const label = node.attrs?.label;
+ const nameCode = node.attrs?.nameCode;
+
+ return {
+ id,
+ label:
+ typeof label === "string" && label.trim() !== ""
+ ? label.trim().slice(0, RICH_TEXT_MENTION_LABEL_MAX)
+ : String(id),
+ nameCode:
+ typeof nameCode === "string" && nameCode !== "" && nameCode.length <= 255
+ ? nameCode
+ : null,
+ };
+};
+
+/**
+ * The path of a mentioned member's profile - the same as `userProfileHref` in
+ * `@vitnode/core`.
+ */
+export const richTextMentionHref = (nameCode: string): string =>
+ `/users/${encodeURIComponent(nameCode)}`;
+
+/**
+ * Every member mentioned in the given documents, once each, in document
+ * order. Mentions with invalid attrs are skipped. Universal.
+ *
+ * @example
+ * ```ts
+ * import { richTextMentionsOf } from "@vitnode/api/content/rich-text";
+ *
+ * const userIds = richTextMentionsOf(post.content).map(mention => mention.id);
+ * ```
+ */
+export const richTextMentionsOf = (
+ ...docs: readonly (null | RichTextNode | undefined)[]
+): RichTextMention[] => {
+ const found = new Map();
+
+ const walk = (node: RichTextNode, depth: number) => {
+ if (depth > MENTIONS_MAX_DEPTH || typeof node !== "object") return;
+
+ const mention = richTextMentionOf(node);
+ if (mention && !found.has(mention.id)) found.set(mention.id, mention);
+
+ if (Array.isArray(node.content)) {
+ for (const child of node.content) walk(child, depth + 1);
+ }
+ };
+
+ for (const doc of docs) {
+ if (doc && typeof doc === "object") walk(doc, 0);
+ }
+
+ return [...found.values()];
+};
diff --git a/packages/api/src/content/rich-text/plain-text.ts b/packages/api/src/content/rich-text/plain-text.ts
index dd717843ab..2a28b911e7 100644
--- a/packages/api/src/content/rich-text/plain-text.ts
+++ b/packages/api/src/content/rich-text/plain-text.ts
@@ -1,5 +1,7 @@
import type { RichTextNode } from "./document";
+import { richTextMentionOf } from "./mentions";
+
const PLAIN_TEXT_MAX_DEPTH = 256;
const ROW_TYPES: ReadonlySet = new Set(["tableRow"]);
@@ -15,6 +17,11 @@ const inlineText = (node: RichTextNode): string => {
}
case "hardBreak":
return "\n";
+ case "mention": {
+ const mention = richTextMentionOf(node);
+
+ return mention ? `@${mention.label}` : "";
+ }
case "text":
return typeof node.text === "string" ? node.text : "";
default: {
diff --git a/packages/api/src/content/server/emit.ts b/packages/api/src/content/server/emit.ts
index 5b47914d36..986fcc8db7 100644
--- a/packages/api/src/content/server/emit.ts
+++ b/packages/api/src/content/server/emit.ts
@@ -31,6 +31,7 @@ import { followContentSubmissionContainer } from "../approvals/server/follow-con
import { contentContainerFieldOf } from "../containers/association";
import { contentEventDefinitionOf } from "../event-definitions";
import { contentIdKey } from "../ids";
+import { queueContentMentions } from "./mentions";
import { invalidateContentPages } from "./page-cache";
import { publishContentRefresh } from "./refresh/publish";
@@ -174,6 +175,15 @@ export const emitContentEvent = async (
});
}
+ // Mentions follow the text: new ones notify, removed ones are retracted.
+ await queueContentMentions(c, {
+ action,
+ contentId: payload.contentId,
+ definition,
+ payload,
+ pluginId: options?.pluginId ?? event.pluginId,
+ });
+
// After the caches above, so whoever reads again on this signal misses them.
await publishContentRefresh(c, {
action,
diff --git a/packages/api/src/content/server/mention-target.ts b/packages/api/src/content/server/mention-target.ts
new file mode 100644
index 0000000000..efe1a92ea0
--- /dev/null
+++ b/packages/api/src/content/server/mention-target.ts
@@ -0,0 +1,40 @@
+import type { MentionTargetDefinition } from "../../lib/mentions/targets";
+import type { AnyContentTypeDefinition } from "../types";
+import type { AnyContentModel } from "./model";
+
+import { contentDefinitionOf } from "./model";
+import { contentNotificationAccess } from "./notifications/access";
+
+/** The rich-text fields whose `@mentions` notify - every one without `mentions: false`. */
+export const contentMentionFields = (
+ definition: AnyContentTypeDefinition,
+): string[] =>
+ Object.entries(definition.fields).flatMap(([name, field]) =>
+ field.kind === "richText" && field.mentions !== false ? [name] : [],
+ );
+
+/**
+ * The mention target of a content type with mention fields: a member hears
+ * about a mention while the record (and its thread root) is public and the
+ * type's access rules let them read it.
+ */
+export const contentMentionTarget = (
+ model: AnyContentModel,
+): MentionTargetDefinition => {
+ const definition = contentDefinitionOf(model);
+ const access = contentNotificationAccess({
+ content: definition,
+ policy: "content",
+ });
+
+ return {
+ access: async ({ c, id, rootId, userIds }) =>
+ await access({
+ c,
+ data: { contentId: id, contentTypeId: definition.id, rootId },
+ subject: null,
+ userIds,
+ }),
+ type: definition.id,
+ };
+};
diff --git a/packages/api/src/content/server/mentions.ts b/packages/api/src/content/server/mentions.ts
new file mode 100644
index 0000000000..f5bc9ffc72
--- /dev/null
+++ b/packages/api/src/content/server/mentions.ts
@@ -0,0 +1,343 @@
+import type { PgColumn, PgTable } from "drizzle-orm/pg-core";
+import type { Context } from "hono";
+
+import { eq } from "drizzle-orm";
+
+import type { RichTextNode } from "../../content/rich-text/document";
+import type { EnvVitNode } from "../../middlewares/global.middleware";
+import type { ContentEventAction } from "../events";
+import type { ContentId } from "../ids";
+import type { AnyContentTypeDefinition } from "../types";
+import type { AnyContentModel } from "./model";
+
+import { deleteMentions, syncMentions } from "../../lib/mentions/sync";
+import { contentMentionsQueueTask } from "../../modules/content/tasks/content-mentions.task";
+import { contentIdKey } from "../ids";
+import { contentMentionFields } from "./mention-target";
+import { contentDefinitionOf, findContentModel } from "./model";
+import { readContentNotificationRow } from "./notifications/access";
+import { contentNotificationText } from "./notifications/define";
+import {
+ contentNotificationActorId,
+ contentNotificationRegistryOf,
+} from "./notifications/intents";
+import { contentReactionTarget } from "./reaction-target";
+import { readTranslationRow } from "./report-target";
+import { toAuthorIds } from "./search-document";
+import { isContentBaseRowPublic } from "./visibility";
+
+type Row = Record;
+
+/** Writes that can add, remove or reveal mentions. */
+const SYNCING_ACTIONS: ReadonlySet = new Set([
+ "created",
+ "published",
+ "translation_created",
+ "translation_published",
+ "translation_restored",
+ "translation_updated",
+ "unhidden",
+ "updated",
+]);
+
+const mentionsChanged = (
+ definition: AnyContentTypeDefinition,
+ action: ContentEventAction,
+ payload: object,
+): boolean => {
+ if (action !== "updated") return true;
+ if (!("changedFields" in payload) || !Array.isArray(payload.changedFields)) {
+ return true;
+ }
+ const fields = new Set(contentMentionFields(definition));
+
+ return (payload.changedFields as unknown[]).some(
+ field => typeof field === "string" && fields.has(field),
+ );
+};
+
+/** Whether a write can add, remove or reveal mentions of a type with mention fields. */
+const writeMayMention = (
+ definition: AnyContentTypeDefinition,
+ action: ContentEventAction,
+ payload: object,
+): boolean =>
+ contentMentionFields(definition).length > 0 &&
+ (action === "deleted" ||
+ (SYNCING_ACTIONS.has(action) &&
+ mentionsChanged(definition, action, payload)));
+
+/**
+ * Queues a record's mentions for syncing after a committed content write -
+ * `emitContentEvent` calls it for every write. A no-op for types without
+ * mention fields and for writes that cannot change them (hiding or
+ * unpublishing only hides the notifications, through their access check).
+ * Never throws: the write already committed.
+ */
+export const queueContentMentions = async (
+ c: Context,
+ {
+ action,
+ contentId,
+ definition,
+ payload,
+ pluginId,
+ }: {
+ action: ContentEventAction;
+ contentId: ContentId;
+ definition: AnyContentTypeDefinition;
+ payload: object;
+ pluginId: string;
+ },
+): Promise => {
+ if (!writeMayMention(definition, action, payload)) return;
+
+ try {
+ const queued = await c.get("queue").dispatch(contentMentionsQueueTask, {
+ actorId: contentNotificationActorId(c),
+ contentTypeId: definition.id,
+ deleted: action === "deleted",
+ itemId: contentIdKey(contentId),
+ pluginId,
+ });
+ if (queued.id !== null) {
+ (
+ c.get("notifications") as
+ | undefined
+ | { processAfterResponse?: (queueId: number) => void }
+ )?.processAfterResponse?.(queued.id);
+ }
+ } catch (error) {
+ await c
+ .get("log")
+ ?.error(
+ `[mentions] ${definition.id}: mentions of ${contentIdKey(contentId)} were not queued (${error instanceof Error ? error.message : String(error)}).`,
+ );
+ }
+};
+
+const firstUserId = (value: unknown): null | number =>
+ toAuthorIds(value).at(0) ?? null;
+
+/** The member who wrote the record: the search author, or the public write owner. */
+const authorOf = (
+ definition: AnyContentTypeDefinition,
+ row: Row,
+): null | number => {
+ const field =
+ definition.search.authorField ?? definition.publicWrite.ownerField;
+
+ return field ? firstUserId(row[field]) : null;
+};
+
+/** The published translations' rich text of the localized mention fields. */
+const translationDocuments = async (
+ c: Context,
+ model: AnyContentModel,
+ fields: readonly string[],
+ itemId: unknown,
+): Promise => {
+ const table = model.translationTable as null | PgTable;
+ const columns = model.translationColumns as null | Record;
+ const tableColumns = table as unknown as null | Record;
+ if (!table || !columns || !tableColumns?.itemId) return [];
+
+ const localized = fields.filter(field => columns[field]);
+ if (localized.length === 0) return [];
+
+ const rows = (await c
+ .get("db")
+ .select()
+ .from(table)
+ .where(eq(tableColumns.itemId, itemId))) as Row[];
+
+ return rows
+ .filter(
+ row =>
+ !("publishedAt" in row) ||
+ (row.publishedAt !== null &&
+ new Date(row.publishedAt as Date | string) <= new Date()),
+ )
+ .flatMap(row =>
+ localized.map(field => row[field] as RichTextNode | undefined),
+ )
+ .filter((doc): doc is RichTextNode => !!doc && typeof doc === "object");
+};
+
+/** Title and link for the notification, from the thread rule or the record itself. */
+const describe = async (
+ c: Context,
+ {
+ content,
+ model,
+ parent,
+ pluginId,
+ root,
+ }: {
+ content: Row;
+ model: AnyContentModel;
+ parent: null | Row;
+ pluginId: string;
+ root: null | Row;
+ },
+): Promise<{
+ exclude: number[];
+ title: string;
+ url: null | string;
+}> => {
+ const definition = contentDefinitionOf(model);
+ const thread = contentNotificationRegistryOf(c)
+ ?.rulesFor(definition.id, "firstPublication")
+ .map(entry => entry.rule)
+ .find(rule => rule.kind === "threadReply");
+
+ if (thread && thread.kind === "threadReply" && root) {
+ // The thread rule already tells these members about the reply.
+ const exclude = [
+ thread.parentAuthor && parent
+ ? firstUserId(parent[thread.authorField])
+ : null,
+ thread.rootAuthorField ? firstUserId(root[thread.rootAuthorField]) : null,
+ ].filter((id): id is number => id !== null);
+
+ return {
+ exclude,
+ title: contentNotificationText(
+ thread.title
+ ? thread.title({ content, root })
+ : await rootTitleOf(c, rootDefinitionOf(definition), root),
+ ),
+ url: thread.target({ content, parent, root }),
+ };
+ }
+
+ const preview = (
+ await contentReactionTarget(model, pluginId).preview?.(c, {
+ ids: [String(content.id)],
+ })
+ )?.get(String(content.id));
+
+ return {
+ exclude: [],
+ title: contentNotificationText(preview?.title),
+ url: preview?.url ?? null,
+ };
+};
+
+const rootTitleOf = async (
+ c: Context,
+ rootDefinition: AnyContentTypeDefinition | null,
+ root: Row,
+): Promise => {
+ const titleField = rootDefinition?.admin.titleField;
+ if (!rootDefinition || !titleField) return "";
+ if (root[titleField] !== undefined) return root[titleField];
+ if (!rootDefinition.localization.enabled) return "";
+
+ const entry = findContentModel(
+ c.get("core").contentModels,
+ rootDefinition.id,
+ );
+ const itemId = root.id;
+ if (!entry || (typeof itemId !== "number" && typeof itemId !== "string")) {
+ return "";
+ }
+ const translation = await readTranslationRow(c, c.get("db"), entry.model, {
+ itemId,
+ locale: rootDefinition.localization.defaultLocale,
+ });
+
+ return translation?.[titleField] ?? "";
+};
+
+const rootDefinitionOf = (
+ definition: AnyContentTypeDefinition,
+): AnyContentTypeDefinition | null => {
+ if (!definition.thread.enabled) return null;
+ const field = definition.fields[definition.thread.rootField];
+
+ return field?.kind === "relation" ? field.target() : null;
+};
+
+const keyOf = (value: unknown): null | string =>
+ typeof value === "number" || typeof value === "string" ? String(value) : null;
+
+/**
+ * Syncs one record's stored mentions with its current text - the
+ * `content-mentions` queue task. A record that is not public notifies
+ * nobody yet; its next publication syncs again. Server-only.
+ */
+export const processContentMentions = async (
+ c: Context,
+ {
+ actorId,
+ contentTypeId,
+ deleted,
+ itemId,
+ pluginId,
+ }: {
+ actorId: null | number;
+ contentTypeId: string;
+ deleted: boolean;
+ itemId: string;
+ pluginId: string;
+ },
+): Promise => {
+ const entry = findContentModel(c.get("core").contentModels, contentTypeId);
+ const content = deleted
+ ? null
+ : await readContentNotificationRow(c, contentTypeId, itemId);
+ if (!entry || !content) {
+ await deleteMentions({
+ c,
+ id: itemId,
+ pluginId: entry?.pluginId ?? pluginId,
+ targetType: contentTypeId,
+ });
+
+ return;
+ }
+ if (!isContentBaseRowPublic(content)) return;
+
+ const { model } = entry;
+ const definition = contentDefinitionOf(model);
+ const fields = contentMentionFields(definition);
+ const documents = [
+ ...fields.map(field => content[field] as RichTextNode | undefined),
+ ...(await translationDocuments(c, model, fields, content.id)),
+ ];
+
+ const rootDefinition = rootDefinitionOf(definition);
+ const rootId = definition.thread.enabled
+ ? keyOf(content[definition.thread.rootField])
+ : null;
+ const parentId = definition.thread.enabled
+ ? keyOf(content[definition.thread.parentField])
+ : null;
+ const [root, parent] = await Promise.all([
+ rootDefinition && rootId
+ ? readContentNotificationRow(c, rootDefinition.id, rootId)
+ : null,
+ parentId ? readContentNotificationRow(c, definition.id, parentId) : null,
+ ]);
+ const { exclude, title, url } = await describe(c, {
+ content,
+ model,
+ parent,
+ pluginId: entry.pluginId,
+ root,
+ });
+
+ await syncMentions({
+ actorId: authorOf(definition, content) ?? actorId,
+ c,
+ documents,
+ exclude,
+ id: itemId,
+ pluginId: entry.pluginId,
+ rootId,
+ target: definition.id,
+ title,
+ url,
+ });
+};
diff --git a/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts b/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts
index e82ac2de4d..9b2d1838a5 100644
--- a/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts
+++ b/packages/api/src/content/server/notifications/content-notifications.postgres.test.ts
@@ -453,7 +453,7 @@ describe.skipIf(!POSTGRES_TEST_URL)(
expect.objectContaining({ actorId: null, recipientIds: [WATCHER] }),
]);
await expect(inbox(WATCHER)).resolves.toEqual([
- expect.objectContaining({ available: true, title: "A topic" }),
+ expect.objectContaining({ title: "A topic" }),
]);
});
@@ -630,7 +630,6 @@ describe.skipIf(!POSTGRES_TEST_URL)(
await drain();
await expect(inbox(COMMENTER)).resolves.toEqual([
expect.objectContaining({
- available: true,
target: "/pending",
title: "ntest.decision.rejected",
}),
@@ -642,11 +641,9 @@ describe.skipIf(!POSTGRES_TEST_URL)(
await expect(events(DECISION_TYPE)).resolves.toHaveLength(2);
await expect(inbox(COMMENTER)).resolves.toEqual([
expect.objectContaining({
- available: true,
title: "ntest.decision.approved",
}),
expect.objectContaining({
- available: true,
title: "ntest.decision.rejected",
}),
]);
@@ -777,7 +774,6 @@ describe.skipIf(!POSTGRES_TEST_URL)(
await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([
expect.objectContaining({
- available: true,
target: expect.stringMatching(/#comment-\d+$/),
title: "ntest.reply.reply",
}),
@@ -975,26 +971,23 @@ describe.skipIf(!POSTGRES_TEST_URL)(
},
],
])(
- "shows a placeholder while %s, and the notification again once restored",
+ "deletes the notification for good once %s",
async (_, hide, restore) => {
const ids = await notifiedComment();
await expect(inbox(TOPIC_AUTHOR)).resolves.toMatchObject([
- { available: true, title: "ntest.reply.comment" },
+ { title: "ntest.reply.comment" },
]);
await hide(ids);
- await expect(inbox(TOPIC_AUTHOR)).resolves.toMatchObject([
- {
- available: false,
- target: null,
- title: "core.notifications.unavailable",
- },
- ]);
+ await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([]);
+ await expect(
+ (await contextAs(TOPIC_AUTHOR))
+ .get("notifications")
+ .state(TOPIC_AUTHOR),
+ ).resolves.toMatchObject({ unread: 0 });
await restore(ids);
- await expect(inbox(TOPIC_AUTHOR)).resolves.toMatchObject([
- { available: true, title: "ntest.reply.comment" },
- ]);
+ await expect(inbox(TOPIC_AUTHOR)).resolves.toEqual([]);
},
);
diff --git a/packages/api/src/content/server/report-target.ts b/packages/api/src/content/server/report-target.ts
index 663d45d86c..9596ee62e0 100644
--- a/packages/api/src/content/server/report-target.ts
+++ b/packages/api/src/content/server/report-target.ts
@@ -221,7 +221,7 @@ const readBaseRow = async (
return row ?? null;
};
-const readTranslationRow = async (
+export const readTranslationRow = async (
c: Context,
db: ContentDatabase,
model: AnyContentModel,
diff --git a/packages/api/src/content/types.ts b/packages/api/src/content/types.ts
index 284d618327..f4c812fb3e 100644
--- a/packages/api/src/content/types.ts
+++ b/packages/api/src/content/types.ts
@@ -159,6 +159,8 @@ export interface ContentRichTextField<
kind: "richText";
localized: TLocalized;
maxBytes?: number;
+ /** `@mentions` notify members; `undefined` means on. */
+ mentions?: boolean;
uploads?: boolean;
}
diff --git a/packages/api/src/database/mentions.ts b/packages/api/src/database/mentions.ts
new file mode 100644
index 0000000000..2b85bb6f22
--- /dev/null
+++ b/packages/api/src/database/mentions.ts
@@ -0,0 +1,44 @@
+import { camelCase, index, uniqueIndex } from "drizzle-orm/pg-core";
+
+import { core_notification_events } from "./notifications";
+import { core_users } from "./users";
+
+/**
+ * One member `@mentioned` in one target - mirrors the mentions in the
+ * target's current text. The target is polymorphic (a content record or a
+ * plugin's own row), so it has no foreign key: delete effects and the daily
+ * cleanup remove rows of targets that are gone.
+ */
+export const core_mentions = camelCase.table.withRLS(
+ "core_mentions",
+ t => ({
+ id: t.serial().primaryKey(),
+ pluginId: t.varchar({ length: 100 }).notNull(),
+ /** The content type id, or a custom mention target's `type`. */
+ targetType: t.varchar({ length: 100 }).notNull(),
+ targetId: t.varchar({ length: 100 }).notNull(),
+ userId: t
+ .integer()
+ .notNull()
+ .references(() => core_users.id, { onDelete: "cascade" }),
+ actorId: t.integer().references(() => core_users.id, {
+ onDelete: "set null",
+ }),
+ /** The `core.mention` event that notified the member; retracted with the row. */
+ eventId: t
+ .bigint({ mode: "number" })
+ .references(() => core_notification_events.id, { onDelete: "set null" }),
+ notified: t.boolean().notNull().default(false),
+ createdAt: t.timestamp().notNull().defaultNow(),
+ }),
+ t => [
+ uniqueIndex("core_mentions_target_user_idx").on(
+ t.pluginId,
+ t.targetType,
+ t.targetId,
+ t.userId,
+ ),
+ index("core_mentions_user_id_idx").on(t.userId, t.createdAt),
+ index("core_mentions_event_id_idx").on(t.eventId),
+ ],
+);
diff --git a/packages/api/src/database/roles.ts b/packages/api/src/database/roles.ts
index abeba62de5..e8f5662c55 100644
--- a/packages/api/src/database/roles.ts
+++ b/packages/api/src/database/roles.ts
@@ -1,5 +1,7 @@
import { camelCase, index } from "drizzle-orm/pg-core";
+import { ROLE_DEFAULT_MAX_MENTIONS_PER_ITEM } from "@/lib/mentions/limits";
+
export const core_roles = camelCase.table.withRLS(
"core_roles",
t => ({
@@ -37,6 +39,10 @@ export const core_roles = camelCase.table.withRLS(
maxReactionsPerItem: t.integer().default(1),
// Reactions per day over every reaction; null = unlimited.
reactionsPerDay: t.integer(),
+ /** Members of this role may `@mention` others and so notify them. */
+ allowMentions: t.boolean().notNull().default(true),
+ // Members one post of theirs notifies by mentions; null = unlimited.
+ maxMentionsPerItem: t.integer().default(ROLE_DEFAULT_MAX_MENTIONS_PER_ITEM),
}),
t => [index("core_roles_updated_at_id_idx").on(t.updatedAt, t.id)],
);
diff --git a/packages/api/src/events/mentions.ts b/packages/api/src/events/mentions.ts
new file mode 100644
index 0000000000..db805b6730
--- /dev/null
+++ b/packages/api/src/events/mentions.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+
+import { manifest } from "@/manifest";
+
+import { defineEvent } from "../lib/event-definition";
+
+const pluginId = manifest.id;
+
+const mentionTarget = {
+ actorId: z.number().int().nullable(),
+ pluginId: z.string(),
+ targetId: z.string(),
+ targetType: z.string(),
+};
+
+/**
+ * Members were `@mentioned` for the first time in a target's text. `notified`
+ * is `false` for those who got no notification: they can't read the target,
+ * the author's role may not mention, or the role's per-item cap was reached.
+ */
+export const mentionCreatedEvent = defineEvent({
+ pluginId,
+ name: "mention.created",
+ payload: z.object({
+ ...mentionTarget,
+ users: z.array(z.object({ id: z.number().int(), notified: z.boolean() })),
+ }),
+});
+
+/** An edit removed mentions; their notifications are already retracted. */
+export const mentionRemovedEvent = defineEvent({
+ pluginId,
+ name: "mention.removed",
+ payload: z.object({
+ ...mentionTarget,
+ userIds: z.array(z.number().int()),
+ }),
+});
+
+/** Every `mention.*` event core defines. */
+export const mentionEventDefinitions = [
+ mentionCreatedEvent,
+ mentionRemovedEvent,
+];
diff --git a/packages/api/src/lib/mentions/limits.ts b/packages/api/src/lib/mentions/limits.ts
new file mode 100644
index 0000000000..f64ecd8642
--- /dev/null
+++ b/packages/api/src/lib/mentions/limits.ts
@@ -0,0 +1,5 @@
+/** Members one record notifies by `@mentions` for a new role. Browser-safe. */
+export const ROLE_DEFAULT_MAX_MENTIONS_PER_ITEM = 25;
+
+/** Highest per-record mention cap a role can have; `null` is unlimited. Browser-safe. */
+export const ROLE_MAX_MENTIONS_PER_ITEM = 1000;
diff --git a/packages/api/src/lib/mentions/notification.ts b/packages/api/src/lib/mentions/notification.ts
new file mode 100644
index 0000000000..6746aaa754
--- /dev/null
+++ b/packages/api/src/lib/mentions/notification.ts
@@ -0,0 +1,75 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { z } from "zod";
+
+import { core_mentions } from "@/database/mentions";
+import { buildNotificationType } from "@/lib/notifications/registry";
+
+import { findMentionTarget } from "./targets";
+
+/**
+ * Sent to a member `@mentioned` in rich text, once the target is public and
+ * they can read it. Every mention is its own inbox item; removing a mention
+ * retracts its notification.
+ */
+export const mentionNotification = buildNotificationType({
+ id: "core.mention",
+ version: 1,
+ schema: z.object({
+ mentionId: z.number().int(),
+ pluginId: z.string(),
+ rootId: z.string().nullable(),
+ targetId: z.string(),
+ targetType: z.string(),
+ title: z.string(),
+ url: z.string().nullable(),
+ }),
+ category: "social",
+ label: "core.notifications.types.mention.label",
+ description: "core.notifications.types.mention.description",
+ defaults: { email: "immediate", inApp: true },
+ email: true,
+ // The mention must still be in the text, and the target readable now.
+ access: async ({ c, data, userIds }) => {
+ if (userIds.length === 0) return [];
+ const target = findMentionTarget(c.get("core").mentions, {
+ pluginId: data.pluginId,
+ type: data.targetType,
+ });
+ if (!target) return [];
+
+ const rows = await c
+ .get("db")
+ .select({ userId: core_mentions.userId })
+ .from(core_mentions)
+ .where(
+ and(
+ eq(core_mentions.id, data.mentionId),
+ inArray(core_mentions.userId, userIds),
+ ),
+ );
+ if (rows.length === 0) return [];
+
+ return await target.definition.access({
+ c,
+ id: data.targetId,
+ rootId: data.rootId,
+ userIds: rows.map(row => row.userId),
+ });
+ },
+ present: ({ actorCount, actors, data, t }) => {
+ const values = {
+ count: Math.max(actorCount, 1),
+ name: actors[0]?.name ?? t("core.notifications.someone"),
+ };
+
+ return {
+ target: data.url,
+ title: data.title
+ ? t("core.notifications.types.mention.title_in", {
+ ...values,
+ title: data.title,
+ })
+ : t("core.notifications.types.mention.title", values),
+ };
+ },
+});
diff --git a/packages/api/src/lib/mentions/policy.ts b/packages/api/src/lib/mentions/policy.ts
new file mode 100644
index 0000000000..04a487f8f7
--- /dev/null
+++ b/packages/api/src/lib/mentions/policy.ts
@@ -0,0 +1,100 @@
+import type { Context } from "hono";
+
+import { eq, inArray } from "drizzle-orm";
+
+import { core_roles } from "@/database/roles";
+import { core_users } from "@/database/users";
+import { getUserRoleIds } from "@/lib/check-staff-permission";
+import { mostGenerousLimit } from "@/lib/reactions/policy";
+
+/** One role's mention settings. */
+export interface RoleMentionSettings {
+ allowMentions: boolean;
+ /** `null` = unlimited. */
+ maxMentionsPerItem: null | number;
+}
+
+/** What one member may do with `@mentions`, from all their roles. */
+export interface MentionPolicy {
+ /** One of their roles allows mentioning others. */
+ canMention: boolean;
+ /** Members one record of theirs notifies by mentions; `null` = unlimited. */
+ maxPerItem: null | number;
+}
+
+const NO_MENTIONS: MentionPolicy = { canMention: false, maxPerItem: 0 };
+
+/**
+ * What a member's roles allow together; the most generous role wins. Only
+ * roles with `allowMentions` count. Pure.
+ */
+export const effectiveMentionPolicy = (
+ roles: readonly RoleMentionSettings[],
+): MentionPolicy => {
+ const mentioning = roles.filter(role => role.allowMentions);
+ if (mentioning.length === 0) return NO_MENTIONS;
+
+ return {
+ canMention: true,
+ maxPerItem: mostGenerousLimit(
+ mentioning.map(role => role.maxMentionsPerItem),
+ ),
+ };
+};
+
+/**
+ * The mention policy of any member, e.g. the author of a record a background
+ * task processes. Server-only.
+ */
+export const mentionPolicyOf = async (
+ c: Context,
+ user: { id: number; roleId: number },
+): Promise => {
+ const roleIds = await getUserRoleIds(c, user);
+ const roles = await c
+ .get("db")
+ .select({
+ allowMentions: core_roles.allowMentions,
+ maxMentionsPerItem: core_roles.maxMentionsPerItem,
+ })
+ .from(core_roles)
+ .where(inArray(core_roles.id, roleIds));
+
+ return effectiveMentionPolicy(roles);
+};
+
+/** The mention policy of a member by id; nothing for an unknown id. Server-only. */
+export const mentionPolicyOfUserId = async (
+ c: Context,
+ userId: null | number | undefined,
+): Promise => {
+ if (!userId) return NO_MENTIONS;
+
+ const [user] = await c
+ .get("db")
+ .select({ id: core_users.id, roleId: core_users.roleId })
+ .from(core_users)
+ .where(eq(core_users.id, userId))
+ .limit(1);
+
+ return user ? await mentionPolicyOf(c, user) : NO_MENTIONS;
+};
+
+const resolved = new WeakMap>();
+
+/**
+ * The signed-in member's mention policy, read once per request. Guests and
+ * suspended members (who reach routes as guests) get nothing. Server-only.
+ */
+export const resolveMentionPolicy = async (
+ c: Context,
+): Promise => {
+ const cached = resolved.get(c);
+ if (cached) return await cached;
+
+ const user = c.get("user");
+ const policy = user ? mentionPolicyOf(c, user) : Promise.resolve(NO_MENTIONS);
+ resolved.set(c, policy);
+
+ return await policy;
+};
diff --git a/packages/api/src/lib/mentions/sync.ts b/packages/api/src/lib/mentions/sync.ts
new file mode 100644
index 0000000000..2c8ea86ecf
--- /dev/null
+++ b/packages/api/src/lib/mentions/sync.ts
@@ -0,0 +1,293 @@
+import type { Context } from "hono";
+
+import { and, eq, inArray, sql } from "drizzle-orm";
+
+import type { RichTextNode } from "@/content/rich-text/document";
+import type { EnvVitNode } from "@/middlewares/global.middleware";
+
+import { richTextMentionsOf } from "@/content/rich-text/mentions";
+import { core_mentions } from "@/database/mentions";
+import { mentionCreatedEvent, mentionRemovedEvent } from "@/events/mentions";
+import { loadMentionedUsers } from "@/models/mentions/users";
+import { detachNotificationEvents } from "@/models/notifications/inbox";
+
+import type { MentionTargetDefinition } from "./targets";
+
+import { mentionNotification } from "./notification";
+import { mentionPolicyOfUserId } from "./policy";
+import { findMentionTarget } from "./targets";
+
+/** Most mentioned members one target stores; the rest are ignored. */
+const MENTIONS_PER_TARGET_MAX = 1000;
+
+export interface SyncMentionsArgs {
+ /** Who wrote the text: their roles decide whether and how many members it notifies. */
+ actorId: null | number;
+ c: Context;
+ /** The target's current rich text - every field that can mention, in reading order. */
+ documents: readonly (null | RichTextNode | undefined)[];
+ /** Members not to notify, e.g. those another notification about the same write already reached. */
+ exclude?: readonly number[];
+ /** The target's id, as its `access` reads it. */
+ id: number | string;
+ /** The plugin that registered the target. */
+ pluginId: string;
+ /** The thread the target belongs to; mentions in one thread group in the inbox. */
+ rootId?: null | number | string;
+ /** The registered target, or its `type`. */
+ target: MentionTargetDefinition | string;
+ /** Plain-text title shown in the notification. */
+ title: string;
+ /** Same-site path the notification opens, `null` for none. */
+ url: null | string;
+}
+
+export interface SyncMentionsResult {
+ /** Members mentioned for the first time. */
+ added: number[];
+ /** The added members who were notified. */
+ notified: number[];
+ /** Members no longer mentioned; their notifications are retracted. */
+ removed: number[];
+}
+
+/**
+ * Makes the stored mentions of a target mirror its current text: members
+ * mentioned for the first time are stored and - when the author's role may
+ * mention and they can read the target - notified with `core.mention`, up to
+ * the role's per-item cap; members no longer mentioned lose the mention and
+ * its notification. Idempotent: calling it again with the same text changes
+ * nothing. Call it after every committed write of the text, outside the
+ * write's transaction. Server-only.
+ *
+ * @example
+ * ```ts
+ * import { syncMentions } from "@vitnode/api/mentions";
+ *
+ * await syncMentions({
+ * c,
+ * pluginId: "@vitnode/newsroom",
+ * target: letterMentionTarget,
+ * id: letter.id,
+ * actorId: letter.authorId,
+ * documents: [letter.content],
+ * title: letter.title,
+ * url: `/letters/${letter.id}`,
+ * });
+ * ```
+ *
+ * @throws {Error} When the target is not registered by `pluginId`.
+ */
+export const syncMentions = async ({
+ actorId,
+ c,
+ documents,
+ exclude = [],
+ id,
+ pluginId,
+ rootId = null,
+ target,
+ title,
+ url,
+}: SyncMentionsArgs): Promise => {
+ const targetType = typeof target === "string" ? target : target.type;
+ const registered = findMentionTarget(c.get("core").mentions, {
+ pluginId,
+ type: targetType,
+ });
+ if (!registered) {
+ throw new Error(
+ `[Mentions] Target "${targetType}" is not registered by ${pluginId}.`,
+ );
+ }
+
+ const targetId = String(id);
+ const root = rootId === null ? null : String(rootId);
+ const mentioned = richTextMentionsOf(...documents)
+ .map(mention => mention.id)
+ .filter(userId => userId !== actorId)
+ .slice(0, MENTIONS_PER_TARGET_MAX);
+ const existing = new Set(
+ (await loadMentionedUsers(c, mentioned)).map(user => user.id),
+ );
+ const wanted = mentioned.filter(userId => existing.has(userId));
+ const policy = await mentionPolicyOfUserId(c, actorId);
+
+ const ofTarget = and(
+ eq(core_mentions.pluginId, pluginId),
+ eq(core_mentions.targetType, targetType),
+ eq(core_mentions.targetId, targetId),
+ );
+
+ const outcome = await c.get("db").transaction(async tx => {
+ // Two saves of one target must not both see a member as new.
+ await tx.execute(
+ sql`select pg_advisory_xact_lock(hashtext(${`mentions:${pluginId}:${targetType}:${targetId}`}))`,
+ );
+
+ const stored = await tx
+ .select({
+ eventId: core_mentions.eventId,
+ notified: core_mentions.notified,
+ userId: core_mentions.userId,
+ })
+ .from(core_mentions)
+ .where(ofTarget);
+ const storedIds = new Set(stored.map(row => row.userId));
+ const wantedIds = new Set(wanted);
+
+ const gone = stored.filter(row => !wantedIds.has(row.userId));
+ if (gone.length > 0) {
+ await tx.delete(core_mentions).where(
+ and(
+ ofTarget,
+ inArray(
+ core_mentions.userId,
+ gone.map(row => row.userId),
+ ),
+ ),
+ );
+ }
+
+ const fresh = wanted.filter(userId => !storedIds.has(userId));
+ const inserted =
+ fresh.length === 0
+ ? []
+ : await tx
+ .insert(core_mentions)
+ .values(
+ fresh.map(userId => ({
+ actorId,
+ pluginId,
+ targetId,
+ targetType,
+ userId,
+ })),
+ )
+ .onConflictDoNothing()
+ .returning({ id: core_mentions.id, userId: core_mentions.userId });
+
+ const notified: number[] = [];
+ if (inserted.length > 0 && policy.canMention) {
+ const kept = stored.filter(
+ row => row.notified && wantedIds.has(row.userId),
+ ).length;
+ const room =
+ policy.maxPerItem === null
+ ? Infinity
+ : Math.max(policy.maxPerItem - kept, 0);
+ const skipped = new Set(exclude);
+ const readers = new Set(
+ await registered.definition.access({
+ c,
+ id: targetId,
+ rootId: root,
+ userIds: inserted
+ .map(row => row.userId)
+ .filter(userId => !skipped.has(userId)),
+ }),
+ );
+ const rowOf = new Map(inserted.map(row => [row.userId, row]));
+ const chosen = fresh
+ .filter(userId => readers.has(userId) && rowOf.has(userId))
+ .slice(0, room === Infinity ? undefined : room);
+
+ for (const userId of chosen) {
+ const row = rowOf.get(userId);
+ if (!row) continue;
+
+ const { eventId } = await c.get("notifications").publish({
+ actorId,
+ data: {
+ mentionId: row.id,
+ pluginId,
+ rootId: root,
+ targetId,
+ targetType,
+ title,
+ url,
+ },
+ idempotencyKey: `mention:${row.id}`,
+ recipients: [userId],
+ subject: { id: targetId, type: targetType },
+ tx,
+ type: mentionNotification,
+ });
+ await tx
+ .update(core_mentions)
+ .set({ eventId, notified: true })
+ .where(eq(core_mentions.id, row.id));
+ notified.push(userId);
+ }
+ }
+
+ return {
+ added: inserted.map(row => row.userId),
+ gone,
+ notified,
+ };
+ });
+ // Delivers right away, also from a queue task, which has no response to
+ // flush after.
+ if (outcome.notified.length > 0) c.get("notifications").flushAfterResponse();
+
+ const retracted = outcome.gone.flatMap(row =>
+ row.eventId === null ? [] : [row.eventId],
+ );
+ if (retracted.length > 0) {
+ await detachNotificationEvents(c, retracted);
+ }
+
+ const base = { actorId, pluginId, targetId, targetType };
+ const notifiedIds = new Set(outcome.notified);
+ if (outcome.added.length > 0) {
+ await c.get("events").emit(mentionCreatedEvent, {
+ ...base,
+ users: outcome.added.map(userId => ({
+ id: userId,
+ notified: notifiedIds.has(userId),
+ })),
+ });
+ }
+ const removed = outcome.gone.map(row => row.userId);
+ if (removed.length > 0) {
+ await c
+ .get("events")
+ .emit(mentionRemovedEvent, { ...base, userIds: removed });
+ }
+
+ return { added: outcome.added, notified: outcome.notified, removed };
+};
+
+/**
+ * Forgets every mention of a target and retracts their notifications - for
+ * a target that was deleted. Server-only.
+ */
+export const deleteMentions = async ({
+ c,
+ id,
+ pluginId,
+ targetType,
+}: {
+ c: Context;
+ id: number | string;
+ pluginId: string;
+ targetType: string;
+}): Promise => {
+ const rows = await c
+ .get("db")
+ .delete(core_mentions)
+ .where(
+ and(
+ eq(core_mentions.pluginId, pluginId),
+ eq(core_mentions.targetType, targetType),
+ eq(core_mentions.targetId, String(id)),
+ ),
+ )
+ .returning({ eventId: core_mentions.eventId });
+
+ const eventIds = rows.flatMap(row =>
+ row.eventId === null ? [] : [row.eventId],
+ );
+ if (eventIds.length > 0) await detachNotificationEvents(c, eventIds);
+};
diff --git a/packages/api/src/lib/mentions/targets.ts b/packages/api/src/lib/mentions/targets.ts
new file mode 100644
index 0000000000..4b3f34464d
--- /dev/null
+++ b/packages/api/src/lib/mentions/targets.ts
@@ -0,0 +1,105 @@
+import type { Context } from "hono";
+
+import type { EnvVitNode } from "@/middlewares/global.middleware";
+
+import { MODERATION_IDENTIFIER_PATTERN } from "@/lib/moderation/const";
+
+/** Thrown at startup when a mention target is misconfigured. */
+export class MentionsRegistryError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "MentionsRegistryError";
+ }
+}
+
+/**
+ * Something whose rich text can `@mention` members and that is not a Content
+ * Engine type (those get a target automatically for every rich-text field
+ * that keeps `mentions` on). Create it with {@link defineMentionTarget},
+ * register it in `buildApiPlugin({ mentions: { targets } })` and call
+ * `syncMentions` after every write of its text.
+ */
+export interface MentionTargetDefinition {
+ /**
+ * The members among `userIds` who may read target `id` now. Called before a
+ * mention notifies, before every email about it and each time an inbox
+ * shows it, so a member who loses access stops seeing it. Batched - never
+ * once per member. Server-only.
+ */
+ access: (args: {
+ c: Context;
+ id: string;
+ /** The thread root `syncMentions` was given, if any. */
+ rootId: null | string;
+ userIds: number[];
+ }) => Promise;
+ /** Stable id stored with every mention, lowercase and dot-separated, e.g. `"newsroom.letter"`. */
+ type: string;
+}
+
+export interface RegisteredMentionTarget {
+ definition: MentionTargetDefinition;
+ pluginId: string;
+}
+
+/**
+ * Validates a custom mention target when the module loads. Server-only.
+ *
+ * @example
+ * ```ts
+ * import { defineMentionTarget } from "@vitnode/api/mentions";
+ *
+ * export const letterMentionTarget = defineMentionTarget({
+ * type: "newsroom.letter",
+ * access: async ({ userIds }) => userIds, // a public letter
+ * });
+ * ```
+ *
+ * @throws {MentionsRegistryError} When `type` is not lowercase and dot-separated.
+ */
+export const defineMentionTarget = (
+ definition: MentionTargetDefinition,
+): MentionTargetDefinition => {
+ if (!MODERATION_IDENTIFIER_PATTERN.test(definition.type)) {
+ throw new MentionsRegistryError(
+ `Mention target type "${definition.type}" must be lowercase and dot separated, like "forum.topic".`,
+ );
+ }
+
+ return definition;
+};
+
+/** The `mentions` option of `buildApiPlugin`. */
+export interface MentionsPluginConfig {
+ /** Custom mention targets; content types add theirs automatically. */
+ targets?: MentionTargetDefinition[];
+}
+
+export interface MentionsRegistry {
+ targets: RegisteredMentionTarget[];
+}
+
+export const validateMentionsRegistry = (
+ targets: readonly RegisteredMentionTarget[],
+): MentionsRegistry => {
+ const byKey = new Map();
+ for (const entry of targets) {
+ const key = `${entry.pluginId}:${entry.definition.type}`;
+ if (byKey.has(key)) {
+ throw new MentionsRegistryError(
+ `Mention target "${entry.definition.type}" is registered twice by ${entry.pluginId}.`,
+ );
+ }
+ byKey.set(key, entry);
+ }
+
+ return { targets: [...byKey.values()] };
+};
+
+export const findMentionTarget = (
+ registry: MentionsRegistry | undefined,
+ { pluginId, type }: { pluginId: string; type: string },
+): RegisteredMentionTarget | undefined =>
+ registry?.targets.find(
+ entry => entry.pluginId === pluginId && entry.definition.type === type,
+ );
diff --git a/packages/api/src/lib/notifications/core-types.ts b/packages/api/src/lib/notifications/core-types.ts
index 6e8859f0a2..4f08163c14 100644
--- a/packages/api/src/lib/notifications/core-types.ts
+++ b/packages/api/src/lib/notifications/core-types.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { resolveLangValue } from "@/lib/helpers/multi-lang";
+import { mentionNotification } from "@/lib/mentions/notification";
import { buildNotificationType } from "./registry";
@@ -190,4 +191,5 @@ export const coreNotificationTypes = [
accountSuspendedNotification,
suspensionRevokedNotification,
reactionReceivedNotification,
+ mentionNotification,
];
diff --git a/packages/api/src/lib/notifications/registry.ts b/packages/api/src/lib/notifications/registry.ts
index 59ddf01e2e..856d9b4300 100644
--- a/packages/api/src/lib/notifications/registry.ts
+++ b/packages/api/src/lib/notifications/registry.ts
@@ -123,8 +123,8 @@ export interface NotificationTypeDefinition> {
migrate?: (data: unknown, fromVersion: number) => unknown;
/**
* Renders one inbox item in the recipient's language. Runs on the API each
- * time the item is listed or emailed; a throw or empty title shows a "no
- * longer available" placeholder.
+ * time the item is listed or emailed; a throw or empty title leaves the item
+ * out of the list.
*/
present: (args: NotificationPresentArgs) => NotificationPresentation;
/** Validates `data` on publish and whenever stored data is read. */
diff --git a/packages/api/src/lib/plugin.ts b/packages/api/src/lib/plugin.ts
index 5bf3671dbe..aa1d5c9300 100644
--- a/packages/api/src/lib/plugin.ts
+++ b/packages/api/src/lib/plugin.ts
@@ -30,6 +30,10 @@ import {
validateContentTypes,
withContentPermissions,
} from "@/content/registry";
+import {
+ contentMentionFields,
+ contentMentionTarget,
+} from "@/content/server/mention-target";
import { contentDefinitionOf } from "@/content/server/model";
import { contentReactionTarget } from "@/content/server/reaction-target";
import { contentReportTarget } from "@/content/server/report-target";
@@ -42,6 +46,10 @@ import type { CronJobConfig } from "./cron";
import type { RegisteredEditablePage } from "./editable-pages";
import type { EventDefinition } from "./event-definition";
import type { EventListenerConfig } from "./events";
+import type {
+ MentionsPluginConfig,
+ MentionTargetDefinition,
+} from "./mentions/targets";
import type { ModerationPluginConfig } from "./moderation/registry";
import type { ModerationReportTargetDefinition } from "./moderation/targets";
import type { BaseBuildModuleReturn, BuildModuleReturn } from "./module";
@@ -104,6 +112,8 @@ export interface BuildPluginApiReturn<
/** Every module's routes, each module mounted at `/{module.name}`. */
hono: OpenAPIHono;
manifest?: PluginManifest
;
+ /** Declared mention targets plus one per content model with mention fields. */
+ mentions?: Required;
messages?: LocaleMessagesMap;
/**
* Declared targets and scopes, plus one report target per content model with
@@ -189,6 +199,7 @@ export function buildApiPlugin<
editablePages,
eventDefinitions,
manifest,
+ mentions,
messages,
moderation,
modules = [] as unknown as Modules,
@@ -232,6 +243,11 @@ export function buildApiPlugin<
eventDefinitions?: readonly EventDefinition[];
/** The plugin's generated manifest (`src/manifest.gen.ts`). */
manifest: PluginManifest
;
+ /**
+ * `@mention` targets beyond those content models add (every rich-text
+ * field keeps mentions on unless it sets `mentions: false`).
+ */
+ mentions?: MentionsPluginConfig;
/**
* Lazy loaders for the plugin's server-side messages (emails, notifications),
* keyed by locale code. Separate from the frontend tree `buildPlugin` takes.
@@ -425,6 +441,15 @@ export function buildApiPlugin<
.map(model => contentReactionTarget(model, pluginId)),
];
+ const mentionTargets: MentionTargetDefinition[] = [
+ ...(mentions?.targets ?? []),
+ ...contentModels
+ .filter(
+ model => contentMentionFields(contentDefinitionOf(model)).length > 0,
+ )
+ .map(model => contentMentionTarget(model)),
+ ];
+
return {
pluginId,
aiActions,
@@ -464,6 +489,7 @@ export function buildApiPlugin<
reportTargets,
new Set(Object.keys(permissionStaff?.config.moderator ?? {})),
),
+ mentions: { targets: mentionTargets },
reactions: { targets: reactionTargets },
moderation: {
reportTargets,
diff --git a/packages/api/src/locales/en.json b/packages/api/src/locales/en.json
index 18bc619936..adedf4aa44 100644
--- a/packages/api/src/locales/en.json
+++ b/packages/api/src/locales/en.json
@@ -62,7 +62,6 @@
}
},
"notifications": {
- "unavailable": "This notification is no longer available.",
"someone": "Someone",
"categories": {
"account": "Account",
@@ -106,6 +105,12 @@
"description": "When someone reacts to something you wrote.",
"title": "{count, plural, offset:1 =1 {{name} reacted to your post} =2 {{name} and 1 other person reacted to your post} other {{name} and # others reacted to your post}}",
"body": "{title}"
+ },
+ "mention": {
+ "label": "Mentions",
+ "description": "When someone mentions you with @.",
+ "title": "{count, plural, offset:1 =1 {{name} mentioned you} =2 {{name} and 1 other person mentioned you} other {{name} and # others mentioned you}}",
+ "title_in": "{count, plural, offset:1 =1 {{name} mentioned you in \"{title}\"} =2 {{name} and 1 other person mentioned you in \"{title}\"} other {{name} and # others mentioned you in \"{title}\"}}"
}
},
"email": {
diff --git a/packages/api/src/mentions.ts b/packages/api/src/mentions.ts
new file mode 100644
index 0000000000..0a11edf6ea
--- /dev/null
+++ b/packages/api/src/mentions.ts
@@ -0,0 +1,11 @@
+export {
+ deleteMentions,
+ syncMentions,
+ type SyncMentionsArgs,
+ type SyncMentionsResult,
+} from "./lib/mentions/sync";
+export {
+ defineMentionTarget,
+ type MentionsPluginConfig,
+ type MentionTargetDefinition,
+} from "./lib/mentions/targets";
diff --git a/packages/api/src/middlewares/global.middleware.ts b/packages/api/src/middlewares/global.middleware.ts
index c4321521eb..f456d5c41b 100644
--- a/packages/api/src/middlewares/global.middleware.ts
+++ b/packages/api/src/middlewares/global.middleware.ts
@@ -70,6 +70,7 @@ import type { RegisteredEditablePage } from "../lib/editable-pages";
import type { EventDefinition } from "../lib/event-definition";
import type { EventListenerConfig } from "../lib/events";
import type { InstalledPluginRegistry } from "../lib/installed-plugins";
+import type { MentionsRegistry } from "../lib/mentions/targets";
import type { VitNodeMetadata } from "../lib/metadata";
import type { ModerationRegistry } from "../lib/moderation/registry";
import type { NotificationWorkerSettings } from "../lib/notifications/preferences";
@@ -105,6 +106,7 @@ import {
loggerMiddleware,
type LoggerMiddlewareType,
} from "../lib/logger-middleware";
+import { validateMentionsRegistry } from "../lib/mentions/targets";
import { validateModerationRegistry } from "../lib/moderation/registry";
import { resolveNotificationWorkerSettings } from "../lib/notifications/preferences";
import { createNotificationRegistry } from "../lib/notifications/registry";
@@ -256,6 +258,8 @@ export interface EnvVariablesVitNode {
sources: MessagesSource[];
};
installedPlugins: InstalledPluginRegistry;
+ /** Every mention target: custom ones and one per content type with mention fields. */
+ mentions: MentionsRegistry;
metadata: VitNodeMetadata;
moderation: ModerationRegistry;
notifications?: NotificationRegistry;
@@ -673,6 +677,15 @@ export const globalMiddleware = ({
),
});
+ const mentionsMetadata = validateMentionsRegistry(
+ plugins.flatMap(plugin =>
+ (plugin.mentions?.targets ?? []).map(definition => ({
+ definition,
+ pluginId: plugin.pluginId,
+ })),
+ ),
+ );
+
const reactionsMetadata = validateReactionsRegistry(
plugins.flatMap(plugin =>
(plugin.reactions?.targets ?? []).map(definition => ({
@@ -735,6 +748,7 @@ export const globalMiddleware = ({
permissionStaff: permissionStaffMetadata,
moderation: moderationMetadata,
notifications: notificationsMetadata,
+ mentions: mentionsMetadata,
reactions: reactionsMetadata,
notificationWorkers,
ogImage: resolveOgImageConfig({
diff --git a/packages/api/src/models/mentions/users.ts b/packages/api/src/models/mentions/users.ts
new file mode 100644
index 0000000000..da61fdb1b6
--- /dev/null
+++ b/packages/api/src/models/mentions/users.ts
@@ -0,0 +1,125 @@
+import type { Context } from "hono";
+
+import {
+ and,
+ asc,
+ eq,
+ ilike,
+ inArray,
+ ne,
+ notExists,
+ or,
+ sql,
+} from "drizzle-orm";
+
+import { core_users_deletions } from "@/database/account-deletions";
+import { core_files } from "@/database/files";
+import { core_users } from "@/database/users";
+import { OPEN_ACCOUNT_DELETION_STATUSES } from "@/lib/account-deletion/requests";
+import { storageUrlOf } from "@/lib/storage-url";
+
+/** Most members one `GET /users/mentioned` call resolves. */
+export const MENTIONED_USERS_MAX_IDS = 50;
+
+/** Most suggestions one `GET /users/mentions` call returns. */
+export const MENTION_SUGGESTIONS_MAX = 10;
+
+/** A member offered in the `@` popup. */
+export interface MentionCandidate {
+ avatarColor: string;
+ avatarUrl: null | string;
+ id: number;
+ name: string;
+ nameCode: string;
+}
+
+/** A mentioned member's current name and URL name. */
+export interface MentionedUser {
+ id: number;
+ name: string;
+ nameCode: string;
+}
+
+const escapeLike = (value: string): string =>
+ value.replace(/[\\%_]/g, char => `\\${char}`);
+
+/** Members with an account deletion on the way look deleted already. */
+const notBeingDeleted = notExists(
+ sql`(select 1 from ${core_users_deletions} where ${core_users_deletions.userId} = ${core_users.id} and ${inArray(core_users_deletions.status, OPEN_ACCOUNT_DELETION_STATUSES)})`,
+);
+
+/**
+ * Members whose URL name or name starts with `term`, then whose name contains
+ * it - for the editor's `@` popup, without the member typing. Server-only.
+ */
+export const searchMentionCandidates = async (
+ c: Context,
+ {
+ excludeUserId,
+ limit,
+ term,
+ }: { excludeUserId?: number; limit: number; term: string },
+): Promise => {
+ const escaped = escapeLike(term.toLowerCase());
+ const prefix = `${escaped}%`;
+ const rank = sql`case
+ when lower(${core_users.nameCode}) like ${prefix} then 0
+ when lower(${core_users.name}) like ${prefix} then 1
+ else 2 end`;
+
+ const rows = await c
+ .get("db")
+ .select({
+ avatarColor: core_users.avatarColor,
+ avatarKey: core_files.key,
+ id: core_users.id,
+ name: core_users.name,
+ nameCode: core_users.nameCode,
+ })
+ .from(core_users)
+ .leftJoin(core_files, eq(core_files.id, core_users.avatarId))
+ .where(
+ and(
+ or(
+ sql`lower(${core_users.nameCode}) like ${prefix}`,
+ ilike(core_users.name, `%${escaped}%`),
+ ),
+ notBeingDeleted,
+ excludeUserId === undefined
+ ? undefined
+ : ne(core_users.id, excludeUserId),
+ ),
+ )
+ .orderBy(rank, asc(sql`length(${core_users.name})`), asc(core_users.name))
+ .limit(limit);
+
+ return rows.map(row => ({
+ avatarColor: row.avatarColor,
+ avatarUrl: storageUrlOf(c, row.avatarKey),
+ id: row.id,
+ name: row.name,
+ nameCode: row.nameCode,
+ }));
+};
+
+/**
+ * The current name and URL name of every member still around among `ids` -
+ * a missing id is a deleted member. Server-only.
+ */
+export const loadMentionedUsers = async (
+ c: Context,
+ ids: readonly number[],
+): Promise => {
+ if (ids.length === 0) return [];
+
+ return await c
+ .get("db")
+ .select({
+ id: core_users.id,
+ name: core_users.name,
+ nameCode: core_users.nameCode,
+ })
+ .from(core_users)
+ .where(and(inArray(core_users.id, [...ids]), notBeingDeleted))
+ .orderBy(asc(core_users.id));
+};
diff --git a/packages/api/src/models/notifications/fanout.ts b/packages/api/src/models/notifications/fanout.ts
index d7060540ed..fb899b6a9c 100644
--- a/packages/api/src/models/notifications/fanout.ts
+++ b/packages/api/src/models/notifications/fanout.ts
@@ -374,7 +374,14 @@ const processBatch = async (
const deltas = new Map(
inApp.map(userId => [userId, wasCounted.get(userId) ? 0 : 1]),
);
- states.push(...(await applyUnreadDeltas(tx, deltas, "created")));
+ const itemIdOf = new Map(items.map(item => [item.userId, item.id]));
+ const created = await applyUnreadDeltas(tx, deltas, "created");
+ states.push(
+ ...created.map(update => ({
+ ...update,
+ notificationId: itemIdOf.get(update.userId),
+ })),
+ );
delivered = inApp.length;
}
diff --git a/packages/api/src/models/notifications/inbox.ts b/packages/api/src/models/notifications/inbox.ts
index fecc850b48..8b12afe2db 100644
--- a/packages/api/src/models/notifications/inbox.ts
+++ b/packages/api/src/models/notifications/inbox.ts
@@ -6,6 +6,7 @@ import {
inArray,
isNotNull,
isNull,
+ or,
sql,
} from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
@@ -23,8 +24,9 @@ import {
core_notification_user_state,
core_notifications,
} from "@/database/notifications";
+import { withPagination } from "@/lib/with-pagination";
-import type { NotificationActor } from "./render";
+import type { NotificationActor, NotificationEventRow } from "./render";
import type { NotificationsContext, NotificationsDb } from "./shared";
import { applyUnreadDeltas, lockUserStates } from "./fanout";
@@ -46,7 +48,6 @@ export interface NotificationListItem {
activitySeq: number;
actorCount: number;
actors: NotificationActor[];
- available: boolean;
body: null | string;
category: string;
createdAt: Date;
@@ -87,6 +88,36 @@ const parseCursorJson = (raw: string): unknown => {
}
};
+type PresentedListItem = "gone" | "skipped" | NotificationListItem;
+
+const removeGoneItems = async (
+ c: NotificationsContext,
+ userId: number,
+ gone: readonly { eventId: number; id: number }[],
+) => {
+ try {
+ await removeNotificationItems(c, {
+ where: and(
+ eq(core_notifications.userId, userId),
+ or(
+ ...gone.map(({ eventId, id }) =>
+ and(
+ eq(core_notifications.id, id),
+ eq(core_notifications.latestEventId, eventId),
+ ),
+ ),
+ ),
+ ),
+ });
+ } catch (error) {
+ void c
+ .get("log")
+ .error(
+ `[Notifications] Failed to remove unavailable inbox items: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+};
+
const decodeCursor = (raw: string) => {
const cursor = cursorSchema.safeParse(parseCursorJson(raw));
if (!cursor.success) {
@@ -114,6 +145,94 @@ export const getNotificationState = async (
return row ?? { revision: 0, unread: 0 };
};
+interface NotificationRow {
+ event: NotificationEventRow;
+ item: typeof core_notifications.$inferSelect;
+}
+
+const presentNotificationRows = async (
+ c: NotificationsContext,
+ {
+ language,
+ page,
+ userId,
+ }: {
+ language?: string;
+ page: readonly NotificationRow[];
+ userId: number;
+ },
+): Promise => {
+ const summaries = await loadActorSummaries(
+ c,
+ page.map(row => row.item.id),
+ );
+ const translator = createTranslatorCache(c);
+ const { locale, t } = await translator(language);
+
+ const presentItem = async ({
+ event,
+ item,
+ }: NotificationRow): Promise => {
+ const resolved = resolveEvent(c, event);
+ if (!resolved) return "gone";
+
+ try {
+ const allowed = await checkNotificationAccess({
+ c,
+ data: resolved.data,
+ event,
+ registered: resolved.registered,
+ userIds: [userId],
+ });
+ if (!allowed.has(userId)) return "gone";
+ } catch {
+ return "skipped";
+ }
+
+ const actors = summaries.get(item.id) ?? { actorCount: 0, actors: [] };
+ const presented = presentNotification(c, {
+ actors,
+ data: resolved.data,
+ event,
+ eventCount: item.eventCount,
+ locale,
+ registered: resolved.registered,
+ t,
+ });
+ if (!presented) return "skipped";
+
+ return {
+ activitySeq: item.activitySeq,
+ actorCount: actors.actorCount,
+ actors: actors.actors,
+ body: presented.body ?? null,
+ category: item.category,
+ createdAt: item.createdAt,
+ eventCount: item.eventCount,
+ id: item.id,
+ lastActivityAt: item.lastActivityAt,
+ pluginId: item.pluginId,
+ readAt: item.readAt,
+ subject:
+ item.subjectType && item.subjectId
+ ? { id: item.subjectId, type: item.subjectType }
+ : null,
+ target: presented.target,
+ title: presented.title,
+ type: item.type,
+ unread: item.readSeq < item.activitySeq,
+ };
+ };
+
+ const presented = await Promise.all(page.map(presentItem));
+ const gone = page
+ .filter((_, index) => presented[index] === "gone")
+ .map(({ event, item }) => ({ eventId: event.id, id: item.id }));
+ if (gone.length > 0) await removeGoneItems(c, userId, gone);
+
+ return presented.filter(result => typeof result !== "string");
+};
+
export const listNotifications = async (
c: NotificationsContext,
{
@@ -166,81 +285,11 @@ export const listNotifications = async (
const page = rows.slice(0, limit);
const last = page.at(-1);
- const summaries = await loadActorSummaries(
- c,
- page.map(row => row.item.id),
- );
- const translator = createTranslatorCache(c);
- const { locale, t } = await translator(language);
-
- const items = await Promise.all(
- page.map(async ({ event, item }): Promise => {
- const base = {
- activitySeq: item.activitySeq,
- category: item.category,
- createdAt: item.createdAt,
- eventCount: item.eventCount,
- id: item.id,
- lastActivityAt: item.lastActivityAt,
- pluginId: item.pluginId,
- readAt: item.readAt,
- type: item.type,
- unread: item.readSeq < item.activitySeq,
- };
- const unavailable: NotificationListItem = {
- ...base,
- actorCount: 0,
- actors: [],
- available: false,
- body: null,
- subject: null,
- target: null,
- title: t("core.notifications.unavailable"),
- };
-
- const resolved = resolveEvent(c, event);
- if (!resolved) return unavailable;
-
- try {
- const allowed = await checkNotificationAccess({
- c,
- data: resolved.data,
- event,
- registered: resolved.registered,
- userIds: [userId],
- });
- if (!allowed.has(userId)) return unavailable;
- } catch {
- return unavailable;
- }
-
- const actors = summaries.get(item.id) ?? { actorCount: 0, actors: [] };
- const presented = presentNotification(c, {
- actors,
- data: resolved.data,
- event,
- eventCount: item.eventCount,
- locale,
- registered: resolved.registered,
- t,
- });
- if (!presented) return unavailable;
-
- return {
- ...base,
- actorCount: actors.actorCount,
- actors: actors.actors,
- available: true,
- body: presented.body ?? null,
- subject:
- item.subjectType && item.subjectId
- ? { id: item.subjectId, type: item.subjectType }
- : null,
- target: presented.target,
- title: presented.title,
- };
- }),
- );
+ const items = await presentNotificationRows(c, {
+ language,
+ page,
+ userId,
+ });
return {
items,
@@ -251,6 +300,86 @@ export const listNotifications = async (
};
};
+export const NOTIFICATION_TABLE_ORDER_BY = [
+ "lastActivityAt",
+ "category",
+] as const;
+
+export type NotificationTableOrderBy =
+ (typeof NOTIFICATION_TABLE_ORDER_BY)[number];
+
+/**
+ * One numbered page of the signed-in user's inbox with totals, for the
+ * notifications table. Archived items never count. Items whose source is gone
+ * are dropped from the page and removed, so a page can hold fewer rows than
+ * `pageSize` until the next read.
+ */
+export const listNotificationsTable = async (
+ c: NotificationsContext,
+ {
+ categories,
+ language,
+ order,
+ orderBy,
+ query,
+ status,
+ userId,
+ }: {
+ categories: string[];
+ language?: string;
+ order: "asc" | "desc";
+ orderBy: NotificationTableOrderBy;
+ query: { cursor?: string; first?: string; last?: string; page?: string };
+ status?: "read" | "unread";
+ userId: number;
+ },
+) => {
+ const { edges, pageInfo } = await withPagination({
+ c,
+ orderBy: { column: core_notifications[orderBy], order },
+ params: { query },
+ primaryCursor: core_notifications.id,
+ query: async ({ cursorSelection, limit, offset, orderBy: order, where }) =>
+ await c
+ .get("db")
+ .select({
+ ...cursorSelection,
+ event: notificationEventColumns,
+ id: core_notifications.id,
+ item: core_notifications,
+ })
+ .from(core_notifications)
+ .innerJoin(
+ core_notification_events,
+ eq(core_notification_events.id, core_notifications.latestEventId),
+ )
+ .where(where)
+ .orderBy(order)
+ .limit(limit)
+ .offset(offset),
+ table: core_notifications,
+ where: and(
+ eq(core_notifications.userId, userId),
+ isNull(core_notifications.archivedAt),
+ status === "unread" ? UNREAD_SQL : undefined,
+ status === "read"
+ ? sql`${core_notifications.readSeq} >= ${core_notifications.activitySeq}`
+ : undefined,
+ categories.length > 0
+ ? inArray(core_notifications.category, categories)
+ : undefined,
+ ),
+ });
+
+ const items = await presentNotificationRows(c, {
+ language,
+ page: edges,
+ userId,
+ });
+
+ return { edges: items, pageInfo: { ...pageInfo, count: items.length } };
+};
+
type ItemRow = typeof core_notifications.$inferSelect;
const USERS_PER_RECONCILE_BATCH = 200;
diff --git a/packages/api/src/modules/admin/roles/roles.schema.ts b/packages/api/src/modules/admin/roles/roles.schema.ts
index 068a76c328..6012f5f3d9 100644
--- a/packages/api/src/modules/admin/roles/roles.schema.ts
+++ b/packages/api/src/modules/admin/roles/roles.schema.ts
@@ -1,6 +1,7 @@
import { z } from "@hono/zod-openapi";
import { EMOJI_ICON_MAX_LENGTH } from "@/lib/emoji-icon";
+import { ROLE_MAX_MENTIONS_PER_ITEM } from "@/lib/mentions/limits";
import { ROLE_EDIT_OWN_CONTENT_MAX_MINUTES } from "@/lib/own-content";
// Role names are not a column on `core_roles` - every translation lives in
@@ -26,6 +27,14 @@ export const zodRoleImageSizeSchema = z
export const zodRolePrefixSchema = z.string().max(EMOJI_ICON_MAX_LENGTH);
+// Members one record notifies by `@mentions`. `null` means unlimited.
+export const zodRoleMaxMentionsPerItemSchema = z
+ .number()
+ .int()
+ .min(1)
+ .max(ROLE_MAX_MENTIONS_PER_ITEM)
+ .nullable();
+
export const zodRoleEditOwnContentMinutesSchema = z
.number()
.int()
diff --git a/packages/api/src/modules/admin/roles/routes/create.route.ts b/packages/api/src/modules/admin/roles/routes/create.route.ts
index 22156a22f5..05820e9e7e 100644
--- a/packages/api/src/modules/admin/roles/routes/create.route.ts
+++ b/packages/api/src/modules/admin/roles/routes/create.route.ts
@@ -13,6 +13,7 @@ import { saveLanguageWords } from "@/lib/save-language-words";
import {
zodRoleEditOwnContentMinutesSchema,
zodRoleImageSizeSchema,
+ zodRoleMaxMentionsPerItemSchema,
zodRoleNameSchema,
zodRolePrefixSchema,
zodRoleStorageSchema,
@@ -34,6 +35,8 @@ export const zodCreateRoleAdminSchema = z.object({
editOwnContentMinutes: zodRoleEditOwnContentMinutesSchema.optional(),
allowDeleteOwnContent: z.boolean().optional(),
allowHideOwnContent: z.boolean().optional(),
+ allowMentions: z.boolean().optional(),
+ maxMentionsPerItem: zodRoleMaxMentionsPerItemSchema.optional(),
maxAvatarSize: zodRoleImageSizeSchema.optional(),
allowUploadCover: z.boolean().optional(),
maxCoverSize: zodRoleImageSizeSchema.optional(),
@@ -86,6 +89,8 @@ export const createRoleAdminRoute = buildRoute({
editOwnContentMinutes,
allowDeleteOwnContent,
allowHideOwnContent,
+ allowMentions,
+ maxMentionsPerItem,
maxAvatarSize,
allowUploadCover,
maxCoverSize,
@@ -113,6 +118,8 @@ export const createRoleAdminRoute = buildRoute({
editOwnContentMinutes: editOwnContentMinutes ?? null,
allowDeleteOwnContent: allowDeleteOwnContent ?? false,
allowHideOwnContent: allowHideOwnContent ?? false,
+ ...(allowMentions === undefined ? {} : { allowMentions }),
+ ...(maxMentionsPerItem === undefined ? {} : { maxMentionsPerItem }),
...(maxAvatarSize === undefined ? {} : { maxAvatarSize }),
...(allowUploadCover === undefined ? {} : { allowUploadCover }),
...(maxCoverSize === undefined ? {} : { maxCoverSize }),
diff --git a/packages/api/src/modules/admin/roles/routes/list.route.ts b/packages/api/src/modules/admin/roles/routes/list.route.ts
index c84e89f0ba..31c84ce498 100644
--- a/packages/api/src/modules/admin/roles/routes/list.route.ts
+++ b/packages/api/src/modules/admin/roles/routes/list.route.ts
@@ -47,6 +47,8 @@ const rolesAdminListSchema = z.object({
editOwnContentMinutes: z.number().nullable(),
allowDeleteOwnContent: z.boolean(),
allowHideOwnContent: z.boolean(),
+ allowMentions: z.boolean(),
+ maxMentionsPerItem: z.number().nullable(),
maxAvatarSize: z.number(),
allowUploadCover: z.boolean(),
maxCoverSize: z.number(),
@@ -142,6 +144,8 @@ export const listRolesAdminRoute = buildRoute({
editOwnContentMinutes: core_roles.editOwnContentMinutes,
allowDeleteOwnContent: core_roles.allowDeleteOwnContent,
allowHideOwnContent: core_roles.allowHideOwnContent,
+ allowMentions: core_roles.allowMentions,
+ maxMentionsPerItem: core_roles.maxMentionsPerItem,
maxAvatarSize: core_roles.maxAvatarSize,
allowUploadCover: core_roles.allowUploadCover,
maxCoverSize: core_roles.maxCoverSize,
diff --git a/packages/api/src/modules/admin/roles/routes/show.route.ts b/packages/api/src/modules/admin/roles/routes/show.route.ts
index 6f0613f893..c3df4cc7c6 100644
--- a/packages/api/src/modules/admin/roles/routes/show.route.ts
+++ b/packages/api/src/modules/admin/roles/routes/show.route.ts
@@ -34,6 +34,8 @@ const roleAdminSchema = z.object({
editOwnContentMinutes: z.number().nullable(),
allowDeleteOwnContent: z.boolean(),
allowHideOwnContent: z.boolean(),
+ allowMentions: z.boolean(),
+ maxMentionsPerItem: z.number().nullable(),
maxAvatarSize: z.number(),
allowUploadCover: z.boolean(),
maxCoverSize: z.number(),
@@ -105,6 +107,8 @@ export const showRoleAdminRoute = buildRoute({
editOwnContentMinutes: core_roles.editOwnContentMinutes,
allowDeleteOwnContent: core_roles.allowDeleteOwnContent,
allowHideOwnContent: core_roles.allowHideOwnContent,
+ allowMentions: core_roles.allowMentions,
+ maxMentionsPerItem: core_roles.maxMentionsPerItem,
maxAvatarSize: core_roles.maxAvatarSize,
allowUploadCover: core_roles.allowUploadCover,
maxCoverSize: core_roles.maxCoverSize,
diff --git a/packages/api/src/modules/admin/roles/routes/update.route.ts b/packages/api/src/modules/admin/roles/routes/update.route.ts
index bffadbef1b..4759880064 100644
--- a/packages/api/src/modules/admin/roles/routes/update.route.ts
+++ b/packages/api/src/modules/admin/roles/routes/update.route.ts
@@ -16,6 +16,7 @@ import { assertCanManageAdminRole } from "../lib/assert-manage-admin-role";
import {
zodRoleEditOwnContentMinutesSchema,
zodRoleImageSizeSchema,
+ zodRoleMaxMentionsPerItemSchema,
zodRoleNameSchema,
zodRolePrefixSchema,
zodRoleStorageSchema,
@@ -38,6 +39,8 @@ export const zodUpdateRoleAdminSchema = z
editOwnContentMinutes: zodRoleEditOwnContentMinutesSchema,
allowDeleteOwnContent: z.boolean(),
allowHideOwnContent: z.boolean(),
+ allowMentions: z.boolean(),
+ maxMentionsPerItem: zodRoleMaxMentionsPerItemSchema,
maxAvatarSize: zodRoleImageSizeSchema,
allowUploadCover: z.boolean(),
maxCoverSize: zodRoleImageSizeSchema,
@@ -154,6 +157,12 @@ export const updateRoleAdminRoute = buildRoute({
if (body.allowHideOwnContent !== undefined) {
values.allowHideOwnContent = body.allowHideOwnContent;
}
+ if (body.allowMentions !== undefined) {
+ values.allowMentions = body.allowMentions;
+ }
+ if (body.maxMentionsPerItem !== undefined) {
+ values.maxMentionsPerItem = body.maxMentionsPerItem;
+ }
if (body.allowUploadAvatar !== undefined) {
values.allowUploadAvatar = body.allowUploadAvatar;
diff --git a/packages/api/src/modules/content/content.module.ts b/packages/api/src/modules/content/content.module.ts
index 3ca11939cc..69aaf39ea5 100644
--- a/packages/api/src/modules/content/content.module.ts
+++ b/packages/api/src/modules/content/content.module.ts
@@ -4,6 +4,7 @@ import { contentRefreshWebSocket } from "@/content/server/refresh/socket";
import { contentEditorialCleanupCron } from "./cron/content-editorial-cleanup.cron";
import { contentSearchAccessCron } from "./cron/content-search-access.cron";
+import { contentMentionsQueueTask } from "./tasks/content-mentions.task";
import { contentNotificationsQueueTask } from "./tasks/content-notifications.task";
import { contentScheduleEffectsQueueTask } from "./tasks/content-schedule-effects.task";
import { contentScheduleQueueTask } from "./tasks/content-schedule.task";
@@ -18,6 +19,7 @@ export const contentModule = buildModule({
contentScheduleEffectsQueueTask,
contentSearchDependentsQueueTask,
contentNotificationsQueueTask,
+ contentMentionsQueueTask,
],
webSockets: [contentLiveWebSocket, contentRefreshWebSocket],
});
diff --git a/packages/api/src/modules/content/tasks/content-mentions.task.ts b/packages/api/src/modules/content/tasks/content-mentions.task.ts
new file mode 100644
index 0000000000..5a19214414
--- /dev/null
+++ b/packages/api/src/modules/content/tasks/content-mentions.task.ts
@@ -0,0 +1,25 @@
+import { z } from "zod";
+
+import { buildQueueTask } from "@/builders";
+import { CONTENT_QUEUE_TASK_MENTIONS } from "@/content/const";
+
+export const contentMentionsQueueTask = buildQueueTask({
+ name: CONTENT_QUEUE_TASK_MENTIONS,
+ payload: z.object({
+ /** Who made the write; the record's author wins when it has one. */
+ actorId: z.number().int().positive().nullable(),
+ contentTypeId: z.string().min(1),
+ /** The record was deleted: forget its mentions and retract them. */
+ deleted: z.boolean(),
+ itemId: z.string().min(1),
+ pluginId: z.string().min(1),
+ }),
+ description:
+ "Sync a record's @mentions with its text after a write: notify newly mentioned members who can read it, retract removed mentions. Idempotent.",
+ maxAttempts: 5,
+ handler: async (c, payload) => {
+ const { processContentMentions } =
+ await import("../../../content/server/mentions");
+ await processContentMentions(c, payload);
+ },
+});
diff --git a/packages/api/src/modules/notifications/notifications.module.ts b/packages/api/src/modules/notifications/notifications.module.ts
index d6d278f91f..fe4dffdb39 100644
--- a/packages/api/src/modules/notifications/notifications.module.ts
+++ b/packages/api/src/modules/notifications/notifications.module.ts
@@ -6,6 +6,7 @@ import {
notificationsScheduleCron,
} from "./cron/notifications.cron";
import { archiveNotificationRoute } from "./routes/archive.route";
+import { inboxNotificationsRoute } from "./routes/inbox.route";
import { listNotificationsRoute } from "./routes/list.route";
import { markAllNotificationsReadRoute } from "./routes/mark-all-read.route";
import { markNotificationReadRoute } from "./routes/mark-read.route";
@@ -23,6 +24,7 @@ export const notificationsModule = buildModule({
name: "notifications",
routes: [
listNotificationsRoute,
+ inboxNotificationsRoute,
notificationStateRoute,
markAllNotificationsReadRoute,
markNotificationReadRoute,
diff --git a/packages/api/src/modules/notifications/notifications.schema.ts b/packages/api/src/modules/notifications/notifications.schema.ts
index 63b3d5dfff..67776aeb72 100644
--- a/packages/api/src/modules/notifications/notifications.schema.ts
+++ b/packages/api/src/modules/notifications/notifications.schema.ts
@@ -24,7 +24,6 @@ export const zodNotificationItem = z.object({
activitySeq: z.number(),
actorCount: z.number(),
actors: z.array(zodNotificationActor),
- available: z.boolean(),
body: z.string().nullable(),
category: z.string(),
createdAt: z.date(),
diff --git a/packages/api/src/modules/notifications/routes/inbox.route.ts b/packages/api/src/modules/notifications/routes/inbox.route.ts
new file mode 100644
index 0000000000..0806b0bac2
--- /dev/null
+++ b/packages/api/src/modules/notifications/routes/inbox.route.ts
@@ -0,0 +1,73 @@
+import { z } from "zod";
+
+import { buildRoute } from "@/builders";
+import {
+ zodPaginationPageInfo,
+ zodPaginationQuery,
+} from "@/lib/with-pagination";
+import {
+ listNotificationsTable,
+ NOTIFICATION_TABLE_ORDER_BY,
+} from "@/models/notifications/inbox";
+
+import { requireNotificationUser } from "../lib/require-notification-user";
+import {
+ unauthorizedResponse,
+ zodNotificationItem,
+} from "../notifications.schema";
+
+const CATEGORY = /^[a-z0-9_-]{1,50}$/;
+
+export const inboxNotificationsRoute = buildRoute({
+ route: {
+ method: "get",
+ description:
+ "One numbered page of the signed-in user's notifications with totals, for the notifications table. Filter by read status and categories, sort by last activity or category. Listing never marks anything read.",
+ path: "/inbox",
+ request: {
+ query: zodPaginationQuery.extend({
+ category: z
+ .string()
+ .max(500)
+ .refine(
+ value => value.split(",").every(part => CATEGORY.test(part)),
+ "Categories are comma-separated ids.",
+ )
+ .optional(),
+ order: z.enum(["asc", "desc"]).optional(),
+ orderBy: z.enum(NOTIFICATION_TABLE_ORDER_BY).optional(),
+ status: z.enum(["read", "unread"]).optional(),
+ }),
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: z.object({
+ edges: z.array(zodNotificationItem),
+ pageInfo: zodPaginationPageInfo,
+ }),
+ },
+ },
+ description: "One page of notifications",
+ },
+ ...unauthorizedResponse,
+ },
+ },
+ handler: async c => {
+ const user = requireNotificationUser(c);
+ const { category, order, orderBy, status, ...query } = c.req.valid("query");
+
+ return c.json(
+ await listNotificationsTable(c, {
+ categories: category ? [...new Set(category.split(","))] : [],
+ language: user.language,
+ order: order ?? "desc",
+ orderBy: orderBy ?? "lastActivityAt",
+ query,
+ status,
+ userId: user.id,
+ }),
+ );
+ },
+});
diff --git a/packages/api/src/modules/users/routes/mentioned.route.ts b/packages/api/src/modules/users/routes/mentioned.route.ts
new file mode 100644
index 0000000000..0f2daa31aa
--- /dev/null
+++ b/packages/api/src/modules/users/routes/mentioned.route.ts
@@ -0,0 +1,64 @@
+import { z } from "@hono/zod-openapi";
+import { HTTPException } from "hono/http-exception";
+
+import { buildRoute } from "@/builders";
+import {
+ loadMentionedUsers,
+ MENTIONED_USERS_MAX_IDS,
+} from "@/models/mentions/users";
+
+const parseIds = (value: string): number[] => [
+ ...new Set(
+ value
+ .split(",")
+ .map(Number)
+ .filter(id => id > 0 && id <= 2_147_483_647),
+ ),
+];
+
+export const mentionedUsersRoute = buildRoute({
+ route: {
+ method: "get",
+ description: `Current name and URL name of up to ${MENTIONED_USERS_MAX_IDS} mentioned members, so \`@mentions\` keep linking after a rename. Deleted members are left out.`,
+ path: "/mentioned",
+ request: {
+ query: z.object({
+ ids: z
+ .string()
+ .max(MENTIONED_USERS_MAX_IDS * 11)
+ .regex(/^\d{1,10}(?:,\d{1,10})*$/)
+ .openapi({ example: "1,2,3" }),
+ }),
+ },
+ responses: {
+ 400: {
+ description: `No valid id, or more than ${MENTIONED_USERS_MAX_IDS}`,
+ },
+ 200: {
+ content: {
+ "application/json": {
+ schema: z.object({
+ users: z.array(
+ z.object({
+ id: z.number(),
+ name: z.string(),
+ nameCode: z.string(),
+ }),
+ ),
+ }),
+ },
+ },
+ description: "Members found",
+ },
+ },
+ },
+ handler: async c => {
+ const ids = parseIds(c.req.valid("query").ids);
+ if (ids.length === 0 || ids.length > MENTIONED_USERS_MAX_IDS) {
+ throw new HTTPException(400, { message: "Invalid ids" });
+ }
+ const users = await loadMentionedUsers(c, ids);
+
+ return c.json({ users }, 200, { "Cache-Control": "private, max-age=60" });
+ },
+});
diff --git a/packages/api/src/modules/users/routes/mentions.route.ts b/packages/api/src/modules/users/routes/mentions.route.ts
new file mode 100644
index 0000000000..a2f470124e
--- /dev/null
+++ b/packages/api/src/modules/users/routes/mentions.route.ts
@@ -0,0 +1,70 @@
+import { z } from "@hono/zod-openapi";
+import { HTTPException } from "hono/http-exception";
+
+import { buildRoute } from "@/builders";
+import { resolveMentionPolicy } from "@/lib/mentions/policy";
+import {
+ MENTION_SUGGESTIONS_MAX,
+ searchMentionCandidates,
+} from "@/models/mentions/users";
+
+export const mentionSuggestionsRoute = buildRoute({
+ route: {
+ method: "get",
+ description:
+ "Members to offer in the editor's `@` popup: URL name or name starting with the term first, then names containing it. Needs a role that may mention.",
+ path: "/mentions",
+ request: {
+ query: z.object({
+ search: z.string().trim().min(1).max(64),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(MENTION_SUGGESTIONS_MAX)
+ .optional(),
+ }),
+ },
+ responses: {
+ 200: {
+ content: {
+ "application/json": {
+ schema: z.object({
+ users: z.array(
+ z.object({
+ id: z.number(),
+ name: z.string(),
+ nameCode: z.string(),
+ avatarColor: z.string(),
+ avatarUrl: z.string().nullable(),
+ }),
+ ),
+ }),
+ },
+ },
+ description: "Matching members",
+ },
+ 401: { description: "Not signed in" },
+ 403: { description: "None of the member's roles may mention" },
+ },
+ },
+ handler: async c => {
+ const user = c.get("user");
+ if (!user) {
+ throw new HTTPException(401, { message: "Unauthorized" });
+ }
+ const policy = await resolveMentionPolicy(c);
+ if (!policy.canMention) {
+ throw new HTTPException(403, { message: "Mentions are not allowed" });
+ }
+
+ const { limit = 6, search } = c.req.valid("query");
+ const users = await searchMentionCandidates(c, {
+ excludeUserId: user.id,
+ limit,
+ term: search,
+ });
+
+ return c.json({ users }, 200, { "Cache-Control": "private, max-age=30" });
+ },
+});
diff --git a/packages/api/src/modules/users/routes/session.route.ts b/packages/api/src/modules/users/routes/session.route.ts
index 9699d10211..1d50c085c5 100644
--- a/packages/api/src/modules/users/routes/session.route.ts
+++ b/packages/api/src/modules/users/routes/session.route.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { buildRoute } from "@/builders";
import { getStaffFlags } from "@/lib/check-staff-permission";
+import { resolveMentionPolicy } from "@/lib/mentions/policy";
import { getNotificationState } from "@/models/notifications/inbox";
import { zodNotificationState } from "@/modules/notifications/notifications.schema";
@@ -39,6 +40,9 @@ export const sessionRoute = buildRoute({
birthday: z.date().nullable(),
isAdmin: z.boolean(),
isModerator: z.boolean(),
+ canMention: z
+ .boolean()
+ .describe("One of the user's roles may `@mention` members"),
notifications: zodNotificationState,
})
.nullable(),
@@ -67,11 +71,21 @@ export const sessionRoute = buildRoute({
});
}
- const [{ isAdmin, isModerator }, notifications] = await Promise.all([
- getStaffFlags(c, user),
- getNotificationState(c.get("db"), user.id),
- ]);
+ const [{ isAdmin, isModerator }, notifications, mentions] =
+ await Promise.all([
+ getStaffFlags(c, user),
+ getNotificationState(c.get("db"), user.id),
+ resolveMentionPolicy(c),
+ ]);
- return c.json({ user: { ...user, isAdmin, isModerator, notifications } });
+ return c.json({
+ user: {
+ ...user,
+ canMention: mentions.canMention,
+ isAdmin,
+ isModerator,
+ notifications,
+ },
+ });
},
});
diff --git a/packages/api/src/modules/users/users.module.ts b/packages/api/src/modules/users/users.module.ts
index 4a10d7b973..583bfc0359 100644
--- a/packages/api/src/modules/users/users.module.ts
+++ b/packages/api/src/modules/users/users.module.ts
@@ -12,6 +12,8 @@ import { cancelDeletionSignInRoute } from "./routes/cancel-deletion-sign-in.rout
import { changePasswordRoute } from "./routes/change-password.route";
import { listDevicesRoute } from "./routes/devices.route";
import { mePolicyRoute } from "./routes/me-policy.route";
+import { mentionedUsersRoute } from "./routes/mentioned.route";
+import { mentionSuggestionsRoute } from "./routes/mentions.route";
import { permissionsRoute } from "./routes/permissions.route";
import { personalDataExportRoute } from "./routes/personal-data.route";
import { presenceBatchRoute } from "./routes/presence-batch.route";
@@ -60,6 +62,8 @@ export const usersModule = buildModule({
presenceBatchRoute,
presenceRoute,
userTimelineRoute,
+ mentionSuggestionsRoute,
+ mentionedUsersRoute,
],
modules: [
ssoUserModule,
diff --git a/packages/api/src/plugin.ts b/packages/api/src/plugin.ts
index c32c57dbfe..55d67ca78d 100644
--- a/packages/api/src/plugin.ts
+++ b/packages/api/src/plugin.ts
@@ -10,6 +10,7 @@ import { contentAccessEventDefinitions } from "./events/content-access";
import { contentApprovalEventDefinitions } from "./events/content-approvals";
import { contentContainerEventDefinitions } from "./events/content-containers";
import { fileEventDefinitions } from "./events/files";
+import { mentionEventDefinitions } from "./events/mentions";
import { moderationEventDefinitions } from "./events/moderation";
import { notificationEventDefinitions } from "./events/notifications";
import { pageEventDefinitions } from "./events/pages";
@@ -60,6 +61,7 @@ export const newBuildPluginApiCore = buildApiPlugin({
...contentApprovalEventDefinitions,
...contentContainerEventDefinitions,
...fileEventDefinitions,
+ ...mentionEventDefinitions,
...moderationEventDefinitions,
...notificationEventDefinitions,
...pageEventDefinitions,
diff --git a/packages/vitnode/package.json b/packages/vitnode/package.json
index f2d577863d..7923198470 100644
--- a/packages/vitnode/package.json
+++ b/packages/vitnode/package.json
@@ -248,6 +248,7 @@
"@tiptap/extension-drag-handle-react": "^3.33.0",
"@tiptap/extension-emoji": "^3.33.0",
"@tiptap/extension-list": "^3.33.0",
+ "@tiptap/extension-mention": "^3.35.0",
"@tiptap/extension-table": "^3.33.0",
"@tiptap/extension-text-align": "^3.33.0",
"@tiptap/extension-text-style": "^3.33.0",
diff --git a/packages/vitnode/src/components/rich-text/mention.tsx b/packages/vitnode/src/components/rich-text/mention.tsx
new file mode 100644
index 0000000000..3009176392
--- /dev/null
+++ b/packages/vitnode/src/components/rich-text/mention.tsx
@@ -0,0 +1,46 @@
+import type { RichTextMention } from "@vitnode/api/content/rich-text/mentions";
+
+import { useQuery } from "@tanstack/react-query";
+
+import { mentionedUserQueryOptions } from "@/views/mentions/mentions-query";
+
+import { UserPreview } from "../user-preview";
+
+/**
+ * An `@mention` in rendered rich text: a link to the member's profile with
+ * the preview card. It shows the stored snapshot first and then the member's
+ * current name, so renames never break it. A deleted member stays as plain
+ * text; a failed lookup keeps the snapshot.
+ */
+export const RichTextMentionLink = ({
+ mention,
+}: {
+ mention: RichTextMention;
+}) => {
+ const { data, isSuccess } = useQuery(mentionedUserQueryOptions(mention.id));
+
+ if (isSuccess && data === null) {
+ return (
+
+ @{mention.label}
+
+ );
+ }
+
+ const name = data?.name ?? mention.label;
+ const nameCode = data?.nameCode ?? mention.nameCode;
+
+ if (!nameCode) {
+ return (
+
+ @{name}
+
+ );
+ }
+
+ return (
+
+ @{name}
+
+ );
+};
diff --git a/packages/vitnode/src/components/rich-text/rich-text-content.tsx b/packages/vitnode/src/components/rich-text/rich-text-content.tsx
index b47846adb1..ba85a38f1c 100644
--- a/packages/vitnode/src/components/rich-text/rich-text-content.tsx
+++ b/packages/vitnode/src/components/rich-text/rich-text-content.tsx
@@ -12,6 +12,7 @@ import {
richTextNodeElement,
} from "@vitnode/api/content/rich-text/elements";
import { richTextToHtml } from "@vitnode/api/content/rich-text/html";
+import { richTextMentionOf } from "@vitnode/api/content/rich-text/mentions";
import { cn } from "cn";
import React from "react";
@@ -21,6 +22,7 @@ import {
isRestrictedUploadNode,
RestrictedUpload,
} from "./deleted-upload";
+import { RichTextMentionLink } from "./mention";
export interface RichTextNodeRendererProps {
children?: React.ReactNode;
@@ -172,6 +174,12 @@ const renderNode = (
if (isRestrictedUploadNode(node)) return ;
+ if (node.type === "mention") {
+ const mention = richTextMentionOf(node);
+
+ return mention ? : null;
+ }
+
const element = richTextNodeElement(node);
return element ? (
@@ -185,7 +193,8 @@ const renderNode = (
* Renders a stored rich-text document as React elements, without an editor
* and without `dangerouslySetInnerHTML`. Built-in nodes and marks map to
* sanitised HTML elements; unknown ones render only their children unless
- * `nodes` or `marks` supplies a renderer. Universal - works in SSR.
+ * `nodes` or `marks` supplies a renderer. An `@mention` links to the
+ * member's current profile with the preview card. Universal - works in SSR.
*/
export const RichTextContent = ({
className,
diff --git a/packages/vitnode/src/components/tiptap/extension.ts b/packages/vitnode/src/components/tiptap/extension.ts
index bfb3501cfc..1445fab132 100644
--- a/packages/vitnode/src/components/tiptap/extension.ts
+++ b/packages/vitnode/src/components/tiptap/extension.ts
@@ -18,6 +18,7 @@ import { EditorAttachment } from "./attachment/attachment";
import { customEmojiToTipTap } from "./emoji/custom-emoji";
import { emojiSuggestion } from "./emoji/emoji-suggestion";
import { EditorImage } from "./image/image";
+import { createEditorMention } from "./mention/mention";
import { Panel } from "./panel";
import { SlashCommand } from "./slash-command/slash-command";
import { SubmitFormShortcut } from "./submit-form-shortcut";
@@ -25,13 +26,18 @@ import { EditorUploads } from "./uploads/extension";
export const SUPPORTED_HEADINGS_LEVELS = [1, 2, 3, 4] as const;
+const mentionsOff = () => false;
+
export const createTipTapExtensions = ({
customEmojis,
+ getMentionsEnabled = mentionsOff,
getUploadRuntime = () => null,
placeholder,
undoRedo = true,
}: {
customEmojis?: EditorEmojiSection[];
+ /** Whether typing `@` opens the member popup right now. Off by default. */
+ getMentionsEnabled?: () => boolean;
getUploadRuntime?: () => EditorUploadRuntime | null;
placeholder?: string;
undoRedo?: boolean;
@@ -86,6 +92,7 @@ export const createTipTapExtensions = ({
resizable: true,
},
}),
+ createEditorMention({ isEnabled: getMentionsEnabled }),
EditorImage,
EditorAttachment,
EditorUploads.configure({ getRuntime: getUploadRuntime }),
diff --git a/packages/vitnode/src/components/tiptap/mention/mention-suggestion-list.tsx b/packages/vitnode/src/components/tiptap/mention/mention-suggestion-list.tsx
new file mode 100644
index 0000000000..5ce8664c2b
--- /dev/null
+++ b/packages/vitnode/src/components/tiptap/mention/mention-suggestion-list.tsx
@@ -0,0 +1,241 @@
+import type { SuggestionKeyDownProps } from "@tiptap/suggestion";
+
+import { useQuery } from "@tanstack/react-query";
+import { cn } from "cn";
+import { RotateCwIcon } from "lucide-react";
+import React from "react";
+import { useTranslations } from "use-intl";
+
+import { Avatar } from "@/components/avatar";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ MentionsRequestError,
+ mentionSuggestionsQueryOptions,
+} from "@/views/mentions/mentions-query";
+
+import type { MentionCommandProps } from "./mention-suggestion";
+
+import {
+ SUGGESTION_POPUP_CLASS,
+ useActiveDescendant,
+} from "../suggestion-popup";
+
+/** Typing pauses this long before the members are looked up. */
+const SEARCH_DELAY_MS = 150;
+
+const SKELETON_ROWS = 3;
+
+const MENTION_MIN_QUERY_LENGTH = 3;
+
+export interface MentionSuggestionListRef {
+ onKeyDown: (props: SuggestionKeyDownProps) => boolean;
+}
+
+export interface MentionSuggestionListProps {
+ command: (props: MentionCommandProps) => void;
+ query: string;
+ ref?: React.Ref;
+ textbox?: HTMLElement;
+}
+
+const useDelayedValue = (value: string, delay: number): string => {
+ const [delayed, setDelayed] = React.useState(value);
+
+ React.useEffect(() => {
+ const timer = setTimeout(() => {
+ setDelayed(value);
+ }, delay);
+
+ return () => {
+ clearTimeout(timer);
+ };
+ }, [delay, value]);
+
+ return delayed;
+};
+
+// Keeps the caret in the editor when a click lands on the popup.
+const keepEditorFocus = (event: React.MouseEvent) => {
+ event.preventDefault();
+};
+
+export const MentionSuggestionList = ({
+ command,
+ query,
+ ref,
+ textbox,
+}: MentionSuggestionListProps) => {
+ const t = useTranslations("core.global.editor.mention");
+ const term = query.trim();
+ const isReady = term.length >= MENTION_MIN_QUERY_LENGTH;
+ const search = useDelayedValue(isReady ? term : "", SEARCH_DELAY_MS);
+ const suggestions = useQuery(mentionSuggestionsQueryOptions(search));
+ const items = React.useMemo(
+ () => (isReady && search !== "" ? (suggestions.data ?? []) : []),
+ [isReady, search, suggestions.data],
+ );
+ const [activeIndex, setActiveIndex] = React.useState(0);
+ const [renderedItems, setRenderedItems] = React.useState(items);
+ const listRef = React.useRef(null);
+ const baseId = React.useId();
+ const listId = `${baseId}-list`;
+ const optionIdOf = (index: number) => `${baseId}-option-${index}`;
+
+ if (renderedItems !== items) {
+ setRenderedItems(items);
+ setActiveIndex(0);
+ }
+
+ const select = (index: number) => {
+ const item = items[index];
+ if (!item) return;
+
+ command({ id: item.id, label: item.name, nameCode: item.nameCode });
+ };
+
+ React.useImperativeHandle(ref, () => ({
+ onKeyDown: ({ event }) => {
+ if (items.length === 0) return false;
+
+ if (event.key === "ArrowUp") {
+ setActiveIndex(current => (current + items.length - 1) % items.length);
+
+ return true;
+ }
+
+ if (event.key === "ArrowDown") {
+ setActiveIndex(current => (current + 1) % items.length);
+
+ return true;
+ }
+
+ if (event.key === "Enter" || event.key === "Tab") {
+ select(activeIndex);
+
+ return true;
+ }
+
+ return false;
+ },
+ }));
+
+ useActiveDescendant({
+ activeId: items[activeIndex] ? optionIdOf(activeIndex) : undefined,
+ listId,
+ textbox,
+ });
+
+ React.useEffect(() => {
+ listRef.current
+ ?.querySelector("[data-active='true']")
+ ?.scrollIntoView({ block: "nearest" });
+ }, [activeIndex]);
+
+ if (!isReady) return null;
+
+ // Waiting for the typing pause or for the first answer.
+ if (search === "" || (suggestions.isPending && items.length === 0)) {
+ return (
+
+ );
+};
diff --git a/packages/vitnode/src/components/tiptap/mention/mention-suggestion.ts b/packages/vitnode/src/components/tiptap/mention/mention-suggestion.ts
new file mode 100644
index 0000000000..99992270f5
--- /dev/null
+++ b/packages/vitnode/src/components/tiptap/mention/mention-suggestion.ts
@@ -0,0 +1,72 @@
+import type { SuggestionOptions } from "@tiptap/suggestion";
+
+import { ReactRenderer } from "@tiptap/react";
+
+import type {
+ MentionSuggestionListProps,
+ MentionSuggestionListRef,
+} from "./mention-suggestion-list";
+
+import {
+ mountSuggestionPopup,
+ SUGGESTION_POPUP_WRAPPER_CLASS,
+} from "../suggestion-popup";
+import { MentionSuggestionList } from "./mention-suggestion-list";
+
+/** What a picked member inserts. */
+export interface MentionCommandProps {
+ id: number;
+ label: string;
+ nameCode: string;
+}
+
+/**
+ * The `@` popup. The list fetches its own members, so `items` stays empty
+ * and the popup can show loading, empty and error states while it waits.
+ */
+export const mentionSuggestion = ({
+ isEnabled,
+}: {
+ isEnabled: () => boolean;
+}): Omit, "editor"> => ({
+ allow: () => isEnabled(),
+ allowSpaces: false,
+ char: "@",
+ items: () => [],
+ render: () => {
+ let component: null | ReactRenderer<
+ MentionSuggestionListRef,
+ MentionSuggestionListProps
+ > = null;
+ let unmount: (() => void) | null = null;
+
+ return {
+ onStart: props => {
+ component = new ReactRenderer(MentionSuggestionList, {
+ className: SUGGESTION_POPUP_WRAPPER_CLASS,
+ editor: props.editor,
+ props: {
+ command: props.command,
+ query: props.query,
+ textbox: props.editor.view.dom,
+ },
+ });
+ unmount = mountSuggestionPopup(props.mount, component.element);
+ },
+ onUpdate: props => {
+ component?.updateProps({
+ command: props.command,
+ query: props.query,
+ textbox: props.editor.view.dom,
+ });
+ },
+ onKeyDown: props => component?.ref?.onKeyDown(props) ?? false,
+ onExit: () => {
+ unmount?.();
+ unmount = null;
+ component?.destroy();
+ component = null;
+ },
+ };
+ },
+});
diff --git a/packages/vitnode/src/components/tiptap/mention/mention.ts b/packages/vitnode/src/components/tiptap/mention/mention.ts
new file mode 100644
index 0000000000..6f798367d1
--- /dev/null
+++ b/packages/vitnode/src/components/tiptap/mention/mention.ts
@@ -0,0 +1,74 @@
+import { Mention, type MentionOptions } from "@tiptap/extension-mention";
+
+import {
+ type MentionCommandProps,
+ mentionSuggestion,
+} from "./mention-suggestion";
+
+const mentionIdFrom = (element: HTMLElement): null | number => {
+ const id = Number(element.getAttribute("data-id"));
+
+ return Number.isInteger(id) && id > 0 ? id : null;
+};
+
+const labelOf = (attrs: Record): string => {
+ const { id, label } = attrs;
+
+ return typeof label === "string" && label !== "" ? label : String(id);
+};
+
+/**
+ * The `@mention` node. Its attrs are `id` (the member), `label` and
+ * `nameCode` (a snapshot of their name and URL name). It is always part of
+ * the schema, so documents keep their mentions in any editor; the `@` popup
+ * only opens while `isEnabled()` is true.
+ */
+export const createEditorMention = ({
+ isEnabled,
+}: {
+ isEnabled: () => boolean;
+}) =>
+ Mention.extend>({
+ addAttributes() {
+ return {
+ id: {
+ default: null,
+ parseHTML: mentionIdFrom,
+ renderHTML: attributes =>
+ attributes.id ? { "data-id": attributes.id } : {},
+ },
+ label: {
+ default: null,
+ parseHTML: element => element.getAttribute("data-label"),
+ renderHTML: attributes =>
+ attributes.label ? { "data-label": attributes.label } : {},
+ },
+ nameCode: {
+ default: null,
+ parseHTML: element => element.getAttribute("data-name-code"),
+ renderHTML: attributes =>
+ attributes.nameCode
+ ? { "data-name-code": attributes.nameCode }
+ : {},
+ },
+ };
+ },
+
+ parseHTML() {
+ return [
+ { tag: 'span[data-type="mention"]' },
+ // Copied from a rendered post, where a mention is a profile link.
+ { priority: 60, tag: 'a[data-type="mention"]' },
+ ];
+ },
+ }).configure({
+ deleteTriggerWithBackspace: true,
+ HTMLAttributes: { class: "mention" },
+ renderHTML: ({ node, options }) => [
+ "span",
+ options.HTMLAttributes,
+ `@${labelOf(node.attrs)}`,
+ ],
+ renderText: ({ node }) => `@${labelOf(node.attrs)}`,
+ suggestion: mentionSuggestion({ isEnabled }),
+ });
diff --git a/packages/vitnode/src/components/tiptap/mention/use-can-mention.ts b/packages/vitnode/src/components/tiptap/mention/use-can-mention.ts
new file mode 100644
index 0000000000..c3dbd8d5c5
--- /dev/null
+++ b/packages/vitnode/src/components/tiptap/mention/use-can-mention.ts
@@ -0,0 +1,32 @@
+import { QueryClientContext } from "@tanstack/react-query";
+import React from "react";
+
+import type { SessionApi } from "@/tanstack/auth/session-api";
+
+import { SESSION_QUERY_KEY } from "@/tanstack/auth/state";
+
+const subscribeToNothing = () => () => undefined;
+
+/**
+ * Whether the signed-in member's roles may mention, read from the session
+ * already in the query cache - never fetched here. `false` without a session
+ * or outside a `QueryClientProvider`.
+ */
+export const useCanMention = (): boolean => {
+ const queryClient = React.useContext(QueryClientContext);
+ const subscribe = React.useCallback(
+ (onChange: () => void) =>
+ queryClient
+ ? queryClient.getQueryCache().subscribe(onChange)
+ : subscribeToNothing(),
+ [queryClient],
+ );
+
+ return React.useSyncExternalStore(
+ subscribe,
+ () =>
+ queryClient?.getQueryData(SESSION_QUERY_KEY)?.user
+ ?.canMention === true,
+ () => false,
+ );
+};
diff --git a/packages/vitnode/src/components/tiptap/tiptap-editor.tsx b/packages/vitnode/src/components/tiptap/tiptap-editor.tsx
index 3e5d9faf72..efe86e4ae4 100644
--- a/packages/vitnode/src/components/tiptap/tiptap-editor.tsx
+++ b/packages/vitnode/src/components/tiptap/tiptap-editor.tsx
@@ -22,6 +22,7 @@ import { useEditorConfig } from "@/components/editor-provider";
import { TipTapDragHandle } from "./drag-handle";
import { EditorSkeleton } from "./editor-skeleton";
import { createTipTapExtensions } from "./extension";
+import { useCanMention } from "./mention/use-can-mention";
import { editorEmojiItems, toRichTextDocument } from "./rich-text-json";
import { TipTapToolbar } from "./toolbar/tiptap-toolbar";
import { ReusableUploadsBar } from "./uploads/reusable-uploads-bar";
@@ -67,6 +68,13 @@ export type TipTapEditorBaseProps = Omit<
> & {
disableScroll?: boolean;
extensions?: Extensions;
+ /**
+ * Typing `@` offers members to mention, who are notified once the content
+ * is published and they can read it. On by default; it only opens for
+ * signed-in members whose role may mention. Set `false` for a field whose
+ * Content Engine definition has `mentions: false`.
+ */
+ mentions?: boolean;
onEditor?: (editor: Editor | null) => void;
placeholder?: string;
/**
@@ -121,6 +129,19 @@ const ON_CHANGE_DELAY_MS = 200;
const NO_REUSABLE_UPLOADS: EditorReusableUpload[] = [];
+/** Whether the `@` popup may open, read by the mention extension on each `@`. */
+class MentionsSwitch {
+ private enabled = false;
+
+ isEnabled(): boolean {
+ return this.enabled;
+ }
+
+ set(enabled: boolean): void {
+ this.enabled = enabled;
+ }
+}
+
const EDITOR_CLASS =
"max-w-full min-h-40 py-4 ps-5 pe-4 text-base focus:outline-none md:text-sm";
@@ -132,6 +153,7 @@ export const TipTapEditor = (props: TipTapEditorProps) => {
disableScroll,
extensions,
format: _format,
+ mentions = true,
placeholder,
undoRedo,
reusableUploads,
@@ -148,6 +170,14 @@ export const TipTapEditor = (props: TipTapEditorProps) => {
const emojiItems = React.useMemo(() => editorEmojiItems(emojis), [emojis]);
const placeholderText = placeholder ?? t("placeholder");
const invalid = rest["aria-invalid"];
+ const canMention = useCanMention();
+ const mentionsEnabled = mentions && canMention;
+ // Read by the extension, so the extension list stays stable when the
+ // session or the prop changes.
+ const [mentionsSwitch] = React.useState(() => new MentionsSwitch());
+ React.useEffect(() => {
+ mentionsSwitch.set(mentionsEnabled);
+ }, [mentionsEnabled, mentionsSwitch]);
const uploadOptions: EditorUploadsOptions =
typeof uploads === "object" ? uploads : {};
@@ -200,13 +230,21 @@ export const TipTapEditor = (props: TipTapEditorProps) => {
() => [
...createTipTapExtensions({
customEmojis: emojis,
+ getMentionsEnabled: () => mentionsSwitch.isEnabled(),
getUploadRuntime: () => uploadRuntime,
placeholder: placeholderText,
undoRedo,
}),
...(extensions ?? []),
],
- [emojis, extensions, placeholderText, undoRedo, uploadRuntime],
+ [
+ emojis,
+ extensions,
+ mentionsSwitch,
+ placeholderText,
+ undoRedo,
+ uploadRuntime,
+ ],
);
const editorProps = React.useMemo(
() => ({
diff --git a/packages/vitnode/src/locales/en.json b/packages/vitnode/src/locales/en.json
index 3267592331..56263515ed 100644
--- a/packages/vitnode/src/locales/en.json
+++ b/packages/vitnode/src/locales/en.json
@@ -463,6 +463,14 @@
"title": "Error panel",
"hint": "Flag a blocker or a risk"
}
+ },
+ "mention": {
+ "label": "Members to mention",
+ "loading": "Looking for members…",
+ "empty": "No members found.",
+ "load_error": "Members didn't load. Check your connection and try again.",
+ "forbidden": "Your role can't mention members.",
+ "retry": "Try again"
}
},
"theme": {
@@ -703,6 +711,10 @@
"mark_all_read": "Mark all as read",
"all_read": "All caught up",
"all_read_desc": "Every notification is marked as read.",
+ "mark_all_read_confirm": {
+ "title": "Mark {count, plural, one {# notification} other {all # notifications}} as read?",
+ "desc": "They stay in your inbox, but nothing will stand out as new anymore. You can still mark single ones as unread later."
+ },
"mark_read": "Mark as read",
"mark_unread": "Mark as unread",
"archive": "Archive",
@@ -1855,8 +1867,7 @@
},
"warn": "Warn author",
"live": {
- "new_comments": "New comments were posted.",
- "show_new": "Show new comments",
+ "new_count": "{count, plural, one {# new comment} other {# new comments}}",
"refresh_failed": "Could not refresh the comments, so some may be out of date.",
"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.",
@@ -2616,15 +2627,19 @@
"notifications": {
"title": "Notifications",
"desc": "Everything that happened while you were away. Opening this page never marks anything as read.",
- "list_label": "Notifications",
- "filter_all": "All",
"filter_unread": "Unread",
- "all_categories": "All categories",
- "category_label": "Filter by category",
"mark_all_read": "Mark all as read",
- "settings": "Notification settings",
- "loading": "Loading…",
- "load_more": "Load more",
+ "settings_button": "Settings",
+ "summary": "{total} {total, plural, one {notification} other {notifications}} · {unread} unread",
+ "column_status": "Status",
+ "column_notification": "Notification",
+ "column_category": "Category",
+ "column_received": "Received",
+ "column_actions": "Actions",
+ "filter_status": "Status",
+ "filter_status_all": "Any status",
+ "filter_category": "Category",
+ "status_read": "Read",
"load_error": {
"title": "Notifications didn't load",
"desc": "Something went wrong while fetching them. Check your connection and try again."
@@ -4730,6 +4745,15 @@
"delete_account": {
"allow": "Allow deleting own account",
"allow_desc": "Members of this role can delete their account in Settings → Privacy & data. Staff can always delete an account in the AdminCP."
+ },
+ "mentions": {
+ "allow": "Allow mentioning members",
+ "allow_desc": "Typing @ in the editor offers members to mention, and they get a notification.",
+ "max_per_item": "Members notified per post",
+ "max_per_item_desc": "How many mentioned members one post can notify. Extra mentions still show, without a notification.",
+ "in_unit": "members",
+ "or": "or",
+ "unlimited": "Unlimited"
}
}
},
diff --git a/packages/vitnode/src/pages/notifications.tsx b/packages/vitnode/src/pages/notifications.tsx
index 6bb97e6543..3e4eb68a1c 100644
--- a/packages/vitnode/src/pages/notifications.tsx
+++ b/packages/vitnode/src/pages/notifications.tsx
@@ -1,9 +1,8 @@
import type { PluginRoutePageProps } from "@/routing";
import type { NotificationsRouteData } from "../tanstack/notifications/route";
-import type { NotificationsRouteSearch } from "../tanstack/notifications/route-search";
+import type { UncheckedNotificationsSearch } from "../tanstack/notifications/route-search";
-import { NotificationsBreadcrumb } from "../tanstack/notifications/breadcrumb";
import { loadNotificationsRoute } from "../tanstack/notifications/route";
import { NotificationsRouteContent } from "../tanstack/notifications/screen";
import { defineAuthenticatedRoute } from "../tanstack/plugin-routes";
@@ -12,7 +11,10 @@ const NotificationsPage = ({
loaderData,
navigate,
search,
-}: PluginRoutePageProps) => (
+}: PluginRoutePageProps<
+ NotificationsRouteData,
+ UncheckedNotificationsSearch
+>) => (
({
load: async ({ context, search, t }) =>
await loadNotificationsRoute({ ...context, search, t }),
head: ({ loaderData }) => ({ robots: "noindex, nofollow", ...loaderData }),
-
- breadcrumb: NotificationsBreadcrumb,
});
export default NotificationsPage;
diff --git a/packages/vitnode/src/routes.tsx b/packages/vitnode/src/routes.tsx
index cfe96957f4..f33671f3fa 100644
--- a/packages/vitnode/src/routes.tsx
+++ b/packages/vitnode/src/routes.tsx
@@ -272,7 +272,9 @@ export const routes = defineRoutes([
page("/notifications", {
component: lazy(() => import("./pages/notifications")),
messages: NOTIFICATIONS_NAMESPACES,
- pendingComponent: () => ,
+ pendingComponent: () => (
+
+ ),
requires: "authenticated",
search: normalizeNotificationsRouteSearch,
}),
diff --git a/packages/vitnode/src/tanstack/admin/roles/query.ts b/packages/vitnode/src/tanstack/admin/roles/query.ts
index 0a14f57cd8..d191975611 100644
--- a/packages/vitnode/src/tanstack/admin/roles/query.ts
+++ b/packages/vitnode/src/tanstack/admin/roles/query.ts
@@ -82,6 +82,8 @@ export const useAdminRoleMutations = (): {
allowDeleteOwnContent: values.allowDeleteOwnContent,
allowEditOwnContent: values.allowEditOwnContent,
allowHideOwnContent: values.allowHideOwnContent,
+ allowMentions: values.allowMentions,
+ maxMentionsPerItem: values.maxMentionsPerItem,
allowEditPersonalInfo: values.allowEditPersonalInfo,
allowDeleteAccount: values.allowDeleteAccount,
allowBrowseAnonymously: values.allowBrowseAnonymously,
diff --git a/packages/vitnode/src/tanstack/auth/state.test.ts b/packages/vitnode/src/tanstack/auth/state.test.ts
index a5805d7e71..3618c5a21e 100644
--- a/packages/vitnode/src/tanstack/auth/state.test.ts
+++ b/packages/vitnode/src/tanstack/auth/state.test.ts
@@ -16,6 +16,7 @@ const anonymousSession: SessionApi = { user: null };
const userFixture = (overrides: Partial = {}): AuthUser => ({
avatarColor: "#101010",
avatarUrl: null,
+ canMention: true,
headline: null,
phone: null,
birthday: null,
diff --git a/packages/vitnode/src/tanstack/comments/content-comments.tsx b/packages/vitnode/src/tanstack/comments/content-comments.tsx
index c922c7d03d..317513d160 100644
--- a/packages/vitnode/src/tanstack/comments/content-comments.tsx
+++ b/packages/vitnode/src/tanstack/comments/content-comments.tsx
@@ -438,12 +438,49 @@ export const ContentCommentsLoadMore = ({
);
};
+/**
+ * The divider above the first comment that other people posted while the
+ * thread was open, such as "2 new comments", in the primary color. Renders a
+ * list item, so place it inside the thread's `` right before that
+ * comment; renders nothing when there are no new comments.
+ *
+ * @example
+ * ```tsx
+ * {comments.tree.map(node => (
+ *
+ * {node.id === comments.newCommentIds[0] ? : null}
+ *
+ *
+ * ))}
+ * ```
+ */
+export const ContentCommentsNewSeparator = ({
+ className,
+}: {
+ className?: string;
+}) => {
+ const t = useTranslations("core.comments");
+ const { comments } = useContentCommentsContext();
+ const count = comments.newCommentIds.length;
+ if (count === 0) return null;
+
+ return (
+
+
+
+ {t("live.new_count", { count })}
+
+
+
+ );
+};
+
/**
* The live state of the thread, for a section that renders its own layout:
- * **Show new comments** when comments appeared after the loaded ones, and a
- * notice with **Try again** when a background refresh failed - the comments
- * on screen stay. Both are announced politely to screen readers. Renders
- * nothing while there is nothing to say.
+ * a polite screen reader announcement when other people's comments were
+ * added, and a notice with **Try again** when a background refresh failed -
+ * the comments on screen stay. Renders nothing visible while there is
+ * nothing to say.
*/
export const ContentCommentsLiveStatus = ({
className,
@@ -452,10 +489,10 @@ export const ContentCommentsLiveStatus = ({
}) => {
const t = useTranslations("core.comments");
const { comments } = useContentCommentsContext();
- const [isShowing, setIsShowing] = React.useState(false);
const [isRetrying, setIsRetrying] = React.useState(false);
+ const newCount = comments.newCommentIds.length;
const announcement = [
- comments.hasNewComments ? t("live.new_comments") : null,
+ newCount > 0 ? t("live.new_count", { count: newCount }) : null,
comments.refreshError ? t("live.refresh_failed") : null,
]
.filter(Boolean)
@@ -467,38 +504,6 @@ export const ContentCommentsLiveStatus = ({
{announcement}
- {comments.hasNewComments ? (
-
-
- {t("live.new_comments")}
-
-
-
- ) : null}
{comments.refreshError ? (
{comments.tree.map(node => (
-
+
+ {node.id === comments.newCommentIds[0] ? (
+
+ ) : null}
+
+
))}
)}
diff --git a/packages/vitnode/src/tanstack/comments/index.ts b/packages/vitnode/src/tanstack/comments/index.ts
index 2409e61192..15a960ca19 100644
--- a/packages/vitnode/src/tanstack/comments/index.ts
+++ b/packages/vitnode/src/tanstack/comments/index.ts
@@ -9,6 +9,7 @@ export {
ContentCommentsComposer,
ContentCommentsLiveStatus,
ContentCommentsLoadMore,
+ ContentCommentsNewSeparator,
} from "./content-comments";
export type { ContentCommentItemState } from "./item";
export {
diff --git a/packages/vitnode/src/tanstack/comments/live.test.ts b/packages/vitnode/src/tanstack/comments/live.test.ts
index f184116621..047a127311 100644
--- a/packages/vitnode/src/tanstack/comments/live.test.ts
+++ b/packages/vitnode/src/tanstack/comments/live.test.ts
@@ -380,30 +380,20 @@ describe("createContentCommentsLive", () => {
readPage: 0,
threadReads: 0,
});
- expect(live.getSnapshot().hasNew).toBe(false);
+ expect(live.getSnapshot().arrived).toStrictEqual([]);
});
- it("a new comment at the end of the thread: 0 requests, then 1 page read on showNew", async () => {
+ it("a new comment at the end of the thread: 1 page read, appended right away", async () => {
const { data, live, readPage, requests, server } = await setup({
branches: 6,
loadedPages: 3,
});
server.state.branches.push([node(90)]);
+ const before = data()?.pages.map(item => item.items) ?? [];
live.signal({ branchId: 90, kind: "branch" });
await vi.advanceTimersByTimeAsync(SETTLE_MS);
- expect(requests()).toStrictEqual({
- readBranches: 0,
- readPage: 0,
- threadReads: 0,
- });
- expect(live.getSnapshot().hasNew).toBe(true);
-
- const before = data()?.pages.map(item => item.items) ?? [];
- const shown = await live.showNew();
-
- expect(shown).toBe(true);
expect(requests()).toStrictEqual({
readBranches: 0,
readPage: 1,
@@ -416,7 +406,7 @@ describe("createContentCommentsLive", () => {
expect(after[index].items).toBe(items);
});
expect(ids(after[3].items)).toStrictEqual([90]);
- expect(live.getSnapshot().hasNew).toBe(false);
+ expect(live.getSnapshot().arrived).toStrictEqual(["90"]);
});
it("five quick signals for one loaded branch: 1 branch read", async () => {
diff --git a/packages/vitnode/src/tanstack/comments/live.ts b/packages/vitnode/src/tanstack/comments/live.ts
index 2802270d4b..172fc2aaac 100644
--- a/packages/vitnode/src/tanstack/comments/live.ts
+++ b/packages/vitnode/src/tanstack/comments/live.ts
@@ -48,6 +48,7 @@ export const CONTENT_COMMENTS_MAX_BRANCH_REQUESTS = 2;
/** Spreads the reads of every viewer of a busy thread after a server restart. */
const RECONNECT_JITTER_MS = 1_500;
+const OWN_POST_HOLD_MS = 15_000;
const keyOf = (id: ContentId): string => String(id);
@@ -208,8 +209,7 @@ const tailCursor = (
};
export interface ContentCommentsLiveSnapshot {
- /** A comment appeared after the loaded ones, at the end of the thread. */
- hasNew: boolean;
+ arrived: readonly string[];
/** A background refresh failed; what is on screen may be out of date. */
refreshError: boolean;
}
@@ -250,9 +250,10 @@ const DETACHED = async (): Promise =>
* `/thread/branches`, and merges it in place. Changes to the same branches
* within `debounceMs` (at most `maxWaitMs`) share one request; at most
* `maxRequests` run at once, never two for the same branch.
- * - A change in a branch that is not loaded is not fetched. At the end of the
- * thread it raises `hasNew`, and `showNew()` reads only what follows the
- * last loaded comment; before the end, "Load more" will read it anyway.
+ * - A change in a branch that is not loaded is not fetched before the end of
+ * the thread - "Load more" will read it anyway. At the end, it reads only
+ * what follows the last loaded comment and appends it right away, listing
+ * the new top-level comments in `arrived`.
* - Nothing is merged while the thread query fetches - an infinite fetch
* writes back the pages it started from - and an answer that started
* before a full refetch is dropped and asked again.
@@ -292,7 +293,7 @@ export const createContentCommentsLive = ({
const idleWaiters: (() => void)[] = [];
const listeners = new Set<() => void>();
let snapshot: ContentCommentsLiveSnapshot = {
- hasNew: false,
+ arrived: [],
refreshError: false,
};
let epoch = 0;
@@ -300,11 +301,12 @@ export const createContentCommentsLive = ({
let active = 0;
let disposed = false;
let reconcileTimer: ReturnType | undefined;
+ let ownPosts = 0;
const setSnapshot = (next: Partial): void => {
const merged = { ...snapshot, ...next };
if (
- merged.hasNew === snapshot.hasNew &&
+ merged.arrived === snapshot.arrived &&
merged.refreshError === snapshot.refreshError
) {
return;
@@ -354,7 +356,7 @@ export const createContentCommentsLive = ({
removals.clear();
failed.clear();
newBranches.clear();
- setSnapshot({ hasNew: false, refreshError: false });
+ setSnapshot({ arrived: [], refreshError: false });
beforeChange();
await queryClient.resetQueries({ exact: true, queryKey: threadKey });
};
@@ -555,7 +557,7 @@ export const createContentCommentsLive = ({
failed.clear();
const loaded = loadedBranches(data());
for (const key of newBranches) if (loaded.has(key)) newBranches.delete(key);
- setSnapshot({ hasNew: newBranches.size > 0, refreshError: false });
+ setSnapshot({ refreshError: false });
};
let reconciling: null | Promise = null;
@@ -592,21 +594,64 @@ export const createContentCommentsLive = ({
}
beforeChange();
+ const loadedBefore = loadedBranches(data());
queryClient.setQueryData(threadKey, old =>
old ? appendContentCommentsTail(old, tail, tailCursor(old)) : old,
);
refreshPermissions(new Set(tail.items.map(item => keyOf(item.id))));
const loaded = loadedBranches(data());
+ const appended = tail.items
+ .filter(item => item.depth === 1)
+ .map(item => keyOf(item.id))
+ .filter(key => loaded.has(key) && !loadedBefore.has(key));
const missing = [...newBranches].filter(key => !loaded.has(key));
newBranches.clear();
- setSnapshot({ hasNew: false });
+ setSnapshot({
+ ...(appended.length > 0
+ ? { arrived: [...snapshot.arrived, ...appended] }
+ : {}),
+ refreshError: false,
+ });
// Published long after it was written, so it sits among loaded ones.
if (missing.length > 0) await reconcileNow();
return true;
};
+ let autoShowing: null | Promise = null;
+ let showAgain = false;
+
+ const pendingAtEnd = (): boolean => {
+ const current = data();
+ if (!current || current.pages.at(-1)?.pageInfo.hasNextPage !== false) {
+ return false;
+ }
+ const loaded = loadedBranches(current);
+
+ return [...newBranches].some(key => !loaded.has(key));
+ };
+
+ const showArrived = (): void => {
+ if (disposed || ownPosts > 0) return;
+ if (autoShowing) {
+ showAgain = true;
+
+ return;
+ }
+ autoShowing = (async () => {
+ if (!(await showNew()) && !disposed && pendingAtEnd()) {
+ setSnapshot({ refreshError: true });
+ }
+ })().finally(() => {
+ autoShowing = null;
+ if (showAgain) {
+ showAgain = false;
+ if (pendingAtEnd()) showArrived();
+ }
+ });
+ };
+
const onCacheEvent = (event: QueryCacheNotifyEvent): void => {
if (event.type !== "updated" || event.query.queryHash !== threadHash) {
return;
@@ -698,6 +743,11 @@ export const createContentCommentsLive = ({
* loaded pages when that is what failed - and resolves once it is done.
*/
retry: async (): Promise => {
+ if (failed.size === 0 && pendingAtEnd()) {
+ await showNew();
+
+ return;
+ }
if (failed.size === 0) {
await reconcileNow();
@@ -716,6 +766,24 @@ export const createContentCommentsLive = ({
await request(keys.slice(start, start + CONTENT_THREAD_BRANCHES_MAX));
}
},
+ holdNew: (): (() => void) => {
+ ownPosts++;
+ let held = true;
+ const release = (): void => {
+ if (!held) return;
+ held = false;
+ clearTimeout(timer);
+ ownPosts--;
+ const loaded = loadedBranches(data());
+ for (const key of newBranches) {
+ if (loaded.has(key)) newBranches.delete(key);
+ }
+ if (ownPosts === 0 && pendingAtEnd()) showArrived();
+ };
+ const timer = setTimeout(release, OWN_POST_HOLD_MS);
+
+ return release;
+ },
/** One signal from the thread's live room. */
signal: (signal: ContentRefreshSignal): void => {
if (disposed) return;
@@ -739,11 +807,9 @@ export const createContentCommentsLive = ({
return;
}
- // Not on screen: "Load more" reads it fresh when it is reached, and at
- // the end of the thread the reader decides when to show it.
if (current && current.pages.at(-1)?.pageInfo.hasNextPage === false) {
newBranches.add(key);
- setSnapshot({ hasNew: true });
+ showArrived();
}
},
subscribe: (listener: () => void): (() => void) => {
@@ -777,8 +843,6 @@ export const createContentCommentsLive = ({
}
}
},
- /** Shows the comments that appeared at the end of the thread. */
- showNew: async (): Promise => await showNew(),
};
};
diff --git a/packages/vitnode/src/tanstack/comments/use-content-comments.test.tsx b/packages/vitnode/src/tanstack/comments/use-content-comments.test.tsx
index a4aff81ed0..5379baf740 100644
--- a/packages/vitnode/src/tanstack/comments/use-content-comments.test.tsx
+++ b/packages/vitnode/src/tanstack/comments/use-content-comments.test.tsx
@@ -71,6 +71,7 @@ const user: AuthUser = {
avatarColor: "#101010",
avatarUrl: null,
birthday: null,
+ canMention: true,
coverUrl: null,
createdAt: "2026-01-01T00:00:00.000Z",
email: "test@test.com",
diff --git a/packages/vitnode/src/tanstack/comments/use-content-comments.ts b/packages/vitnode/src/tanstack/comments/use-content-comments.ts
index 01ac638a82..a4b0101b58 100644
--- a/packages/vitnode/src/tanstack/comments/use-content-comments.ts
+++ b/packages/vitnode/src/tanstack/comments/use-content-comments.ts
@@ -19,7 +19,7 @@ import type {
ContentPermissions,
ContentPermissionsResponse,
} from "../content/permissions";
-import type { ContentCommentsLive } from "./live";
+import type { ContentCommentsLive, ContentCommentsLiveSnapshot } from "./live";
import type {
ContentCommentNode,
ContentCommentsBranches,
@@ -31,6 +31,7 @@ import type {
import { useSessionQuery } from "../auth/session-query";
import { useContentLiveRefresh } from "../content/live-refresh";
import { useContentPermissions } from "../content/permissions";
+import { contentCommentAuthor } from "./author";
import { ContentCommentsRequestError, createContentCommentsLive } from "./live";
import {
buildContentCommentTree,
@@ -219,7 +220,10 @@ type WriteTarget = { id: TId } | { parentId: null | TId };
const noopSubscribe = () => () => undefined;
-const EMPTY_LIVE_SNAPSHOT = { hasNew: false, refreshError: false };
+const EMPTY_LIVE_SNAPSHOT: ContentCommentsLiveSnapshot = {
+ arrived: [],
+ refreshError: false,
+};
const emptySnapshot = () => EMPTY_LIVE_SNAPSHOT;
@@ -369,11 +373,6 @@ export interface ContentCommentsController<
field: string;
/** Whether more top-level comments wait on the server. */
hasMore: boolean;
- /**
- * Live only: comments appeared after the last loaded one, at the end of the
- * thread. They stay off screen until `showNewComments()`.
- */
- hasNewComments: boolean;
/** Hides one comment, with an optional reason of at most 500 characters. */
hide: (id: TId, reason: null | string) => Promise;
/** `true` while the next page loads. */
@@ -394,6 +393,12 @@ export interface ContentCommentsController<
>;
/** Loads the next page; resolves to `false` when it failed. */
loadMore: () => Promise;
+ /**
+ * Live only: top-level comments by other people that were added at the end
+ * of the thread while it was open, oldest first. Render
+ * `ContentCommentsNewSeparator` before the first of them.
+ */
+ newCommentIds: readonly TId[];
/** The visitor's permissions for one comment, all `false` until known or after a failure. */
permissionsOf: (id: TId) => ContentPermissions;
/** The reacted-to target of one comment, or `null` without `reactions`. */
@@ -427,11 +432,6 @@ export interface ContentCommentsController<
retryRefresh: () => Promise;
/** Marks one comment busy while its editor loads, so its menu waits. */
setEditing: (id: null | TId) => void;
- /**
- * Live only: reads the comments that appeared at the end of the thread and
- * appends them below the loaded ones. Resolves to `false` when that failed.
- */
- showNewComments: () => Promise;
/**
* `pending` before the first page, `error` when it failed, then `success` -
* also after a failed background refresh, which `refreshError` reports.
@@ -696,6 +696,20 @@ export const useContentComments = <
live?.getSnapshot ?? emptySnapshot,
);
+ const viewerId = session.data?.user?.id ?? null;
+ const newCommentIds = React.useMemo(() => {
+ if (liveSnapshot.arrived.length === 0) return [];
+ const byKey = new Map(items.map(item => [String(item.id), item]));
+
+ return liveSnapshot.arrived.flatMap(key => {
+ const node = byKey.get(key);
+ if (!node?.record) return [];
+ const author = contentCommentAuthor(node.record);
+
+ return viewerId !== null && author?.id === viewerId ? [] : [node.id];
+ });
+ }, [items, liveSnapshot.arrived, viewerId]);
+
const liveContentTypeId = liveConfig?.contentTypeId;
const liveRootId = liveConfig?.rootId;
const liveScope = React.useMemo(
@@ -729,6 +743,11 @@ export const useContentComments = <
// Where the last write landed, so `written` refreshes only that branch.
const lastWriteRef = React.useRef>(null);
+ const releaseNewHoldRef = React.useRef<(() => void) | null>(null);
+ const releaseNewHold = () => {
+ releaseNewHoldRef.current?.();
+ releaseNewHoldRef.current = null;
+ };
const requestPermissions = config.permissions;
const permissions = useContentPermissions({
@@ -824,7 +843,7 @@ export const useContentComments = <
},
field,
hasMore: comments.hasNextPage,
- hasNewComments: liveSnapshot.hasNew,
+ newCommentIds,
hide: async (id, reason) =>
visibility
? await run(
@@ -866,8 +885,19 @@ export const useContentComments = <
requestCreate: async input => {
if (!create) throw new Error("This thread has no `create`.");
lastWriteRef.current = { parentId: input.parentId };
-
- return await create(input);
+ releaseNewHold();
+ if (input.parentId !== null) return await create(input);
+
+ releaseNewHoldRef.current = live?.holdNew() ?? null;
+ try {
+ const res = await create(input);
+ if (!res.ok) releaseNewHold();
+
+ return res;
+ } catch (error) {
+ releaseNewHold();
+ throw error;
+ }
},
requestSave: async (id, input) => {
if (!edit) throw new Error("This thread has no `edit`.");
@@ -887,7 +917,6 @@ export const useContentComments = <
setEditing: id => {
markBusy(id === null ? null : { action: "edit", id });
},
- showNewComments: async () => (live ? await live.showNew() : false),
status: comments.data ? "success" : comments.status,
trackDraft,
tree,
@@ -900,7 +929,11 @@ export const useContentComments = <
written: async record => {
const target = lastWriteRef.current;
lastWriteRef.current = null;
- await refreshAfterWrite(target);
+ try {
+ await refreshAfterWrite(target);
+ } finally {
+ releaseNewHold();
+ }
const parsed = zodWrittenRecord.safeParse(record);
return parsed.success ? contentCommentWriteOutcome(parsed.data) : "draft";
diff --git a/packages/vitnode/src/tanstack/notifications/actions.ts b/packages/vitnode/src/tanstack/notifications/actions.ts
index 0b37272dc3..7fece2ca4f 100644
--- a/packages/vitnode/src/tanstack/notifications/actions.ts
+++ b/packages/vitnode/src/tanstack/notifications/actions.ts
@@ -94,7 +94,7 @@ export const useNotificationActions = (userId: number) => {
);
}
- if (!newTab && item.available && item.target) {
+ if (!newTab && item.target) {
void router.navigate({ href: item.target });
}
},
diff --git a/packages/vitnode/src/tanstack/notifications/bell.test.tsx b/packages/vitnode/src/tanstack/notifications/bell.test.tsx
index a9f005914a..bfcad06e73 100644
--- a/packages/vitnode/src/tanstack/notifications/bell.test.tsx
+++ b/packages/vitnode/src/tanstack/notifications/bell.test.tsx
@@ -25,7 +25,6 @@ const item = (
activitySeq: 2,
actorCount: 0,
actors: [],
- available: true,
body: null,
category: "social",
createdAt: "2026-10-04T08:00:00.000Z",
diff --git a/packages/vitnode/src/tanstack/notifications/bell.tsx b/packages/vitnode/src/tanstack/notifications/bell.tsx
index b370dc7089..833329231d 100644
--- a/packages/vitnode/src/tanstack/notifications/bell.tsx
+++ b/packages/vitnode/src/tanstack/notifications/bell.tsx
@@ -27,7 +27,7 @@ const SignedInBell = ({
return (
void actions.markAllRead()}
+ onMarkAllRead={actions.markAllRead}
onOpenChange={setOpen}
onOpenItem={(item, options) => {
actions.open(item, options);
diff --git a/packages/vitnode/src/tanstack/notifications/breadcrumb.tsx b/packages/vitnode/src/tanstack/notifications/breadcrumb.tsx
deleted file mode 100644
index 18cab27537..0000000000
--- a/packages/vitnode/src/tanstack/notifications/breadcrumb.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-import { useTranslations } from "use-intl";
-
-export const NotificationsBreadcrumb = () => {
- const t = useTranslations("core.notifications");
-
- return <>{t("title")}>;
-};
diff --git a/packages/vitnode/src/tanstack/notifications/cache.ts b/packages/vitnode/src/tanstack/notifications/cache.ts
index cf26ab1707..c8a6379d1d 100644
--- a/packages/vitnode/src/tanstack/notifications/cache.ts
+++ b/packages/vitnode/src/tanstack/notifications/cache.ts
@@ -1,25 +1,21 @@
-import type { InfiniteData, QueryClient } from "@tanstack/react-query";
+import type { QueryClient } from "@tanstack/react-query";
import type {
NotificationItemView,
NotificationsPage,
+ NotificationsTablePage,
} from "@/views/notifications/notifications-query";
import { notificationsListRoot } from "@/views/notifications/notifications-query";
-type ListData = InfiniteData | NotificationsPage;
+type ListData = NotificationsPage | NotificationsTablePage;
const mapPages = (
data: ListData | undefined,
map: (items: NotificationItemView[]) => NotificationItemView[],
): ListData | undefined => {
if (!data) return data;
- if ("pages" in data) {
- return {
- ...data,
- pages: data.pages.map(page => ({ ...page, items: map(page.items) })),
- };
- }
+ if ("edges" in data) return { ...data, edges: map(data.edges) };
return { ...data, items: map(data.items) };
};
diff --git a/packages/vitnode/src/tanstack/notifications/new-notification-toasts.tsx b/packages/vitnode/src/tanstack/notifications/new-notification-toasts.tsx
new file mode 100644
index 0000000000..dcb4ba8066
--- /dev/null
+++ b/packages/vitnode/src/tanstack/notifications/new-notification-toasts.tsx
@@ -0,0 +1,68 @@
+import type { NotificationStateMessage } from "@vitnode/api/lib/notifications/types";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { notificationsStateChannel } from "@vitnode/api/ws/notifications";
+import { toast } from "sonner";
+
+import {
+ NOTIFICATION_TOAST_CLASS_NAME,
+ NotificationToastBanner,
+} from "@/views/notifications/notification-toast-banner";
+import { recentNotificationsQueryOptions } from "@/views/notifications/notifications-query";
+import { useVitNodeWebSocket } from "@/ws/use-websocket";
+
+import { useSessionQuery } from "../auth/session-query";
+import { useNotificationActions } from "./actions";
+
+const TYPES_WITH_OWN_LIVE_TOAST = new Set(["core.admin_message"]);
+const NOTIFICATION_TOAST_DURATION_MS = 8000;
+
+const NewNotificationToastsForUser = ({ userId }: { userId: number }) => {
+ const queryClient = useQueryClient();
+ const actions = useNotificationActions(userId);
+
+ const showToast = async (notificationId: number) => {
+ const page = await queryClient
+ .query({ ...recentNotificationsQueryOptions({ userId }), staleTime: 0 })
+ .catch(() => null);
+ const item = page?.items.find(entry => entry.id === notificationId);
+ if (!item?.unread || TYPES_WITH_OWN_LIVE_TOAST.has(item.type)) return;
+
+ toast.custom(
+ id => (
+ {
+ toast.dismiss(id);
+ actions.open(item, { newTab: false });
+ }}
+ />
+ ),
+ {
+ classNames: { toast: NOTIFICATION_TOAST_CLASS_NAME },
+ duration: NOTIFICATION_TOAST_DURATION_MS,
+ id: `notification-${item.id}-${item.activitySeq}`,
+ },
+ );
+ };
+
+ useVitNodeWebSocket(notificationsStateChannel, {
+ onMessage: (message: NotificationStateMessage) => {
+ if (message.reason !== "created" || message.notificationId === undefined)
+ return;
+
+ void showToast(message.notificationId);
+ },
+ });
+
+ return null;
+};
+
+export const NewNotificationToasts = () => {
+ const { data: session } = useSessionQuery();
+ const userId = session?.user?.id ?? null;
+
+ return userId === null ? null : (
+
+ );
+};
diff --git a/packages/vitnode/src/tanstack/notifications/route-search.ts b/packages/vitnode/src/tanstack/notifications/route-search.ts
index 9e8e21ca1a..57ecfc6a15 100644
--- a/packages/vitnode/src/tanstack/notifications/route-search.ts
+++ b/packages/vitnode/src/tanstack/notifications/route-search.ts
@@ -1,15 +1,77 @@
+import type {
+ NotificationsTableOrderBy,
+ NotificationsTableParams,
+ NotificationsTableStatus,
+} from "@/views/notifications/notifications-query";
+
+import { DEFAULT_TABLE_PAGE_SIZE } from "@/components/table/url-state";
+import { asSearchValue } from "@/lib/table-params";
+import { normalizeNotificationsTableParams } from "@/views/notifications/notifications-query";
+
+const DEFAULT_PAGE_SIZE = String(DEFAULT_TABLE_PAGE_SIZE);
+
export interface NotificationsRouteSearch {
category?: string;
- filter?: "unread";
+ first?: number;
+ order?: "asc" | "desc";
+ orderBy?: NotificationsTableOrderBy;
+ page?: number;
+ status?: NotificationsTableStatus;
}
-const CATEGORY = /^[a-z0-9_-]{1,50}$/;
+export type UncheckedNotificationsSearch =
+ | NotificationsRouteSearch
+ | Record;
+
+export const notificationsRouteParams = (
+ input: UncheckedNotificationsSearch,
+): NotificationsTableParams =>
+ normalizeNotificationsTableParams({
+ category: asSearchValue(input.category),
+ first: asSearchValue(input.first),
+ order: asSearchValue(input.order),
+ orderBy: asSearchValue(input.orderBy),
+ page: asSearchValue(input.page),
+ status:
+ asSearchValue(input.status) ??
+ ("filter" in input && input.filter === "unread" ? "unread" : undefined),
+ });
export const normalizeNotificationsRouteSearch = (
- input: Record,
-): NotificationsRouteSearch => ({
- ...(typeof input.category === "string" && CATEGORY.test(input.category)
- ? { category: input.category }
- : {}),
- ...(input.filter === "unread" ? { filter: "unread" as const } : {}),
-});
+ input: UncheckedNotificationsSearch,
+): NotificationsRouteSearch => {
+ const { category, first, order, orderBy, page, status } =
+ notificationsRouteParams(input);
+
+ return {
+ ...(page === undefined ? {} : { page: Number(page) }),
+ ...(first === undefined || first === DEFAULT_PAGE_SIZE
+ ? {}
+ : { first: Number(first) }),
+ ...(order === undefined ? {} : { order }),
+ ...(orderBy === undefined ? {} : { orderBy }),
+ ...(status === undefined ? {} : { status }),
+ ...(category === undefined ? {} : { category }),
+ };
+};
+
+export const notificationsSearchParams = (
+ input: UncheckedNotificationsSearch,
+): URLSearchParams => {
+ const params = new URLSearchParams();
+
+ for (const [key, value] of Object.entries(
+ normalizeNotificationsRouteSearch(input),
+ )) {
+ params.set(key, String(value));
+ }
+
+ return params;
+};
+
+export const notificationsSearchFrom = (
+ nextSearch: string,
+): NotificationsRouteSearch =>
+ normalizeNotificationsRouteSearch(
+ Object.fromEntries(new URLSearchParams(nextSearch)),
+ );
diff --git a/packages/vitnode/src/tanstack/notifications/route.ts b/packages/vitnode/src/tanstack/notifications/route.ts
index 2906845b71..3a6481a596 100644
--- a/packages/vitnode/src/tanstack/notifications/route.ts
+++ b/packages/vitnode/src/tanstack/notifications/route.ts
@@ -4,10 +4,12 @@ import type { PluginRouteTranslator } from "@/routing";
import {
notificationPreferencesQueryOptions,
- notificationsInfiniteQueryOptions,
+ notificationsTableQueryOptions,
} from "@/views/notifications/notifications-query";
-import type { NotificationsRouteSearch } from "./route-search";
+import type { UncheckedNotificationsSearch } from "./route-search";
+
+import { notificationsRouteParams } from "./route-search";
export interface NotificationsRouteData {
description: string;
@@ -23,18 +25,15 @@ export const loadNotificationsRoute = async ({
}: {
auth: { user: { id: number } };
queryClient: QueryClient;
- search: NotificationsRouteSearch;
+ search: UncheckedNotificationsSearch;
t: PluginRouteTranslator;
}): Promise => {
const userId = auth.user.id;
await Promise.all([
- queryClient.infiniteQuery({
- ...notificationsInfiniteQueryOptions({
- filter: {
- category: search.category,
- unread: search.filter === "unread",
- },
+ queryClient.query({
+ ...notificationsTableQueryOptions({
+ params: notificationsRouteParams(search),
userId,
}),
staleTime: "static",
diff --git a/packages/vitnode/src/tanstack/notifications/screen.tsx b/packages/vitnode/src/tanstack/notifications/screen.tsx
index 87a80036a9..115533bb28 100644
--- a/packages/vitnode/src/tanstack/notifications/screen.tsx
+++ b/packages/vitnode/src/tanstack/notifications/screen.tsx
@@ -1,14 +1,33 @@
-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import type { QueryClient } from "@tanstack/react-query";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
+import { cn } from "cn";
import {
+ ArchiveIcon,
BellIcon,
BellOffIcon,
CheckCheckIcon,
+ MailIcon,
+ MailOpenIcon,
RotateCwIcon,
Settings2Icon,
} from "lucide-react";
+import React from "react";
import { useTranslations } from "use-intl";
+import type { ColumnDef } from "@/components/table/data-table-content";
+import type { FilterDataTable } from "@/components/table/filters";
+import type { DataTableNavigation } from "@/components/table/navigation";
+import type { NotificationItemView } from "@/views/notifications/notifications-query";
+
+import { DateFormat } from "@/components/date-format";
+import { ContentDataTable } from "@/components/table/content";
+import { DataTableSkeleton } from "@/components/table/data-table-content";
+import { FiltersDataTable } from "@/components/table/filters";
+import { DataTableNavigationProvider } from "@/components/table/navigation";
+import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
+import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Empty,
@@ -19,71 +38,170 @@ import {
EmptyTitle,
} from "@/components/ui/empty";
import { PageTitle } from "@/components/ui/page-title";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { NotificationItem } from "@/views/notifications/notification-item";
+import { TooltipWithContent } from "@/components/ui/tooltip";
+import { MarkAllReadConfirm } from "@/views/notifications/mark-all-read-confirm";
+import { NotificationAvatar } from "@/views/notifications/notification-avatar";
+import { isModifiedClick } from "@/views/notifications/notification-item";
import { useNotificationState } from "@/views/notifications/notification-state-store";
import { NOTIFICATION_SETTINGS_HREF } from "@/views/notifications/notifications-bell-content";
import {
notificationPreferencesQueryOptions,
- notificationsInfiniteQueryOptions,
+ notificationsListRoot,
+ notificationsTableQueryOptions,
} from "@/views/notifications/notifications-query";
import type { NotificationsRouteData } from "./route";
-import type { NotificationsRouteSearch } from "./route-search";
+import type {
+ NotificationsRouteSearch,
+ UncheckedNotificationsSearch,
+} from "./route-search";
import { RouteMessages } from "../i18n/route-messages";
import { useNotificationActions } from "./actions";
import { NOTIFICATIONS_NAMESPACES } from "./namespaces";
-
-const ALL = "all";
+import {
+ notificationsRouteParams,
+ notificationsSearchFrom,
+ notificationsSearchParams,
+} from "./route-search";
type NotificationsScreenProps = NotificationsRouteData & {
- navigate: (options: { search: NotificationsRouteSearch }) => unknown;
- search: NotificationsRouteSearch;
+ navigate: (options: {
+ resetScroll: boolean;
+ search: NotificationsRouteSearch;
+ }) => unknown;
+ search: UncheckedNotificationsSearch;
};
-const NotificationsList = ({
+type NotificationActions = ReturnType;
+
+const refreshNotificationsTable = async (
+ queryClient: QueryClient,
+ userId: number,
+) =>
+ await queryClient.invalidateQueries({
+ queryKey: [...notificationsListRoot(userId), "table"],
+ });
+
+const titleClassName =
+ "focus-visible:ring-ring line-clamp-2 rounded-sm text-start text-sm leading-relaxed text-pretty underline-offset-4 outline-none hover:underline focus-visible:ring-2";
+
+const NotificationTitle = ({
+ actions,
+ item,
+}: {
+ actions: NotificationActions;
+ item: NotificationItemView;
+}) => {
+ const className = cn(
+ titleClassName,
+ item.unread ? "text-foreground font-medium" : "text-muted-foreground",
+ );
+
+ if (item.target === null) {
+ return (
+
+ );
+ }
+
+ return (
+ {
+ const newTab = isModifiedClick(event);
+ if (!newTab) event.preventDefault();
+ actions.open(item, { newTab });
+ }}
+ >
+ {item.title}
+
+ );
+};
+
+const RowActions = ({
+ item,
+ onArchive,
+ onToggleRead,
+}: {
+ item: NotificationItemView;
+ onArchive: (item: NotificationItemView) => void;
+ onToggleRead: (item: NotificationItemView) => void;
+}) => {
+ const t = useTranslations("core.global.notifications");
+ const toggleLabel = item.unread ? t("mark_read") : t("mark_unread");
+
+ return (
+