From 244ec21f788c7792e7e324ec8ec4f548787f5748 Mon Sep 17 00:00:00 2001 From: aXenDeveloper Date: Mon, 23 Nov 2026 22:17:45 +0100 Subject: [PATCH] =?UTF-8?q?feat(mentions):=20=E2=9C=A8=20Add=20@mentions?= =?UTF-8?q?=20to=20the=20rich-text=20editor=20with=20notifications?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - @mentions in the rich-text editor, enabled by default, delivered right away - Mention notifications, new notification toasts and a mark-all-read confirmation dialog - Simplified notification fanout/inbox processing and type handling - Mentions implementation plan and docs Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../20261123121401_add_mentions/migration.sql | 22 + .../20261123121401_add_mentions/snapshot.json | 559 ++++++++++++++++++ .../docs/content-engine/comments-api.mdx | 5 +- .../docs/content-engine/notifications-api.mdx | 6 +- .../docs/content-engine/notifications.mdx | 10 +- .../docs/content-engine/threads-live.mdx | 10 +- .../docs/dev/events/built-in-events.mdx | 18 + .../docs/dev/mentions-editor-popup.webp | Bin 0 -> 12670 bytes .../docs/dev/mentions-role-settings.webp | Bin 0 -> 27924 bytes apps/web/content/docs/dev/mentions.mdx | 178 ++++++ apps/web/content/docs/dev/meta.json | 1 + .../content/docs/dev/notifications/access.mdx | 8 +- .../dev/notifications/inbox-and-realtime.mdx | 22 +- .../dev/notifications/notification-types.mdx | 4 +- .../docs/dev/notifications/reference.mdx | 21 +- .../dev/notifications/troubleshooting.mdx | 6 +- .../content/docs/dev/routing/breadcrumbs.mdx | 2 +- apps/web/src/locales/@vitnode/core/pl.json | 39 +- packages/api/scripts/prepare-database.ts | 1 + .../approval-notifications.postgres.test.ts | 33 +- packages/api/src/content/const.ts | 3 + packages/api/src/content/fields.ts | 7 + .../api/src/content/rich-text/elements.ts | 29 + packages/api/src/content/rich-text/index.ts | 8 + .../api/src/content/rich-text/mentions.ts | 103 ++++ .../api/src/content/rich-text/plain-text.ts | 7 + packages/api/src/content/server/emit.ts | 10 + .../api/src/content/server/mention-target.ts | 40 ++ packages/api/src/content/server/mentions.ts | 343 +++++++++++ .../content-notifications.postgres.test.ts | 27 +- .../api/src/content/server/report-target.ts | 2 +- packages/api/src/content/types.ts | 2 + packages/api/src/database/mentions.ts | 44 ++ packages/api/src/database/roles.ts | 6 + packages/api/src/events/mentions.ts | 44 ++ packages/api/src/lib/mentions/limits.ts | 5 + packages/api/src/lib/mentions/notification.ts | 75 +++ packages/api/src/lib/mentions/policy.ts | 100 ++++ packages/api/src/lib/mentions/sync.ts | 293 +++++++++ packages/api/src/lib/mentions/targets.ts | 105 ++++ .../api/src/lib/notifications/core-types.ts | 2 + .../api/src/lib/notifications/registry.ts | 4 +- packages/api/src/lib/plugin.ts | 26 + packages/api/src/locales/en.json | 7 +- packages/api/src/mentions.ts | 11 + .../api/src/middlewares/global.middleware.ts | 14 + packages/api/src/models/mentions/users.ts | 125 ++++ .../api/src/models/notifications/fanout.ts | 9 +- .../api/src/models/notifications/inbox.ts | 283 ++++++--- .../src/modules/admin/roles/roles.schema.ts | 9 + .../admin/roles/routes/create.route.ts | 7 + .../modules/admin/roles/routes/list.route.ts | 4 + .../modules/admin/roles/routes/show.route.ts | 4 + .../admin/roles/routes/update.route.ts | 9 + .../api/src/modules/content/content.module.ts | 2 + .../content/tasks/content-mentions.task.ts | 25 + .../notifications/notifications.module.ts | 2 + .../notifications/notifications.schema.ts | 1 - .../notifications/routes/inbox.route.ts | 73 +++ .../modules/users/routes/mentioned.route.ts | 64 ++ .../modules/users/routes/mentions.route.ts | 70 +++ .../src/modules/users/routes/session.route.ts | 24 +- .../api/src/modules/users/users.module.ts | 4 + packages/api/src/plugin.ts | 2 + packages/vitnode/package.json | 1 + .../src/components/rich-text/mention.tsx | 46 ++ .../rich-text/rich-text-content.tsx | 11 +- .../src/components/tiptap/extension.ts | 7 + .../mention/mention-suggestion-list.tsx | 241 ++++++++ .../tiptap/mention/mention-suggestion.ts | 72 +++ .../src/components/tiptap/mention/mention.ts | 74 +++ .../tiptap/mention/use-can-mention.ts | 32 + .../src/components/tiptap/tiptap-editor.tsx | 40 +- packages/vitnode/src/locales/en.json | 42 +- packages/vitnode/src/pages/notifications.tsx | 12 +- packages/vitnode/src/routes.tsx | 4 +- .../vitnode/src/tanstack/admin/roles/query.ts | 2 + .../vitnode/src/tanstack/auth/state.test.ts | 1 + .../tanstack/comments/content-comments.tsx | 97 +-- .../vitnode/src/tanstack/comments/index.ts | 1 + .../src/tanstack/comments/live.test.ts | 18 +- .../vitnode/src/tanstack/comments/live.ts | 94 ++- .../comments/use-content-comments.test.tsx | 1 + .../tanstack/comments/use-content-comments.ts | 67 ++- .../src/tanstack/notifications/actions.ts | 2 +- .../src/tanstack/notifications/bell.test.tsx | 1 - .../src/tanstack/notifications/bell.tsx | 2 +- .../src/tanstack/notifications/breadcrumb.tsx | 7 - .../src/tanstack/notifications/cache.ts | 12 +- .../notifications/new-notification-toasts.tsx | 68 +++ .../tanstack/notifications/route-search.ts | 80 ++- .../src/tanstack/notifications/route.ts | 17 +- .../src/tanstack/notifications/screen.tsx | 529 +++++++++++------ .../plugin-routes/components.test.tsx | 4 +- .../src/tanstack/plugin-routes/components.tsx | 12 +- .../tanstack/realtime/realtime-listeners.tsx | 2 + packages/vitnode/src/tiptap.css | 8 + .../core/users/roles/role-form-content.tsx | 48 ++ .../views/core/users/roles/roles-query.ts | 2 + .../src/views/mentions/mentions-query.ts | 131 ++++ .../notifications/mark-all-read-confirm.tsx | 39 ++ .../notifications/notification-avatar.tsx | 49 ++ .../views/notifications/notification-item.tsx | 34 +- .../notification-toast-banner.tsx | 68 +++ .../notifications/notification-type-icon.ts | 53 ++ .../notifications-bell-content.tsx | 18 +- .../notifications/notifications-query.ts | 147 +++-- plans/mentions.md | 470 +++++++++++++++ plugins/blog/src/pages/post-comments.tsx | 28 +- pnpm-lock.yaml | 16 + 111 files changed, 5112 insertions(+), 579 deletions(-) create mode 100644 apps/api/migrations/20261123121401_add_mentions/migration.sql create mode 100644 apps/api/migrations/20261123121401_add_mentions/snapshot.json create mode 100644 apps/web/content/docs/dev/mentions-editor-popup.webp create mode 100644 apps/web/content/docs/dev/mentions-role-settings.webp create mode 100644 apps/web/content/docs/dev/mentions.mdx create mode 100644 packages/api/src/content/rich-text/mentions.ts create mode 100644 packages/api/src/content/server/mention-target.ts create mode 100644 packages/api/src/content/server/mentions.ts create mode 100644 packages/api/src/database/mentions.ts create mode 100644 packages/api/src/events/mentions.ts create mode 100644 packages/api/src/lib/mentions/limits.ts create mode 100644 packages/api/src/lib/mentions/notification.ts create mode 100644 packages/api/src/lib/mentions/policy.ts create mode 100644 packages/api/src/lib/mentions/sync.ts create mode 100644 packages/api/src/lib/mentions/targets.ts create mode 100644 packages/api/src/mentions.ts create mode 100644 packages/api/src/models/mentions/users.ts create mode 100644 packages/api/src/modules/content/tasks/content-mentions.task.ts create mode 100644 packages/api/src/modules/notifications/routes/inbox.route.ts create mode 100644 packages/api/src/modules/users/routes/mentioned.route.ts create mode 100644 packages/api/src/modules/users/routes/mentions.route.ts create mode 100644 packages/vitnode/src/components/rich-text/mention.tsx create mode 100644 packages/vitnode/src/components/tiptap/mention/mention-suggestion-list.tsx create mode 100644 packages/vitnode/src/components/tiptap/mention/mention-suggestion.ts create mode 100644 packages/vitnode/src/components/tiptap/mention/mention.ts create mode 100644 packages/vitnode/src/components/tiptap/mention/use-can-mention.ts delete mode 100644 packages/vitnode/src/tanstack/notifications/breadcrumb.tsx create mode 100644 packages/vitnode/src/tanstack/notifications/new-notification-toasts.tsx create mode 100644 packages/vitnode/src/views/mentions/mentions-query.ts create mode 100644 packages/vitnode/src/views/notifications/mark-all-read-confirm.tsx create mode 100644 packages/vitnode/src/views/notifications/notification-avatar.tsx create mode 100644 packages/vitnode/src/views/notifications/notification-toast-banner.tsx create mode 100644 packages/vitnode/src/views/notifications/notification-type-icon.ts create mode 100644 plans/mentions.md 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 0000000000000000000000000000000000000000..022e7993d22ab43426fc99257a3dc59d0d30ad57 GIT binary patch literal 12670 zcmcJ!b9iOnwk8}~6<2H<72B!Usn|xv-mz`lX2rHEsZ?y+&Q5mM@0{D+=bqd5+`j!i z-~40DvDP!k9D3*bEU3sxO1iOvfoV#JDrqQjlUV=J>y5y3!0CW6rQm|B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zU`NDrgbI}~k44XQe%1Ly3-!t{X;ZGS(;D)K>EKU!zxMcRkxG|HqtMJTE_vv`jqZiw z8MwNZ{W$;d60)c{)@GFc0ea5|noln4ZWUaUB`$v`{}^mb)Ex(9I0OM-s2 z>YugM?VMz|000b(cZh9;lwB_Jw->X(60m9qR(BRlV~I)q5q3Bv0_&d+#~VMj3iC@w z3^O**0+qjS1bP{$WLPC6><0V=w+81a<+K8w!nA{ zx*K0U)n2-N98~HtE7OZ=RA}=dWRU_~TP|HSe1+=nKOi-RJo?Kdh_&kRL$~}+kvZ&k zD{lL|kzxq{uo$IQGo^oj``Eb59>38%C4QiUvyyX<=x`X!gEj#-fd(RVS44#$`s3mt z0f4PpmA?(iK~1J#z9XFl?@);<*K*Sz3;W2+(yPjd&crC+A1PA?6G=*{ii{w#M%X&b zXd`JA3rSNhVuti$^104k0upvjrr8ec4@~Q;Q|LY4>buI_fzjHG(oFVY^v`r{NghLY z`xn$*nw;PySj`?f(j*>|frqJ6-$80vX4`B@ae?MduH1I*zoUHhFf~9SJCw|Bu7zIRu$RsY2cbErHkg(<2+2P5E5sv6u?z^cOnbu zrTH5;pk>b7sRJtrZ-(c;QRJ>?L6o@s)3*Ol*KCviVu8jaUB2_VdM?)xjX~;Ga^3F~ O$&WQdV-kV?X7N8-&&Lt~ literal 0 HcmV?d00001 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 ( +

    + + {t("loading")} + + {Array.from({ length: SKELETON_ROWS }, (_, index) => ( +
    + + +
    + ))} +
    + ); + } + + if (suggestions.isError && items.length === 0) { + const forbidden = + suggestions.error instanceof MentionsRequestError && + suggestions.error.status === 403; + + return ( +
    +

    + {forbidden ? t("forbidden") : t("load_error")} +

    + {!forbidden && ( + + )} +
    + ); + } + + if (items.length === 0) { + return ( +
    + {t("empty")} +
    + ); + } + + return ( +
    + {items.map((item, index) => ( + + ))} +
    + ); +}; 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 ( +
    1. +
    2. + ); +}; + /** * 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 ? ( -
      - - -
      - ) : 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 ( +
    + + + + + + +
    + ); +}; + +const NotificationsTable = ({ + navigation, search, userId, }: { - search: NotificationsRouteSearch; + navigation: DataTableNavigation; + search: UncheckedNotificationsSearch; userId: number; }) => { const t = useTranslations("core.notifications"); + const tGlobal = useTranslations("core.global.notifications"); + const queryClient = useQueryClient(); const actions = useNotificationActions(userId); - const query = useInfiniteQuery( - notificationsInfiniteQueryOptions({ - filter: { category: search.category, unread: search.filter === "unread" }, - userId, - }), + const state = useNotificationState(userId); + const params = notificationsRouteParams(search); + const query = useQuery(notificationsTableQueryOptions({ params, userId })); + const preferences = useQuery(notificationPreferencesQueryOptions({ userId })); + + const categoryLabels = new Map( + (preferences.data?.types ?? []).map(type => [ + type.category, + type.categoryLabel, + ]), ); + const archive = async (item: NotificationItemView) => { + await actions.archive(item); + await refreshNotificationsTable(queryClient, userId); + }; + if (query.isPending) { - return ( -
    - {t("loading")} - {Array.from({ length: 4 }, (_, index) => ( -
    - -
    - - -
    -
    - ))} -
    - ); + return ; } - if (query.isError) { + if (query.isError && !query.data) { return ( @@ -107,67 +225,192 @@ const NotificationsList = ({ ); } - const items = query.data.pages.flatMap(page => page.items); - if (items.length === 0) { - return ( - - - - - - - {search.filter === "unread" - ? t("empty_unread_title") - : t("empty_title")} - - {t("empty_desc")} - - - ); - } + const columns: ColumnDef[] = [ + { + id: "status", + header: {t("column_status")}, + className: "w-2", + cell: ({ row }) => + row.unread ? ( + + + ) : ( + {t("status_read")} + ), + }, + { + accessorKey: "title", + header: t("column_notification"), + className: "min-w-72 whitespace-normal", + cell: ({ row }) => ( +
    + +
    + + {row.body ? ( +

    + {row.body} +

    + ) : null} +
    +
    + ), + }, + { + accessorKey: "category", + header: t("column_category"), + className: "w-32", + cell: ({ row }) => ( + + {categoryLabels.get(row.category) ?? row.category} + + ), + }, + { + accessorKey: "lastActivityAt", + header: t("column_received"), + align: "right", + className: "w-36 whitespace-nowrap", + cell: ({ row }) => ( + + + + ), + }, + { + id: "actions", + header: {t("column_actions")}, + align: "right", + className: "w-20", + cell: ({ row }) => ( + void archive(item)} + onToggleRead={item => void actions.toggleRead(item)} + /> + ), + }, + ]; + + const filters: FilterDataTable[] = [ + { + id: "status", + label: t("filter_status"), + options: [ + { label: t("filter_unread"), value: "unread" }, + { label: t("status_read"), value: "read" }, + ], + single: { allLabel: t("filter_status_all") }, + }, + ...(categoryLabels.size > 1 + ? [ + { + id: "category", + label: t("filter_category"), + options: [...categoryLabels].map(([value, label]) => ({ + label, + value, + })), + }, + ] + : []), + ]; return (
    -
      - {items.map(item => ( - void actions.archive(item)} - onOpen={actions.open} - onToggleRead={item => void actions.toggleRead(item)} - /> - ))} -
    - {query.hasNextPage ? ( - + {query.isError ? ( + + ) : null} + + +
    ); }; -export const NotificationsRouteContent = ({ - description, - navigate, - search, - title, - userId, -}: NotificationsScreenProps) => ( +const MarkAllReadAction = ({ userId }: { userId: number }) => { + const t = useTranslations("core.notifications"); + const queryClient = useQueryClient(); + const actions = useNotificationActions(userId); + const unread = useNotificationState(userId)?.unread ?? 0; + + return ( + { + await actions.markAllRead(); + await refreshNotificationsTable(queryClient, userId); + }} + unread={unread} + > + + + ); +}; + +export const NotificationsRouteContent = (props: NotificationsScreenProps) => ( - + ); @@ -179,100 +422,42 @@ const NotificationsScreen = ({ userId, }: NotificationsScreenProps) => { const t = useTranslations("core.notifications"); - const actions = useNotificationActions(userId); - const state = useNotificationState(userId); - const preferences = useQuery(notificationPreferencesQueryOptions({ userId })); - const categories = [ - ...new Map( - (preferences.data?.types ?? []).map(type => [ - type.category, - type.categoryLabel, - ]), - ), - ]; + + const navigation = React.useMemo( + () => ({ + navigate: async nextSearch => { + await navigate({ + resetScroll: false, + search: notificationsSearchFrom(nextSearch), + }); + }, + searchParams: notificationsSearchParams(search), + }), + [navigate, search], + ); return ( -
    +
    -
    - +
    +
    -
    - - navigate({ - search: { - ...search, - filter: value === "unread" ? "unread" : undefined, - }, - }) - } - value={search.filter ?? ALL} - > - - {t("filter_all")} - - {t("filter_unread")} - {state && state.unread > 0 ? ` (${state.unread})` : ""} - - - - - {categories.length > 1 ? ( - - ) : null} -
    - - +
    ); }; diff --git a/packages/vitnode/src/tanstack/plugin-routes/components.test.tsx b/packages/vitnode/src/tanstack/plugin-routes/components.test.tsx index 4ff06319b6..1ac44e16f1 100644 --- a/packages/vitnode/src/tanstack/plugin-routes/components.test.tsx +++ b/packages/vitnode/src/tanstack/plugin-routes/components.test.tsx @@ -153,10 +153,12 @@ describe("pluginRouteBreadcrumb", () => { const { load, ready, ref } = moduleWith({}); const deferred = pluginRouteBreadcrumb(ref, []); + expect(deferred.resolve()).toBeUndefined(); + ready(); await load(); - expect(deferred.resolve()).toBeUndefined(); + expect(deferred.resolve()).toBe(false); }); }); diff --git a/packages/vitnode/src/tanstack/plugin-routes/components.tsx b/packages/vitnode/src/tanstack/plugin-routes/components.tsx index 5b360290dd..e6ed46e55d 100644 --- a/packages/vitnode/src/tanstack/plugin-routes/components.tsx +++ b/packages/vitnode/src/tanstack/plugin-routes/components.tsx @@ -168,13 +168,13 @@ export const pluginRouteBreadcrumb = ( return breadcrumbDeferred( () => { - const declared = module.current?.route.breadcrumb; + const loaded = module.current; - // `undefined` is "the module has not arrived yet, ask again"; `false` and - // `null` are both "this route contributes no crumb". They are kept apart - // here because only the first is worth re-resolving. - if (declared === undefined) return undefined; - if (declared === false || declared === null) return false; + if (loaded === undefined) return undefined; + const declared = loaded.route.breadcrumb; + if (declared === undefined || declared === false || declared === null) { + return false; + } // A group draws its own ``s, so it stays a group all the // way to the trail - wrapping it in one would nest items inside an item. diff --git a/packages/vitnode/src/tanstack/realtime/realtime-listeners.tsx b/packages/vitnode/src/tanstack/realtime/realtime-listeners.tsx index 922549f700..f4d36365de 100644 --- a/packages/vitnode/src/tanstack/realtime/realtime-listeners.tsx +++ b/packages/vitnode/src/tanstack/realtime/realtime-listeners.tsx @@ -7,6 +7,7 @@ import { WebSocketAuthSync } from "@/views/layouts/theme/web-socket-auth-sync"; import { removeUserIdentityQueries } from "../auth/queries"; import { invalidateSession, useSessionQuery } from "../auth/session-query"; +import { NewNotificationToasts } from "../notifications/new-notification-toasts"; import { NotificationStateSync } from "../notifications/state-sync"; import { socketUserIdFromSession } from "./session"; @@ -32,6 +33,7 @@ export const RealtimeListeners = () => { <> + ); diff --git a/packages/vitnode/src/tiptap.css b/packages/vitnode/src/tiptap.css index 2e50cfd53e..adca5baf66 100644 --- a/packages/vitnode/src/tiptap.css +++ b/packages/vitnode/src/tiptap.css @@ -252,6 +252,14 @@ } } + .mention { + @apply text-primary font-medium no-underline underline-offset-4 hover:underline; + } + + &.ProseMirror .mention { + @apply bg-primary/10 rounded-sm px-0.5 hover:no-underline; + } + [data-type="emoji"] { @apply inline-block align-middle; diff --git a/packages/vitnode/src/views/admin/views/core/users/roles/role-form-content.tsx b/packages/vitnode/src/views/admin/views/core/users/roles/role-form-content.tsx index 20dadcbf32..fab7b4fb51 100644 --- a/packages/vitnode/src/views/admin/views/core/users/roles/role-form-content.tsx +++ b/packages/vitnode/src/views/admin/views/core/users/roles/role-form-content.tsx @@ -2,6 +2,10 @@ import { useSuspenseQuery } from "@tanstack/react-query"; import { AI_ACTION_LIMITS } from "@vitnode/api/lib/ai/action"; import { EMOJI_ICON_MAX_LENGTH } from "@vitnode/api/lib/emoji-icon"; import { multiLangValueSchema } from "@vitnode/api/lib/helpers/multi-lang"; +import { + ROLE_DEFAULT_MAX_MENTIONS_PER_ITEM, + ROLE_MAX_MENTIONS_PER_ITEM, +} from "@vitnode/api/lib/mentions/limits"; import { ROLE_EDIT_OWN_CONTENT_MAX_MINUTES } from "@vitnode/api/lib/own-content"; import { toast } from "sonner"; import { useTranslations } from "use-intl"; @@ -73,6 +77,7 @@ export interface AdminRoleFormValues { allowEditOwnContent: boolean; allowEditPersonalInfo: boolean; allowHideOwnContent: boolean; + allowMentions: boolean; allowUploadAvatar: boolean; allowUploadCover: boolean; allowUploadFiles: boolean; @@ -81,6 +86,7 @@ export interface AdminRoleFormValues { forceBrowseAnonymously: boolean; maxAvatarSize: number; maxCoverSize: number; + maxMentionsPerItem: null | number; maxStorageForSubmit: null | number; name: { languageCode: string; value: string }[]; prefix: string; @@ -97,6 +103,7 @@ export interface AdminRoleFormData { allowEditOwnContent: boolean; allowEditPersonalInfo: boolean; allowHideOwnContent: boolean; + allowMentions: boolean; allowUploadAvatar: boolean; allowUploadCover: boolean; allowUploadFiles: boolean; @@ -106,6 +113,7 @@ export interface AdminRoleFormData { id: number; maxAvatarSize: number; maxCoverSize: number; + maxMentionsPerItem: null | number; maxStorageForSubmit: null | number; name: { languageCode: string; name: string }[]; prefix: null | string; @@ -301,6 +309,17 @@ export const AdminRoleFormContent = ({ .nullable() .default(data?.editOwnContentMinutes ?? null) .describe(t("form.edit_own_content.minutes_desc")), + allowMentions: z.boolean().default(data?.allowMentions ?? true), + maxMentionsPerItem: z + .number() + .int() + .min(1) + .max(ROLE_MAX_MENTIONS_PER_ITEM) + .nullable() + .default( + data ? data.maxMentionsPerItem : ROLE_DEFAULT_MAX_MENTIONS_PER_ITEM, + ) + .describe(t("form.mentions.max_per_item_desc")), allowEditPersonalInfo: z .boolean() .default(data?.allowEditPersonalInfo ?? true), @@ -493,6 +512,35 @@ export const AdminRoleFormContent = ({ id: "allowHideOwnContent", tab: "content", }, + { + children: [ + { + component: props => ( + + ), + id: "maxMentionsPerItem", + }, + ], + component: props => ( + + ), + id: "allowMentions", + tab: "content", + }, { component: props => ( + queryOptions({ + enabled: search !== "", + placeholderData: keepPreviousData, + queryFn: async ({ signal }) => { + const response = await fetcher({ + plugin: manifest.id, + args: { query: { search } }, + method: "get", + module: "users", + options: { signal }, + path: "/mentions", + }); + if (!response.ok) throw new MentionsRequestError(response.status); + + return (await response.json()).users; + }, + queryKey: [...MENTIONS_QUERY_ROOT, "suggestions", search] as const, + retry: false, + staleTime: RECORD_STALE_TIME, + }); + +/** A mentioned member's current name and URL name. */ +export interface MentionedUser { + id: number; + name: string; + nameCode: string; +} + +interface PendingLookup { + reject: (error: unknown) => void; + resolve: (user: MentionedUser | null) => void; +} + +// Browser-only: the lookup runs from `useQuery`, which never fetches during +// SSR, so this queue never holds two visitors' ids. +const pending = new Map(); +let flushTimer: ReturnType | undefined; + +const fetchMentionedUsers = async ( + ids: readonly number[], +): Promise> => { + const response = await fetcher({ + plugin: manifest.id, + args: { query: { ids: ids.join(",") } }, + method: "get", + module: "users", + path: "/mentioned", + }); + if (!response.ok) throw new MentionsRequestError(response.status); + + const { users } = await response.json(); + + return new Map(users.map(user => [user.id, user])); +}; + +const flush = () => { + flushTimer = undefined; + const batch = [...pending.entries()]; + pending.clear(); + + for (let start = 0; start < batch.length; start += MENTIONED_BATCH_MAX) { + const chunk = batch.slice(start, start + MENTIONED_BATCH_MAX); + const ids = chunk.map(([id]) => id).sort((a, b) => a - b); + + fetchMentionedUsers(ids).then( + users => { + for (const [id, lookups] of chunk) { + for (const lookup of lookups) lookup.resolve(users.get(id) ?? null); + } + }, + (error: unknown) => { + for (const [, lookups] of chunk) { + for (const lookup of lookups) lookup.reject(error); + } + }, + ); + } +}; + +/** + * One member's current name, fetched together with every other mention that + * asks within the same few milliseconds - a page of comments sends one + * request, not one per mention. Resolves `null` for a deleted member. + */ +const loadMentionedUser = async (id: number): Promise => + await new Promise((resolve, reject) => { + const lookups = pending.get(id) ?? []; + lookups.push({ reject, resolve }); + pending.set(id, lookups); + flushTimer ??= setTimeout(flush, MENTIONED_BATCH_WINDOW_MS); + }); + +/** + * The current name and URL name of a mentioned member, so a mention follows + * renames. Read it in the browser only - the snapshot stored in the mention + * is what SSR renders. + */ +export const mentionedUserQueryOptions = (id: number) => + queryOptions({ + queryFn: async () => await loadMentionedUser(id), + queryKey: [...MENTIONS_QUERY_ROOT, "user", id] as const, + retry: false, + staleTime: 5 * 60_000, + }); diff --git a/packages/vitnode/src/views/notifications/mark-all-read-confirm.tsx b/packages/vitnode/src/views/notifications/mark-all-read-confirm.tsx new file mode 100644 index 0000000000..79cfd7e751 --- /dev/null +++ b/packages/vitnode/src/views/notifications/mark-all-read-confirm.tsx @@ -0,0 +1,39 @@ +import type React from "react"; + +import { CheckCheckIcon } from "lucide-react"; +import { useTranslations } from "use-intl"; + +import { ConfirmActionAlertDialog } from "@/components/confirm-action/confirm-action-alert-dialog"; + +export const MarkAllReadConfirm = ({ + children, + onConfirm, + unread, +}: { + children: React.ReactElement; + onConfirm: () => Promise; + unread: number; +}) => { + const t = useTranslations("core.global.notifications"); + + return ( + + ); +}; diff --git a/packages/vitnode/src/views/notifications/notification-avatar.tsx b/packages/vitnode/src/views/notifications/notification-avatar.tsx new file mode 100644 index 0000000000..f144166a51 --- /dev/null +++ b/packages/vitnode/src/views/notifications/notification-avatar.tsx @@ -0,0 +1,49 @@ +import { cn } from "cn"; +import { createElement } from "react"; + +import { Avatar } from "@/components/avatar"; + +import type { NotificationItemView } from "./notifications-query"; + +import { notificationTypeIcon } from "./notification-type-icon"; + +export const NotificationAvatar = ({ + item, + size = 36, + surface = "popover", +}: { + item: Pick; + size?: 36 | 40; + surface?: "background" | "popover"; +}) => { + const actor = item.actors.at(0); + const typeIcon = notificationTypeIcon(item); + + if (!actor) { + return ( + + ); + } + + return ( + + ); +}; diff --git a/packages/vitnode/src/views/notifications/notification-item.tsx b/packages/vitnode/src/views/notifications/notification-item.tsx index b279d6d358..9c782c813b 100644 --- a/packages/vitnode/src/views/notifications/notification-item.tsx +++ b/packages/vitnode/src/views/notifications/notification-item.tsx @@ -1,13 +1,14 @@ import { cn } from "cn"; -import { ArchiveIcon, BellOffIcon, MailIcon, MailOpenIcon } from "lucide-react"; +import { ArchiveIcon, MailIcon, MailOpenIcon } from "lucide-react"; import { useTranslations } from "use-intl"; -import { Avatar } from "@/components/avatar"; import { DateFormat } from "@/components/date-format"; import { Button } from "@/components/ui/button"; import type { NotificationItemView } from "./notifications-query"; +import { NotificationAvatar } from "./notification-avatar"; + export interface NotificationItemProps { item: NotificationItemView; onArchive?: (item: NotificationItemView) => void; @@ -16,7 +17,7 @@ export interface NotificationItemProps { variant?: "compact" | "full"; } -const isModifiedClick = (event: React.MouseEvent) => +export const isModifiedClick = (event: React.MouseEvent) => event.metaKey || event.ctrlKey || event.shiftKey || @@ -31,26 +32,13 @@ const NotificationItemContent = ({ variant: NonNullable; }) => { const t = useTranslations("core.global.notifications"); - const actor = item.actors.at(0); return ( <> - - {actor && item.available ? ( - - ) : ( - - {item.available ? ( - - ) : ( - - )} - - )} - + {item.title} @@ -128,7 +115,6 @@ export const NotificationItem = ({ onToggleRead, variant = "full", }: NotificationItemProps) => { - const linkTarget = item.available ? item.target : null; const content = ; return ( @@ -138,10 +124,10 @@ export const NotificationItem = ({ item.unread && "bg-primary/5", )} > - {linkTarget !== null ? ( + {item.target !== null ? ( { const newTab = isModifiedClick(event); if (!newTab) event.preventDefault(); diff --git a/packages/vitnode/src/views/notifications/notification-toast-banner.tsx b/packages/vitnode/src/views/notifications/notification-toast-banner.tsx new file mode 100644 index 0000000000..bccdc4b697 --- /dev/null +++ b/packages/vitnode/src/views/notifications/notification-toast-banner.tsx @@ -0,0 +1,68 @@ +import { cn } from "cn"; + +import { DateFormat } from "@/components/date-format"; + +import type { NotificationItemView } from "./notifications-query"; + +import { NotificationAvatar } from "./notification-avatar"; + +export const NOTIFICATION_TOAST_CLASS_NAME = + "rounded-2xl! p-3! bg-popover/70! backdrop-blur-xl! backdrop-saturate-150! [&>[data-close-button]]:z-10"; + +const splitTitle = (item: NotificationItemView) => { + const actor = item.actors.at(0); + if (!actor || item.actorCount > 1 || !item.title.startsWith(actor.name)) { + return { detail: null, heading: item.title }; + } + + const rest = item.title.slice(actor.name.length).trim(); + if (!rest) return { detail: null, heading: item.title }; + + return { + detail: rest.charAt(0).toLocaleUpperCase() + rest.slice(1), + heading: actor.name, + }; +}; + +export const NotificationToastBanner = ({ + item, + onOpen, +}: { + item: NotificationItemView; + onOpen: () => void; +}) => { + const { detail, heading } = splitTitle(item); + + return ( + + ); +}; diff --git a/packages/vitnode/src/views/notifications/notification-type-icon.ts b/packages/vitnode/src/views/notifications/notification-type-icon.ts new file mode 100644 index 0000000000..da72bb14cb --- /dev/null +++ b/packages/vitnode/src/views/notifications/notification-type-icon.ts @@ -0,0 +1,53 @@ +import { + AtSignIcon, + BanIcon, + BellIcon, + ClipboardCheckIcon, + ClockIcon, + FileTextIcon, + type LucideIcon, + MegaphoneIcon, + ReplyIcon, + ShieldAlertIcon, + ShieldCheckIcon, + ShieldIcon, + SmilePlusIcon, + UserRoundIcon, + UsersIcon, +} from "lucide-react"; + +const TYPE_ICONS: Record = { + "core.account_suspended": BanIcon, + "core.admin_message": MegaphoneIcon, + "core.mention": AtSignIcon, + "core.reaction_received": SmilePlusIcon, + "core.suspension_revoked": ShieldCheckIcon, + "core.warning_issued": ShieldAlertIcon, + "core.warning_revoked": ShieldCheckIcon, +}; + +const SUFFIX_ICONS: [suffix: string, icon: LucideIcon][] = [ + ["_reply", ReplyIcon], + ["_pending", ClockIcon], + ["_decision", ClipboardCheckIcon], +]; + +const CATEGORY_ICONS: Record = { + account: UserRoundIcon, + content: FileTextIcon, + moderation: ShieldIcon, + social: UsersIcon, + system: BellIcon, +}; + +export const notificationTypeIcon = ({ + category, + type, +}: { + category: string; + type: string; +}): LucideIcon => + TYPE_ICONS[type] ?? + SUFFIX_ICONS.find(([suffix]) => type.endsWith(suffix))?.[1] ?? + CATEGORY_ICONS[category] ?? + BellIcon; diff --git a/packages/vitnode/src/views/notifications/notifications-bell-content.tsx b/packages/vitnode/src/views/notifications/notifications-bell-content.tsx index 59c2f94691..b84ca07cf8 100644 --- a/packages/vitnode/src/views/notifications/notifications-bell-content.tsx +++ b/packages/vitnode/src/views/notifications/notifications-bell-content.tsx @@ -28,6 +28,7 @@ import { Skeleton } from "@/components/ui/skeleton"; import type { NotificationItemProps } from "./notification-item"; import type { NotificationItemView } from "./notifications-query"; +import { MarkAllReadConfirm } from "./mark-all-read-confirm"; import { NotificationItem } from "./notification-item"; const NOTIFICATIONS_HREF = "/notifications"; @@ -40,7 +41,7 @@ const formatUnreadBadge = (count: number): null | string => { }; export interface NotificationsBellContentProps { - onMarkAllRead: () => void; + onMarkAllRead: () => Promise; onOpenChange: (open: boolean) => void; onOpenItem: NotificationItemProps["onOpen"]; onRetry: () => void; @@ -97,15 +98,12 @@ export const NotificationsBellContent = ({
    {t("title")} - + + +
    diff --git a/packages/vitnode/src/views/notifications/notifications-query.ts b/packages/vitnode/src/views/notifications/notifications-query.ts index 36423ae8fa..fb43097ed5 100644 --- a/packages/vitnode/src/views/notifications/notifications-query.ts +++ b/packages/vitnode/src/views/notifications/notifications-query.ts @@ -1,12 +1,14 @@ import type { NotificationEmailMode } from "@vitnode/api/lib/notifications/types"; -import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query"; +import { keepPreviousData, queryOptions } from "@tanstack/react-query"; import { manifest } from "@vitnode/api/manifest"; +import { DEFAULT_TABLE_PAGE_SIZE } from "@/components/table/url-state"; import { OPERATIONAL_STALE_TIME, RECORD_STALE_TIME, } from "@/lib/query-freshness"; +import { readFirstValue, readPageSize } from "@/lib/table-params"; import { fetcher } from "@/tanstack/fetcher"; export interface NotificationActorView { @@ -21,7 +23,6 @@ export interface NotificationItemView { activitySeq: number; actorCount: number; actors: NotificationActorView[]; - available: boolean; body: null | string; category: string; createdAt: Date | string; @@ -57,32 +58,16 @@ export const NOTIFICATIONS_IDENTITY_ROOT = ["notifications", "user"] as const; export const notificationsListRoot = (userId: number) => [...NOTIFICATIONS_IDENTITY_ROOT, userId, "list"] as const; -export interface NotificationsListFilter { - category?: string; - unread?: boolean; -} - export const fetchNotificationsPage = async ({ - category, - cursor, limit, signal, - unread, -}: NotificationsListFilter & { - cursor?: null | string; +}: { limit: number; signal?: AbortSignal; }): Promise => { const response = await fetcher({ plugin: manifest.id, - args: { - query: { - category, - cursor: cursor ?? undefined, - limit, - unread: unread ? "true" : undefined, - }, - }, + args: { query: { limit } }, method: "get", module: "notifications", options: { signal }, @@ -93,32 +78,114 @@ export const fetchNotificationsPage = async ({ return await response.json(); }; -const NOTIFICATIONS_PAGE_SIZE = 20; const NOTIFICATIONS_RECENT_SIZE = 8; +const NOTIFICATIONS_MAX_PAGE_SIZE = 50; + +export const NOTIFICATIONS_TABLE_ORDER_BY = [ + "lastActivityAt", + "category", +] as const; +export type NotificationsTableOrderBy = + (typeof NOTIFICATIONS_TABLE_ORDER_BY)[number]; + +export const NOTIFICATIONS_TABLE_STATUSES = ["unread", "read"] as const; +export type NotificationsTableStatus = + (typeof NOTIFICATIONS_TABLE_STATUSES)[number]; + +const CATEGORY = /^[a-z0-9_-]{1,50}$/; + +/** The notifications table's request, as the `/inbox` route reads it. */ +export interface NotificationsTableParams { + category?: string; + first?: string; + order?: "asc" | "desc"; + orderBy?: NotificationsTableOrderBy; + page?: string; + status?: NotificationsTableStatus; +} + +export type RawNotificationsTableParams = Partial< + Record +>; + +/** Keeps only the table params the route accepts; page 1 and unknown values are dropped. */ +export const normalizeNotificationsTableParams = ( + raw: RawNotificationsTableParams = {}, +): NotificationsTableParams => { + const params: NotificationsTableParams = {}; + + const page = readFirstValue(raw.page); + if (/^[1-9]\d{0,8}$/.test(page) && page !== "1") params.page = page; + + params.first = + readPageSize(readFirstValue(raw.first), NOTIFICATIONS_MAX_PAGE_SIZE) ?? + String(DEFAULT_TABLE_PAGE_SIZE); + + const orderBy = readFirstValue(raw.orderBy) as NotificationsTableOrderBy; + if (NOTIFICATIONS_TABLE_ORDER_BY.includes(orderBy)) params.orderBy = orderBy; + + const order = readFirstValue(raw.order); + if (order === "asc" || order === "desc") params.order = order; + + const status = readFirstValue(raw.status) as NotificationsTableStatus; + if (NOTIFICATIONS_TABLE_STATUSES.includes(status)) params.status = status; + + const categories = [ + ...new Set( + readFirstValue(raw.category) + .split(",") + .filter(value => CATEGORY.test(value)), + ), + ]; + if (categories.length > 0) params.category = categories.join(","); + + return params; +}; + +export interface NotificationsTablePage { + edges: NotificationItemView[]; + pageInfo: { + count: number; + currentPage: null | number; + endCursor: null | string; + hasNextPage: boolean; + hasPreviousPage: boolean; + pageSize: number; + startCursor: null | string; + totalCount: number; + totalPages: number; + }; +} + +export const fetchNotificationsTablePage = async ( + params: NotificationsTableParams, + { signal }: { signal?: AbortSignal } = {}, +): Promise => { + const response = await fetcher({ + plugin: manifest.id, + args: { query: params }, + method: "get", + module: "notifications", + options: { signal }, + path: "/inbox", + }); + if (!response.ok) throw new NotificationsRequestError(response.status); + + return await response.json(); +}; -export const notificationsInfiniteQueryOptions = ({ - filter, +export const notificationsTableQueryOptions = ({ + params, userId, }: { - filter: NotificationsListFilter; + params: NotificationsTableParams; userId: number; }) => - infiniteQueryOptions({ - getNextPageParam: (page: NotificationsPage) => page.nextCursor ?? undefined, - initialPageParam: null as null | string, - queryFn: async ({ pageParam, signal }) => - await fetchNotificationsPage({ - ...filter, - cursor: pageParam, - limit: NOTIFICATIONS_PAGE_SIZE, - signal, - }), - queryKey: [ - ...notificationsListRoot(userId), - "page", - filter.unread ? "unread" : "all", - filter.category ?? "", - ] as const, + queryOptions({ + placeholderData: keepPreviousData, + queryFn: async ({ signal }) => + await fetchNotificationsTablePage(params, { signal }), + queryKey: [...notificationsListRoot(userId), "table", params] as const, retry: false, staleTime: OPERATIONAL_STALE_TIME, }); diff --git a/plans/mentions.md b/plans/mentions.md new file mode 100644 index 0000000000..a10a28e206 --- /dev/null +++ b/plans/mentions.md @@ -0,0 +1,470 @@ +# Mentions (`@nick`) + +Status: implemented (phases 1-5); tests still to write in a separate session. +Owner: core (`@vitnode/api` + `@vitnode/core`). + +## Implemented differently from this plan + +- **Per-role cap, not a global setting.** `core_roles.maxMentionsPerItem` + (default 25, `null` = unlimited) sits next to `allowMentions` in **Edit role + → Content**. There is no `mentions.maxNotifiedPerItem` in Settings. +- **Retraction recounts groups.** `notifications.remove()` deletes whole inbox + items, so a removed mention detaches its own event instead + (`detachNotificationEvents`, event id stored in `core_mentions.eventId`): a + grouped "Anna and 1 other person" drops back to "Anna". The type's `access` + also requires the `core_mentions` row, so an event retracted before its + fan-out never reaches anyone. +- **One hook for every write path.** `emitContentEvent` queues a + `content-mentions` task (created, updated with a mention field in + `changedFields`, published, unhidden, translation writes, deleted) instead + of `recordContentMentions` at each call site. The task reloads the record, + skips it unless public, and calls `syncMentions`. Approvals and scheduled + publishes go through `emitContentEvent` too. +- **Actor is the record's author** (search author field, else the public + write owner), so a moderator's edit or approval still notifies as the + author, with the author's role policy. +- **Titles and links** come from the type's `threadReply` rule for replies, + otherwise from the record's search entry or row (as reaction timelines do). +- **No server-side `resolveMentionedUsers`.** Emails and RSS don't render rich + text today, so only the browser resolves current names + (`GET /users/mentioned`, batched across the page in one request). +- **Suggestions leave out the member typing.** No extra indexes on + `core_users` yet; the search is `ILIKE` with a prefix rank. +- **Not done yet:** the daily cleanup cron for rows of records deleted by a + cascade (their notifications are already hidden by `access`), the slash-menu + item, mentions in rich-text fields nested inside a `field.group`, and + thread participants first in the popup. + +Type `@` in any rich-text editor (on by default), pick a member from the +popup, and the post shows `@Name` as a link with the user preview card. Once the +post is public and readable by that member, they get a **"Anna mentioned you in +…"** notification (in-app, email optional). + +## Goals + +1. **One mention node for every editor.** Comments, forum topics, blog posts, + newsroom articles and the AdminCP live editor all use the same TipTap node, + the same popup and the same stored shape. +2. **On by default, opt-out per field.** Every `field.richText()` and every + `AutoFormEditor` / `TipTapEditor` supports mentions with no config. A field + that shouldn't have them turns them off: `field.richText({ mentions: false })` + on the server and `mentions={false}` on the editor. +3. **Notify once, only people who can read it.** A member is notified the first + time a public record mentions them. Edits notify only newly added people. + Drafts, pending approval, hidden records and records the member can't read + notify nobody. +4. **Plugins outside the Content Engine can use it too**, through + `defineMentionTarget`, like `defineReactionTarget`. + +## What already exists (and what we reuse) + +| Piece | Where | How we use it | +| ------------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| TipTap 3 + `@tiptap/suggestion` | `packages/vitnode/src/components/tiptap/*` | The `@` popup copies the emoji `:` popup (`emoji/emoji-suggestion.ts`, `suggestion-popup.ts`, `useActiveDescendant`). | +| Extension list | `components/tiptap/extension.ts` (`createTipTapExtensions`) | Mention node added here, so `richTextDocumentFromHtml` round-trips it too. | +| Stored JSON | `@vitnode/api/content/rich-text/document.ts` | No allow-list on save: a `mention` node already passes validation. No schema change needed. | +| Render allow-list | `content/rich-text/elements.ts` (`richTextNodeElement`) | New `case "mention"`. Today an atom `mention` renders **nothing** (unknown nodes render only children). | +| Plain text | `content/rich-text/plain-text.ts` | Already prints `attrs.label` for unknown inline nodes; change it to `@label` for `mention`. | +| Email/RSS HTML | `content/rich-text/html.ts` (`richTextToHtml`) | New `mention` case (absolute profile link). Today it renders nothing. | +| File-id walker | `content/access/server/files.ts` (`richTextFileIdsOf`) | Same walker shape for `richTextMentionsOf`. | +| Preview card | `components/user-preview.tsx` (`UserPreview`) | Mentions render through it (listed as "possible later" in `user-preview-card.md`). | +| Notifications | `buildNotificationType`, `c.get("notifications").publish` | New core type `core.mention`; settings page, AdminCP policy and email channel come for free. | +| CE notification intents | `content/server/notifications/intents.ts`, `process.ts` | New durable intent `mentions`, processed by the same task, under the same public-state checks. | +| CE read access | `contentNotificationAccess({ policy: "content" })` | Filters recipients on delivery, before every email and on every inbox load. | +| Reaction targets | `lib/reactions/targets.ts`, `content/server/reaction-target.ts` | The pattern for `defineMentionTarget` + automatic `contentMentionTarget` per content type. | + +Missing today: a member-facing user search (`/search/authors` only finds +authors of public content, `/moderation/members` is staff-only), a CE trigger on +**edit**, and any block/ignore feature. + +## Decisions + +- **Official `@tiptap/extension-mention`** (`^3.33.0`, same line as the other + TipTap packages, added to `packages/vitnode` only), extended with one attr. + Writing our own node on top of `Suggestion` buys nothing. +- **Stored node:** + + ```json + { + "type": "mention", + "attrs": { "id": 42, "label": "Anna Nowak", "nameCode": "anna-nowak" } + } + ``` + + `id` is the source of truth for everything: notifications, extraction **and + the link**. `label` and `nameCode` are only a fallback snapshot - for the + first paint, plain text and the search index. +- **Links resolve by `id`, so renames never break them.** The renderer looks up + the current `name` and `nameCode` of every mentioned id in one batched call + (`GET /users/mentioned?ids=`, see Server §2b) and links to + `/profile/{current nameCode}` with the current name. Until the lookup answers + it shows the snapshot (no skeleton - the snapshot is real content). A deleted + member renders as plain `@label` text with no link. No nameCode history table. +- **Validated at render, not trusted.** The renderer drops the link (keeps + `@label` as text) unless `id` is a positive integer and `nameCode` matches the + nameCode pattern. `label` is text only, capped at 255 chars. +- **Roles decide who can mention, with no daily limit.** New role setting + `allowMentions` (default `true`, guests `false`), the most generous of the + primary and secondary roles wins. A member without it gets no `@` popup, + `GET /users/mentions` answers `403`, and their mentions still render as links + but notify nobody (checked in `syncMentions` on the actor). +- **Anyone can be picked, only readers are notified.** The popup doesn't check + access to the current record. `syncMentions` stores every mentioned member but + publishes only to those the target's `access` lets read it; fan-out, every + inbox load and every email check `access` again, so a member who loses + access later stops seeing the notification. +- **On by default.** The server scans every rich-text field except those with + `mentions: false`; a mention node pasted into an opted-out field still renders + as a profile link but notifies nobody. The editor shows the `@` popup unless + `mentions={false}`. Rich text outside the Content Engine (warnings, report + notes, plugin tables) gets the popup and rendering too, but notifies only + where that feature calls `syncMentions` with its own target - a mention never + notifies through a target that can't check read access. +- **Two switches, not one.** The form can't read the server's field config, so + an opted-out field sets `mentions: false` on the field **and** + `mentions={false}` on its `AutoFormEditor`. Forgetting the editor side only + shows a popup whose mentions don't notify - never a leak. +- **One row per (target, user)** in `core_mentions`, mirroring the mentions in + the current text. Insert `ON CONFLICT DO NOTHING RETURNING` decides who is + new, so saves and retries never notify twice. +- **Removing a mention retracts its notification.** Users in `core_mentions` + but no longer in the text lose their row and their notification + (their event is detached, so a grouped item is recounted), read or not. An email that + already went out can't be unsent. Adding them back later is a new mention and + notifies again - the idempotency key is the new row's id, so the old key + doesn't swallow it. +- **The worker re-reads the record.** The intent carries ids only; the worker + loads the current row, checks it is public, extracts mentions from the current + values (all published translations of a localized field) and diffs against + `core_mentions`. A stale intent can't notify about text that was removed. +- **Cap: 10 notified members per record** (`mentions.maxNotifiedPerItem`, + AdminCP → Settings → Content, 0 = no cap). This is spam protection for one + post, not a limit on mentioning: more mentions still render, and the rest are + stored with `notified = false`. Only members who pass `access` count. +- **No double notification for a reply.** When the record also triggers a + `threadReply` notification, the mention worker skips the users that rule + already notifies (root and parent authors). +- **Suggestions need a signed-in member.** Guests get no popup (the extension + isn't loaded), so the endpoint never helps enumerate members anonymously. +- **Self-mentions render but don't notify** (`publish` already drops the actor). + +## Data model + +### `packages/api/src/database/mentions.ts` + +```ts +export const core_mentions = pgTable( + "core_mentions", + t => ({ + id: t.serial().primaryKey(), + pluginId: t.varchar({ length: 100 }).notNull(), + targetType: t.varchar({ length: 100 }).notNull(), // content type id or custom target id + targetId: t.integer().notNull(), + userId: t.integer().notNull().references(() => core_users.id, { onDelete: "cascade" }), + actorId: t.integer().references(() => core_users.id, { onDelete: "set null" }), + notified: t.boolean().notNull().default(false), + createdAt: t.timestamp().notNull().defaultNow(), + }), + t => [ + uniqueIndex().on(t.pluginId, t.targetType, t.targetId, t.userId), + index().on(t.userId, t.createdAt), // "mentions of me" later + ], +); +``` + +Polymorphic target, so no FK to it: CE delete effects remove the rows, and a +daily `mentions-cleanup` cron (like `reactions-cleanup`) removes rows of records +deleted by a cascade. + +### Changes to existing tables + +- `core_roles.allowMentions boolean not null default true`; the seed sets it to + `false` for the guest role. +- Two indexes for the suggestion search on `core_users`: + `lower(name_code) text_pattern_ops` and `lower(name) text_pattern_ops`. + +## Server + +### 1. Pure helpers (`@vitnode/api/content/rich-text/mentions.ts`, browser-safe) + +- `richTextMentionsOf(doc): { id: number; label: string; nameCode: string }[]` + - unique by `id`, document order, invalid attrs skipped. +- `MENTION_NODE = "mention"` and the attr schema, shared by the editor and the + renderer. + +### 2. Suggestions: `GET /users/mentions?search=&limit=` + +- Core `users` module, requires a user session and `allowMentions` on one of + the member's roles (`403` otherwise), `search` rate-limit category. +- No access check against the record being written - every active member can + be suggested (decided; notifications filter by access instead). +- Matches `nameCode` prefix first, then `name` prefix, then `name` contains; + skips deleted and banned members; `limit` default 6, max 10; `search` 1–64 + chars. +- Returns `{ id, name, nameCode, avatarColor, avatarUrl }[]` (the + `search/authors` shape, so the list row is the same component). +- `Cache-Control: private, max-age=30`. +- Phase 2: optional `context={contentTypeId}:{rootId}` that puts thread + participants first, and an empty `search` that returns only them. + +### 2b. Current names: `GET /users/mentioned?ids=` + +- Core `users` module, public (guests read posts too), `ids` 1–50 positive + integers, deduped and sorted so the cache key is stable. +- Returns `{ id, name, nameCode }[]` for active members only; a missing id means + deleted, and the renderer falls back to plain `@label`. Nothing private: the + same fields as the public profile. +- `Cache-Control: public, max-age=300` plus the API cache keyed by the sorted + ids, invalidated per user on rename / delete. +- Server-side twin `resolveMentionedUsers(c, ids)` (same query) for output with + no browser: email (`richTextToHtml`) and RSS. + +### 3. Mention targets (`@vitnode/api/mentions`) + +```ts +export const defineMentionTarget = (def: { + id: string; // plugin-scoped, like reaction targets + /** Members of `userIds` who may read the target now. Batched. */ + access: (args: { c: Context; id: TId; userIds: number[] }) => Promise; + /** Title and same-site URL for the notification, or null when gone. */ + preview: (args: { c: Context; id: TId }) => Promise<{ title: string; url: string } | null>; +}) => def; + +/** + * Make `core_mentions` mirror the mentions in `documents`: store and notify + * new readers, retract removed ones. Idempotent. + */ +export const syncMentions = async (args: { + c: Context; + target: MentionTarget; + id: number; + actorId: number; + documents: RichTextDocument[]; + exclude?: number[]; + tx?: Transaction; +}) => { /* see steps below */ }; +``` + +`syncMentions` in one transaction: + +1. Extract ids from `documents` (`richTextMentionsOf`), drop the actor and + deleted members. +2. **Removed**: rows not in the text → delete, then + `notifications.remove({ subject, userIds })`. +3. **New**: insert `ON CONFLICT DO NOTHING RETURNING id, user_id`. +4. If the actor's roles lack `allowMentions`, stop here (rows kept, nobody + notified - if they gain it later, only mentions added after that notify). +5. Filter the new users through `target.access`, drop `exclude`, apply the cap, + set `notified = true` and publish one `core.mention` event per user. +6. Emit `mention.created` / `mention.removed` after commit. + +Registered through `buildApiPlugin({ mentionTargets })`; every content type with +at least one rich-text field not opted out gets +`contentMentionTarget(model, pluginId)` +automatically (access = `contentNotificationAccess({ policy: "content" })`, +preview = the same title/URL the reaction target uses). + +### 4. Content Engine + +- `mentions?: boolean` (default `true`) on `field.richText()` in + `content/fields.ts`, with JSDoc saying it is on by default and how to opt + out. Existing content types get mentions without a code change. +- New intent `recordContentMentions({ tx, contentTypeId, contentId, actorId })` + in `notifications/intents.ts`, recorded inside the write transaction **only + when a rich-text field with mentions changed or the record just became + public** (a title-only edit records nothing): + - `public-write-service.ts` create (L605) and update (L742), next to + `assertRichTextFileOrigins`; + - `editorial-service.ts` where first publication and published revisions are + committed; + - admin plain writes (`routes.ts` create/update) and `localized-admin-routes.ts`; + - `schedule-effects.ts` (scheduled publish) and the moderation approval path + (`recordContentModerationDecision` with an approved decision) - a record + that was pending at save time is checked again when it goes public. +- `processContentMentionsIntent` in `process.ts`: reload under `FOR SHARE`, + skip unless public, extract, exclude `threadReply` recipients, call + `syncMentions` in one transaction. +- Delete: `recordContentNotificationCleanup` also deletes `core_mentions` rows + of the record (the notifications themselves are detached by subject already). + +### 5. Notification type `core.mention` (`lib/notifications/core-types.ts`) + +```ts +export const mentionNotification = buildNotificationType({ + id: "core.mention", + version: 1, + category: "social", + label: "core.notifications.types.mention.label", + description: "core.notifications.types.mention.desc", + schema: z.object({ + pluginId: z.string(), + targetType: z.string(), + targetId: z.number().int(), + rootId: z.number().int().nullable(), + title: z.string(), + url: z.string().nullable(), + }), + defaults: { inApp: true, email: "immediate" }, + email: true, + grouping: { key: ({ data }) => `${data.pluginId}:${data.targetType}:${data.rootId ?? data.targetId}`, windowMinutes: 60 }, + access: mentionTargetAccess, // groups by target, delegates to each target's access + present: ({ actorCount, actors, data, t }) => ({ + title: t("core.notifications.types.mention.title", { + count: actorCount, + name: actors[0]?.name ?? t("core.notifications.someone"), + title: data.title, + }), + target: data.url, + }), +}); +``` + +- Idempotency key `mention:{core_mentions.id}` (one event per new mention row, + ≤ 10 per record). A retried worker reuses the row, so it can't notify twice; + a mention removed and added back gets a new row, so it notifies again. +- Subject `{ type: "mention", id: "{pluginId}:{targetType}:{targetId}" }`, so + retraction removes exactly this record's mention for the given users. Check + in phase 3 that `remove()` on one event of a grouped inbox row recounts the + group ("Anna and 2 others") instead of dropping the whole row. +- Copy in `packages/api/src/locales/en.json` (+ the other locales): + - `title`: `{count, plural, one {{name} mentioned you in "{title}"} other {{name} and # others mentioned you in "{title}"}}` + - `label`: "Mentions", `desc`: "When someone mentions you with @." +- The member settings page and the AdminCP **Notifications → Types** policy pick + the type up automatically. + +### 6. Events (`packages/api/src/events/mentions.ts`) + +- `mention.created` - `{ pluginId, targetType, targetId, actorId, users: + { id, notified }[] }`, emitted after commit for the newly stored mentions + (also the ones over the cap or without access, with `notified: false`). +- `mention.removed` - `{ pluginId, targetType, targetId, actorId, userIds }`, + emitted after commit when an edit removes mentions (their notifications are + already retracted). +- Documented in `apps/web/content/docs/dev/events/built-in-events.mdx`. + +## Front end + +### Editor (`packages/vitnode/src/components/tiptap/mention/`) + +- `mention-extension.ts` - `Mention.extend({ addAttributes: nameCode })` + configured with `char: "@"`, `allowSpaces: false`, + `deleteTriggerWithBackspace: true`, `renderText: "@" + label`, and a + `suggestion` built like `emojiSuggestion`. +- `mention-suggestion.ts` - `items: ({ query }) => + queryClient.query(userMentionsQueryOptions(query))` with a 150 ms debounce; + the `queryClient` comes from `useQueryClient()` in `TipTapEditor` through the + extension options. Results are cached by query, so typing back and forth + doesn't refetch. +- `mention-suggestion-list.tsx` - the popup (`SUGGESTION_POPUP_CLASS`): + - row = `Avatar` (24px) + name + muted `@nameCode`, `role="option"`, + keyboard ↑ ↓ Enter Tab Esc, `useActiveDescendant` on the editor; + - loading: 3 skeleton rows of the same size, `aria-busy`, one sr-only + `role="status"`; + - empty query: hint row "Type a name" (phase 2: thread participants); + - no match: "No members found"; + - error: inline message with `role="alert"` and a **Try again** button + (`RotateCwIcon`) that refetches in place. +- In the editor the node renders as an inline chip (`text-primary + font-medium`, `bg-primary/10`, rounded), not a link, so clicking it doesn't + navigate away from a draft. +- `createTipTapExtensions({ mentions })` adds the node **always** (so existing + mentions keep parsing and rendering in any editor) but the `@` suggestion + only when `mentions` is on (the default), a user is signed in and one of + their roles has `allowMentions` (read from the session's permissions, the + same place `canReact` comes from). +- `AutoFormEditor` and `TipTapEditor` get `mentions?: boolean`, default `true`. + No plugin changes needed: core comments, forum, blog, newsroom, ModCP and the + AdminCP collaborative editor (atom nodes sync through Yjs as is) all get the + popup. `mentions={false}` only where a field opts out on the server. +- Toolbar: no button; the slash menu gets **Mention someone** (inserts `@`). + +### Rendering + +- `richTextNodeElement` (`@vitnode/api/content/rich-text/elements.ts`): + `case "mention"` → `@{name}`, + taking `name` / `nameCode` from an optional resolved map and falling back to + the snapshot attrs. +- `RichTextContent` collects the mention ids of its document once (memoized + `richTextMentionsOf`) and runs one `useQuery(mentionedUsersQueryOptions(ids))` + (`GET /users/mentioned`, `staleTime` 5 min, no query when there are no + mentions). Default `nodes.mention` → `` with + `@{current name}`; snapshot while pending, plain `@label` text when the id is + gone. A failed lookup keeps the snapshot - mentions are never blanked. Every + existing caller (comments, forum, blog, newsroom, ModCP snapshots) gets this + without changes. +- `richTextToHtml` takes the same resolved map from `resolveMentionedUsers`, + so emails and RSS link to the current profile URL (absolute). +- `richTextToPlainText` → `@label` (excerpts, search index, notification + bodies, audit diffs). + +## AdminCP + +- **Settings → Content**: "Notify up to N mentioned members per post" + (`mentions.maxNotifiedPerItem`, default 10, 0 = no cap). Sheet + `AutoForm`, + toast after save. +- **Roles → edit role**: a **Can mention members** switch (`allowMentions`) in + the role's content permissions, saved with the role form. No daily limit. +- **Notifications → Types**: `core.mention` appears on its own. + +## Docs + +- `apps/web/content/docs/dev/mentions.mdx` - mentions are on by default, + turning them off for a field (`field.richText({ mentions: false })` + + `AutoFormEditor mentions={false}`), custom + targets with `defineMentionTarget` / `syncMentions`, and what notifies when. +- Content Engine field reference: the `mentions` option. +- Member guide: mentioning someone and turning mention emails off. +- AdminCP guide (roles): the **Can mention members** switch. +- `built-in-events.mdx`: `mention.created`, `mention.removed`. +- JSDoc on `defineMentionTarget`, `syncMentions`, `richTextMentionsOf`, the + `mentions` field option and the `mentions` editor prop. + +## Phases + +1. **Node + rendering** - `@tiptap/extension-mention`, `richTextMentionsOf`, + render cases (React, HTML, email, plain text), `UserPreview` in + `RichTextContent`. +2. **Suggestions + current names** - `GET /users/mentions`, + `GET /users/mentioned` + `resolveMentionedUsers`, indexes, popup with + skeleton/empty/error states, `mentions` prop (default `true`) on the + editors, `core_roles.allowMentions` + role switch. +3. **Storage + notifications** - `core_mentions` + migration, + `defineMentionTarget`, `syncMentions` (add, notify, retract), + `core.mention` type, `mention.created` / `mention.removed` events, cap + setting. +4. **Content Engine** - `field.richText({ mentions })`, `contentMentionTarget`, + `recordContentMentions` at every write path, worker, delete cleanup + cron, + `threadReply` de-duplication. Comments, forum topics, blog posts and + newsroom content get it with no plugin change. +5. **Docs**. +6. **Later** - thread participants first in the popup, a "Mentions" filter in + the notification inbox, a mentions tab on the profile timeline. + +Tests (separate session, after it works): `richTextMentionsOf` (dedupe, order, +invalid attrs), the renderer (bad `nameCode`/`id` → plain text, renamed +member → current name and link, deleted member → plain text, failed lookup → +snapshot), `GET /users/mentions` (401 for guests, 403 without +`allowMentions`, ordering, banned/deleted skipped, limit), +`GET /users/mentioned` (id limits, deleted ids missing), `syncMentions` (new +vs existing rows, cap counts only readers, self, idempotent retry, actor +without `allowMentions` notifies nobody, removed mention retracts, removed and +re-added notifies again), the CE worker (draft / pending / hidden / unreadable +recipient notify nobody, edit notifies only new members, approval later +notifies, reply authors not notified twice, localized fields), and the +suggestion list (keyboard, select inserts a node, error retry). + +## Decided + +- **Renamed members** → links resolve by `id` (`GET /users/mentioned`); no + nameCode history. +- **Permission** → role switch `allowMentions`, no daily limit. +- **Default email** → `immediate`. +- **Removing a mention** → retracts its notification. +- **Popup and access** → the popup suggests everyone; only members who can + read the record are notified. + +## Open questions + +- **Block / ignore.** VitNode has no ignore feature. When it lands, ignored + members should be filtered in `syncMentions` (and probably hidden from the + popup). diff --git a/plugins/blog/src/pages/post-comments.tsx b/plugins/blog/src/pages/post-comments.tsx index 43bc3e8933..4cd05ab11e 100644 --- a/plugins/blog/src/pages/post-comments.tsx +++ b/plugins/blog/src/pages/post-comments.tsx @@ -21,6 +21,7 @@ import { ContentCommentsComposer, ContentCommentsLiveStatus, ContentCommentsLoadMore, + ContentCommentsNewSeparator, ContentCommentsRoot, } from "@vitnode/core/tanstack/comments"; import { reactionSummaryQueryOptions } from "@vitnode/core/tanstack/reactions"; @@ -261,11 +262,27 @@ const subscribeToHash = (onChange: () => void) => { const linksToComment = () => window.location.hash.startsWith(`#${CONTENT_COMMENT_ANCHOR_PREFIX}`); +const ConversationRows = ({ + firstNewId, + nodes, +}: { + firstNewId: CommentTreeNode["id"] | undefined; + nodes: readonly CommentTreeNode[]; +}) => + nodes.map(node => ( + + {node.id === firstNewId ? : null} + + + )); + const CommentList = ({ + newCommentIds, reactionTarget, tree, viewerId, }: { + newCommentIds: readonly CommentTreeNode["id"][]; reactionTarget: (id: number) => ContentTarget | null; tree: readonly CommentTreeNode[]; viewerId: null | number; @@ -296,6 +313,8 @@ const CommentList = ({ const head = hiddenCount > 0 ? visible.slice(0, HEAD_COUNT + revealed) : visible; const tail = hiddenCount > 0 ? visible.slice(-TAIL_COUNT) : []; + const newIdSet = new Set(newCommentIds); + const firstNewId = visible.find(node => newIdSet.has(node.id))?.id; const revealMore = () => { const firstNew = visible[head.length]?.record; @@ -360,17 +379,13 @@ const CommentList = ({ isRanking && "opacity-60", )} > - {head.map(node => ( - - ))} + {hiddenCount > 0 ? ( <>
      - {tail.map(node => ( - - ))} +
    ) : null} @@ -477,6 +492,7 @@ const PostCommentsThread = ({ ) : (