Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add workspace document likes (#18999)

Rdmclin26812aba64dad
diff --git a/apps/server/src/routers/lambda/__tests__/integration/documentLike.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/documentLike.integration.test.ts
new file mode 100644
index 00000000000..86455fda1aa
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/documentLike.integration.test.ts
@@ -0,0 +1,190 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { documentLikes, documents, workspaceMembers, workspaces } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { documentLikeRouter } from '../../documentLike';
+import { cleanupTestUser, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+const notifyDocumentLiked = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+const revokeDocumentLikeNotification = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => testDB) }));
+vi.mock('@/business/server/document-like/notifyActivity', () => ({
+ notifyDocumentLiked,
+ revokeDocumentLikeNotification,
+}));
+const publishResourceEvent = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));
+vi.mock('@/server/services/resourceEvents', () => ({ publishResourceEvent }));
+const afterResponseTasks = vi.hoisted(() => [] as Promise<unknown>[]);
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({
+ after: (work: () => unknown) => void afterResponseTasks.push(Promise.resolve().then(work)),
+}));
+
+const flushAfterResponse = async () => {
+ while (afterResponseTasks.length > 0) await Promise.all(afterResponseTasks.splice(0));
+};
+
+const context = (userId: string, workspaceId?: string) => ({
+ jwtPayload: { userId },
+ userId,
+ workspaceId,
+});
+
+describe('documentLikeRouter integration', () => {
+ let db: LobeChatDatabase;
+ let documentId: string;
+ let memberId: string;
+ let outsiderId: string;
+ let ownerId: string;
+ let viewerId: string;
+ let workspaceId: string;
+
+ beforeEach(async () => {
+ notifyDocumentLiked.mockClear();
+ revokeDocumentLikeNotification.mockClear();
+ publishResourceEvent.mockClear();
+ db = await getTestDB();
+ testDB = db;
+ [ownerId, memberId, viewerId, outsiderId] = await Promise.all([
+ createTestUser(db),
+ createTestUser(db),
+ createTestUser(db),
+ createTestUser(db),
+ ]);
+ const [workspace] = await db
+ .insert(workspaces)
+ .values({ name: 'Document likes', primaryOwnerId: ownerId, slug: `dl-${ownerId}` })
+ .returning();
+ workspaceId = workspace.id;
+ await db.insert(workspaceMembers).values([
+ { role: 'owner', userId: ownerId, workspaceId },
+ { role: 'member', userId: memberId, workspaceId },
+ { role: 'viewer', userId: viewerId, workspaceId },
+ ]);
+ const [document] = await db
+ .insert(documents)
+ .values({
+ fileType: 'custom',
+ source: `document-${ownerId}`,
+ sourceType: 'api',
+ title: 'Likeable document',
+ totalCharCount: 0,
+ totalLineCount: 0,
+ userId: ownerId,
+ workspaceId,
+ })
+ .returning();
+ documentId = document.id;
+ });
+
+ afterEach(async () => {
+ await flushAfterResponse();
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await Promise.all(
+ [ownerId, memberId, viewerId, outsiderId].map((id) => cleanupTestUser(db, id)),
+ );
+ });
+
+ it('lets members and viewers like, notifies the author once, and withdraws on unlike', async () => {
+ const member = documentLikeRouter.createCaller(context(memberId, workspaceId));
+ const viewer = documentLikeRouter.createCaller(context(viewerId, workspaceId));
+ const owner = documentLikeRouter.createCaller(context(ownerId, workspaceId));
+
+ await expect(member.summary({ documentId })).resolves.toEqual({
+ liked: false,
+ likers: [],
+ total: 0,
+ });
+
+ const liked = await member.like({ documentId });
+ expect(liked.liked).toBe(true);
+ expect(liked.total).toBe(1);
+ expect(liked.likers.map(({ id }) => id)).toEqual([memberId]);
+
+ // Idempotent retry: no second notification or event.
+ await member.like({ documentId });
+ const viewerLiked = await viewer.like({ documentId });
+ expect(viewerLiked.total).toBe(2);
+ await flushAfterResponse();
+
+ expect(notifyDocumentLiked).toHaveBeenCalledTimes(2);
+ expect(notifyDocumentLiked).toHaveBeenCalledWith({
+ actorUserId: memberId,
+ documentId,
+ recipientUserId: ownerId,
+ workspaceId,
+ });
+ expect(publishResourceEvent).toHaveBeenCalledTimes(2);
+ expect(publishResourceEvent).toHaveBeenCalledWith(
+ { id: documentId, type: 'document' },
+ { actorId: memberId, type: 'document.likesChanged' },
+ );
+
+ const ownerView = await owner.summary({ documentId });
+ expect(ownerView.liked).toBe(false);
+ expect(ownerView.total).toBe(2);
+
+ const unliked = await member.unlike({ documentId });
+ expect(unliked).toMatchObject({ liked: false, total: 1 });
+ await member.unlike({ documentId });
+ await flushAfterResponse();
+
+ expect(revokeDocumentLikeNotification).toHaveBeenCalledTimes(1);
+ expect(revokeDocumentLikeNotification).toHaveBeenCalledWith({
+ actorUserId: memberId,
+ documentId,
+ recipientUserId: ownerId,
+ workspaceId,
+ });
+ expect(publishResourceEvent).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not notify the author for their own like', async () => {
+ const owner = documentLikeRouter.createCaller(context(ownerId, workspaceId));
+ await owner.like({ documentId });
+ await owner.unlike({ documentId });
+ await flushAfterResponse();
+
+ expect(notifyDocumentLiked).not.toHaveBeenCalled();
+ expect(revokeDocumentLikeNotification).not.toHaveBeenCalled();
+ expect(publishResourceEvent).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not notify an author who was removed from the workspace', async () => {
+ await db
+ .update(workspaceMembers)
+ .set({ deletedAt: new Date() })
+ .where(eq(workspaceMembers.userId, ownerId));
+
+ const member = documentLikeRouter.createCaller(context(memberId, workspaceId));
+ const liked = await member.like({ documentId });
+ expect(liked.total).toBe(1);
+ await flushAfterResponse();
+
+ // The like lands, but the stale author id must not receive workspace
+ // content (the notification carries the document title).
+ expect(notifyDocumentLiked).not.toHaveBeenCalled();
+
+ // Withdrawal is cleanup, not disclosure — it still reaches the inbox.
+ await member.unlike({ documentId });
+ await flushAfterResponse();
+ expect(revokeDocumentLikeNotification).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects non-members and documents outside the workspace', async () => {
+ const outsider = documentLikeRouter.createCaller(context(outsiderId, workspaceId));
+ await expect(outsider.like({ documentId })).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(outsider.summary({ documentId })).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ const member = documentLikeRouter.createCaller(context(memberId, workspaceId));
+ await expect(member.like({ documentId: 'missing-document' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+
+ expect(await db.select().from(documentLikes)).toEqual([]);
+ expect(notifyDocumentLiked).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/documentLike.ts b/apps/server/src/routers/lambda/documentLike.ts
new file mode 100644
index 00000000000..71f2cf9ec00
--- /dev/null
+++ b/apps/server/src/routers/lambda/documentLike.ts
@@ -0,0 +1,243 @@
+import { TRPCError } from '@trpc/server';
+import { and, eq, isNull } from 'drizzle-orm';
+import { z } from 'zod';
+
+import type { DocumentLikeActivityParams } from '@/business/server/document-like/notifyActivity';
+import {
+ notifyDocumentLiked,
+ revokeDocumentLikeNotification,
+} from '@/business/server/document-like/notifyActivity';
+import { wsProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import {
+ DOCUMENT_LIKE_DOCUMENT_NOT_FOUND,
+ DocumentLikeModel,
+} from '@/database/models/documentLike';
+import { RbacModel } from '@/database/models/rbac';
+import { documentLikes, workspaceMembers } from '@/database/schemas';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { publishResourceEvent } from '@/server/services/resourceEvents';
+import {
+ assertCanPerformResourceAction,
+ canPerformResourceAction,
+ getResourceMeta,
+} from '@/server/services/resourcePermission';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+const documentIdSchema = z.object({ documentId: z.string().trim().min(1).max(255) });
+
+const documentLikeProcedure = wsProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
+ let permissionCodes: Promise<string[]> | undefined;
+ const getPermissionCodes = () => {
+ permissionCodes ??= Promise.all([
+ ctx.serverDB
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, ctx.workspaceId),
+ eq(workspaceMembers.userId, ctx.userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ )
+ .limit(1),
+ new RbacModel(ctx.serverDB, ctx.userId).getUserPermissions({ workspaceId: ctx.workspaceId }),
+ ]).then(([membership, codes]) => (membership[0] ? codes : []));
+ return permissionCodes;
+ };
+
+ return next({
+ ctx: {
+ documentLikeModel: new DocumentLikeModel(ctx.serverDB, ctx.userId, ctx.workspaceId),
+ getDocumentLikePermissionCodes: getPermissionCodes,
+ },
+ });
+});
+
+interface LikeContext {
+ getDocumentLikePermissionCodes: () => Promise<string[]>;
+ serverDB: Parameters<typeof assertCanPerformResourceAction>[0]['db'];
+ userId: string;
+ workspaceId: string;
+}
+
+/**
+ * Liking is a read-level social action: any active member who can view the
+ * document may like it, so no dedicated RBAC code is consulted.
+ */
+const assertDocumentView = async (ctx: LikeContext, documentId: string) => {
+ const grantedPermissions = await ctx.getDocumentLikePermissionCodes();
+ if (grantedPermissions.length === 0) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Workspace membership required' });
+ }
+ await assertCanPerformResourceAction({
+ action: 'view',
+ db: ctx.serverDB,
+ grantedPermissions,
+ resourceId: documentId,
+ resourceType: 'document',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+};
+
+const toNotFound = (error: unknown): never => {
+ if (error instanceof Error && error.message === DOCUMENT_LIKE_DOCUMENT_NOT_FOUND) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Document not found' });
+ }
+ throw error;
+};
+
+const publishLikesChanged = (ctx: Pick<LikeContext, 'userId'>, documentId: string) => {
+ after(() =>
+ publishResourceEvent(
+ { id: documentId, type: 'document' },
+ { actorId: ctx.userId, type: 'document.likesChanged' },
+ ),
+ );
+};
+
+/**
+ * A like notification carries the document title, so before dispatch the
+ * recipient (the document author) must still be an active member who can view
+ * the document — membership is soft-deleted and documents survive removal, so
+ * a stale author id must not receive workspace content. Mirrors the
+ * document-comment notification path.
+ */
+const canRecipientViewDocument = async (
+ ctx: LikeContext,
+ params: DocumentLikeActivityParams,
+): Promise<boolean> => {
+ const [meta, permissionsByUserId] = await Promise.all([
+ getResourceMeta(ctx.serverDB, 'document', params.documentId),
+ RbacModel.getWorkspaceUsersPermissions({
+ db: ctx.serverDB,
+ requireMembership: true,
+ userIds: [params.recipientUserId],
+ workspaceId: ctx.workspaceId,
+ }),
+ ]);
+ if (!meta) return false;
+ const grantedPermissions = permissionsByUserId.get(params.recipientUserId);
+ if (!grantedPermissions) return false;
+
+ return canPerformResourceAction({
+ action: 'view',
+ db: ctx.serverDB,
+ effectiveAccessLevel: 'view',
+ grantedPermissions,
+ meta,
+ resourceId: params.documentId,
+ resourceType: 'document',
+ userId: params.recipientUserId,
+ workspaceId: ctx.workspaceId,
+ });
+};
+
+const runActivityBestEffort = (
+ ctx: LikeContext,
+ label: string,
+ params: DocumentLikeActivityParams,
+ run: (params: DocumentLikeActivityParams) => Promise<void>,
+ options: {
+ /**
+ * after() callbacks carry no cross-request ordering, so a rapid
+ * like→unlike (or unlike→like) can execute this callback after the
+ * opposite mutation already landed. Each callback therefore re-reads the
+ * ground truth — whether the actor's like row currently exists — and only
+ * acts when it matches this expectation, so the last mutation's outcome
+ * always wins regardless of callback ordering.
+ */
+ expectLikeRow: boolean;
+ /**
+ * Withdrawing a notification is cleanup, not disclosure — it should reach
+ * a removed author's inbox too, so revoke skips the access recheck.
+ */
+ skipRecipientAccessCheck?: boolean;
+ },
+) => {
+ if (params.recipientUserId === params.actorUserId) return;
+ after(async () => {
+ try {
+ const [likeRow] = await ctx.serverDB
+ .select({ id: documentLikes.id })
+ .from(documentLikes)
+ .where(
+ and(
+ eq(documentLikes.documentId, params.documentId),
+ eq(documentLikes.userId, params.actorUserId),
+ ),
+ )
+ .limit(1);
+ if (Boolean(likeRow) !== options.expectLikeRow) return;
+
+ if (!options.skipRecipientAccessCheck && !(await canRecipientViewDocument(ctx, params))) {
+ return;
+ }
+ await run(params);
+ } catch (error) {
+ console.error(`[document-like] Failed to ${label}`, error);
+ }
+ });
+};
+
+export const documentLikeRouter = router({
+ like: documentLikeProcedure.input(documentIdSchema).mutation(async ({ ctx, input }) => {
+ await assertDocumentView(ctx, input.documentId);
+ try {
+ const result = await ctx.documentLikeModel.like(input.documentId);
+ if (result.created) {
+ runActivityBestEffort(
+ ctx,
+ 'send like notification',
+ {
+ actorUserId: ctx.userId,
+ documentId: input.documentId,
+ recipientUserId: result.documentAuthorUserId,
+ workspaceId: ctx.workspaceId,
+ },
+ notifyDocumentLiked,
+ { expectLikeRow: true },
+ );
+ publishLikesChanged(ctx, input.documentId);
+ }
+ return result.summary;
+ } catch (error) {
+ return toNotFound(error);
+ }
+ }),
+
+ summary: documentLikeProcedure.input(documentIdSchema).query(async ({ ctx, input }) => {
+ await assertDocumentView(ctx, input.documentId);
+ try {
+ return await ctx.documentLikeModel.summary(input.documentId);
+ } catch (error) {
+ return toNotFound(error);
+ }
+ }),
+
+ unlike: documentLikeProcedure.input(documentIdSchema).mutation(async ({ ctx, input }) => {
+ await assertDocumentView(ctx, input.documentId);
+ try {
+ const result = await ctx.documentLikeModel.unlike(input.documentId);
+ if (result.removed) {
+ runActivityBestEffort(
+ ctx,
+ 'revoke like notification',
+ {
+ actorUserId: ctx.userId,
+ documentId: input.documentId,
+ recipientUserId: result.documentAuthorUserId,
+ workspaceId: ctx.workspaceId,
+ },
+ revokeDocumentLikeNotification,
+ { expectLikeRow: false, skipRecipientAccessCheck: true },
+ );
+ publishLikesChanged(ctx, input.documentId);
+ }
+ return result.summary;
+ } catch (error) {
+ return toNotFound(error);
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 6d2670c6051..e1cc246eee7 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -50,6 +50,7 @@ import { connectorRouter } from './connector';
import { deviceRouter } from './device';
import { documentRouter } from './document';
import { documentCommentRouter } from './documentComment';
+import { documentLikeRouter } from './documentLike';
import { expertiseRouter } from './expertise';
import { exporterRouter } from './exporter';
import { fileRouter } from './file';
@@ -128,6 +129,7 @@ export const lambdaRouter = router({
device: deviceRouter,
document: documentRouter,
documentComment: documentCommentRouter,
+ documentLike: documentLikeRouter,
exporter: exporterRouter,
file: fileRouter,
followUpAction: followUpActionRouter,
diff --git a/apps/server/src/services/resourceEvents/types.ts b/apps/server/src/services/resourceEvents/types.ts
index a0266111d21..cb7d33d02f9 100644
--- a/apps/server/src/services/resourceEvents/types.ts
+++ b/apps/server/src/services/resourceEvents/types.ts
@@ -7,7 +7,11 @@ export interface ResourceRef {
}
export type ResourceEventType =
- 'doc.updated' | 'document.commentsChanged' | 'lock.changed' | 'topic.commentsChanged';
+ | 'doc.updated'
+ | 'document.commentsChanged'
+ | 'document.likesChanged'
+ | 'lock.changed'
+ | 'topic.commentsChanged';
export interface ResourceEvent {
/** User id that triggered the event; allows subscriber-side attribution or filtering. */
diff --git a/locales/ar/file.json b/locales/ar/file.json
index bc41c2a10c0..bfa30081c06 100644
--- a/locales/ar/file.json
+++ b/locales/ar/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "تم حذف هذا التعليق.",
"pageEditor.comments.edit": "تعديل",
"pageEditor.comments.edited": "(تم التعديل)",
- "pageEditor.comments.empty": "لا توجد تعليقات حتى الآن. ابدأ المحادثة أدناه.",
"pageEditor.comments.hideReplies": "إخفاء الردود",
"pageEditor.comments.loadMore": "تحميل المزيد من التعليقات",
"pageEditor.comments.loadMoreReplies": "تحميل المزيد من الردود",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "سجل الإصدارات",
"pageEditor.history.versionCount_one": "نسخة واحدة {{count}}",
"pageEditor.history.versionCount_other": "{{count}} نسخ",
+ "pageEditor.likes.count": "{{count}} إعجاب",
+ "pageEditor.likes.failed": "فشل في تحديث إعجابك. حاول مرة أخرى.",
+ "pageEditor.likes.like": "هل تجد هذه الصفحة مفيدة؟ أعطها إعجابًا",
+ "pageEditor.likes.liked": "تم الإعجاب",
+ "pageEditor.likes.more": "+{{count}} المزيد",
"pageEditor.linkCopied": "تم نسخ الرابط",
"pageEditor.lock.editingByOther": "{{name}} يقوم بتعديل هذه الصفحة. لا يمكن حفظ تغييراتك الآن.",
"pageEditor.lock.editingBySomeone": "شخص آخر يقوم بتعديل هذه الصفحة. لا يمكن حفظ تغييراتك الآن.",
diff --git a/locales/ar/notification.json b/locales/ar/notification.json
index 95112fb0b4d..ecbf0805ebc 100644
--- a/locales/ar/notification.json
+++ b/locales/ar/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "تعليق جديد على مستندك",
"document_comment_mentioned": "{{actorLabel}} أشار إليك في تعليق على \"{{documentTitle}}\".",
"document_comment_mentioned_title": "تم الإشارة إليك في تعليق على مستند",
+ "document_liked": "{{actorLabel}} أعجب بوثيقتك \"{{documentTitle}}\".",
+ "document_liked_title": "أحدهم أعجب بوثيقتك",
"email.footer.contactSupport": "اتصل بالدعم",
"email.footer.joinDiscord": "انضم إلى Discord",
"email.footer.manage": "إدارة الإشعارات",
diff --git a/locales/bg-BG/file.json b/locales/bg-BG/file.json
index e40831df93b..cfd57e1adbc 100644
--- a/locales/bg-BG/file.json
+++ b/locales/bg-BG/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Този коментар беше изтрит.",
"pageEditor.comments.edit": "Редактирай",
"pageEditor.comments.edited": "(редактирано)",
- "pageEditor.comments.empty": "Все още няма коментари. Започнете разговора по-долу.",
"pageEditor.comments.hideReplies": "Скрий отговорите",
"pageEditor.comments.loadMore": "Зареди още коментари",
"pageEditor.comments.loadMoreReplies": "Зареди още отговори",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "История на версиите",
"pageEditor.history.versionCount_one": "{{count}} версия",
"pageEditor.history.versionCount_other": "{{count}} версии",
+ "pageEditor.likes.count": "{{count}} харесвания",
+ "pageEditor.likes.failed": "Неуспешно актуализиране на вашето харесване. Опитайте отново.",
+ "pageEditor.likes.like": "Намирате тази страница за полезна? Харесайте я.",
+ "pageEditor.likes.liked": "Харесано",
+ "pageEditor.likes.more": "+{{count}} още",
"pageEditor.linkCopied": "Връзката е копирана",
"pageEditor.lock.editingByOther": "{{name}} редактира тази страница. Вашите промени не могат да бъдат запазени в момента.",
"pageEditor.lock.editingBySomeone": "Някой друг редактира тази страница. Вашите промени не могат да бъдат запазени в момента.",
diff --git a/locales/bg-BG/notification.json b/locales/bg-BG/notification.json
index 25a6535b444..ff79f115f9f 100644
--- a/locales/bg-BG/notification.json
+++ b/locales/bg-BG/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Нов коментар във вашия документ",
"document_comment_mentioned": "{{actorLabel}} ви спомена в коментар на \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Бяхте споменати в коментар на документ",
+ "document_liked": "{{actorLabel}} хареса вашия документ „{{documentTitle}}“.",
+ "document_liked_title": "Някой хареса вашия документ",
"email.footer.contactSupport": "Свържете се с поддръжката",
"email.footer.joinDiscord": "Присъединете се към Discord",
"email.footer.manage": "Управление на известията",
diff --git a/locales/de-DE/file.json b/locales/de-DE/file.json
index db141f8ec96..593138a9fcc 100644
--- a/locales/de-DE/file.json
+++ b/locales/de-DE/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Dieser Kommentar wurde gelöscht.",
"pageEditor.comments.edit": "Bearbeiten",
"pageEditor.comments.edited": "(bearbeitet)",
- "pageEditor.comments.empty": "Noch keine Kommentare. Beginnen Sie unten das Gespräch.",
"pageEditor.comments.hideReplies": "Antworten ausblenden",
"pageEditor.comments.loadMore": "Mehr Kommentare laden",
"pageEditor.comments.loadMoreReplies": "Mehr Antworten laden",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Versionsverlauf",
"pageEditor.history.versionCount_one": "{{count}} Version",
"pageEditor.history.versionCount_other": "{{count}} Versionen",
+ "pageEditor.likes.count": "{{count}} Likes",
+ "pageEditor.likes.failed": "Fehler beim Aktualisieren Ihres Likes. Versuchen Sie es erneut.",
+ "pageEditor.likes.like": "Finden Sie diese Seite hilfreich? Geben Sie ihr ein Like.",
+ "pageEditor.likes.liked": "Gefällt mir",
+ "pageEditor.likes.more": "+{{count}} mehr",
"pageEditor.linkCopied": "Link kopiert",
"pageEditor.lock.editingByOther": "{{name}} bearbeitet diese Seite. Ihre Änderungen können momentan nicht gespeichert werden.",
"pageEditor.lock.editingBySomeone": "Jemand anderes bearbeitet diese Seite. Ihre Änderungen können momentan nicht gespeichert werden.",
diff --git a/locales/de-DE/notification.json b/locales/de-DE/notification.json
index edeef4633bf..0d87a73a868 100644
--- a/locales/de-DE/notification.json
+++ b/locales/de-DE/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Neuer Kommentar zu Ihrem Dokument",
"document_comment_mentioned": "{{actorLabel}} hat Sie in einem Kommentar zu \"{{documentTitle}}\" erwähnt.",
"document_comment_mentioned_title": "Sie wurden in einem Dokumentkommentar erwähnt",
+ "document_liked": "{{actorLabel}} hat Ihr Dokument \"{{documentTitle}}\" mit \"Gefällt mir\" markiert.",
+ "document_liked_title": "Jemand hat Ihr Dokument mit \"Gefällt mir\" markiert",
"email.footer.contactSupport": "Support kontaktieren",
"email.footer.joinDiscord": "Discord beitreten",
"email.footer.manage": "Benachrichtigungen verwalten",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index 988d67d344b..07a1ef55ab1 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "This comment was deleted.",
"pageEditor.comments.edit": "Edit",
"pageEditor.comments.edited": "(edited)",
- "pageEditor.comments.empty": "No comments yet. Start the conversation below.",
"pageEditor.comments.hideReplies": "Hide replies",
"pageEditor.comments.loadMore": "Load more comments",
"pageEditor.comments.loadMoreReplies": "Load more replies",
@@ -177,6 +176,13 @@
"pageEditor.history.title": "Version History",
"pageEditor.history.versionCount_one": "{{count}} version",
"pageEditor.history.versionCount_other": "{{count}} versions",
+ "pageEditor.likes.count": "{{count}} likes",
+ "pageEditor.likes.count_one": "{{count}} like",
+ "pageEditor.likes.count_other": "{{count}} likes",
+ "pageEditor.likes.failed": "Failed to update your like. Try again.",
+ "pageEditor.likes.like": "Find this page helpful? Give it a like",
+ "pageEditor.likes.liked": "Liked",
+ "pageEditor.likes.more": "+{{count}} more",
"pageEditor.linkCopied": "Link copied",
"pageEditor.lock.editingByOther": "{{name}} is editing this page. Your changes can’t be saved right now.",
"pageEditor.lock.editingBySomeone": "Someone else is editing this page. Your changes can’t be saved right now.",
diff --git a/locales/en-US/notification.json b/locales/en-US/notification.json
index d06c6a7ec66..911e070945c 100644
--- a/locales/en-US/notification.json
+++ b/locales/en-US/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "New comment on your document",
"document_comment_mentioned": "{{actorLabel}} mentioned you in a comment on \"{{documentTitle}}\".",
"document_comment_mentioned_title": "You were mentioned in a document comment",
+ "document_liked": "{{actorLabel}} liked your document \"{{documentTitle}}\".",
+ "document_liked_title": "Someone liked your document",
"email.footer.contactSupport": "Contact support",
"email.footer.joinDiscord": "Join Discord",
"email.footer.manage": "Manage notifications",
diff --git a/locales/es-ES/file.json b/locales/es-ES/file.json
index 1772b320de3..36ad442e0c1 100644
--- a/locales/es-ES/file.json
+++ b/locales/es-ES/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Este comentario fue eliminado.",
"pageEditor.comments.edit": "Editar",
"pageEditor.comments.edited": "(editado)",
- "pageEditor.comments.empty": "Aún no hay comentarios. Comienza la conversación abajo.",
"pageEditor.comments.hideReplies": "Ocultar respuestas",
"pageEditor.comments.loadMore": "Cargar más comentarios",
"pageEditor.comments.loadMoreReplies": "Cargar más respuestas",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Historial de versiones",
"pageEditor.history.versionCount_one": "{{count}} versión",
"pageEditor.history.versionCount_other": "{{count}} versiones",
+ "pageEditor.likes.count": "{{count}} me gusta",
+ "pageEditor.likes.failed": "No se pudo actualizar tu me gusta. Inténtalo de nuevo.",
+ "pageEditor.likes.like": "¿Te parece útil esta página? Dale un me gusta",
+ "pageEditor.likes.liked": "Me gusta",
+ "pageEditor.likes.more": "+{{count}} más",
"pageEditor.linkCopied": "Enlace copiado",
"pageEditor.lock.editingByOther": "{{name}} está editando esta página. Tus cambios no se pueden guardar en este momento.",
"pageEditor.lock.editingBySomeone": "Alguien más está editando esta página. Tus cambios no se pueden guardar en este momento.",
diff --git a/locales/es-ES/notification.json b/locales/es-ES/notification.json
index 8e1fb79ce17..6c626881544 100644
--- a/locales/es-ES/notification.json
+++ b/locales/es-ES/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Nuevo comentario en tu documento",
"document_comment_mentioned": "{{actorLabel}} te mencionó en un comentario en \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Fuiste mencionado en un comentario de un documento",
+ "document_liked": "{{actorLabel}} le gustó tu documento \"{{documentTitle}}\".",
+ "document_liked_title": "A alguien le gustó tu documento",
"email.footer.contactSupport": "Contactar soporte",
"email.footer.joinDiscord": "Unirse a Discord",
"email.footer.manage": "Gestionar notificaciones",
diff --git a/locales/fa-IR/file.json b/locales/fa-IR/file.json
index 4cb75a95f61..9c2de71ba48 100644
--- a/locales/fa-IR/file.json
+++ b/locales/fa-IR/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "این نظر حذف شده است.",
"pageEditor.comments.edit": "ویرایش",
"pageEditor.comments.edited": "(ویرایش شده)",
- "pageEditor.comments.empty": "هنوز نظری وجود ندارد. مکالمه را در زیر شروع کنید.",
"pageEditor.comments.hideReplies": "پنهان کردن پاسخ‌ها",
"pageEditor.comments.loadMore": "بارگذاری نظرات بیشتر",
"pageEditor.comments.loadMoreReplies": "بارگذاری پاسخ‌های بیشتر",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "تاریخچه نسخه‌ها",
"pageEditor.history.versionCount_one": "{{count}} نسخه",
"pageEditor.history.versionCount_other": "{{count}} نسخه",
+ "pageEditor.likes.count": "{{count}} پسند",
+ "pageEditor.likes.failed": "به‌روزرسانی پسند شما انجام نشد. دوباره تلاش کنید.",
+ "pageEditor.likes.like": "آیا این صفحه را مفید یافتید؟ به آن یک پسند بدهید",
+ "pageEditor.likes.liked": "پسندیده شد",
+ "pageEditor.likes.more": "+{{count}} بیشتر",
"pageEditor.linkCopied": "لینک کپی شد",
"pageEditor.lock.editingByOther": "{{name}} در حال ویرایش این صفحه است. تغییرات شما در حال حاضر ذخیره نمی‌شود.",
"pageEditor.lock.editingBySomeone": "شخص دیگری در حال ویرایش این صفحه است. تغییرات شما در حال حاضر ذخیره نمی‌شود.",
diff --git a/locales/fa-IR/notification.json b/locales/fa-IR/notification.json
index c265f1e1db6..d6f5a4064ef 100644
--- a/locales/fa-IR/notification.json
+++ b/locales/fa-IR/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "نظر جدید روی سند شما",
"document_comment_mentioned": "{{actorLabel}} شما را در نظری روی \"{{documentTitle}}\" ذکر کرد.",
"document_comment_mentioned_title": "شما در یک نظر سند ذکر شدید",
+ "document_liked": "{{actorLabel}} سند شما را با عنوان \"{{documentTitle}}\" پسندید.",
+ "document_liked_title": "کسی سند شما را پسندید",
"email.footer.contactSupport": "تماس با پشتیبانی",
"email.footer.joinDiscord": "به دیسکورد بپیوندید",
"email.footer.manage": "مدیریت اعلان‌ها",
diff --git a/locales/fr-FR/file.json b/locales/fr-FR/file.json
index 41dcf7849ac..4e0413dc58d 100644
--- a/locales/fr-FR/file.json
+++ b/locales/fr-FR/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Ce commentaire a été supprimé.",
"pageEditor.comments.edit": "Modifier",
"pageEditor.comments.edited": "(modifié)",
- "pageEditor.comments.empty": "Aucun commentaire pour le moment. Lancez la conversation ci-dessous.",
"pageEditor.comments.hideReplies": "Masquer les réponses",
"pageEditor.comments.loadMore": "Charger plus de commentaires",
"pageEditor.comments.loadMoreReplies": "Charger plus de réponses",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Historique des versions",
"pageEditor.history.versionCount_one": "{{count}} version",
"pageEditor.history.versionCount_other": "{{count}} versions",
+ "pageEditor.likes.count": "{{count}} mentions J’aime",
+ "pageEditor.likes.failed": "Échec de la mise à jour de votre mention J’aime. Veuillez réessayer.",
+ "pageEditor.likes.like": "Vous trouvez cette page utile ? Donnez-lui une mention J’aime",
+ "pageEditor.likes.liked": "Mention J’aime",
+ "pageEditor.likes.more": "+{{count}} de plus",
"pageEditor.linkCopied": "Lien copié",
"pageEditor.lock.editingByOther": "{{name}} est en train de modifier cette page. Vos modifications ne peuvent pas être enregistrées pour le moment.",
"pageEditor.lock.editingBySomeone": "Quelqu'un d'autre est en train de modifier cette page. Vos modifications ne peuvent pas être enregistrées pour le moment.",
diff --git a/locales/fr-FR/notification.json b/locales/fr-FR/notification.json
index c9d7ae7e93b..8e758396ba0 100644
--- a/locales/fr-FR/notification.json
+++ b/locales/fr-FR/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Nouveau commentaire sur votre document",
"document_comment_mentioned": "{{actorLabel}} vous a mentionné dans un commentaire sur \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Vous avez été mentionné dans un commentaire de document",
+ "document_liked": "{{actorLabel}} a aimé votre document \"{{documentTitle}}\".",
+ "document_liked_title": "Quelqu'un a aimé votre document",
"email.footer.contactSupport": "Contacter le support",
"email.footer.joinDiscord": "Rejoindre Discord",
"email.footer.manage": "Gérer les notifications",
diff --git a/locales/it-IT/file.json b/locales/it-IT/file.json
index d0b02b94a1d..4f1f516d20d 100644
--- a/locales/it-IT/file.json
+++ b/locales/it-IT/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Questo commento è stato eliminato.",
"pageEditor.comments.edit": "Modifica",
"pageEditor.comments.edited": "(modificato)",
- "pageEditor.comments.empty": "Ancora nessun commento. Inizia la conversazione qui sotto.",
"pageEditor.comments.hideReplies": "Nascondi risposte",
"pageEditor.comments.loadMore": "Carica più commenti",
"pageEditor.comments.loadMoreReplies": "Carica più risposte",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Cronologia versioni",
"pageEditor.history.versionCount_one": "{{count}} versione",
"pageEditor.history.versionCount_other": "{{count}} versioni",
+ "pageEditor.likes.count": "{{count}} mi piace",
+ "pageEditor.likes.failed": "Impossibile aggiornare il tuo mi piace. Riprova.",
+ "pageEditor.likes.like": "Trovi utile questa pagina? Dai un mi piace",
+ "pageEditor.likes.liked": "Mi piace",
+ "pageEditor.likes.more": "+{{count}} altri",
"pageEditor.linkCopied": "Link copiato",
"pageEditor.lock.editingByOther": "{{name}} sta modificando questa pagina. Le tue modifiche non possono essere salvate in questo momento.",
"pageEditor.lock.editingBySomeone": "Qualcun altro sta modificando questa pagina. Le tue modifiche non possono essere salvate in questo momento.",
diff --git a/locales/it-IT/notification.json b/locales/it-IT/notification.json
index 84630a52269..e0705d196c3 100644
--- a/locales/it-IT/notification.json
+++ b/locales/it-IT/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Nuovo commento sul tuo documento",
"document_comment_mentioned": "{{actorLabel}} ti ha menzionato in un commento su \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Sei stato menzionato in un commento sul documento",
+ "document_liked": "{{actorLabel}} ha apprezzato il tuo documento \"{{documentTitle}}\".",
+ "document_liked_title": "Qualcuno ha apprezzato il tuo documento",
"email.footer.contactSupport": "Contatta il supporto",
"email.footer.joinDiscord": "Unisciti a Discord",
"email.footer.manage": "Gestisci notifiche",
diff --git a/locales/ja-JP/file.json b/locales/ja-JP/file.json
index 7f16a9bc09e..347747be560 100644
--- a/locales/ja-JP/file.json
+++ b/locales/ja-JP/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "このコメントは削除されました。",
"pageEditor.comments.edit": "編集",
"pageEditor.comments.edited": "(編集済み)",
- "pageEditor.comments.empty": "まだコメントがありません。以下に会話を始めてください。",
"pageEditor.comments.hideReplies": "返信を非表示",
"pageEditor.comments.loadMore": "さらにコメントを読み込む",
"pageEditor.comments.loadMoreReplies": "さらに返信を読み込む",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "バージョン履歴",
"pageEditor.history.versionCount_one": "{{count}} 件のバージョン",
"pageEditor.history.versionCount_other": "{{count}} 件のバージョン",
+ "pageEditor.likes.count": "{{count}} 件のいいね",
+ "pageEditor.likes.failed": "いいねの更新に失敗しました。もう一度お試しください。",
+ "pageEditor.likes.like": "このページは役に立ちましたか?いいねを押してください",
+ "pageEditor.likes.liked": "いいね済み",
+ "pageEditor.likes.more": "+{{count}} 件のその他",
"pageEditor.linkCopied": "リンクをコピーしました",
"pageEditor.lock.editingByOther": "{{name}}がこのページを編集しています。現在、変更を保存することはできません。",
"pageEditor.lock.editingBySomeone": "他の誰かがこのページを編集しています。現在、変更を保存することはできません。",
diff --git a/locales/ja-JP/notification.json b/locales/ja-JP/notification.json
index 42bc6cd4d13..c2a33755f71 100644
--- a/locales/ja-JP/notification.json
+++ b/locales/ja-JP/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "あなたのドキュメントへの新しいコメント",
"document_comment_mentioned": "{{actorLabel}}が「{{documentTitle}}」のコメントであなたに言及しました。",
"document_comment_mentioned_title": "ドキュメントのコメントで言及されました",
+ "document_liked": "{{actorLabel}}があなたのドキュメント「{{documentTitle}}」を気に入りました。",
+ "document_liked_title": "誰かがあなたのドキュメントを気に入りました",
"email.footer.contactSupport": "サポートに連絡する",
"email.footer.joinDiscord": "Discordに参加する",
"email.footer.manage": "通知を管理する",
diff --git a/locales/ko-KR/file.json b/locales/ko-KR/file.json
index 1a732a209e3..2b2b06af6c4 100644
--- a/locales/ko-KR/file.json
+++ b/locales/ko-KR/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "이 댓글은 삭제되었습니다.",
"pageEditor.comments.edit": "편집",
"pageEditor.comments.edited": "(편집됨)",
- "pageEditor.comments.empty": "아직 댓글이 없습니다. 아래에서 대화를 시작하세요.",
"pageEditor.comments.hideReplies": "답글 숨기기",
"pageEditor.comments.loadMore": "댓글 더 보기",
"pageEditor.comments.loadMoreReplies": "답글 더 보기",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "버전 기록",
"pageEditor.history.versionCount_one": "{{count}}개 버전",
"pageEditor.history.versionCount_other": "{{count}}개 버전",
+ "pageEditor.likes.count": "{{count}}개 좋아요",
+ "pageEditor.likes.failed": "좋아요를 업데이트하지 못했습니다. 다시 시도해 주세요.",
+ "pageEditor.likes.like": "이 페이지가 도움이 되었나요? 좋아요를 눌러주세요.",
+ "pageEditor.likes.liked": "좋아요 완료",
+ "pageEditor.likes.more": "+{{count}}개 더 보기",
"pageEditor.linkCopied": "링크가 복사되었습니다",
"pageEditor.lock.editingByOther": "{{name}}님이 이 페이지를 편집 중입니다. 현재는 변경 사항을 저장할 수 없습니다.",
"pageEditor.lock.editingBySomeone": "다른 사람이 이 페이지를 편집 중입니다. 현재는 변경 사항을 저장할 수 없습니다.",
diff --git a/locales/ko-KR/notification.json b/locales/ko-KR/notification.json
index 33d9f32dd78..cf81db42ea8 100644
--- a/locales/ko-KR/notification.json
+++ b/locales/ko-KR/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "귀하의 문서에 대한 새 댓글",
"document_comment_mentioned": "{{actorLabel}}님이 \"{{documentTitle}}\"의 댓글에서 귀하를 언급했습니다.",
"document_comment_mentioned_title": "문서 댓글에서 귀하가 언급되었습니다",
+ "document_liked": "{{actorLabel}}님이 귀하의 문서 \"{{documentTitle}}\"을(를) 좋아합니다.",
+ "document_liked_title": "누군가 귀하의 문서를 좋아합니다",
"email.footer.contactSupport": "지원팀에 문의하기",
"email.footer.joinDiscord": "디스코드에 참여하기",
"email.footer.manage": "알림 관리",
diff --git a/locales/nl-NL/file.json b/locales/nl-NL/file.json
index 1ca7735d4c0..f9c21b32e70 100644
--- a/locales/nl-NL/file.json
+++ b/locales/nl-NL/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Deze reactie is verwijderd.",
"pageEditor.comments.edit": "Bewerken",
"pageEditor.comments.edited": "(bewerkt)",
- "pageEditor.comments.empty": "Nog geen reacties. Begin hieronder met het gesprek.",
"pageEditor.comments.hideReplies": "Antwoorden verbergen",
"pageEditor.comments.loadMore": "Meer reacties laden",
"pageEditor.comments.loadMoreReplies": "Meer antwoorden laden",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Versiegeschiedenis",
"pageEditor.history.versionCount_one": "{{count}} versie",
"pageEditor.history.versionCount_other": "{{count}} versies",
+ "pageEditor.likes.count": "{{count}} vind-ik-leuks",
+ "pageEditor.likes.failed": "Het bijwerken van je vind-ik-leuk is mislukt. Probeer het opnieuw.",
+ "pageEditor.likes.like": "Vind je deze pagina nuttig? Geef een vind-ik-leuk",
+ "pageEditor.likes.liked": "Vind-ik-leuk",
+ "pageEditor.likes.more": "+{{count}} meer",
"pageEditor.linkCopied": "Link gekopieerd",
"pageEditor.lock.editingByOther": "{{name}} is deze pagina aan het bewerken. Je wijzigingen kunnen momenteel niet worden opgeslagen.",
"pageEditor.lock.editingBySomeone": "Iemand anders is deze pagina aan het bewerken. Je wijzigingen kunnen momenteel niet worden opgeslagen.",
diff --git a/locales/nl-NL/notification.json b/locales/nl-NL/notification.json
index ba38bfbcabe..2546b7b2de0 100644
--- a/locales/nl-NL/notification.json
+++ b/locales/nl-NL/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Nieuwe opmerking over uw document",
"document_comment_mentioned": "{{actorLabel}} heeft u genoemd in een opmerking over \"{{documentTitle}}\".",
"document_comment_mentioned_title": "U bent genoemd in een documentopmerking",
+ "document_liked": "{{actorLabel}} vond je document \"{{documentTitle}}\" leuk.",
+ "document_liked_title": "Iemand vond je document leuk",
"email.footer.contactSupport": "Neem contact op met ondersteuning",
"email.footer.joinDiscord": "Word lid van Discord",
"email.footer.manage": "Beheer meldingen",
diff --git a/locales/pl-PL/file.json b/locales/pl-PL/file.json
index 7ef4458ff87..87c242edd4f 100644
--- a/locales/pl-PL/file.json
+++ b/locales/pl-PL/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Ten komentarz został usunięty.",
"pageEditor.comments.edit": "Edytuj",
"pageEditor.comments.edited": "(edytowano)",
- "pageEditor.comments.empty": "Brak komentarzy. Rozpocznij rozmowę poniżej.",
"pageEditor.comments.hideReplies": "Ukryj odpowiedzi",
"pageEditor.comments.loadMore": "Załaduj więcej komentarzy",
"pageEditor.comments.loadMoreReplies": "Załaduj więcej odpowiedzi",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Historia wersji",
"pageEditor.history.versionCount_one": "{{count}} wersja",
"pageEditor.history.versionCount_other": "{{count}} wersji",
+ "pageEditor.likes.count": "{{count}} polubień",
+ "pageEditor.likes.failed": "Nie udało się zaktualizować polubienia. Spróbuj ponownie.",
+ "pageEditor.likes.like": "Czy ta strona jest pomocna? Polub ją",
+ "pageEditor.likes.liked": "Polubione",
+ "pageEditor.likes.more": "+{{count}} więcej",
"pageEditor.linkCopied": "Link skopiowany",
"pageEditor.lock.editingByOther": "{{name}} edytuje tę stronę. Twoje zmiany nie mogą zostać zapisane w tej chwili.",
"pageEditor.lock.editingBySomeone": "Ktoś inny edytuje tę stronę. Twoje zmiany nie mogą zostać zapisane w tej chwili.",
diff --git a/locales/pl-PL/notification.json b/locales/pl-PL/notification.json
index a57bc3361b1..14de7f4ef87 100644
--- a/locales/pl-PL/notification.json
+++ b/locales/pl-PL/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Nowy komentarz do Twojego dokumentu",
"document_comment_mentioned": "{{actorLabel}} wspomniał Cię w komentarzu do \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Zostałeś wspomniany w komentarzu do dokumentu",
+ "document_liked": "{{actorLabel}} polubił Twój dokument \"{{documentTitle}}\".",
+ "document_liked_title": "Ktoś polubił Twój dokument",
"email.footer.contactSupport": "Skontaktuj się z pomocą techniczną",
"email.footer.joinDiscord": "Dołącz do Discorda",
"email.footer.manage": "Zarządzaj powiadomieniami",
diff --git a/locales/pt-BR/file.json b/locales/pt-BR/file.json
index 08ac7ea89e5..ee95ab9a8b1 100644
--- a/locales/pt-BR/file.json
+++ b/locales/pt-BR/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Este comentário foi excluído.",
"pageEditor.comments.edit": "Editar",
"pageEditor.comments.edited": "(editado)",
- "pageEditor.comments.empty": "Ainda não há comentários. Inicie a conversa abaixo.",
"pageEditor.comments.hideReplies": "Ocultar respostas",
"pageEditor.comments.loadMore": "Carregar mais comentários",
"pageEditor.comments.loadMoreReplies": "Carregar mais respostas",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Histórico de Versões",
"pageEditor.history.versionCount_one": "{{count}} versão",
"pageEditor.history.versionCount_other": "{{count}} versões",
+ "pageEditor.likes.count": "{{count}} curtidas",
+ "pageEditor.likes.failed": "Falha ao atualizar sua curtida. Tente novamente.",
+ "pageEditor.likes.like": "Achou esta página útil? Dê uma curtida",
+ "pageEditor.likes.liked": "Curtido",
+ "pageEditor.likes.more": "+{{count}} mais",
"pageEditor.linkCopied": "Link copiado",
"pageEditor.lock.editingByOther": "{{name}} está editando esta página. Suas alterações não podem ser salvas no momento.",
"pageEditor.lock.editingBySomeone": "Outra pessoa está editando esta página. Suas alterações não podem ser salvas no momento.",
diff --git a/locales/pt-BR/notification.json b/locales/pt-BR/notification.json
index 4fa26f23e4d..25e6a858900 100644
--- a/locales/pt-BR/notification.json
+++ b/locales/pt-BR/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Novo comentário no seu documento",
"document_comment_mentioned": "{{actorLabel}} mencionou você em um comentário no \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Você foi mencionado em um comentário de documento",
+ "document_liked": "{{actorLabel}} curtiu seu documento \"{{documentTitle}}\".",
+ "document_liked_title": "Alguém curtiu seu documento",
"email.footer.contactSupport": "Entrar em contato com o suporte",
"email.footer.joinDiscord": "Participar do Discord",
"email.footer.manage": "Gerenciar notificações",
diff --git a/locales/ru-RU/file.json b/locales/ru-RU/file.json
index 7bd79e3695c..931c8753ba8 100644
--- a/locales/ru-RU/file.json
+++ b/locales/ru-RU/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Этот комментарий был удален.",
"pageEditor.comments.edit": "Редактировать",
"pageEditor.comments.edited": "(отредактировано)",
- "pageEditor.comments.empty": "Пока нет комментариев. Начните разговор ниже.",
"pageEditor.comments.hideReplies": "Скрыть ответы",
"pageEditor.comments.loadMore": "Загрузить больше комментариев",
"pageEditor.comments.loadMoreReplies": "Загрузить больше ответов",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "История версий",
"pageEditor.history.versionCount_one": "{{count}} версия",
"pageEditor.history.versionCount_other": "{{count}} версий",
+ "pageEditor.likes.count": "{{count}} лайков",
+ "pageEditor.likes.failed": "Не удалось обновить ваш лайк. Попробуйте снова.",
+ "pageEditor.likes.like": "Эта страница полезна? Поставьте лайк",
+ "pageEditor.likes.liked": "Понравилось",
+ "pageEditor.likes.more": "+{{count}} ещё",
"pageEditor.linkCopied": "Ссылка скопирована",
"pageEditor.lock.editingByOther": "{{name}} редактирует эту страницу. Ваши изменения не могут быть сохранены прямо сейчас.",
"pageEditor.lock.editingBySomeone": "Кто-то другой редактирует эту страницу. Ваши изменения не могут быть сохранены прямо сейчас.",
diff --git a/locales/ru-RU/notification.json b/locales/ru-RU/notification.json
index 7c1d4c17b57..1c7e4552f7a 100644
--- a/locales/ru-RU/notification.json
+++ b/locales/ru-RU/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Новый комментарий к вашему документу",
"document_comment_mentioned": "{{actorLabel}} упомянул вас в комментарии к \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Вы были упомянуты в комментарии к документу",
+ "document_liked": "{{actorLabel}} понравился ваш документ \"{{documentTitle}}\".",
+ "document_liked_title": "Кому-то понравился ваш документ",
"email.footer.contactSupport": "Связаться с поддержкой",
"email.footer.joinDiscord": "Присоединиться к Discord",
"email.footer.manage": "Управление уведомлениями",
diff --git a/locales/tr-TR/file.json b/locales/tr-TR/file.json
index 5f6a685af43..763916ef9bb 100644
--- a/locales/tr-TR/file.json
+++ b/locales/tr-TR/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Bu yorum silindi.",
"pageEditor.comments.edit": "Düzenle",
"pageEditor.comments.edited": "(düzenlendi)",
- "pageEditor.comments.empty": "Henüz yorum yok. Aşağıdan konuşmayı başlatın.",
"pageEditor.comments.hideReplies": "Yanıtları gizle",
"pageEditor.comments.loadMore": "Daha fazla yorum yükle",
"pageEditor.comments.loadMoreReplies": "Daha fazla yanıt yükle",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Sürüm Geçmişi",
"pageEditor.history.versionCount_one": "{{count}} sürüm",
"pageEditor.history.versionCount_other": "{{count}} sürüm",
+ "pageEditor.likes.count": "{{count}} beğeni",
+ "pageEditor.likes.failed": "Beğeninizi güncellemek başarısız oldu. Tekrar deneyin.",
+ "pageEditor.likes.like": "Bu sayfayı faydalı buldunuz mu? Beğeni bırakın",
+ "pageEditor.likes.liked": "Beğenildi",
+ "pageEditor.likes.more": "+{{count}} daha",
"pageEditor.linkCopied": "Bağlantı kopyalandı",
"pageEditor.lock.editingByOther": "{{name}} bu sayfayı düzenliyor. Şu anda değişiklikleriniz kaydedilemiyor.",
"pageEditor.lock.editingBySomeone": "Başka biri bu sayfayı düzenliyor. Şu anda değişiklikleriniz kaydedilemiyor.",
diff --git a/locales/tr-TR/notification.json b/locales/tr-TR/notification.json
index 582c5d3bd3e..b03eba62845 100644
--- a/locales/tr-TR/notification.json
+++ b/locales/tr-TR/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Belgenizde yeni bir yorum",
"document_comment_mentioned": "{{actorLabel}} \"{{documentTitle}}\" üzerindeki bir yorumda sizi bahsetti.",
"document_comment_mentioned_title": "Bir belge yorumunda bahsedildiniz",
+ "document_liked": "{{actorLabel}} belgenizi beğendi: \"{{documentTitle}}\".",
+ "document_liked_title": "Birisi belgenizi beğendi",
"email.footer.contactSupport": "Destek ile iletişime geçin",
"email.footer.joinDiscord": "Discord'a katılın",
"email.footer.manage": "Bildirimleri yönet",
diff --git a/locales/vi-VN/file.json b/locales/vi-VN/file.json
index 58dd93b883e..6df82d322a2 100644
--- a/locales/vi-VN/file.json
+++ b/locales/vi-VN/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "Bình luận này đã bị xóa.",
"pageEditor.comments.edit": "Chỉnh sửa",
"pageEditor.comments.edited": "(đã chỉnh sửa)",
- "pageEditor.comments.empty": "Chưa có bình luận nào. Bắt đầu cuộc trò chuyện bên dưới.",
"pageEditor.comments.hideReplies": "Ẩn phản hồi",
"pageEditor.comments.loadMore": "Tải thêm bình luận",
"pageEditor.comments.loadMoreReplies": "Tải thêm phản hồi",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "Lịch sử phiên bản",
"pageEditor.history.versionCount_one": "{{count}} phiên bản",
"pageEditor.history.versionCount_other": "{{count}} phiên bản",
+ "pageEditor.likes.count": "{{count}} lượt thích",
+ "pageEditor.likes.failed": "Không thể cập nhật lượt thích của bạn. Vui lòng thử lại.",
+ "pageEditor.likes.like": "Bạn thấy trang này hữu ích? Hãy thích nó",
+ "pageEditor.likes.liked": "Đã thích",
+ "pageEditor.likes.more": "+{{count}} thêm",
"pageEditor.linkCopied": "Đã sao chép liên kết",
"pageEditor.lock.editingByOther": "{{name}} đang chỉnh sửa trang này. Thay đổi của bạn hiện không thể lưu được.",
"pageEditor.lock.editingBySomeone": "Người khác đang chỉnh sửa trang này. Thay đổi của bạn hiện không thể lưu được.",
diff --git a/locales/vi-VN/notification.json b/locales/vi-VN/notification.json
index 7987687191a..e552e7a7e59 100644
--- a/locales/vi-VN/notification.json
+++ b/locales/vi-VN/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "Bình luận mới về tài liệu của bạn",
"document_comment_mentioned": "{{actorLabel}} đã nhắc đến bạn trong một bình luận về \"{{documentTitle}}\".",
"document_comment_mentioned_title": "Bạn đã được nhắc đến trong một bình luận tài liệu",
+ "document_liked": "{{actorLabel}} đã thích tài liệu của bạn \"{{documentTitle}}\".",
+ "document_liked_title": "Ai đó đã thích tài liệu của bạn",
"email.footer.contactSupport": "Liên hệ hỗ trợ",
"email.footer.joinDiscord": "Tham gia Discord",
"email.footer.manage": "Quản lý thông báo",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index a0b542004cf..ff685699406 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "这条评论已被删除",
"pageEditor.comments.edit": "编辑",
"pageEditor.comments.edited": "(已编辑)",
- "pageEditor.comments.empty": "还没有评论,在下方开始讨论吧",
"pageEditor.comments.hideReplies": "收起回复",
"pageEditor.comments.loadMore": "加载更多评论",
"pageEditor.comments.loadMoreReplies": "加载更多回复",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "版本历史",
"pageEditor.history.versionCount_one": "共 {{count}} 个版本",
"pageEditor.history.versionCount_other": "共 {{count}} 个版本",
+ "pageEditor.likes.count": "{{count}} 人点赞",
+ "pageEditor.likes.failed": "点赞操作失败,请重试",
+ "pageEditor.likes.like": "觉得不错?点个赞",
+ "pageEditor.likes.liked": "已点赞",
+ "pageEditor.likes.more": "+{{count}} 人",
"pageEditor.linkCopied": "链接已复制",
"pageEditor.lock.editingByOther": "{{name}} 正在编辑此页面,你的更改暂时无法保存。",
"pageEditor.lock.editingBySomeone": "其他人正在编辑此页面,你的更改暂时无法保存。",
diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.json
index ef575c3fe6b..65e060f8a4f 100644
--- a/locales/zh-CN/notification.json
+++ b/locales/zh-CN/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "你的文档有新评论",
"document_comment_mentioned": "{{actorLabel}} 在文档「{{documentTitle}}」的评论中提到了你。",
"document_comment_mentioned_title": "你在文档评论中被提及",
+ "document_liked": "{{actorLabel}} 赞了你的文档「{{documentTitle}}」。",
+ "document_liked_title": "你的文档收到点赞",
"email.footer.contactSupport": "联系支持",
"email.footer.joinDiscord": "加入 Discord",
"email.footer.manage": "管理通知",
diff --git a/locales/zh-TW/file.json b/locales/zh-TW/file.json
index 333fcc97b2b..03221440bd7 100644
--- a/locales/zh-TW/file.json
+++ b/locales/zh-TW/file.json
@@ -107,7 +107,6 @@
"pageEditor.comments.deleted": "此評論已被刪除。",
"pageEditor.comments.edit": "編輯",
"pageEditor.comments.edited": "(已編輯)",
- "pageEditor.comments.empty": "目前沒有評論。請在下方開始對話。",
"pageEditor.comments.hideReplies": "隱藏回覆",
"pageEditor.comments.loadMore": "載入更多評論",
"pageEditor.comments.loadMoreReplies": "載入更多回覆",
@@ -177,6 +176,11 @@
"pageEditor.history.title": "版本記錄",
"pageEditor.history.versionCount_one": "{{count}} 個版本",
"pageEditor.history.versionCount_other": "{{count}} 個版本",
+ "pageEditor.likes.count": "{{count}} 個讚",
+ "pageEditor.likes.failed": "更新您的讚失敗。請再試一次。",
+ "pageEditor.likes.like": "覺得這頁有幫助嗎?給個讚吧",
+ "pageEditor.likes.liked": "已讚",
+ "pageEditor.likes.more": "+{{count}} 更多",
"pageEditor.linkCopied": "連結已複製",
"pageEditor.lock.editingByOther": "{{name}} 正在編輯此頁面。您的更改目前無法保存。",
"pageEditor.lock.editingBySomeone": "其他人正在編輯此頁面。您的更改目前無法保存。",
diff --git a/locales/zh-TW/notification.json b/locales/zh-TW/notification.json
index 5063c7f727b..8b521fc7f3c 100644
--- a/locales/zh-TW/notification.json
+++ b/locales/zh-TW/notification.json
@@ -40,6 +40,8 @@
"document_comment_activity_title": "您的文件有新的評論",
"document_comment_mentioned": "{{actorLabel}} 在「{{documentTitle}}」的評論中提到了您。",
"document_comment_mentioned_title": "您在文件評論中被提及",
+ "document_liked": "{{actorLabel}} 喜歡您的文件「{{documentTitle}}」。",
+ "document_liked_title": "有人喜歡您的文件",
"email.footer.contactSupport": "聯絡支援",
"email.footer.joinDiscord": "加入 Discord",
"email.footer.manage": "管理通知",
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 6ba3f7b425b..33b88dffe01 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -207,6 +207,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
device: 'blocked',
document: rw('knowledge:read', 'knowledge:write'),
documentComment: rw('knowledge:read', 'knowledge:write'),
+ documentLike: rw('knowledge:read', 'knowledge:write'),
expertise: rw('agent:read', 'agent:write'),
// whole-account backup dump (settings incl. market tokens, providers, agents)
exporter: 'blocked',
diff --git a/packages/database/src/models/__tests__/documentLike.test.ts b/packages/database/src/models/__tests__/documentLike.test.ts
index b06b74e9127..aad4eab43b2 100644
--- a/packages/database/src/models/__tests__/documentLike.test.ts
+++ b/packages/database/src/models/__tests__/documentLike.test.ts
@@ -77,13 +77,15 @@ describe('DocumentLikeModel', () => {
});
it('likes idempotently, reports the document author, and stamps the workspace', async () => {
- await expect(memberModel.like(documentId)).resolves.toEqual({
+ await expect(memberModel.like(documentId)).resolves.toMatchObject({
created: true,
documentAuthorUserId: authorId,
+ summary: { liked: true, total: 1 },
});
- await expect(memberModel.like(documentId)).resolves.toEqual({
+ await expect(memberModel.like(documentId)).resolves.toMatchObject({
created: false,
documentAuthorUserId: authorId,
+ summary: { liked: true, total: 1 },
});
const rows = await serverDB
@@ -126,13 +128,15 @@ describe('DocumentLikeModel', () => {
await memberModel.like(documentId);
await authorModel.like(documentId);
- await expect(memberModel.unlike(documentId)).resolves.toEqual({
+ await expect(memberModel.unlike(documentId)).resolves.toMatchObject({
documentAuthorUserId: authorId,
removed: true,
+ summary: { liked: false, total: 1 },
});
- await expect(memberModel.unlike(documentId)).resolves.toEqual({
+ await expect(memberModel.unlike(documentId)).resolves.toMatchObject({
documentAuthorUserId: authorId,
removed: false,
+ summary: { liked: false, total: 1 },
});
const summary = await authorModel.summary(documentId);
diff --git a/packages/database/src/models/documentLike.ts b/packages/database/src/models/documentLike.ts
index 428f23343b8..e9f3591ac92 100644
--- a/packages/database/src/models/documentLike.ts
+++ b/packages/database/src/models/documentLike.ts
@@ -10,14 +10,20 @@ export const DOCUMENT_LIKE_WORKSPACE_REQUIRED =
'Document likes are workspace-scoped; a workspaceId is required';
export const DOCUMENT_LIKE_DOCUMENT_NOT_FOUND = 'Document not found in current workspace';
-/** Number of liker profiles returned with a summary. */
-export const DOCUMENT_LIKE_SUMMARY_LIKERS_LIMIT = 20;
+/**
+ * Defensive cap on liker profiles returned with a summary. Likers render as a
+ * full wrapped list in the UI, and workspace membership keeps real counts far
+ * below this; the cap only bounds the payload for pathological data.
+ */
+export const DOCUMENT_LIKE_SUMMARY_LIKERS_LIMIT = 200;
export interface LikeDocumentResult {
/** false when the current user had already liked the document. */
created: boolean;
/** Author of the document; receives the like notification. */
documentAuthorUserId: string;
+ /** Post-mutation summary, read inside the same transaction. */
+ summary: DocumentLikeSummary;
}
export interface UnlikeDocumentResult {
@@ -25,6 +31,8 @@ export interface UnlikeDocumentResult {
documentAuthorUserId: string;
/** false when the current user had not liked the document. */
removed: boolean;
+ /** Post-mutation summary, read inside the same transaction. */
+ summary: DocumentLikeSummary;
}
export class DocumentLikeModel {
@@ -70,9 +78,55 @@ export class DocumentLikeModel {
return { ...document, workspaceId };
};
+ /**
+ * Read the summary inside the caller's transaction so mutations return the
+ * post-write state without opening (and locking for) a second transaction.
+ * `knownLiked` skips the current-user probe when the caller just wrote it.
+ */
+ private summarizeInTx = async (
+ tx: LobeChatDatabase,
+ documentId: string,
+ knownLiked?: boolean,
+ ): Promise<DocumentLikeSummary> => {
+ const [[totals], likers] = await Promise.all([
+ tx
+ .select({ total: count() })
+ .from(documentLikes)
+ .where(eq(documentLikes.documentId, documentId)),
+ tx
+ .select({
+ avatar: users.avatar,
+ fullName: users.fullName,
+ id: users.id,
+ username: users.username,
+ })
+ .from(documentLikes)
+ .innerJoin(users, eq(users.id, documentLikes.userId))
+ .where(eq(documentLikes.documentId, documentId))
+ .orderBy(desc(documentLikes.createdAt), desc(documentLikes.id))
+ .limit(DOCUMENT_LIKE_SUMMARY_LIKERS_LIMIT),
+ ]);
+
+ const liked =
+ knownLiked ??
+ (likers.some((liker) => liker.id === this.userId) ||
+ (
+ await tx
+ .select({ id: documentLikes.id })
+ .from(documentLikes)
+ .where(
+ and(eq(documentLikes.documentId, documentId), eq(documentLikes.userId, this.userId)),
+ )
+ .limit(1)
+ ).length > 0);
+
+ return { liked, likers, total: totals?.total ?? 0 };
+ };
+
async like(documentId: string): Promise<LikeDocumentResult> {
return this.db.transaction(async (tx) => {
- const document = await this.lockDocument(tx as LobeChatDatabase, documentId, 'update');
+ const runner = tx as LobeChatDatabase;
+ const document = await this.lockDocument(runner, documentId, 'update');
const [inserted] = await tx
.insert(documentLikes)
@@ -80,64 +134,39 @@ export class DocumentLikeModel {
.onConflictDoNothing({ target: [documentLikes.documentId, documentLikes.userId] })
.returning({ id: documentLikes.id });
- return { created: Boolean(inserted), documentAuthorUserId: document.userId };
+ return {
+ created: Boolean(inserted),
+ documentAuthorUserId: document.userId,
+ summary: await this.summarizeInTx(runner, documentId, true),
+ };
});
}
async unlike(documentId: string): Promise<UnlikeDocumentResult> {
return this.db.transaction(async (tx) => {
- const document = await this.lockDocument(tx as LobeChatDatabase, documentId, 'update');
+ const runner = tx as LobeChatDatabase;
+ const document = await this.lockDocument(runner, documentId, 'update');
const removed = await tx
.delete(documentLikes)
.where(and(eq(documentLikes.documentId, documentId), eq(documentLikes.userId, this.userId)))
.returning({ id: documentLikes.id });
- return { documentAuthorUserId: document.userId, removed: removed.length > 0 };
+ return {
+ documentAuthorUserId: document.userId,
+ removed: removed.length > 0,
+ summary: await this.summarizeInTx(runner, documentId, false),
+ };
});
}
async summary(documentId: string): Promise<DocumentLikeSummary> {
return this.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
// A share lock keeps the workspace validation true for the duration of
// the reads: a concurrent transfer's UPDATE waits for this transaction.
- await this.lockDocument(tx as LobeChatDatabase, documentId, 'share');
-
- const [[totals], likers] = await Promise.all([
- tx
- .select({ total: count() })
- .from(documentLikes)
- .where(eq(documentLikes.documentId, documentId)),
- tx
- .select({
- avatar: users.avatar,
- fullName: users.fullName,
- id: users.id,
- username: users.username,
- })
- .from(documentLikes)
- .innerJoin(users, eq(users.id, documentLikes.userId))
- .where(eq(documentLikes.documentId, documentId))
- .orderBy(desc(documentLikes.createdAt), desc(documentLikes.id))
- .limit(DOCUMENT_LIKE_SUMMARY_LIKERS_LIMIT),
- ]);
-
- const liked = likers.some((liker) => liker.id === this.userId)
- ? true
- : (
- await tx
- .select({ id: documentLikes.id })
- .from(documentLikes)
- .where(
- and(
- eq(documentLikes.documentId, documentId),
- eq(documentLikes.userId, this.userId),
- ),
- )
- .limit(1)
- ).length > 0;
-
- return { liked, likers, total: totals?.total ?? 0 };
+ await this.lockDocument(runner, documentId, 'share');
+ return this.summarizeInTx(runner, documentId);
});
}
}
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 9e2d1480a8a..2b9a92f33a7 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -120,7 +120,6 @@ export default {
'pageEditor.comments.deleted': 'This comment was deleted.',
'pageEditor.comments.edit': 'Edit',
'pageEditor.comments.edited': '(edited)',
- 'pageEditor.comments.empty': 'No comments yet. Start the conversation below.',
'pageEditor.comments.hideReplies': 'Hide replies',
'pageEditor.comments.loadMore': 'Load more comments',
'pageEditor.comments.loadMoreReplies': 'Load more replies',
@@ -134,6 +133,13 @@ export default {
'pageEditor.comments.save': 'Save',
'pageEditor.comments.title': 'Comments',
'pageEditor.comments.updateFailed': 'Failed to update comment. Try again.',
+ 'pageEditor.likes.failed': 'Failed to update your like. Try again.',
+ 'pageEditor.likes.like': 'Find this page helpful? Give it a like',
+ 'pageEditor.likes.liked': 'Liked',
+ 'pageEditor.likes.count': '{{count}} likes',
+ 'pageEditor.likes.count_one': '{{count}} like',
+ 'pageEditor.likes.count_other': '{{count}} likes',
+ 'pageEditor.likes.more': '+{{count}} more',
'pageEditor.deleteConfirm.content':
'This page will be deleted and cannot be recovered. Please proceed with caution.',
'pageEditor.deleteConfirm.title': 'Delete Page',
diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.ts
index ee096d610c2..954657cda74 100644
--- a/packages/locales/src/default/notification.ts
+++ b/packages/locales/src/default/notification.ts
@@ -95,6 +95,8 @@ export default {
'document_comment_activity_title': 'New comment on your document',
'document_comment_mentioned': '{{actorLabel}} mentioned you in a comment on "{{documentTitle}}".',
'document_comment_mentioned_title': 'You were mentioned in a document comment',
+ 'document_liked': '{{actorLabel}} liked your document "{{documentTitle}}".',
+ 'document_liked_title': 'Someone liked your document',
'subscription_payment_failed':
'Your subscription renewal payment failed. Please update your payment method to keep your subscription active.',
'subscription_payment_failed_action': 'Update payment method',
diff --git a/src/business/server/document-like/notifyActivity.ts b/src/business/server/document-like/notifyActivity.ts
new file mode 100644
index 00000000000..5e98fa1f505
--- /dev/null
+++ b/src/business/server/document-like/notifyActivity.ts
@@ -0,0 +1,15 @@
+export interface DocumentLikeActivityParams {
+ actorUserId: string;
+ documentId: string;
+ recipientUserId: string;
+ workspaceId: string;
+}
+
+/** Notify the document author that a member liked their document. */
+export const notifyDocumentLiked = (_params: DocumentLikeActivityParams): Promise<void> =>
+ Promise.resolve();
+
+/** Withdraw the like notification after the member removes their like. */
+export const revokeDocumentLikeNotification = (
+ _params: DocumentLikeActivityParams,
+): Promise<void> => Promise.resolve();
diff --git a/src/features/PageEditor/DocumentComments/index.tsx b/src/features/PageEditor/DocumentComments/index.tsx
index a7295498d39..3b182b0d595 100644
--- a/src/features/PageEditor/DocumentComments/index.tsx
+++ b/src/features/PageEditor/DocumentComments/index.tsx
@@ -1,8 +1,7 @@
'use client';
-import { Center, Empty, Flexbox, Skeleton } from '@lobehub/ui';
+import { Center, Flexbox, Skeleton } from '@lobehub/ui';
import { Button, Text } from '@lobehub/ui/base-ui';
-import { MessageCircle } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -161,11 +160,7 @@ const DocumentComments = memo<{ documentId: string }>(({ documentId }) => {
<AsyncError error={threads.error} variant={'block'} onRetry={() => void threads.reload()} />
) : threads.isLoadingInitial ? (
<SurfaceSkeleton header={false} variant={'list'} />
- ) : threads.items.length === 0 ? (
- <Center className={styles.empty}>
- <Empty description={t('pageEditor.comments.empty')} icon={MessageCircle} />
- </Center>
- ) : (
+ ) : threads.items.length === 0 ? null : (
<Flexbox className={styles.threadList}>
{threads.items.map(({ replyCount, root }) => (
<Thread
diff --git a/src/features/PageEditor/DocumentComments/styles.ts b/src/features/PageEditor/DocumentComments/styles.ts
index fb84c9ee522..022ab4fd312 100644
--- a/src/features/PageEditor/DocumentComments/styles.ts
+++ b/src/features/PageEditor/DocumentComments/styles.ts
@@ -104,9 +104,6 @@ export const styles = createStaticStyles(({ css }) => ({
box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};
}
`,
- empty: css`
- min-height: 120px;
- `,
header: css`
min-height: 32px;
`,
diff --git a/src/features/PageEditor/DocumentLikes/index.tsx b/src/features/PageEditor/DocumentLikes/index.tsx
new file mode 100644
index 00000000000..057945881a6
--- /dev/null
+++ b/src/features/PageEditor/DocumentLikes/index.tsx
@@ -0,0 +1,298 @@
+'use client';
+
+import type { DocumentLikeSummary } from '@lobechat/types';
+import { useAnalytics } from '@lobehub/analytics/react';
+import { Flexbox, Skeleton } from '@lobehub/ui';
+import { Avatar, Text, toast, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ThumbsUp } from 'lucide-react';
+import { memo, useCallback, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
+import AsyncError from '@/components/AsyncError';
+import { useClientDataSWR } from '@/libs/swr';
+import { documentLikeKeys } from '@/libs/swr/keys';
+import { documentLikeService } from '@/services/documentLike';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+const BUTTON_SIZE = 56;
+const ICON_SIZE = 22;
+
+const styles = createStaticStyles(({ css }) => ({
+ avatars: css`
+ flex-wrap: wrap;
+ justify-content: center;
+
+ /* ~15 avatars per row: 15 × (32px avatar + 8px gap) */
+ max-width: 600px;
+ min-height: 32px;
+ `,
+ button: css`
+ cursor: pointer;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: ${BUTTON_SIZE}px;
+ height: ${BUTTON_SIZE}px;
+ padding: 0;
+ border: 1px solid ${cssVar.colorPrimary};
+ border-radius: 50%;
+
+ color: ${cssVar.colorPrimary};
+
+ background: transparent;
+
+ transition:
+ transform ${cssVar.motionDurationMid} ${cssVar.motionEaseOutBack},
+ background-color ${cssVar.motionDurationMid},
+ border-color ${cssVar.motionDurationMid},
+ color ${cssVar.motionDurationMid},
+ box-shadow ${cssVar.motionDurationMid};
+
+ &:hover {
+ transform: scale(1.06);
+ background: ${cssVar.colorPrimaryBg};
+ }
+
+ &:active {
+ transform: scale(0.94);
+ }
+
+ &:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px ${cssVar.colorPrimaryBg};
+ }
+
+ &[aria-pressed='true'] {
+ border-color: ${cssVar.colorWarning};
+ color: ${cssVar.colorWhite};
+ background: ${cssVar.colorWarning};
+ box-shadow: 0 8px 24px ${cssVar.colorWarningBg};
+
+ &:hover {
+ background: ${cssVar.colorWarningHover};
+ }
+
+ &:focus-visible {
+ box-shadow: 0 0 0 3px ${cssVar.colorWarningBg};
+ }
+ }
+
+ &:disabled {
+ cursor: progress;
+ opacity: 0.7;
+ }
+ `,
+ caption: css`
+ display: flex;
+ gap: 16px;
+ align-items: center;
+
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ &::before,
+ &::after {
+ content: '';
+ width: 40px;
+ height: 1px;
+ background: ${cssVar.colorBorderSecondary};
+ }
+ `,
+ section: css`
+ width: 100%;
+ margin-block-start: 48px;
+ `,
+}));
+
+const useDocumentLikeSummary = (workspaceId: string | null, documentId?: string | null) =>
+ useClientDataSWR<DocumentLikeSummary>(
+ workspaceId && documentId ? documentLikeKeys.summary(workspaceId, documentId) : null,
+ () => documentLikeService.summary(documentId!),
+ { dedupingInterval: 30_000 },
+ );
+
+const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {
+ const { t } = useTranslation('file');
+ const workspaceId = useActiveWorkspaceId();
+ const user = useUserStore(userProfileSelectors.userProfile);
+ const { analytics } = useAnalytics();
+ const { data, error, isLoading, mutate } = useDocumentLikeSummary(workspaceId, documentId);
+ // Last user-intended liked state; null when the UI matches the server.
+ const targetRef = useRef<boolean | null>(null);
+ const inFlightRef = useRef(false);
+
+ // Send requests until the server state matches the latest intent. Clicks
+ // landing while a request is in flight only update targetRef (the UI already
+ // flipped optimistically), so every click responds instantly and a rapid
+ // like→unlike coalesces into sequential calls instead of being dropped.
+ const drain = useCallback(async () => {
+ if (inFlightRef.current) return;
+ inFlightRef.current = true;
+ let sent: boolean | undefined;
+ try {
+ let summary: DocumentLikeSummary | undefined;
+ while (targetRef.current !== null && targetRef.current !== sent) {
+ sent = targetRef.current;
+ summary = sent
+ ? await documentLikeService.like(documentId)
+ : await documentLikeService.unlike(documentId);
+ // Bounded dimensions only — no document id, which would create an
+ // unbounded high-cardinality analytics field.
+ analytics?.track({
+ name: 'document_like_toggle',
+ properties: {
+ action: sent ? 'like' : 'unlike',
+ outcome: 'success',
+ spm: 'page_editor.likes.toggle',
+ },
+ });
+ }
+ targetRef.current = null;
+ if (summary) await mutate(summary, { revalidate: false });
+ } catch (toggleError) {
+ console.error('Failed to toggle document like', toggleError);
+ // Attribute the failure to the request that actually failed (`sent`),
+ // not the latest queued intent, which may already point the other way.
+ if (sent !== undefined)
+ analytics?.track({
+ name: 'document_like_toggle',
+ properties: {
+ action: sent ? 'like' : 'unlike',
+ outcome: 'failure',
+ spm: 'page_editor.likes.toggle',
+ },
+ });
+ targetRef.current = null;
+ toast.error(t('pageEditor.likes.failed'));
+ // Recover the truth from the server rather than guessing a rollback
+ // point across coalesced toggles. The recovery fetch itself can fail
+ // (e.g. an outage) — swallow it so drain() never rejects out of a void
+ // call; SWR revalidates again on the next focus/interval and corrects
+ // any stale optimistic state then.
+ await mutate().catch(() => undefined);
+ } finally {
+ inFlightRef.current = false;
+ }
+ }, [analytics, documentId, mutate, t]);
+
+ const toggle = useCallback(() => {
+ if (!data) return;
+
+ const nextLiked = !(targetRef.current ?? data.liked);
+ targetRef.current = nextLiked;
+
+ void mutate(
+ (previous) => {
+ if (!previous) return previous;
+ return nextLiked
+ ? {
+ liked: true,
+ likers: [
+ {
+ avatar: user?.avatar ?? null,
+ fullName: user?.fullName ?? null,
+ id: user?.id ?? 'me',
+ username: user?.username ?? null,
+ },
+ ...previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),
+ ],
+ total: previous.total + 1,
+ }
+ : {
+ liked: false,
+ likers: previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),
+ total: Math.max(0, previous.total - 1),
+ };
+ },
+ { revalidate: false },
+ );
+ void drain();
+ }, [data, drain, mutate, user?.avatar, user?.fullName, user?.id, user?.username]);
+
+ if (!workspaceId) return null;
+
+ // A failed initial load must not masquerade as a zero-like page: surface a
+ // retryable error instead of the idle state with a dead button.
+ if (!data && error)
+ return (
+ <Flexbox data-document-likes align={'center'} className={styles.section} gap={16}>
+ <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />
+ </Flexbox>
+ );
+
+ // Match the surrounding page skeleton while the summary loads instead of
+ // flashing the finished idle state ahead of the rest of the content.
+ if (isLoading && !data)
+ return (
+ <Flexbox data-document-likes align={'center'} className={styles.section} gap={16}>
+ <Skeleton.Avatar active shape={'circle'} size={BUTTON_SIZE} />
+ <Skeleton.Button active style={{ height: 20, width: 200 }} />
+ </Flexbox>
+ );
+
+ const liked = data?.liked ?? false;
+ const likers = data?.likers ?? [];
+ const total = data?.total ?? 0;
+ const overflow = Math.max(0, total - likers.length);
+ // The filled button already says "you liked this"; the caption only carries
+ // the count (or the invite copy while nobody has liked yet).
+ const label =
+ total > 0 ? t('pageEditor.likes.count', { count: total }) : t('pageEditor.likes.like');
+ const ariaLabel = liked ? t('pageEditor.likes.liked') : t('pageEditor.likes.like');
+
+ return (
+ <Flexbox
+ data-document-likes
+ align={'center'}
+ className={styles.section}
+ gap={16}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <button
+ aria-label={ariaLabel}
+ aria-pressed={liked}
+ className={styles.button}
+ disabled={isLoading || !data}
+ type={'button'}
+ onClick={() => void toggle()}
+ >
+ <ThumbsUp
+ fill={liked ? 'currentColor' : 'none'}
+ size={ICON_SIZE}
+ strokeWidth={liked ? 0 : 1.5}
+ />
+ </button>
+ <span className={styles.caption}>
+ <Text as={'span'} color={'inherit'} fontSize={13}>
+ {label}
+ </Text>
+ </span>
+ {(likers.length > 0 || overflow > 0) && (
+ <Flexbox horizontal className={styles.avatars} gap={8}>
+ {likers.map((liker) => {
+ const name = liker.fullName || liker.username || liker.id;
+ return (
+ <Tooltip key={liker.id} title={name}>
+ <Avatar avatar={liker.avatar || name} size={32} />
+ </Tooltip>
+ );
+ })}
+ {overflow > 0 && (
+ <Text fontSize={13} type={'secondary'}>
+ {t('pageEditor.likes.more', { count: overflow })}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+DocumentLikes.displayName = 'DocumentLikes';
+
+export default DocumentLikes;
diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsx
index 168b4f7cf18..12f549b59a9 100644
--- a/src/features/PageEditor/PageEditor.tsx
+++ b/src/features/PageEditor/PageEditor.tsx
@@ -19,6 +19,7 @@ import { usePageStore } from '@/store/page';
import { StyleSheet } from '@/utils/styles';
import DocumentComments from './DocumentComments';
+import DocumentLikes from './DocumentLikes';
import EditorCanvas from './EditorCanvas';
import Header from './Header';
import LockedAlert from './LockedAlert';
@@ -316,6 +317,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {
compact status badge lives in the Header (EditingIndicator). */}
<LockedAlert />
<EditorCanvas askCopilotTarget={askCopilotTarget} />
+ {documentId && <DocumentLikes documentId={documentId} key={documentId} />}
{documentId && <DocumentComments documentId={documentId} />}
</Flexbox>
</WideScreenContainer>
diff --git a/src/features/PageEditor/resourceEventUtils.test.ts b/src/features/PageEditor/resourceEventUtils.test.ts
index d43090cc57a..4b364ac1af8 100644
--- a/src/features/PageEditor/resourceEventUtils.test.ts
+++ b/src/features/PageEditor/resourceEventUtils.test.ts
@@ -7,6 +7,9 @@ describe('shouldIgnoreResourceEvent', () => {
expect(
shouldIgnoreResourceEvent({ actorId: 'user-1', type: 'document.commentsChanged' }, 'user-1'),
).toBe(false);
+ expect(
+ shouldIgnoreResourceEvent({ actorId: 'user-1', type: 'document.likesChanged' }, 'user-1'),
+ ).toBe(false);
});
it('continues to suppress other same-user resource echoes', () => {
diff --git a/src/features/PageEditor/resourceEventUtils.ts b/src/features/PageEditor/resourceEventUtils.ts
index 4b4c07bc465..cc92542e5aa 100644
--- a/src/features/PageEditor/resourceEventUtils.ts
+++ b/src/features/PageEditor/resourceEventUtils.ts
@@ -3,9 +3,12 @@ interface ResourceEventIdentity {
type?: string;
}
+/** Events that must still refresh another window signed in as the same actor. */
+const SAME_USER_FANOUT_EVENTS = new Set(['document.commentsChanged', 'document.likesChanged']);
+
export const shouldIgnoreResourceEvent = (
event: ResourceEventIdentity,
currentUserId?: string,
): boolean =>
- event.type !== 'document.commentsChanged' &&
+ !SAME_USER_FANOUT_EVENTS.has(event.type ?? '') &&
Boolean(event.actorId && currentUserId && event.actorId === currentUserId);
diff --git a/src/features/PageEditor/useResourceEvents.ts b/src/features/PageEditor/useResourceEvents.ts
index ab99dc546f3..d780a1c5b3d 100644
--- a/src/features/PageEditor/useResourceEvents.ts
+++ b/src/features/PageEditor/useResourceEvents.ts
@@ -4,7 +4,7 @@ import { fetchEventSource } from '@lobechat/utils/client';
import { useEffect } from 'react';
import { mutate } from '@/libs/swr';
-import { isDocumentCommentKeyForEvent } from '@/libs/swr/keys';
+import { documentLikeKeys, isDocumentCommentKeyForEvent } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { documentSWRKeys } from '@/services/document/swrKeys';
import { pageSelectors, usePageStore } from '@/store/page';
@@ -82,7 +82,7 @@ export const useResourceEvents = () => {
return;
}
// Content and lock mutations are already reflected locally, but comment
- // events must reach another window signed in as the same account.
+ // and like events must reach another window signed in as the same account.
if (shouldIgnoreResourceEvent(parsed, myUserId)) return;
if (parsed.type === 'doc.updated') {
@@ -97,6 +97,8 @@ export const useResourceEvents = () => {
workspaceId,
}),
);
+ } else if (parsed.type === 'document.likesChanged' && workspaceId) {
+ void mutate(documentLikeKeys.summary(workspaceId, documentId));
} else if (parsed.type === 'lock.changed') {
// Store the holder verbatim; "locked by other" is derived against
// the current user/session at read time (usePageLockedByOther).
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 069b8ff7a72..9c91e0adfed 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -198,6 +198,15 @@ export const documentCommentKeys = {
),
};
+// ---- document like ------------------------------------------------------
+export const documentLikeKeys = {
+ summary: def('documentLike:summary', (workspaceId: string | null, documentId: string) => [
+ 'documentLike:summary',
+ workspaceId ?? '',
+ documentId,
+ ]),
+};
+
export const isDocumentCommentKeyForEvent = (
key: unknown,
event: { documentId: string; rootCommentId?: string; workspaceId: string },
@@ -1410,6 +1419,7 @@ export const swrKeys = {
topic: topicKeys,
topicComment: topicCommentKeys,
documentComment: documentCommentKeys,
+ documentLike: documentLikeKeys,
topicAction: topicActionKeys,
user: userKeys,
userMemory: userMemoryKeys,
diff --git a/src/services/documentLike.ts b/src/services/documentLike.ts
new file mode 100644
index 00000000000..66d4ec1e8a4
--- /dev/null
+++ b/src/services/documentLike.ts
@@ -0,0 +1,11 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+class DocumentLikeService {
+ like = (documentId: string) => lambdaClient.documentLike.like.mutate({ documentId });
+
+ summary = (documentId: string) => lambdaClient.documentLike.summary.query({ documentId });
+
+ unlike = (documentId: string) => lambdaClient.documentLike.unlike.mutate({ documentId });
+}
+
+export const documentLikeService = new DocumentLikeService();