Add comment threads, reactions, notifications and page watching
Comments are now threads: replies hang off a thread's first comment, which alone points at text and can be resolved. Authors can edit their own comments, and anyone who can comment can react with an emoji. Resolved threads stop lighting text in the editor and fold away in the panel. Comments can @mention people. People watch the pages they create or comment on, and can watch or mute a page from its menu. Muting is remembered. The inbox collects comments on watched pages, replies in your threads, mentions (in comments and in page text), pages shared with you and resolved threads. It shows an unread badge in the sidebar, polled every minute, and links straight to the thread. Nobody hears about their own actions or about pages they cannot open, and a notification hides its text once access is lost. Unread notifications are emailed as a digest every few minutes unless the person turns that off. Read ones are pruned after 90 days. The jobs registry can now run jobs on a timer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7968e82cc2
commit
2b78c167e2
31 files changed
+3083
-166
No files matched your search
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// Comment threads, reactions, page watching and notifications.
|
||||
//
|
||||
// A reply is a comment with a parent (always the thread's first comment,
|
||||
// which alone carries the anchor and can be resolved). reactions maps an
|
||||
// emoji to the ids of the people who reacted with it.
|
||||
//
|
||||
// page_watchers.watching false means the person muted the page, so taking
|
||||
// part in it later does not start watching it again.
|
||||
//
|
||||
// pages.mentions remembers who the page already mentions, so a save only
|
||||
// notifies people who were newly mentioned.
|
||||
//
|
||||
// users.notify_email is "digest" (default when empty) or "off".
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
const pages = app.findCollectionByNameOrId("pages");
|
||||
const workspaces = app.findCollectionByNameOrId("workspaces");
|
||||
const comments = app.findCollectionByNameOrId("comments");
|
||||
|
||||
comments.fields.add(new RelationField({ name: "parent", collectionId: comments.id, maxSelect: 1, cascadeDelete: true }));
|
||||
comments.fields.add(new DateField({ name: "resolved_at" }));
|
||||
comments.fields.add(new RelationField({ name: "resolved_by", collectionId: users.id, maxSelect: 1, cascadeDelete: false }));
|
||||
comments.fields.add(new JSONField({ name: "reactions", maxSize: 20000 }));
|
||||
comments.fields.add(new DateField({ name: "edited_at" }));
|
||||
comments.indexes = [
|
||||
"CREATE INDEX idx_comments_page ON comments (page, created)",
|
||||
"CREATE INDEX idx_comments_parent ON comments (parent)",
|
||||
];
|
||||
app.save(comments);
|
||||
|
||||
pages.fields.add(new JSONField({ name: "mentions", maxSize: 20000 }));
|
||||
app.save(pages);
|
||||
|
||||
users.fields.add(new SelectField({ name: "notify_email", values: ["digest", "off"], maxSelect: 1 }));
|
||||
app.save(users);
|
||||
|
||||
app.save(
|
||||
new Collection({
|
||||
type: "base",
|
||||
name: "page_watchers",
|
||||
fields: [
|
||||
{ name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "watching", type: "bool" },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
indexes: [
|
||||
"CREATE UNIQUE INDEX idx_page_watchers_unique ON page_watchers (page, user)",
|
||||
"CREATE INDEX idx_page_watchers_user ON page_watchers (user)",
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
app.save(
|
||||
new Collection({
|
||||
type: "base",
|
||||
name: "notifications",
|
||||
fields: [
|
||||
{ name: "user", type: "relation", collectionId: users.id, maxSelect: 1, required: true, cascadeDelete: true },
|
||||
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, cascadeDelete: true },
|
||||
{ name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, cascadeDelete: true },
|
||||
{ name: "comment", type: "relation", collectionId: comments.id, maxSelect: 1, cascadeDelete: true },
|
||||
{ name: "actor", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false },
|
||||
{
|
||||
name: "type",
|
||||
type: "select",
|
||||
values: ["comment", "reply", "mention", "share", "resolved"],
|
||||
maxSelect: 1,
|
||||
required: true,
|
||||
},
|
||||
// What the notification says beyond its links, e.g. a comment excerpt.
|
||||
{ name: "excerpt", type: "text", max: 300 },
|
||||
{ name: "read_at", type: "date" },
|
||||
{ name: "emailed_at", type: "date" },
|
||||
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
|
||||
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
|
||||
],
|
||||
indexes: [
|
||||
"CREATE INDEX idx_notifications_user ON notifications (user, created)",
|
||||
"CREATE INDEX idx_notifications_unread ON notifications (user, read_at)",
|
||||
"CREATE INDEX idx_notifications_mail ON notifications (emailed_at, read_at)",
|
||||
],
|
||||
}),
|
||||
);
|
||||
},
|
||||
(app) => {
|
||||
for (const name of ["notifications", "page_watchers"]) {
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId(name));
|
||||
} catch (_) {}
|
||||
}
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
users.fields.removeByName("notify_email");
|
||||
app.save(users);
|
||||
const pages = app.findCollectionByNameOrId("pages");
|
||||
pages.fields.removeByName("mentions");
|
||||
app.save(pages);
|
||||
const comments = app.findCollectionByNameOrId("comments");
|
||||
for (const f of ["edited_at", "reactions", "resolved_by", "resolved_at", "parent"]) comments.fields.removeByName(f);
|
||||
comments.indexes = ["CREATE INDEX idx_comments_page ON comments (page, created)"];
|
||||
app.save(comments);
|
||||
},
|
||||
);
|
||||
@@ -45,6 +45,12 @@ export type Job = Schemas["Job"];
|
||||
export type Backup = Schemas["Backup"];
|
||||
export type SharedPage = Schemas["SharedPage"];
|
||||
export type PageGrantRole = Schemas["PageGrantRole"];
|
||||
export type Reaction = Schemas["Reaction"];
|
||||
export type WatchState = Schemas["WatchState"];
|
||||
export type NotificationType = Schemas["NotificationType"];
|
||||
export type Notification = Schemas["Notification"];
|
||||
export type NotificationList = Schemas["NotificationList"];
|
||||
export type NotificationSettings = Schemas["NotificationSettings"];
|
||||
export type PageGrant = Schemas["PageGrant"];
|
||||
export type PageInvite = Schemas["PageInvite"];
|
||||
export type PageAccess = Schemas["PageAccess"];
|
||||
@@ -177,7 +183,27 @@ export function createClient(opts: ClientOptions) {
|
||||
},
|
||||
|
||||
comments: {
|
||||
update: (id: string, body: string) =>
|
||||
request<Comment>("PATCH", `/api/v1/comments/${encodeURIComponent(id)}`, { body }),
|
||||
remove: (id: string) => request<void>("DELETE", `/api/v1/comments/${encodeURIComponent(id)}`),
|
||||
resolve: (id: string, resolved: boolean) =>
|
||||
post<Comment>(`/api/v1/comments/${encodeURIComponent(id)}/resolve`, { resolved }),
|
||||
react: (id: string, emoji: string, on: boolean) =>
|
||||
post<Comment>(`/api/v1/comments/${encodeURIComponent(id)}/reactions`, { emoji, on }),
|
||||
},
|
||||
|
||||
notifications: {
|
||||
list: (opts: { unread?: boolean; limit?: number } = {}) =>
|
||||
request<NotificationList>(
|
||||
"GET",
|
||||
`/api/v1/notifications${query({ unread: opts.unread ? "true" : undefined, limit: opts.limit?.toString() })}`,
|
||||
),
|
||||
/** Marks the listed notifications read, or all of them; resolves to the unread count. */
|
||||
markRead: (input: { ids?: string[]; all?: boolean }) =>
|
||||
post<{ unread: number }>("/api/v1/notifications/read", input),
|
||||
settings: () => request<NotificationSettings>("GET", "/api/v1/notifications/settings"),
|
||||
setSettings: (input: NotificationSettings) =>
|
||||
request<NotificationSettings>("PUT", "/api/v1/notifications/settings", input),
|
||||
},
|
||||
|
||||
files: {
|
||||
@@ -337,8 +363,19 @@ export function createClient(opts: ClientOptions) {
|
||||
return upload<Attachment>(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form);
|
||||
},
|
||||
comments: (id: string) => request<Comment[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/comments`),
|
||||
addComment: (id: string, input: { body: string; quote?: string; anchor?: Record<string, unknown> | null }) =>
|
||||
post<Comment>(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input),
|
||||
watch: (id: string) => request<WatchState>("GET", `/api/v1/pages/${encodeURIComponent(id)}/watch`),
|
||||
setWatch: (id: string, watching: boolean) =>
|
||||
request<WatchState>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/watch`, { watching }),
|
||||
addComment: (
|
||||
id: string,
|
||||
input: {
|
||||
body: string;
|
||||
quote?: string;
|
||||
anchor?: Record<string, unknown> | null;
|
||||
parent?: string;
|
||||
mentions?: string[];
|
||||
},
|
||||
) => post<Comment>(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input),
|
||||
/** The public link; rejects with a 404 ApiError when sharing is off. */
|
||||
shareLink: (id: string) => request<ShareLink>("GET", `/api/v1/pages/${encodeURIComponent(id)}/share`),
|
||||
setShareLink: (id: string, includeSubpages: boolean) =>
|
||||
|
||||
Vendored
+418
-5
@@ -1387,10 +1387,13 @@ export interface paths {
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** The page's inline comments, oldest first */
|
||||
/** The page's comments and replies, oldest first (threads are the ones without a parent) */
|
||||
get: operations["listComments"];
|
||||
put?: never;
|
||||
/** Comment on the page (commenter) */
|
||||
/**
|
||||
* Start a thread on the page, or reply to one (commenter)
|
||||
* @description The author starts watching the page. Watchers, the thread's people and mentioned people are notified.
|
||||
*/
|
||||
post: operations["createComment"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
@@ -1410,10 +1413,124 @@ export interface paths {
|
||||
get?: never;
|
||||
put?: never;
|
||||
post?: never;
|
||||
/** Delete a comment (its author, or a space admin) */
|
||||
/** Delete a comment, and a thread's replies with it (its author, or a space admin) */
|
||||
delete: operations["deleteComment"];
|
||||
options?: never;
|
||||
head?: never;
|
||||
/** Change a comment's text (its author) */
|
||||
patch: operations["updateComment"];
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/comments/{id}/resolve": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Resolve a thread, or open it again (commenter) */
|
||||
post: operations["resolveComment"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/comments/{id}/reactions": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Add or remove the caller's emoji reaction (commenter) */
|
||||
post: operations["reactToComment"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/pages/{id}/watch": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
/** Whether the caller watches the page */
|
||||
get: operations["getPageWatch"];
|
||||
/**
|
||||
* Watch the page, or mute it
|
||||
* @description Muting is remembered, so commenting later does not start watching again.
|
||||
*/
|
||||
put: operations["setPageWatch"];
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/notifications": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** The caller's newest notifications with the unread count */
|
||||
get: operations["listNotifications"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/notifications/read": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** Mark notifications read (the listed ones, or all) */
|
||||
post: operations["markNotificationsRead"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/notifications/settings": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/** The caller's notification preferences */
|
||||
get: operations["getNotificationSettings"];
|
||||
/** Change the caller's notification preferences */
|
||||
put: operations["setNotificationSettings"];
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
@@ -1983,6 +2100,8 @@ export interface components {
|
||||
};
|
||||
Comment: {
|
||||
id: string;
|
||||
/** @description The thread's first comment for a reply; empty for a thread */
|
||||
parent: string;
|
||||
page: string;
|
||||
author: components["schemas"]["MemberUser"];
|
||||
body: string;
|
||||
@@ -1992,7 +2111,53 @@ export interface components {
|
||||
[key: string]: unknown;
|
||||
} | null;
|
||||
created: string;
|
||||
/** @description Empty when never edited */
|
||||
editedAt: string;
|
||||
/** @description Empty unless the thread is resolved */
|
||||
resolvedAt: string;
|
||||
resolvedBy: components["schemas"]["MemberUser"] | null;
|
||||
/** @description Most used first */
|
||||
reactions: components["schemas"]["Reaction"][];
|
||||
canEdit: boolean;
|
||||
canDelete: boolean;
|
||||
/** @description A thread the caller may resolve or reopen */
|
||||
canResolve: boolean;
|
||||
};
|
||||
Reaction: {
|
||||
emoji: string;
|
||||
count: number;
|
||||
mine: boolean;
|
||||
/** @description Names of the people who reacted */
|
||||
people: string[];
|
||||
};
|
||||
WatchState: {
|
||||
watching: boolean;
|
||||
};
|
||||
/** @enum {string} */
|
||||
NotificationType: "comment" | "reply" | "mention" | "share" | "resolved";
|
||||
Notification: {
|
||||
id: string;
|
||||
type: components["schemas"]["NotificationType"];
|
||||
workspace: string;
|
||||
/** @description Null when the page is gone or the caller lost access to it */
|
||||
page: components["schemas"]["PageRef"] | null;
|
||||
/** @description The comment it is about */
|
||||
comment: string;
|
||||
actor: components["schemas"]["MemberUser"] | null;
|
||||
excerpt: string;
|
||||
created: string;
|
||||
read: boolean;
|
||||
};
|
||||
NotificationList: {
|
||||
items: components["schemas"]["Notification"][];
|
||||
unread: number;
|
||||
};
|
||||
NotificationSettings: {
|
||||
/**
|
||||
* @description Unread notifications by email every few minutes
|
||||
* @enum {string}
|
||||
*/
|
||||
email: "digest" | "off";
|
||||
};
|
||||
AdminStats: {
|
||||
/** @enum {string} */
|
||||
@@ -4562,12 +4727,16 @@ export interface operations {
|
||||
content: {
|
||||
"application/json": {
|
||||
body: string;
|
||||
/** @description The commented text */
|
||||
/** @description The commented text (threads only) */
|
||||
quote?: string;
|
||||
/** @description The editor's encoding of the commented range (opaque to the server) */
|
||||
/** @description The editor's encoding of the commented range, opaque to the server (threads only) */
|
||||
anchor?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** @description The thread to reply to */
|
||||
parent?: string;
|
||||
/** @description Ids of the people mentioned in body */
|
||||
mentions?: string[];
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -4608,6 +4777,250 @@ export interface operations {
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
updateComment: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
body: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Comment"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
resolveComment: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
resolved: boolean;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Comment"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
reactToComment: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
emoji: string;
|
||||
on: boolean;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Comment"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
403: components["responses"]["Error"];
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getPageWatch: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["WatchState"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
setPageWatch: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path: {
|
||||
id: string;
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["WatchState"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["WatchState"];
|
||||
};
|
||||
};
|
||||
404: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
listNotifications: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description Only unread ones */
|
||||
unread?: boolean;
|
||||
limit?: number;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["NotificationList"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
markNotificationsRead: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
ids?: string[];
|
||||
all?: boolean;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The unread count afterwards */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
unread: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getNotificationSettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["NotificationSettings"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
setNotificationSettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["NotificationSettings"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["NotificationSettings"];
|
||||
};
|
||||
};
|
||||
400: components["responses"]["Error"];
|
||||
};
|
||||
};
|
||||
getAdminStats: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
||||
@@ -76,6 +76,11 @@ export const iconPaths = {
|
||||
"M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9",
|
||||
"M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9",
|
||||
],
|
||||
bell: ["M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z", "M10 20a2 2 0 0 0 4 0"],
|
||||
"bell-off": ["M6 16V11a6 6 0 0 1 9.5-4.9", "M18 11v5l1.5 2H8", "M10 20a2 2 0 0 0 4 0", "M4 4l16 16"],
|
||||
smile: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M8.5 14a4 4 0 0 0 7 0", "M9 9.5h.01", "M15 9.5h.01"],
|
||||
reply: ["M9 7L4 12l5 5", "M4 12h10a6 6 0 0 1 6 6v1"],
|
||||
pencil: ["M15 5l4 4L8 20H4v-4z"],
|
||||
users: [
|
||||
"M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z",
|
||||
"M3 20a6 6 0 0 1 12 0",
|
||||
|
||||
@@ -2047,17 +2047,25 @@ class SharedPage {
|
||||
class Comment {
|
||||
const Comment({
|
||||
required this.id,
|
||||
required this.parent,
|
||||
required this.page,
|
||||
required this.author,
|
||||
required this.body,
|
||||
required this.quote,
|
||||
required this.anchor,
|
||||
required this.created,
|
||||
required this.editedAt,
|
||||
required this.resolvedAt,
|
||||
required this.resolvedBy,
|
||||
required this.reactions,
|
||||
required this.canEdit,
|
||||
required this.canDelete,
|
||||
required this.canResolve,
|
||||
});
|
||||
|
||||
factory Comment.fromJson(Map<String, dynamic> json) => Comment(
|
||||
id: json['id'] as String,
|
||||
parent: json['parent'] as String,
|
||||
page: json['page'] as String,
|
||||
author: MemberUser.fromJson(json['author'] as Map<String, dynamic>),
|
||||
body: json['body'] as String,
|
||||
@@ -2066,11 +2074,24 @@ class Comment {
|
||||
? null
|
||||
: json['anchor'] as Map<String, dynamic>,
|
||||
created: json['created'] as String,
|
||||
editedAt: json['editedAt'] as String,
|
||||
resolvedAt: json['resolvedAt'] as String,
|
||||
resolvedBy: json['resolvedBy'] == null
|
||||
? null
|
||||
: MemberUser.fromJson(json['resolvedBy'] as Map<String, dynamic>),
|
||||
reactions: (json['reactions'] as List)
|
||||
.map((e) => Reaction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
canEdit: json['canEdit'] as bool,
|
||||
canDelete: json['canDelete'] as bool,
|
||||
canResolve: json['canResolve'] as bool,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
/// The thread's first comment for a reply; empty for a thread
|
||||
final String parent;
|
||||
|
||||
final String page;
|
||||
|
||||
final MemberUser author;
|
||||
@@ -2084,20 +2105,218 @@ class Comment {
|
||||
|
||||
final String created;
|
||||
|
||||
/// Empty when never edited
|
||||
final String editedAt;
|
||||
|
||||
/// Empty unless the thread is resolved
|
||||
final String resolvedAt;
|
||||
|
||||
final MemberUser? resolvedBy;
|
||||
|
||||
/// Most used first
|
||||
final List<Reaction> reactions;
|
||||
|
||||
final bool canEdit;
|
||||
|
||||
final bool canDelete;
|
||||
|
||||
/// A thread the caller may resolve or reopen
|
||||
final bool canResolve;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'parent': parent,
|
||||
'page': page,
|
||||
'author': author.toJson(),
|
||||
'body': body,
|
||||
'quote': quote,
|
||||
'anchor': anchor,
|
||||
'created': created,
|
||||
'editedAt': editedAt,
|
||||
'resolvedAt': resolvedAt,
|
||||
'resolvedBy': resolvedBy?.toJson(),
|
||||
'reactions': reactions.map((e) => e.toJson()).toList(),
|
||||
'canEdit': canEdit,
|
||||
'canDelete': canDelete,
|
||||
'canResolve': canResolve,
|
||||
};
|
||||
}
|
||||
|
||||
class Reaction {
|
||||
const Reaction({
|
||||
required this.emoji,
|
||||
required this.count,
|
||||
required this.mine,
|
||||
required this.people,
|
||||
});
|
||||
|
||||
factory Reaction.fromJson(Map<String, dynamic> json) => Reaction(
|
||||
emoji: json['emoji'] as String,
|
||||
count: (json['count'] as num).toInt(),
|
||||
mine: json['mine'] as bool,
|
||||
people: (json['people'] as List).map((e) => e as String).toList(),
|
||||
);
|
||||
|
||||
final String emoji;
|
||||
|
||||
final int count;
|
||||
|
||||
final bool mine;
|
||||
|
||||
/// Names of the people who reacted
|
||||
final List<String> people;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'emoji': emoji,
|
||||
'count': count,
|
||||
'mine': mine,
|
||||
'people': people.map((e) => e).toList(),
|
||||
};
|
||||
}
|
||||
|
||||
class WatchState {
|
||||
const WatchState({required this.watching});
|
||||
|
||||
factory WatchState.fromJson(Map<String, dynamic> json) =>
|
||||
WatchState(watching: json['watching'] as bool);
|
||||
|
||||
final bool watching;
|
||||
|
||||
Map<String, dynamic> toJson() => {'watching': watching};
|
||||
}
|
||||
|
||||
enum NotificationType {
|
||||
comment('comment'),
|
||||
reply('reply'),
|
||||
mention('mention'),
|
||||
share('share'),
|
||||
resolved('resolved');
|
||||
|
||||
const NotificationType(this.value);
|
||||
final String value;
|
||||
|
||||
static NotificationType fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () => throw FormatException('unknown NotificationType', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class Notification {
|
||||
const Notification({
|
||||
required this.id,
|
||||
required this.type,
|
||||
required this.workspace,
|
||||
required this.page,
|
||||
required this.comment,
|
||||
required this.actor,
|
||||
required this.excerpt,
|
||||
required this.created,
|
||||
required this.read,
|
||||
});
|
||||
|
||||
factory Notification.fromJson(Map<String, dynamic> json) => Notification(
|
||||
id: json['id'] as String,
|
||||
type: NotificationType.fromJson(json['type'] as String),
|
||||
workspace: json['workspace'] as String,
|
||||
page: json['page'] == null
|
||||
? null
|
||||
: PageRef.fromJson(json['page'] as Map<String, dynamic>),
|
||||
comment: json['comment'] as String,
|
||||
actor: json['actor'] == null
|
||||
? null
|
||||
: MemberUser.fromJson(json['actor'] as Map<String, dynamic>),
|
||||
excerpt: json['excerpt'] as String,
|
||||
created: json['created'] as String,
|
||||
read: json['read'] as bool,
|
||||
);
|
||||
|
||||
final String id;
|
||||
|
||||
final NotificationType type;
|
||||
|
||||
final String workspace;
|
||||
|
||||
/// Null when the page is gone or the caller lost access to it
|
||||
final PageRef? page;
|
||||
|
||||
/// The comment it is about
|
||||
final String comment;
|
||||
|
||||
final MemberUser? actor;
|
||||
|
||||
final String excerpt;
|
||||
|
||||
final String created;
|
||||
|
||||
final bool read;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'type': type.toJson(),
|
||||
'workspace': workspace,
|
||||
'page': page?.toJson(),
|
||||
'comment': comment,
|
||||
'actor': actor?.toJson(),
|
||||
'excerpt': excerpt,
|
||||
'created': created,
|
||||
'read': read,
|
||||
};
|
||||
}
|
||||
|
||||
class NotificationList {
|
||||
const NotificationList({required this.items, required this.unread});
|
||||
|
||||
factory NotificationList.fromJson(Map<String, dynamic> json) =>
|
||||
NotificationList(
|
||||
items: (json['items'] as List)
|
||||
.map((e) => Notification.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
unread: (json['unread'] as num).toInt(),
|
||||
);
|
||||
|
||||
final List<Notification> items;
|
||||
|
||||
final int unread;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'items': items.map((e) => e.toJson()).toList(),
|
||||
'unread': unread,
|
||||
};
|
||||
}
|
||||
|
||||
/// Unread notifications by email every few minutes
|
||||
enum NotificationSettingsEmail {
|
||||
digest('digest'),
|
||||
off('off');
|
||||
|
||||
const NotificationSettingsEmail(this.value);
|
||||
final String value;
|
||||
|
||||
static NotificationSettingsEmail fromJson(String value) => values.firstWhere(
|
||||
(e) => e.value == value,
|
||||
orElse: () =>
|
||||
throw FormatException('unknown NotificationSettingsEmail', value),
|
||||
);
|
||||
|
||||
String toJson() => value;
|
||||
}
|
||||
|
||||
class NotificationSettings {
|
||||
const NotificationSettings({required this.email});
|
||||
|
||||
factory NotificationSettings.fromJson(Map<String, dynamic> json) =>
|
||||
NotificationSettings(
|
||||
email: NotificationSettingsEmail.fromJson(json['email'] as String),
|
||||
);
|
||||
|
||||
/// Unread notifications by email every few minutes
|
||||
final NotificationSettingsEmail email;
|
||||
|
||||
Map<String, dynamic> toJson() => {'email': email.toJson()};
|
||||
}
|
||||
|
||||
enum AdminStatsScope {
|
||||
instance('instance'),
|
||||
organization('organization');
|
||||
|
||||
@@ -68,6 +68,11 @@ func run(log *slog.Logger) error {
|
||||
Store: collab.NewPBStore(db), Docs: ycrdt.NewPool(yrs, max(2, runtime.GOMAXPROCS(0))), Log: log,
|
||||
})
|
||||
dirSvc := directory.New(db, authSvc.Forget, hub)
|
||||
hub.OnSaved(func(page, editor string, doc []byte) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
dirSvc.PageSaved(ctx, page, editor, doc)
|
||||
})
|
||||
// The search index follows PocketBase and can be rebuilt from it at any time.
|
||||
index, err := search.Open(cfg.DataDir, db, log)
|
||||
if err != nil {
|
||||
@@ -78,10 +83,14 @@ func run(log *slog.Logger) error {
|
||||
reg.Register("search.index", "Adds changed pages to the search index", 3*time.Second, nil)
|
||||
reg.Register("search.sweep", "Removes deleted pages from the search index", 10*time.Minute, index.Sweep)
|
||||
reg.Register("search.rebuild", "Rebuilds the whole search index from the database", 0, index.Rebuild)
|
||||
reg.Register("notify.digest", "Emails people their unread notifications", 5*time.Minute, dirSvc.SendDigests)
|
||||
reg.Register("notify.prune", "Deletes read notifications older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
|
||||
index.Track(reg.Track)
|
||||
indexCtx, stopIndex := context.WithCancel(context.Background())
|
||||
defer stopIndex()
|
||||
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
|
||||
go reg.Every(indexCtx, "notify.digest", 5*time.Minute)
|
||||
go reg.Every(indexCtx, "notify.prune", 24*time.Hour)
|
||||
dirSvc.UseSearch(index)
|
||||
dirSvc.SetPublicURL(cfg.PublicURL)
|
||||
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
|
||||
|
||||
@@ -181,3 +181,16 @@ func ViewGroups(wsRole string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EditComment: only the author changes what they wrote.
|
||||
func EditComment(actorID, authorID string) error {
|
||||
if actorID == "" || actorID != authorID {
|
||||
return apperr.Forbidden("only the author can edit this comment")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResolveComment and ReactToComment need commenter, like writing one.
|
||||
func ResolveComment(pageRole string) error { return CommentPages(pageRole) }
|
||||
|
||||
func ReactToComment(pageRole string) error { return CommentPages(pageRole) }
|
||||
@@ -111,3 +111,24 @@ func TestCommentRules(t *testing.T) {
|
||||
t.Error("an empty author is nobody's comment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommentActions(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want apperr.Kind
|
||||
}{
|
||||
{"author edits", EditComment("u1", "u1"), ok},
|
||||
{"others cannot edit", EditComment("u2", "u1"), forbidden},
|
||||
{"anonymous cannot edit", EditComment("", ""), forbidden},
|
||||
{"viewer cannot resolve", ResolveComment(SpaceViewer), forbidden},
|
||||
{"commenter resolves", ResolveComment(SpaceCommenter), ok},
|
||||
{"viewer cannot react", ReactToComment(SpaceViewer), forbidden},
|
||||
{"no access hides", ReactToComment(""), notFound},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := kind(c.err); got != c.want {
|
||||
t.Errorf("%s: got kind %v, want %v (%v)", c.name, got, c.want, c.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,51 @@ func (e InviteStatus) Valid() bool {
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for NotificationSettingsEmail.
|
||||
const (
|
||||
Digest NotificationSettingsEmail = "digest"
|
||||
Off NotificationSettingsEmail = "off"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the NotificationSettingsEmail enum.
|
||||
func (e NotificationSettingsEmail) Valid() bool {
|
||||
switch e {
|
||||
case Digest:
|
||||
return true
|
||||
case Off:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for NotificationType.
|
||||
const (
|
||||
NotificationTypeComment NotificationType = "comment"
|
||||
NotificationTypeMention NotificationType = "mention"
|
||||
NotificationTypeReply NotificationType = "reply"
|
||||
NotificationTypeResolved NotificationType = "resolved"
|
||||
NotificationTypeShare NotificationType = "share"
|
||||
)
|
||||
|
||||
// Valid indicates whether the value is a known member of the NotificationType enum.
|
||||
func (e NotificationType) Valid() bool {
|
||||
switch e {
|
||||
case NotificationTypeComment:
|
||||
return true
|
||||
case NotificationTypeMention:
|
||||
return true
|
||||
case NotificationTypeReply:
|
||||
return true
|
||||
case NotificationTypeResolved:
|
||||
return true
|
||||
case NotificationTypeShare:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Defines values for PageGrantType.
|
||||
const (
|
||||
PageGrantTypeGroup PageGrantType = "group"
|
||||
@@ -398,10 +443,27 @@ type Comment struct {
|
||||
Author MemberUser `json:"author"`
|
||||
Body string `json:"body"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Created string `json:"created"`
|
||||
Id string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Quote string `json:"quote"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
|
||||
// CanResolve A thread the caller may resolve or reopen
|
||||
CanResolve bool `json:"canResolve"`
|
||||
Created string `json:"created"`
|
||||
|
||||
// EditedAt Empty when never edited
|
||||
EditedAt string `json:"editedAt"`
|
||||
Id string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
|
||||
// Parent The thread's first comment for a reply; empty for a thread
|
||||
Parent string `json:"parent"`
|
||||
Quote string `json:"quote"`
|
||||
|
||||
// Reactions Most used first
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
|
||||
// ResolvedAt Empty unless the thread is resolved
|
||||
ResolvedAt string `json:"resolvedAt"`
|
||||
ResolvedBy *MemberUser `json:"resolvedBy"`
|
||||
}
|
||||
|
||||
// CreateInviteRequest defines model for CreateInviteRequest.
|
||||
@@ -568,6 +630,41 @@ type NameRequest struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Notification defines model for Notification.
|
||||
type Notification struct {
|
||||
Actor *MemberUser `json:"actor"`
|
||||
|
||||
// Comment The comment it is about
|
||||
Comment string `json:"comment"`
|
||||
Created string `json:"created"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Id string `json:"id"`
|
||||
|
||||
// Page Null when the page is gone or the caller lost access to it
|
||||
Page *PageRef `json:"page"`
|
||||
Read bool `json:"read"`
|
||||
Type NotificationType `json:"type"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
|
||||
// NotificationList defines model for NotificationList.
|
||||
type NotificationList struct {
|
||||
Items []Notification `json:"items"`
|
||||
Unread int `json:"unread"`
|
||||
}
|
||||
|
||||
// NotificationSettings defines model for NotificationSettings.
|
||||
type NotificationSettings struct {
|
||||
// Email Unread notifications by email every few minutes
|
||||
Email NotificationSettingsEmail `json:"email"`
|
||||
}
|
||||
|
||||
// NotificationSettingsEmail Unread notifications by email every few minutes
|
||||
type NotificationSettingsEmail string
|
||||
|
||||
// NotificationType defines model for NotificationType.
|
||||
type NotificationType string
|
||||
|
||||
// Organization defines model for Organization.
|
||||
type Organization struct {
|
||||
Created string `json:"created"`
|
||||
@@ -725,6 +822,16 @@ type PublicSettings struct {
|
||||
Signup bool `json:"signup"`
|
||||
}
|
||||
|
||||
// Reaction defines model for Reaction.
|
||||
type Reaction struct {
|
||||
Count int `json:"count"`
|
||||
Emoji string `json:"emoji"`
|
||||
Mine bool `json:"mine"`
|
||||
|
||||
// People Names of the people who reacted
|
||||
People []string `json:"people"`
|
||||
}
|
||||
|
||||
// Role Instance role. admin manages their own organization; superadmin manages everything.
|
||||
type Role string
|
||||
|
||||
@@ -958,6 +1065,11 @@ type Version struct {
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// WatchState defines model for WatchState.
|
||||
type WatchState struct {
|
||||
Watching bool `json:"watching"`
|
||||
}
|
||||
|
||||
// Workspace defines model for Workspace.
|
||||
type Workspace struct {
|
||||
Created string `json:"created"`
|
||||
@@ -1012,6 +1124,22 @@ type ConfirmVerificationJSONBody struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// UpdateCommentJSONBody defines parameters for UpdateComment.
|
||||
type UpdateCommentJSONBody struct {
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// ReactToCommentJSONBody defines parameters for ReactToComment.
|
||||
type ReactToCommentJSONBody struct {
|
||||
Emoji string `json:"emoji"`
|
||||
On bool `json:"on"`
|
||||
}
|
||||
|
||||
// ResolveCommentJSONBody defines parameters for ResolveComment.
|
||||
type ResolveCommentJSONBody struct {
|
||||
Resolved bool `json:"resolved"`
|
||||
}
|
||||
|
||||
// DownloadFileParams defines parameters for DownloadFile.
|
||||
type DownloadFileParams struct {
|
||||
Token *string `form:"token,omitempty" json:"token,omitempty"`
|
||||
@@ -1025,6 +1153,19 @@ type ListInvitesParams struct {
|
||||
Organization *string `form:"organization,omitempty" json:"organization,omitempty"`
|
||||
}
|
||||
|
||||
// ListNotificationsParams defines parameters for ListNotifications.
|
||||
type ListNotificationsParams struct {
|
||||
// Unread Only unread ones
|
||||
Unread *bool `form:"unread,omitempty" json:"unread,omitempty"`
|
||||
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
// MarkNotificationsReadJSONBody defines parameters for MarkNotificationsRead.
|
||||
type MarkNotificationsReadJSONBody struct {
|
||||
All *bool `json:"all,omitempty"`
|
||||
Ids *[]string `json:"ids,omitempty"`
|
||||
}
|
||||
|
||||
// DeletePageParams defines parameters for DeletePage.
|
||||
type DeletePageParams struct {
|
||||
Permanent *bool `form:"permanent,omitempty" json:"permanent,omitempty"`
|
||||
@@ -1059,11 +1200,17 @@ type UploadAttachmentMultipartBody struct {
|
||||
|
||||
// CreateCommentJSONBody defines parameters for CreateComment.
|
||||
type CreateCommentJSONBody struct {
|
||||
// Anchor The editor's encoding of the commented range (opaque to the server)
|
||||
// Anchor The editor's encoding of the commented range, opaque to the server (threads only)
|
||||
Anchor *map[string]interface{} `json:"anchor,omitempty"`
|
||||
Body string `json:"body"`
|
||||
|
||||
// Quote The commented text
|
||||
// Mentions Ids of the people mentioned in body
|
||||
Mentions *[]string `json:"mentions,omitempty"`
|
||||
|
||||
// Parent The thread to reply to
|
||||
Parent *string `json:"parent,omitempty"`
|
||||
|
||||
// Quote The commented text (threads only)
|
||||
Quote *string `json:"quote,omitempty"`
|
||||
}
|
||||
|
||||
@@ -1221,6 +1368,15 @@ type ConfirmVerificationJSONRequestBody ConfirmVerificationJSONBody
|
||||
// RequestVerificationJSONRequestBody defines body for RequestVerification for application/json ContentType.
|
||||
type RequestVerificationJSONRequestBody = EmailRequest
|
||||
|
||||
// UpdateCommentJSONRequestBody defines body for UpdateComment for application/json ContentType.
|
||||
type UpdateCommentJSONRequestBody UpdateCommentJSONBody
|
||||
|
||||
// ReactToCommentJSONRequestBody defines body for ReactToComment for application/json ContentType.
|
||||
type ReactToCommentJSONRequestBody ReactToCommentJSONBody
|
||||
|
||||
// ResolveCommentJSONRequestBody defines body for ResolveComment for application/json ContentType.
|
||||
type ResolveCommentJSONRequestBody ResolveCommentJSONBody
|
||||
|
||||
// UpdateGroupJSONRequestBody defines body for UpdateGroup for application/json ContentType.
|
||||
type UpdateGroupJSONRequestBody = GroupRequest
|
||||
|
||||
@@ -1230,6 +1386,12 @@ type AddGroupMemberJSONRequestBody = EmailRequest
|
||||
// CreateInviteJSONRequestBody defines body for CreateInvite for application/json ContentType.
|
||||
type CreateInviteJSONRequestBody = CreateInviteRequest
|
||||
|
||||
// MarkNotificationsReadJSONRequestBody defines body for MarkNotificationsRead for application/json ContentType.
|
||||
type MarkNotificationsReadJSONRequestBody MarkNotificationsReadJSONBody
|
||||
|
||||
// SetNotificationSettingsJSONRequestBody defines body for SetNotificationSettings for application/json ContentType.
|
||||
type SetNotificationSettingsJSONRequestBody = NotificationSettings
|
||||
|
||||
// CreateOrgJSONRequestBody defines body for CreateOrg for application/json ContentType.
|
||||
type CreateOrgJSONRequestBody = NameRequest
|
||||
|
||||
@@ -1263,6 +1425,9 @@ type MovePageJSONRequestBody MovePageJSONBody
|
||||
// SetShareLinkJSONRequestBody defines body for SetShareLink for application/json ContentType.
|
||||
type SetShareLinkJSONRequestBody SetShareLinkJSONBody
|
||||
|
||||
// SetPageWatchJSONRequestBody defines body for SetPageWatch for application/json ContentType.
|
||||
type SetPageWatchJSONRequestBody = WatchState
|
||||
|
||||
// UpdateSpaceJSONRequestBody defines body for UpdateSpace for application/json ContentType.
|
||||
type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
|
||||
|
||||
|
||||
@@ -36,13 +36,19 @@ type Options struct {
|
||||
}
|
||||
|
||||
type Hub struct {
|
||||
o Options
|
||||
mu sync.Mutex
|
||||
rooms map[string]*room
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
o Options
|
||||
onSaved func(page, editor string, doc []byte)
|
||||
mu sync.Mutex
|
||||
rooms map[string]*room
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
// OnSaved registers fn to run (in its own goroutine) after a page's content
|
||||
// was saved, with the last editor and the document as Tiptap JSON. Set it
|
||||
// before the hub serves anyone.
|
||||
func (h *Hub) OnSaved(fn func(page, editor string, doc []byte)) { h.onSaved = fn }
|
||||
|
||||
func NewHub(o Options) *Hub {
|
||||
if o.FlushEvery == 0 {
|
||||
o.FlushEvery = time.Second
|
||||
@@ -337,6 +343,9 @@ func (r *room) persistLocked(ctx context.Context, leaving bool) bool {
|
||||
snap.JSON, snap.Text = read.JSON, read.Text
|
||||
err = o.Store.SaveSnapshot(ctx, r.page, snap)
|
||||
}
|
||||
if err == nil && r.h.onSaved != nil {
|
||||
go r.h.onSaved(r.page, snap.LastEditor, snap.JSON)
|
||||
}
|
||||
if err == nil && version {
|
||||
if verr := o.Store.AddVersion(ctx, r.page, snap); verr != nil {
|
||||
o.Log.Error("collab: add version", "page", r.page, "err", verr)
|
||||
|
||||
@@ -6,74 +6,160 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// ---- Inline comments -------------------------------------------------------
|
||||
// ---- Comments --------------------------------------------------------------
|
||||
//
|
||||
// Comments come in threads: the first comment of a thread may point at text
|
||||
// (anchor) and can be resolved; replies (parent = the first comment) only
|
||||
// hold text. Anyone who can comment may react with an emoji.
|
||||
|
||||
// maxReactions caps the distinct emojis on one comment.
|
||||
const maxReactions = 20
|
||||
|
||||
// Reaction is one emoji on a comment with who used it.
|
||||
type Reaction struct {
|
||||
Emoji string `json:"emoji"`
|
||||
Count int `json:"count"`
|
||||
// Mine is whether the caller reacted with it.
|
||||
Mine bool `json:"mine"`
|
||||
// People are the names of the people who reacted, for a tooltip.
|
||||
People []string `json:"people"`
|
||||
}
|
||||
|
||||
type Comment struct {
|
||||
ID string `json:"id"`
|
||||
ID string `json:"id"`
|
||||
// Parent is the thread's first comment for a reply ("" for a thread).
|
||||
Parent string `json:"parent"`
|
||||
Page string `json:"page"`
|
||||
Author MemberUser `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
// Anchor is the editor's encoding of the commented range; the server
|
||||
// stores it without looking inside.
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
EditedAt string `json:"editedAt"`
|
||||
ResolvedAt string `json:"resolvedAt"`
|
||||
ResolvedBy *MemberUser `json:"resolvedBy"`
|
||||
Reactions []Reaction `json:"reactions"`
|
||||
CanEdit bool `json:"canEdit"`
|
||||
CanDelete bool `json:"canDelete"`
|
||||
CanResolve bool `json:"canResolve"`
|
||||
}
|
||||
|
||||
type commentRecord struct {
|
||||
ID string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Author string `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Created string `json:"created"`
|
||||
Expand struct {
|
||||
Author *struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
} `json:"author"`
|
||||
} `json:"expand"`
|
||||
ID string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
Workspace string `json:"workspace"`
|
||||
Parent string `json:"parent"`
|
||||
Author string `json:"author"`
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
Reactions map[string][]string `json:"reactions"`
|
||||
ResolvedAt string `json:"resolved_at"`
|
||||
ResolvedBy string `json:"resolved_by"`
|
||||
EditedAt string `json:"edited_at"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
func (r commentRecord) view(c access.Caller, role string) Comment {
|
||||
// people resolves user ids to MemberUsers, remembering each lookup.
|
||||
type people struct {
|
||||
s *Service
|
||||
seen map[string]*MemberUser
|
||||
}
|
||||
|
||||
func (s *Service) people() *people { return &people{s: s, seen: map[string]*MemberUser{}} }
|
||||
|
||||
func (p *people) get(ctx context.Context, id string) *MemberUser {
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
if m, ok := p.seen[id]; ok {
|
||||
return m
|
||||
}
|
||||
var m *MemberUser
|
||||
if u, err := p.s.getUser(ctx, id); err == nil {
|
||||
m = &MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}
|
||||
}
|
||||
p.seen[id] = m
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *MemberUser) display() string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
if m.Name != "" {
|
||||
return m.Name
|
||||
}
|
||||
return m.Email
|
||||
}
|
||||
|
||||
func (r commentRecord) view(ctx context.Context, c access.Caller, role string, who *people) Comment {
|
||||
out := Comment{
|
||||
ID: r.ID, Page: r.Page, Body: r.Body, Quote: r.Quote, Anchor: r.Anchor, Created: r.Created,
|
||||
CanDelete: access.DeleteComment(c.ID, r.Author, role) == nil,
|
||||
ID: r.ID, Parent: r.Parent, Page: r.Page, Body: r.Body, Quote: r.Quote, Anchor: r.Anchor, Created: r.Created,
|
||||
EditedAt: r.EditedAt, ResolvedAt: r.ResolvedAt, Reactions: []Reaction{},
|
||||
CanEdit: access.EditComment(c.ID, r.Author) == nil,
|
||||
CanDelete: access.DeleteComment(c.ID, r.Author, role) == nil,
|
||||
CanResolve: r.Parent == "" && access.ResolveComment(role) == nil,
|
||||
}
|
||||
if len(out.Anchor) == 0 {
|
||||
out.Anchor = json.RawMessage("null")
|
||||
}
|
||||
if a := r.Expand.Author; a != nil {
|
||||
out.Author = MemberUser{ID: a.ID, Email: a.Email, Name: a.Name}
|
||||
if a := who.get(ctx, r.Author); a != nil {
|
||||
out.Author = *a
|
||||
}
|
||||
if r.ResolvedAt != "" {
|
||||
out.ResolvedBy = who.get(ctx, r.ResolvedBy)
|
||||
}
|
||||
for emoji, ids := range r.Reactions {
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
re := Reaction{Emoji: emoji, Count: len(ids), People: []string{}}
|
||||
for _, id := range ids {
|
||||
re.Mine = re.Mine || id == c.ID
|
||||
if name := who.get(ctx, id).display(); name != "" {
|
||||
re.People = append(re.People, name)
|
||||
}
|
||||
}
|
||||
out.Reactions = append(out.Reactions, re)
|
||||
}
|
||||
sort.Slice(out.Reactions, func(i, j int) bool {
|
||||
if out.Reactions[i].Count != out.Reactions[j].Count {
|
||||
return out.Reactions[i].Count > out.Reactions[j].Count
|
||||
}
|
||||
return out.Reactions[i].Emoji < out.Reactions[j].Emoji
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ListComments lists a page's comments, oldest first (viewer).
|
||||
// ListComments lists a page's comments and replies, oldest first (viewer).
|
||||
func (s *Service) ListComments(ctx context.Context, c access.Caller, pageID string) ([]Comment, error) {
|
||||
p, a, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recs, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created", Expand: "author",
|
||||
Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created,id",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
who := s.people()
|
||||
out := make([]Comment, 0, len(recs))
|
||||
for _, r := range recs {
|
||||
out = append(out, r.view(c, a.role))
|
||||
out = append(out, r.view(ctx, c, a.role, who))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -82,9 +168,54 @@ type CreateCommentInput struct {
|
||||
Body string `json:"body"`
|
||||
Quote string `json:"quote"`
|
||||
Anchor json.RawMessage `json:"anchor"`
|
||||
// Parent makes this a reply to that thread.
|
||||
Parent string `json:"parent"`
|
||||
// Mentions are the ids of people mentioned in Body; they are notified.
|
||||
Mentions []string `json:"mentions"`
|
||||
}
|
||||
|
||||
// CreateComment adds a comment to a page (commenter; not in the trash).
|
||||
func cleanCommentBody(body string) (string, error) {
|
||||
body = strings.TrimSpace(body)
|
||||
switch {
|
||||
case body == "":
|
||||
return "", apperr.InvalidFields(map[string]string{"body": "Write something first."})
|
||||
case len(body) > 5000:
|
||||
return "", apperr.InvalidFields(map[string]string{"body": "The comment is too long (max 5000)."})
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (s *Service) getComment(ctx context.Context, id string) (commentRecord, error) {
|
||||
if !validID(id) {
|
||||
return commentRecord{}, apperr.NotFound("comment not found")
|
||||
}
|
||||
rec, err := pocketbase.Get[commentRecord](ctx, s.pb, "comments", id)
|
||||
return rec, mapPB(err, "comment not found")
|
||||
}
|
||||
|
||||
// commentFor loads a comment and c's access to its page.
|
||||
func (s *Service) commentFor(ctx context.Context, c access.Caller, id string) (commentRecord, pageRecord, spaceAccess, error) {
|
||||
rec, err := s.getComment(ctx, id)
|
||||
if err != nil {
|
||||
return rec, pageRecord{}, spaceAccess{}, err
|
||||
}
|
||||
p, a, err := s.pageFor(ctx, c, rec.Page)
|
||||
if err != nil {
|
||||
return rec, p, a, apperr.NotFound("comment not found")
|
||||
}
|
||||
return rec, p, a, nil
|
||||
}
|
||||
|
||||
func (s *Service) commentView(ctx context.Context, c access.Caller, id, role string) (Comment, error) {
|
||||
rec, err := s.getComment(ctx, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
return rec.view(ctx, c, role, s.people()), nil
|
||||
}
|
||||
|
||||
// CreateComment starts a thread on a page, or replies to one (commenter;
|
||||
// not in the trash). The author starts watching the page.
|
||||
func (s *Service) CreateComment(ctx context.Context, c access.Caller, pageID string, in CreateCommentInput) (Comment, error) {
|
||||
p, a, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
@@ -96,46 +227,168 @@ func (s *Service) CreateComment(ctx context.Context, c access.Caller, pageID str
|
||||
if p.DeletedAt != "" {
|
||||
return Comment{}, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
body := strings.TrimSpace(in.Body)
|
||||
switch {
|
||||
case body == "":
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"body": "Write something first."})
|
||||
case len(body) > 5000:
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"body": "The comment is too long (max 5000)."})
|
||||
case len(in.Anchor) > 4096:
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"anchor": "The anchor is too large."})
|
||||
body, err := cleanCommentBody(in.Body)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
quote := strings.TrimSpace(in.Quote)
|
||||
if r := []rune(quote); len(r) > 500 {
|
||||
quote = string(r[:500])
|
||||
}
|
||||
fields := map[string]any{"page": p.ID, "workspace": p.Workspace, "author": c.ID, "body": body, "quote": quote}
|
||||
if len(in.Anchor) > 0 && json.Valid(in.Anchor) {
|
||||
fields["anchor"] = in.Anchor
|
||||
fields := map[string]any{"page": p.ID, "workspace": p.Workspace, "author": c.ID, "body": body}
|
||||
var root commentRecord
|
||||
if in.Parent != "" {
|
||||
if root, err = s.getComment(ctx, in.Parent); err != nil || root.Page != p.ID {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"parent": "That thread is not on this page."})
|
||||
}
|
||||
if root.Parent != "" {
|
||||
// Replies to a reply join the same thread.
|
||||
if root, err = s.getComment(ctx, root.Parent); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
}
|
||||
fields["parent"] = root.ID
|
||||
} else {
|
||||
if len(in.Anchor) > 4096 {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"anchor": "The anchor is too large."})
|
||||
}
|
||||
quote := strings.TrimSpace(in.Quote)
|
||||
if r := []rune(quote); len(r) > 500 {
|
||||
quote = string(r[:500])
|
||||
}
|
||||
fields["quote"] = quote
|
||||
if len(in.Anchor) > 0 && json.Valid(in.Anchor) {
|
||||
fields["anchor"] = in.Anchor
|
||||
}
|
||||
}
|
||||
rec, err := pocketbase.Create[commentRecord](ctx, s.pb, "comments", fields)
|
||||
if err != nil {
|
||||
return Comment{}, mapPB(err, "page not found")
|
||||
}
|
||||
rec, err = pocketbase.GetExpand[commentRecord](ctx, s.pb, "comments", rec.ID, "author")
|
||||
if err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
return rec.view(c, a.role), nil
|
||||
s.autoWatch(ctx, p.ID, c.ID)
|
||||
s.notifyComment(ctx, c, p, rec, root, in.Mentions)
|
||||
return rec.view(ctx, c, a.role, s.people()), nil
|
||||
}
|
||||
|
||||
// DeleteComment removes a comment (its author, or a space admin).
|
||||
// UpdateComment changes a comment's text (its author).
|
||||
func (s *Service) UpdateComment(ctx context.Context, c access.Caller, id, body string) (Comment, error) {
|
||||
rec, p, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.EditComment(c.ID, rec.Author); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if p.DeletedAt != "" {
|
||||
return Comment{}, apperr.Invalid("restore the page from the trash first")
|
||||
}
|
||||
if body, err = cleanCommentBody(body); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if body != rec.Body {
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, map[string]any{
|
||||
"body": body, "edited_at": pbTime(time.Now()),
|
||||
}); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// ResolveComment marks a thread resolved, or opens it again (commenter).
|
||||
// The people in the thread hear about it.
|
||||
func (s *Service) ResolveComment(ctx context.Context, c access.Caller, id string, resolved bool) (Comment, error) {
|
||||
rec, p, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.ResolveComment(a.role); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if rec.Parent != "" {
|
||||
return Comment{}, apperr.Invalid("only a thread's first comment can be resolved")
|
||||
}
|
||||
if resolved == (rec.ResolvedAt != "") {
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
patch := map[string]any{"resolved_at": "", "resolved_by": ""}
|
||||
if resolved {
|
||||
patch = map[string]any{"resolved_at": pbTime(time.Now()), "resolved_by": c.ID}
|
||||
}
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, patch); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
if resolved {
|
||||
s.notifyResolved(ctx, c, p, rec)
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// validEmoji accepts a short run of symbols: no letters, digits or spaces.
|
||||
func validEmoji(e string) bool {
|
||||
r := []rune(e)
|
||||
if len(r) == 0 || len(r) > 8 || len(e) > 32 {
|
||||
return false
|
||||
}
|
||||
for _, ch := range r {
|
||||
if unicode.IsLetter(ch) || unicode.IsDigit(ch) || unicode.IsSpace(ch) || unicode.IsControl(ch) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ReactToComment adds or removes the caller's emoji on a comment (commenter).
|
||||
func (s *Service) ReactToComment(ctx context.Context, c access.Caller, id, emoji string, on bool) (Comment, error) {
|
||||
rec, _, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
if err := access.ReactToComment(a.role); err != nil {
|
||||
return Comment{}, err
|
||||
}
|
||||
emoji = strings.TrimSpace(emoji)
|
||||
if !validEmoji(emoji) {
|
||||
return Comment{}, apperr.InvalidFields(map[string]string{"emoji": "Pick an emoji."})
|
||||
}
|
||||
reactions := rec.Reactions
|
||||
if reactions == nil {
|
||||
reactions = map[string][]string{}
|
||||
}
|
||||
ids := reactions[emoji]
|
||||
has := false
|
||||
kept := ids[:0:0]
|
||||
for _, uid := range ids {
|
||||
if uid == c.ID {
|
||||
has = true
|
||||
if !on {
|
||||
continue
|
||||
}
|
||||
}
|
||||
kept = append(kept, uid)
|
||||
}
|
||||
switch {
|
||||
case on && has, !on && !has:
|
||||
return rec.view(ctx, c, a.role, s.people()), nil
|
||||
case on:
|
||||
if len(ids) == 0 && len(reactions) >= maxReactions {
|
||||
return Comment{}, apperr.Invalid("this comment has as many different reactions as it can take")
|
||||
}
|
||||
kept = append(kept, c.ID)
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(reactions, emoji)
|
||||
} else {
|
||||
reactions[emoji] = kept
|
||||
}
|
||||
if _, err := pocketbase.Update[commentRecord](ctx, s.pb, "comments", rec.ID, map[string]any{"reactions": reactions}); err != nil {
|
||||
return Comment{}, mapPB(err, "comment not found")
|
||||
}
|
||||
return s.commentView(ctx, c, rec.ID, a.role)
|
||||
}
|
||||
|
||||
// DeleteComment removes a comment, and with a thread's first comment all of
|
||||
// its replies (its author, or a space admin).
|
||||
func (s *Service) DeleteComment(ctx context.Context, c access.Caller, id string) error {
|
||||
if !validID(id) {
|
||||
return apperr.NotFound("comment not found")
|
||||
}
|
||||
rec, err := pocketbase.Get[commentRecord](ctx, s.pb, "comments", id)
|
||||
rec, _, a, err := s.commentFor(ctx, c, id)
|
||||
if err != nil {
|
||||
return mapPB(err, "comment not found")
|
||||
}
|
||||
_, a, err := s.pageFor(ctx, c, rec.Page)
|
||||
if err != nil {
|
||||
return apperr.NotFound("comment not found")
|
||||
return err
|
||||
}
|
||||
if err := access.DeleteComment(c.ID, rec.Author, a.role); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package directory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// ---- Watching pages and notifications --------------------------------------
|
||||
//
|
||||
// People watch a page explicitly, or automatically when they create it or
|
||||
// comment on it (unless they muted it). Watchers hear about new comments;
|
||||
// thread participants about replies and resolutions; people about being
|
||||
// mentioned or having a page shared with them. Nobody is notified about
|
||||
// their own actions, or about a page they cannot open. Unread notifications
|
||||
// go out as an email digest unless the person turned that off.
|
||||
|
||||
// Notification types stored in notifications.type.
|
||||
const (
|
||||
NotifyComment = "comment"
|
||||
NotifyReply = "reply"
|
||||
NotifyMention = "mention"
|
||||
NotifyShare = "share"
|
||||
NotifyResolved = "resolved"
|
||||
)
|
||||
|
||||
// notifyRank decides which type wins when one event reaches someone for
|
||||
// several reasons (a mentioned watcher gets one "mention").
|
||||
var notifyRank = map[string]int{NotifyComment: 1, NotifyResolved: 2, NotifyReply: 3, NotifyShare: 4, NotifyMention: 5}
|
||||
|
||||
type watchRecord struct {
|
||||
ID string `json:"id"`
|
||||
Page string `json:"page"`
|
||||
User string `json:"user"`
|
||||
Watching bool `json:"watching"`
|
||||
}
|
||||
|
||||
func (s *Service) watchRow(ctx context.Context, pageID, userID string) (watchRecord, error) {
|
||||
res, err := pocketbase.List[watchRecord](ctx, s.pb, "page_watchers", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("page = '%s' && user = '%s'", pageID, userID),
|
||||
})
|
||||
if err != nil || len(res.Items) == 0 {
|
||||
return watchRecord{}, err
|
||||
}
|
||||
return res.Items[0], nil
|
||||
}
|
||||
|
||||
// WatchState is whether the caller watches a page.
|
||||
type WatchState struct {
|
||||
Watching bool `json:"watching"`
|
||||
}
|
||||
|
||||
// GetWatch reports whether the caller watches a page (viewer).
|
||||
func (s *Service) GetWatch(ctx context.Context, c access.Caller, pageID string) (WatchState, error) {
|
||||
p, _, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
return WatchState{}, err
|
||||
}
|
||||
row, err := s.watchRow(ctx, p.ID, c.ID)
|
||||
return WatchState{Watching: row.Watching}, err
|
||||
}
|
||||
|
||||
// SetWatch starts or stops watching a page (viewer). Stopping is remembered,
|
||||
// so commenting later does not start it again.
|
||||
func (s *Service) SetWatch(ctx context.Context, c access.Caller, pageID string, on bool) (WatchState, error) {
|
||||
p, _, err := s.pageFor(ctx, c, pageID)
|
||||
if err != nil {
|
||||
return WatchState{}, err
|
||||
}
|
||||
row, err := s.watchRow(ctx, p.ID, c.ID)
|
||||
if err != nil {
|
||||
return WatchState{}, err
|
||||
}
|
||||
switch {
|
||||
case row.ID == "":
|
||||
_, err = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": p.ID, "user": c.ID, "watching": on})
|
||||
case row.Watching != on:
|
||||
_, err = pocketbase.Update[watchRecord](ctx, s.pb, "page_watchers", row.ID, map[string]any{"watching": on})
|
||||
}
|
||||
if err != nil {
|
||||
return WatchState{}, mapPB(err, "page not found")
|
||||
}
|
||||
return WatchState{Watching: on}, nil
|
||||
}
|
||||
|
||||
// autoWatch starts watching for someone who took part in a page, unless they
|
||||
// already decided either way (best effort).
|
||||
func (s *Service) autoWatch(ctx context.Context, pageID, userID string) {
|
||||
row, err := s.watchRow(ctx, pageID, userID)
|
||||
if err != nil || row.ID != "" {
|
||||
return
|
||||
}
|
||||
_, _ = pocketbase.Create[watchRecord](ctx, s.pb, "page_watchers", map[string]any{"page": pageID, "user": userID, "watching": true})
|
||||
}
|
||||
|
||||
func (s *Service) watchers(ctx context.Context, pageID string) []string {
|
||||
rows, err := listAll[watchRecord](ctx, s, "page_watchers", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("page = '%s' && watching = true", pageID), Fields: "user",
|
||||
})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = r.User
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// event is one thing that happened on a page, to tell people about.
|
||||
type event struct {
|
||||
actor string
|
||||
page pageRecord
|
||||
comment string
|
||||
excerpt string
|
||||
// to maps recipients to the notification type each gets.
|
||||
to map[string]string
|
||||
}
|
||||
|
||||
func (e *event) add(userID, kind string) {
|
||||
if userID == "" || userID == e.actor {
|
||||
return
|
||||
}
|
||||
if notifyRank[kind] > notifyRank[e.to[userID]] {
|
||||
e.to[userID] = kind
|
||||
}
|
||||
}
|
||||
|
||||
func excerpt(s string) string {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
if r := []rune(s); len(r) > 200 {
|
||||
return string(r[:199]) + "…"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// send stores the event's notifications, for recipients who can still open
|
||||
// the page (best effort: a failure only loses notifications).
|
||||
func (s *Service) send(ctx context.Context, e event) {
|
||||
for userID, kind := range e.to {
|
||||
if !validID(userID) {
|
||||
continue
|
||||
}
|
||||
u, err := s.getUser(ctx, userID)
|
||||
if err != nil || u.Status == "disabled" {
|
||||
continue
|
||||
}
|
||||
if _, _, _, err := s.pageAccess(ctx, u.Caller(), e.page.ID); err != nil {
|
||||
continue
|
||||
}
|
||||
body := map[string]any{
|
||||
"user": userID, "workspace": e.page.Workspace, "page": e.page.ID, "type": kind, "excerpt": excerpt(e.excerpt),
|
||||
}
|
||||
if e.actor != "" {
|
||||
body["actor"] = e.actor
|
||||
}
|
||||
if e.comment != "" {
|
||||
body["comment"] = e.comment
|
||||
}
|
||||
if _, err := pocketbase.Create[struct{}](ctx, s.pb, "notifications", body); err != nil {
|
||||
slog.Default().Warn("notify: create", "user", userID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// notifyComment tells watchers about a new thread or reply, the thread's
|
||||
// people about a reply, and mentioned people that they were mentioned.
|
||||
func (s *Service) notifyComment(ctx context.Context, c access.Caller, p pageRecord, rec, root commentRecord, mentions []string) {
|
||||
e := event{actor: c.ID, page: p, comment: rec.ID, excerpt: rec.Body, to: map[string]string{}}
|
||||
for _, w := range s.watchers(ctx, p.ID) {
|
||||
e.add(w, NotifyComment)
|
||||
}
|
||||
if root.ID != "" {
|
||||
for _, uid := range s.threadPeople(ctx, root) {
|
||||
e.add(uid, NotifyReply)
|
||||
}
|
||||
}
|
||||
for i, uid := range mentions {
|
||||
if i >= 50 {
|
||||
break
|
||||
}
|
||||
e.add(uid, NotifyMention)
|
||||
}
|
||||
s.send(ctx, e)
|
||||
}
|
||||
|
||||
// threadPeople are the authors in a thread.
|
||||
func (s *Service) threadPeople(ctx context.Context, root commentRecord) []string {
|
||||
out := []string{root.Author}
|
||||
replies, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("parent = '%s'", root.ID), Fields: "author",
|
||||
})
|
||||
if err == nil {
|
||||
for _, r := range replies {
|
||||
out = append(out, r.Author)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) notifyResolved(ctx context.Context, c access.Caller, p pageRecord, root commentRecord) {
|
||||
e := event{actor: c.ID, page: p, comment: root.ID, excerpt: root.Body, to: map[string]string{}}
|
||||
for _, uid := range s.threadPeople(ctx, root) {
|
||||
e.add(uid, NotifyResolved)
|
||||
}
|
||||
s.send(ctx, e)
|
||||
}
|
||||
|
||||
func (s *Service) notifyShare(ctx context.Context, c access.Caller, p pageRecord, userID string) {
|
||||
e := event{actor: c.ID, page: p, excerpt: p.Title, to: map[string]string{}}
|
||||
e.add(userID, NotifyShare)
|
||||
s.send(ctx, e)
|
||||
}
|
||||
|
||||
// mentionIDs collects the user ids of mention nodes in a Tiptap document.
|
||||
func mentionIDs(doc json.RawMessage) []string {
|
||||
var root any
|
||||
if json.Unmarshal(doc, &root) != nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
var walk func(n any)
|
||||
walk = func(n any) {
|
||||
m, ok := n.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if m["type"] == "mention" {
|
||||
if attrs, ok := m["attrs"].(map[string]any); ok {
|
||||
if id, ok := attrs["id"].(string); ok && validID(id) && !seen[id] {
|
||||
seen[id] = true
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if kids, ok := m["content"].([]any); ok {
|
||||
for _, k := range kids {
|
||||
walk(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// PageSaved is called after a page's content was saved by editor (the last
|
||||
// person who edited, possibly ""). People mentioned for the first time are
|
||||
// notified. A page that predates mention tracking (mentions still null) only
|
||||
// records who it mentions, so upgrading does not notify about old mentions.
|
||||
func (s *Service) PageSaved(ctx context.Context, pageID, editor string, doc json.RawMessage) {
|
||||
type rec struct {
|
||||
pageRecord
|
||||
Mentions json.RawMessage `json:"mentions"`
|
||||
}
|
||||
r, err := pocketbase.Get[rec](ctx, s.pb, "pages", pageID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
now := mentionIDs(doc)
|
||||
var before []string
|
||||
known := len(r.Mentions) > 0 && string(r.Mentions) != "null"
|
||||
if known {
|
||||
_ = json.Unmarshal(r.Mentions, &before)
|
||||
}
|
||||
if strings.Join(before, ",") == strings.Join(now, ",") && known {
|
||||
return
|
||||
}
|
||||
if now == nil {
|
||||
now = []string{}
|
||||
}
|
||||
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", pageID, map[string]any{"mentions": now}); err != nil {
|
||||
return
|
||||
}
|
||||
if !known || r.DeletedAt != "" {
|
||||
return
|
||||
}
|
||||
had := map[string]bool{}
|
||||
for _, id := range before {
|
||||
had[id] = true
|
||||
}
|
||||
e := event{actor: editor, page: r.pageRecord, excerpt: r.Title, to: map[string]string{}}
|
||||
for _, id := range now {
|
||||
if !had[id] {
|
||||
e.add(id, NotifyMention)
|
||||
}
|
||||
}
|
||||
s.send(ctx, e)
|
||||
}
|
||||
|
||||
// ---- Reading notifications -------------------------------------------------
|
||||
|
||||
type Notification struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Workspace string `json:"workspace"`
|
||||
// Page is nil when the page is gone or the caller lost access to it.
|
||||
Page *PageRef `json:"page"`
|
||||
Comment string `json:"comment"`
|
||||
Actor *MemberUser `json:"actor"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Created string `json:"created"`
|
||||
Read bool `json:"read"`
|
||||
}
|
||||
|
||||
type NotificationList struct {
|
||||
Items []Notification `json:"items"`
|
||||
Unread int `json:"unread"`
|
||||
}
|
||||
|
||||
type notificationRecord struct {
|
||||
ID string `json:"id"`
|
||||
User string `json:"user"`
|
||||
Workspace string `json:"workspace"`
|
||||
Page string `json:"page"`
|
||||
Comment string `json:"comment"`
|
||||
Actor string `json:"actor"`
|
||||
Type string `json:"type"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
ReadAt string `json:"read_at"`
|
||||
EmailedAt string `json:"emailed_at"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
func (s *Service) unreadCount(ctx context.Context, userID string) (int, error) {
|
||||
return s.count(ctx, "notifications", fmt.Sprintf("user = '%s' && read_at = ''", userID))
|
||||
}
|
||||
|
||||
// ListNotifications lists the caller's newest notifications (all, or only
|
||||
// unread ones) with the unread count.
|
||||
func (s *Service) ListNotifications(ctx context.Context, c access.Caller, unreadOnly bool, limit int) (NotificationList, error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 50
|
||||
}
|
||||
filter := fmt.Sprintf("user = '%s'", c.ID)
|
||||
if unreadOnly {
|
||||
filter += " && read_at = ''"
|
||||
}
|
||||
res, err := pocketbase.List[notificationRecord](ctx, s.pb, "notifications", pocketbase.ListOptions{
|
||||
PerPage: limit, Filter: filter, Sort: "-created,-id",
|
||||
})
|
||||
if err != nil {
|
||||
return NotificationList{}, err
|
||||
}
|
||||
out := NotificationList{Items: []Notification{}}
|
||||
who := s.people()
|
||||
pages := map[string]*PageRef{}
|
||||
for _, r := range res.Items {
|
||||
n := Notification{
|
||||
ID: r.ID, Type: r.Type, Workspace: r.Workspace, Comment: r.Comment, Actor: who.get(ctx, r.Actor),
|
||||
Excerpt: r.Excerpt, Created: r.Created, Read: r.ReadAt != "",
|
||||
}
|
||||
if r.Page != "" {
|
||||
ref, seen := pages[r.Page]
|
||||
if !seen {
|
||||
if p, _, err := s.pageFor(ctx, c, r.Page); err == nil && p.DeletedAt == "" {
|
||||
ref = &PageRef{ID: p.ID, Title: p.Title, Icon: p.Icon}
|
||||
}
|
||||
pages[r.Page] = ref
|
||||
}
|
||||
if ref == nil {
|
||||
// What happened on a page the caller can no longer open stays hidden.
|
||||
n.Excerpt, n.Comment = "", ""
|
||||
}
|
||||
n.Page = ref
|
||||
}
|
||||
out.Items = append(out.Items, n)
|
||||
}
|
||||
if out.Unread, err = s.unreadCount(ctx, c.ID); err != nil {
|
||||
return NotificationList{}, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// MarkNotificationsRead marks the caller's notifications read: the listed
|
||||
// ones, or all of them. It returns the unread count afterwards.
|
||||
func (s *Service) MarkNotificationsRead(ctx context.Context, c access.Caller, ids []string, all bool) (int, error) {
|
||||
now := pbTime(time.Now())
|
||||
if all {
|
||||
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("user = '%s' && read_at = ''", c.ID), Fields: "id",
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for _, r := range rows {
|
||||
ids = append(ids, r.ID)
|
||||
}
|
||||
}
|
||||
if len(ids) > 1000 {
|
||||
return 0, apperr.Invalid("too many notifications at once")
|
||||
}
|
||||
for _, id := range ids {
|
||||
if !validID(id) {
|
||||
continue
|
||||
}
|
||||
rec, err := pocketbase.Get[notificationRecord](ctx, s.pb, "notifications", id)
|
||||
if err != nil || rec.User != c.ID || rec.ReadAt != "" {
|
||||
continue // someone else's or already read: nothing to do
|
||||
}
|
||||
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "notifications", id, map[string]any{"read_at": now}); err != nil {
|
||||
return 0, mapPB(err, "notification not found")
|
||||
}
|
||||
}
|
||||
return s.unreadCount(ctx, c.ID)
|
||||
}
|
||||
|
||||
// NotificationSettings are the caller's notification preferences.
|
||||
type NotificationSettings struct {
|
||||
// Email is "digest" (unread notifications by email every few minutes) or "off".
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (s *Service) GetNotificationSettings(ctx context.Context, c access.Caller) (NotificationSettings, error) {
|
||||
r, err := pocketbase.Get[struct {
|
||||
NotifyEmail string `json:"notify_email"`
|
||||
}](ctx, s.pb, "users", c.ID)
|
||||
if err != nil {
|
||||
return NotificationSettings{}, mapPB(err, "user not found")
|
||||
}
|
||||
if r.NotifyEmail != "off" {
|
||||
r.NotifyEmail = "digest"
|
||||
}
|
||||
return NotificationSettings{Email: r.NotifyEmail}, nil
|
||||
}
|
||||
|
||||
func (s *Service) SetNotificationSettings(ctx context.Context, c access.Caller, in NotificationSettings) (NotificationSettings, error) {
|
||||
if in.Email != "digest" && in.Email != "off" {
|
||||
return NotificationSettings{}, apperr.InvalidFields(map[string]string{"email": "Choose digest or off."})
|
||||
}
|
||||
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "users", c.ID, map[string]any{"notify_email": in.Email}); err != nil {
|
||||
return NotificationSettings{}, mapPB(err, "user not found")
|
||||
}
|
||||
return in, nil
|
||||
}
|
||||
|
||||
// ---- Email digest ----------------------------------------------------------
|
||||
|
||||
// digestDelay leaves time to read a notification in the app before it is mailed.
|
||||
const digestDelay = 10 * time.Minute
|
||||
|
||||
// digestItem is one line of a digest email.
|
||||
type digestItem struct {
|
||||
Text string
|
||||
Link string
|
||||
}
|
||||
|
||||
func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) {
|
||||
if n.Page == "" {
|
||||
return digestItem{}, false
|
||||
}
|
||||
p, err := s.getPage(ctx, n.Page)
|
||||
if err != nil || p.DeletedAt != "" {
|
||||
return digestItem{}, false
|
||||
}
|
||||
actor := who.get(ctx, n.Actor).display()
|
||||
if actor == "" {
|
||||
actor = "Someone"
|
||||
}
|
||||
title := p.Title
|
||||
if title == "" {
|
||||
title = "Untitled"
|
||||
}
|
||||
verb := map[string]string{
|
||||
NotifyComment: "commented on",
|
||||
NotifyReply: "replied in",
|
||||
NotifyMention: "mentioned you in",
|
||||
NotifyShare: "shared",
|
||||
NotifyResolved: "resolved a thread in",
|
||||
}[n.Type]
|
||||
text := fmt.Sprintf("%s %s “%s”", actor, verb, title)
|
||||
if n.Excerpt != "" && n.Type != NotifyShare && n.Excerpt != p.Title {
|
||||
text += ": " + n.Excerpt
|
||||
}
|
||||
link := strings.TrimRight(s.mailer.WebURL, "/") + "/p/" + url.PathEscape(p.ID)
|
||||
if n.Comment != "" {
|
||||
link += "?comment=" + url.QueryEscape(n.Comment)
|
||||
}
|
||||
return digestItem{Text: text, Link: link}, true
|
||||
}
|
||||
|
||||
// SendDigests emails each person their unread notifications that were not
|
||||
// mailed yet and are older than digestDelay, then marks them mailed. People
|
||||
// who turned email off are marked without a mail. It is a background job.
|
||||
func (s *Service) SendDigests(ctx context.Context) error {
|
||||
if s.mailer.Sender == nil {
|
||||
return nil
|
||||
}
|
||||
cutoff := pbTime(time.Now().Add(-digestDelay))
|
||||
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("emailed_at = '' && read_at = '' && created <= '%s'", cutoff), Sort: "created",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
byUser := map[string][]notificationRecord{}
|
||||
for _, r := range rows {
|
||||
byUser[r.User] = append(byUser[r.User], r)
|
||||
}
|
||||
appName := "Docwell"
|
||||
if s.mailer.AppName != nil {
|
||||
appName = s.mailer.AppName(ctx)
|
||||
}
|
||||
who := s.people()
|
||||
var firstErr error
|
||||
for userID, list := range byUser {
|
||||
u, err := pocketbase.Get[struct {
|
||||
Email string `json:"email"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
NotifyEmail string `json:"notify_email"`
|
||||
}](ctx, s.pb, "users", userID)
|
||||
if err == nil && u.NotifyEmail != "off" && u.Status != "disabled" {
|
||||
var items []digestItem
|
||||
for _, n := range list {
|
||||
if it, ok := s.digestLine(ctx, n, who); ok {
|
||||
items = append(items, it)
|
||||
}
|
||||
}
|
||||
if len(items) > 0 {
|
||||
m, err := mail.Render(u.Email, "digest", map[string]any{
|
||||
"AppName": appName, "Name": u.Name, "Count": len(items), "Items": items,
|
||||
"SettingsLink": strings.TrimRight(s.mailer.WebURL, "/") + "/notifications",
|
||||
})
|
||||
if err == nil {
|
||||
err = s.mailer.Sender.Send(ctx, m)
|
||||
}
|
||||
if err != nil {
|
||||
// Leave them unmailed; the next run tries again.
|
||||
if firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
now := pbTime(time.Now())
|
||||
for _, n := range list {
|
||||
_, _ = pocketbase.Update[struct{}](ctx, s.pb, "notifications", n.ID, map[string]any{"emailed_at": now})
|
||||
}
|
||||
}
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// PruneNotifications deletes read notifications older than 90 days. It is a
|
||||
// background job.
|
||||
func (s *Service) PruneNotifications(ctx context.Context) error {
|
||||
cutoff := pbTime(time.Now().Add(-90 * 24 * time.Hour))
|
||||
rows, err := listAll[notificationRecord](ctx, s, "notifications", pocketbase.ListOptions{
|
||||
Filter: fmt.Sprintf("read_at != '' && created < '%s'", cutoff), Fields: "id",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range rows {
|
||||
if err := s.pb.Delete(ctx, "notifications", r.ID); err != nil && !pocketbase.IsNotFound(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package directory
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMentionIDs(t *testing.T) {
|
||||
doc := `{"type":"doc","content":[
|
||||
{"type":"paragraph","content":[
|
||||
{"type":"text","text":"hi "},
|
||||
{"type":"mention","attrs":{"id":"bbbbbbbbbbbbbbb","label":"Bob"}},
|
||||
{"type":"mention","attrs":{"id":"aaaaaaaaaaaaaaa","label":"Ann"}}]},
|
||||
{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[
|
||||
{"type":"mention","attrs":{"id":"bbbbbbbbbbbbbbb"}},
|
||||
{"type":"mention","attrs":{"id":"bad id!"}}]}]}]}]}`
|
||||
got := strings.Join(mentionIDs([]byte(doc)), ",")
|
||||
if got != "aaaaaaaaaaaaaaa,bbbbbbbbbbbbbbb" {
|
||||
t.Fatalf("mentionIDs = %q", got)
|
||||
}
|
||||
if mentionIDs([]byte("null")) != nil || mentionIDs([]byte("{")) != nil {
|
||||
t.Fatal("empty documents should have no mentions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidEmoji(t *testing.T) {
|
||||
for _, e := range []string{"👍", "❤️", "🎉", "👩💻"} {
|
||||
if !validEmoji(e) {
|
||||
t.Errorf("%q should be accepted", e)
|
||||
}
|
||||
}
|
||||
for _, e := range []string{"", "ok", "a b", "1", "👍👍👍👍👍👍👍👍👍", "\n"} {
|
||||
if validEmoji(e) {
|
||||
t.Errorf("%q should be refused", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExcerpt(t *testing.T) {
|
||||
if got := excerpt(" a\n\n b "); got != "a b" {
|
||||
t.Fatalf("excerpt = %q", got)
|
||||
}
|
||||
if got := []rune(excerpt(strings.Repeat("x", 300))); len(got) != 200 || got[199] != '…' {
|
||||
t.Fatalf("long excerpt has %d runes", len(got))
|
||||
}
|
||||
}
|
||||
@@ -342,6 +342,8 @@ func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID strin
|
||||
body := map[string]any{
|
||||
"workspace": a.space.Workspace, "space": a.space.ID, "title": title, "position": pos,
|
||||
"creator": c.ID, "last_editor": c.ID,
|
||||
// Mention tracking starts empty, so first mentions notify (see PageSaved).
|
||||
"mentions": []string{},
|
||||
}
|
||||
if in.Parent != "" {
|
||||
body["parent"] = in.Parent
|
||||
@@ -350,6 +352,7 @@ func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID strin
|
||||
if err != nil {
|
||||
return Page{}, mapPB(err, "page not found")
|
||||
}
|
||||
s.autoWatch(ctx, rec.ID, c.ID)
|
||||
return s.GetPage(ctx, c, rec.ID)
|
||||
}
|
||||
|
||||
|
||||
@@ -387,6 +387,7 @@ func (s *Service) SharePageWithUser(ctx context.Context, c access.Caller, id, em
|
||||
return SharePageResult{}, err
|
||||
}
|
||||
s.kickSubtree(ctx, p)
|
||||
s.notifyShare(ctx, c, p, u.ID)
|
||||
pa, err := s.GetPageAccess(ctx, c, p.ID)
|
||||
return SharePageResult{Access: pa}, err
|
||||
}
|
||||
|
||||
@@ -5,16 +5,29 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/directory"
|
||||
)
|
||||
|
||||
// CommentService is the part of directory.Service for inline comments.
|
||||
// CommentService is the part of directory.Service for comments, page
|
||||
// watching and notifications.
|
||||
type CommentService interface {
|
||||
ListComments(ctx context.Context, c access.Caller, pageID string) ([]directory.Comment, error)
|
||||
CreateComment(ctx context.Context, c access.Caller, pageID string, in directory.CreateCommentInput) (directory.Comment, error)
|
||||
UpdateComment(ctx context.Context, c access.Caller, id, body string) (directory.Comment, error)
|
||||
ResolveComment(ctx context.Context, c access.Caller, id string, resolved bool) (directory.Comment, error)
|
||||
ReactToComment(ctx context.Context, c access.Caller, id, emoji string, on bool) (directory.Comment, error)
|
||||
DeleteComment(ctx context.Context, c access.Caller, id string) error
|
||||
|
||||
GetWatch(ctx context.Context, c access.Caller, pageID string) (directory.WatchState, error)
|
||||
SetWatch(ctx context.Context, c access.Caller, pageID string, on bool) (directory.WatchState, error)
|
||||
|
||||
ListNotifications(ctx context.Context, c access.Caller, unreadOnly bool, limit int) (directory.NotificationList, error)
|
||||
MarkNotificationsRead(ctx context.Context, c access.Caller, ids []string, all bool) (int, error)
|
||||
GetNotificationSettings(ctx context.Context, c access.Caller) (directory.NotificationSettings, error)
|
||||
SetNotificationSettings(ctx context.Context, c access.Caller, in directory.NotificationSettings) (directory.NotificationSettings, error)
|
||||
}
|
||||
|
||||
func (a *api) commentRoutes(mux *routeMux) {
|
||||
@@ -30,7 +43,77 @@ func (a *api) commentRoutes(mux *routeMux) {
|
||||
cm, err := a.dir.CreateComment(r.Context(), caller(r), r.PathValue("id"), in)
|
||||
a.respondStatus(w, http.StatusCreated, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("PATCH /api/v1/comments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Body string }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.UpdateComment(r.Context(), caller(r), r.PathValue("id"), in.Body)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("DELETE /api/v1/comments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
a.respondNoContent(w, a.dir.DeleteComment(r.Context(), caller(r), r.PathValue("id")))
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/comments/{id}/resolve", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Resolved bool }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.ResolveComment(r.Context(), caller(r), r.PathValue("id"), in.Resolved)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/comments/{id}/reactions", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Emoji string
|
||||
On bool
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
cm, err := a.dir.ReactToComment(r.Context(), caller(r), r.PathValue("id"), in.Emoji, in.On)
|
||||
a.respond(w, cm, err)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /api/v1/pages/{id}/watch", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := a.dir.GetWatch(r.Context(), caller(r), r.PathValue("id"))
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/pages/{id}/watch", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Watching bool }
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
st, err := a.dir.SetWatch(r.Context(), caller(r), r.PathValue("id"), in.Watching)
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
|
||||
mux.HandleFunc("GET /api/v1/notifications", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
limit, _ := strconv.Atoi(q.Get("limit"))
|
||||
list, err := a.dir.ListNotifications(r.Context(), caller(r), q.Get("unread") == "true", limit)
|
||||
a.respond(w, list, err)
|
||||
}))
|
||||
mux.HandleFunc("POST /api/v1/notifications/read", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
IDs []string
|
||||
All bool
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
n, err := a.dir.MarkNotificationsRead(r.Context(), caller(r), in.IDs, in.All)
|
||||
a.respond(w, map[string]int{"unread": n}, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/notifications/settings", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
st, err := a.dir.GetNotificationSettings(r.Context(), caller(r))
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/notifications/settings", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in directory.NotificationSettings
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
st, err := a.dir.SetNotificationSettings(r.Context(), caller(r), in)
|
||||
a.respond(w, st, err)
|
||||
}))
|
||||
}
|
||||
@@ -118,3 +118,28 @@ func (r *Registry) Run(name string) error {
|
||||
go func() { _ = r.Track(name, func() error { return run(context.Background()) }) }()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Every runs job name every interval until ctx ends, skipping a tick while
|
||||
// the previous run (or one started by hand) is still going.
|
||||
func (r *Registry) Every(ctx context.Context, name string, interval time.Duration) {
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
r.mu.Lock()
|
||||
e, ok := r.jobs[name]
|
||||
busy := !ok || e.run == nil || e.Running
|
||||
var run func(context.Context) error
|
||||
if !busy {
|
||||
run = e.run
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if !busy {
|
||||
_ = r.Track(name, func() error { return run(ctx) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,3 +49,27 @@ func TestTrackAndRun(t *testing.T) {
|
||||
t.Error("unregistered jobs are tracked too")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvery(t *testing.T) {
|
||||
r := New()
|
||||
runs := make(chan struct{}, 10)
|
||||
r.Register("tick", "", time.Millisecond, func(context.Context) error {
|
||||
runs <- struct{}{}
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { r.Every(ctx, "tick", time.Millisecond); close(done) }()
|
||||
for range 2 {
|
||||
select {
|
||||
case <-runs:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("job did not run")
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
if r.List()[0].Runs < 2 {
|
||||
t.Fatalf("runs = %d", r.List()[0].Runs)
|
||||
}
|
||||
}
|
||||
@@ -22,3 +22,19 @@ func TestRender(t *testing.T) {
|
||||
t.Errorf("text must not repeat the subject: %q", m.Text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigest(t *testing.T) {
|
||||
m, err := Render("a@x.test", "digest", map[string]any{
|
||||
"AppName": "Docwell", "Name": "Ann", "Count": 2, "SettingsLink": "https://w/notifications",
|
||||
"Items": []struct{ Text, Link string }{{"Bob commented on “Plan”: <b>hi</b>", "https://w/p/1"}, {"x", "https://w/p/2"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Subject != "2 new notifications on Docwell" {
|
||||
t.Fatalf("subject = %q", m.Subject)
|
||||
}
|
||||
if !strings.Contains(m.HTML, "<b>hi</b>") || !strings.Contains(m.Text, "https://w/p/2") {
|
||||
t.Fatalf("body:\n%s\n%s", m.HTML, m.Text)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<p>Hello{{if .Name}} {{.Name}}{{end}},</p>
|
||||
<p>Here is what happened while you were away:</p>
|
||||
<ul>
|
||||
{{range .Items}} <li><a href="{{.Link}}">{{.Text}}</a></li>
|
||||
{{end}}</ul>
|
||||
<p>You get this email because you have unread notifications. <a href="{{.SettingsLink}}">Turn these emails off</a> in your notification settings.</p>
|
||||
@@ -0,0 +1,9 @@
|
||||
{{.Count}} new {{if eq .Count 1}}notification{{else}}notifications{{end}} on {{.AppName}}
|
||||
Hello{{if .Name}} {{.Name}}{{end}},
|
||||
|
||||
Here is what happened while you were away:
|
||||
{{range .Items}}
|
||||
- {{.Text}}
|
||||
{{.Link}}
|
||||
{{end}}
|
||||
You get this email because you have unread notifications. Turn these emails off in your notification settings: {{.SettingsLink}}
|
||||
@@ -8,6 +8,7 @@ import { useFormErrors } from "../composables/useFormErrors";
|
||||
import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSidebar";
|
||||
import { useAuthStore } from "../stores/auth";
|
||||
import { useFavoritesStore } from "../stores/favorites";
|
||||
import { useNotificationsStore } from "../stores/notifications";
|
||||
import { useSpacesStore } from "../stores/spaces";
|
||||
import { atLeast, useWorkspacesStore } from "../stores/workspaces";
|
||||
import PageTreeNode from "./PageTreeNode.vue";
|
||||
@@ -22,6 +23,7 @@ const auth = useAuthStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const spaces = useSpacesStore();
|
||||
const favorites = useFavoritesStore();
|
||||
const notifications = useNotificationsStore();
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const { mode } = useTheme();
|
||||
@@ -37,6 +39,8 @@ function showError(e: unknown) {
|
||||
}
|
||||
|
||||
onMounted(() => workspaces.load().catch(showError));
|
||||
onMounted(() => notifications.start());
|
||||
onBeforeUnmount(() => notifications.stop());
|
||||
watch(
|
||||
() => workspaces.current?.id,
|
||||
(id) => {
|
||||
@@ -192,6 +196,15 @@ function signOut() {
|
||||
<RouterLink to="/" :class="[navRow, 'mt-1.5']" :exact-active-class="navActive">
|
||||
<DwIcon name="home" :size="16" />{{ $t("sidebar.home") }}
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'notifications' }" :class="navRow" :active-class="navActive" data-testid="nav-inbox">
|
||||
<DwIcon name="bell" :size="16" />{{ $t("notifications.title") }}
|
||||
<span
|
||||
v-if="notifications.unread"
|
||||
class="ml-auto rounded-full bg-primary px-1.5 text-ui-xs font-semibold tabular-nums text-on-primary"
|
||||
:aria-label="$t('notifications.unreadCount', { n: notifications.unread }, notifications.unread)"
|
||||
>{{ notifications.unread > 99 ? "99+" : notifications.unread }}</span
|
||||
>
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
v-if="ws"
|
||||
:to="{ name: 'workspace-settings', params: { id: ws.id } }"
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { MemberUser } from "@docwell/api-client";
|
||||
import { DwButton } from "@docwell/ui";
|
||||
import { computed, nextTick, ref, watch } from "vue";
|
||||
import { useApi } from "../api";
|
||||
|
||||
// A comment text box with "@" mentions: typing @ and a few letters lists the
|
||||
// workspace's people; picking one inserts "@Name" and remembers their id, so
|
||||
// the server can notify them. Ctrl/Cmd+Enter sends, Esc cancels.
|
||||
const props = defineProps<{
|
||||
workspace: string;
|
||||
placeholder: string;
|
||||
submitLabel: string;
|
||||
busy: boolean;
|
||||
initial?: string;
|
||||
autofocus?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{ submit: [body: string, mentions: string[]]; cancel: [] }>();
|
||||
const api = useApi();
|
||||
|
||||
const body = ref(props.initial ?? "");
|
||||
const box = ref<HTMLTextAreaElement | null>(null);
|
||||
const picked = ref<MemberUser[]>([]);
|
||||
const matches = ref<MemberUser[]>([]);
|
||||
const highlighted = ref(0);
|
||||
// Where the "@" being completed starts, or -1.
|
||||
const at = ref(-1);
|
||||
let lookup = 0;
|
||||
|
||||
watch(
|
||||
() => props.autofocus,
|
||||
async (v) => {
|
||||
if (!v) return;
|
||||
await nextTick();
|
||||
box.value?.focus();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const label = (u: MemberUser) => u.name || u.email;
|
||||
|
||||
async function onInput() {
|
||||
const el = box.value;
|
||||
if (!el) return;
|
||||
const before = body.value.slice(0, el.selectionStart);
|
||||
const m = /(?:^|\s)@([^\s@]{0,30})$/.exec(before);
|
||||
if (!m || !props.workspace) {
|
||||
at.value = -1;
|
||||
matches.value = [];
|
||||
return;
|
||||
}
|
||||
at.value = before.length - m[1]!.length - 1;
|
||||
const id = ++lookup;
|
||||
const found = await api.workspaces.people(props.workspace, m[1]!, 6).catch(() => []);
|
||||
if (id === lookup) {
|
||||
matches.value = found;
|
||||
highlighted.value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function pick(u: MemberUser) {
|
||||
const el = box.value;
|
||||
if (!el || at.value < 0) return;
|
||||
const end = el.selectionStart;
|
||||
const text = `@${label(u)} `;
|
||||
body.value = body.value.slice(0, at.value) + text + body.value.slice(end);
|
||||
if (!picked.value.some((p) => p.id === u.id)) picked.value.push(u);
|
||||
const caret = at.value + text.length;
|
||||
at.value = -1;
|
||||
matches.value = [];
|
||||
await nextTick();
|
||||
el.focus();
|
||||
el.setSelectionRange(caret, caret);
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (matches.value.length) {
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
const n = matches.value.length;
|
||||
highlighted.value = (highlighted.value + (e.key === "ArrowDown" ? 1 : n - 1)) % n;
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" || e.key === "Tab") {
|
||||
e.preventDefault();
|
||||
void pick(matches.value[highlighted.value]!);
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
matches.value = [];
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
emit("cancel");
|
||||
}
|
||||
}
|
||||
|
||||
// Only people whose "@Name" is still in the text count as mentioned.
|
||||
const mentions = computed(() => picked.value.filter((u) => body.value.includes(`@${label(u)}`)).map((u) => u.id));
|
||||
|
||||
function submit() {
|
||||
if (!body.value.trim() || props.busy) return;
|
||||
emit("submit", body.value, mentions.value);
|
||||
}
|
||||
|
||||
/** Clears the box after the comment was saved. */
|
||||
function reset() {
|
||||
body.value = "";
|
||||
picked.value = [];
|
||||
}
|
||||
defineExpose({ reset });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<form @submit.prevent="submit">
|
||||
<div class="relative">
|
||||
<textarea
|
||||
ref="box"
|
||||
v-model="body"
|
||||
rows="2"
|
||||
maxlength="5000"
|
||||
class="dw-input w-full"
|
||||
:aria-label="placeholder"
|
||||
:placeholder="placeholder"
|
||||
data-testid="comment-body"
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
@blur="matches = []"
|
||||
/>
|
||||
<ul
|
||||
v-if="matches.length"
|
||||
class="absolute left-0 top-full z-20 mt-1 w-64 rounded-sm border border-line bg-surface-raised py-1 shadow-dialog"
|
||||
role="listbox"
|
||||
:aria-label="$t('editor.mentions')"
|
||||
>
|
||||
<li v-for="(u, i) in matches" :key="u.id" role="option" :aria-selected="i === highlighted">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-col px-3 py-1 text-left"
|
||||
:class="i === highlighted ? 'bg-surface-hover' : ''"
|
||||
@mousedown.prevent="pick(u)"
|
||||
>
|
||||
<span class="text-ui-md">{{ label(u) }}</span>
|
||||
<span v-if="u.name" class="text-ui-xs text-ink-muted">{{ u.email }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="mt-2 flex justify-end gap-2">
|
||||
<DwButton size="sm" variant="ghost" @click="emit('cancel')">{{ $t("comments.cancel") }}</DwButton>
|
||||
<DwButton size="sm" type="submit" variant="primary" :disabled="busy || !body.trim()" data-testid="comment-send">
|
||||
{{ submitLabel }}
|
||||
</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
@@ -1,16 +1,19 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Comment } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { nextTick, ref, watch } from "vue";
|
||||
import { DwButton, DwCallout, DwIcon } from "@docwell/ui";
|
||||
import { computed, nextTick, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import CommentBox from "./CommentBox.vue";
|
||||
|
||||
// The page's comments beside the text. A new comment starts from a text
|
||||
// selection in the editor (draft); active is the comment whose text is lit.
|
||||
// The page's comment threads beside the text. A new thread starts from a
|
||||
// text selection in the editor (draft); active is the thread whose text is
|
||||
// lit. Resolved threads fold away under their own heading.
|
||||
const props = defineProps<{
|
||||
page: string;
|
||||
workspace: string;
|
||||
comments: Comment[];
|
||||
draft: { quote: string; anchor: Record<string, unknown> | null } | null;
|
||||
active: string;
|
||||
@@ -21,60 +24,82 @@ const api = useApi();
|
||||
const { locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const body = ref("");
|
||||
const QUICK = ["👍", "❤️", "🎉", "😄", "👀", "✅"];
|
||||
|
||||
const busy = ref(false);
|
||||
const box = ref<HTMLTextAreaElement | null>(null);
|
||||
const list = ref<HTMLElement | null>(null);
|
||||
const replyTo = ref("");
|
||||
const editing = ref("");
|
||||
const picker = ref("");
|
||||
const showResolved = ref(false);
|
||||
const newBox = ref<InstanceType<typeof CommentBox> | null>(null);
|
||||
|
||||
interface Thread {
|
||||
root: Comment;
|
||||
replies: Comment[];
|
||||
}
|
||||
const threads = computed(() => {
|
||||
const byRoot = new Map<string, Thread>();
|
||||
for (const c of props.comments) if (!c.parent) byRoot.set(c.id, { root: c, replies: [] });
|
||||
for (const c of props.comments) if (c.parent) byRoot.get(c.parent)?.replies.push(c);
|
||||
return [...byRoot.values()];
|
||||
});
|
||||
const open = computed(() => threads.value.filter((t) => !t.root.resolvedAt));
|
||||
const resolved = computed(() => threads.value.filter((t) => t.root.resolvedAt));
|
||||
|
||||
watch(
|
||||
() => props.draft,
|
||||
async (v) => {
|
||||
body.value = "";
|
||||
errors.reset();
|
||||
if (v) {
|
||||
await nextTick();
|
||||
box.value?.focus();
|
||||
}
|
||||
},
|
||||
() => errors.reset(),
|
||||
);
|
||||
|
||||
// Bring the active comment into view when its text is clicked.
|
||||
// Bring the active thread into view (and out of the resolved fold).
|
||||
watch(
|
||||
() => props.active,
|
||||
async (id) => {
|
||||
if (!id) return;
|
||||
if (resolved.value.some((t) => t.root.id === id || t.replies.some((r) => r.id === id))) showResolved.value = true;
|
||||
await nextTick();
|
||||
list.value?.querySelector(`[data-id="${id}"]`)?.scrollIntoView({ block: "nearest" });
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function submit() {
|
||||
if (!props.draft || !body.value.trim()) return;
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
await api.pages.addComment(props.page, { body: body.value, quote: props.draft.quote, anchor: props.draft.anchor });
|
||||
body.value = "";
|
||||
await action();
|
||||
emit("changed");
|
||||
return true;
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
return false;
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(c: Comment) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
await api.comments.remove(c.id);
|
||||
emit("changed");
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
async function startThread(body: string, mentions: string[]) {
|
||||
if (!props.draft) return;
|
||||
const d = props.draft;
|
||||
if (await run(() => api.pages.addComment(props.page, { body, quote: d.quote, anchor: d.anchor, mentions })))
|
||||
newBox.value?.reset();
|
||||
}
|
||||
async function reply(t: Thread, body: string, mentions: string[]) {
|
||||
if (await run(() => api.pages.addComment(props.page, { body, parent: t.root.id, mentions }))) replyTo.value = "";
|
||||
}
|
||||
async function saveEdit(c: Comment, body: string) {
|
||||
if (await run(() => api.comments.update(c.id, body))) editing.value = "";
|
||||
}
|
||||
const remove = (c: Comment) => run(() => api.comments.remove(c.id));
|
||||
const setResolved = (t: Thread, on: boolean) => run(() => api.comments.resolve(t.root.id, on));
|
||||
function react(c: Comment, emoji: string) {
|
||||
picker.value = "";
|
||||
const mine = c.reactions.find((r) => r.emoji === emoji)?.mine ?? false;
|
||||
return run(() => api.comments.react(c.id, emoji, !mine));
|
||||
}
|
||||
|
||||
const who = (c: Comment) => c.author.name || c.author.email || "";
|
||||
const when = (s: string) =>
|
||||
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
|
||||
</script>
|
||||
@@ -87,60 +112,187 @@ const when = (s: string) =>
|
||||
</div>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<form v-if="draft" class="rounded-md border border-line-strong bg-surface-raised p-3" @submit.prevent="submit">
|
||||
<div v-if="draft" class="rounded-md border border-line-strong bg-surface-raised p-3">
|
||||
<p v-if="draft.quote" class="mb-2 line-clamp-3 border-l-2 border-warning pl-2 text-ui-sm text-ink-muted">
|
||||
{{ draft.quote }}
|
||||
</p>
|
||||
<textarea
|
||||
ref="box"
|
||||
v-model="body"
|
||||
rows="3"
|
||||
maxlength="5000"
|
||||
class="dw-input w-full"
|
||||
:aria-label="$t('comments.write')"
|
||||
<CommentBox
|
||||
ref="newBox"
|
||||
:workspace="workspace"
|
||||
:placeholder="$t('comments.write')"
|
||||
data-testid="comment-body"
|
||||
@keydown.ctrl.enter.prevent="submit"
|
||||
@keydown.meta.enter.prevent="submit"
|
||||
@keydown.esc.prevent="emit('cancel')"
|
||||
:submit-label="$t('comments.send')"
|
||||
:busy="busy"
|
||||
autofocus
|
||||
@submit="startThread"
|
||||
@cancel="emit('cancel')"
|
||||
/>
|
||||
<p v-if="errors.fields.value.body" class="text-ui-sm text-danger">{{ errors.fields.value.body }}</p>
|
||||
<div class="mt-2 flex justify-end gap-2">
|
||||
<DwButton size="sm" variant="ghost" @click="emit('cancel')">{{ $t("comments.cancel") }}</DwButton>
|
||||
<DwButton size="sm" type="submit" variant="primary" :disabled="busy || !body.trim()" data-testid="comment-send">
|
||||
{{ $t("comments.send") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
</form>
|
||||
<p v-else-if="canComment && !comments.length" class="text-ui-sm text-ink-muted">{{ $t("comments.hint") }}</p>
|
||||
</div>
|
||||
<p v-else-if="canComment && !threads.length" class="text-ui-sm text-ink-muted">{{ $t("comments.hint") }}</p>
|
||||
|
||||
<ul ref="list" class="flex flex-col gap-2">
|
||||
<li
|
||||
v-for="c in comments"
|
||||
:key="c.id"
|
||||
:data-id="c.id"
|
||||
class="cursor-pointer rounded-md border p-3"
|
||||
:class="c.id === active ? 'border-warning bg-warning-soft/40' : 'border-line bg-surface-raised'"
|
||||
data-testid="comment"
|
||||
@click="emit('select', c.id)"
|
||||
>
|
||||
<p v-if="c.quote" class="mb-1 line-clamp-2 border-l-2 border-warning pl-2 text-ui-sm text-ink-muted">
|
||||
{{ c.quote }}
|
||||
</p>
|
||||
<p class="text-ui-sm">
|
||||
<span class="font-semibold">{{ c.author.name || c.author.email || $t("page.someone") }}</span>
|
||||
<span class="text-ink-muted"> · {{ when(c.created) }}</span>
|
||||
</p>
|
||||
<p class="mt-1 text-ui-md whitespace-pre-wrap">{{ c.body }}</p>
|
||||
<button
|
||||
v-if="c.canDelete"
|
||||
class="mt-1 text-ui-sm text-danger hover:underline"
|
||||
:disabled="busy"
|
||||
@click.stop="remove(c)"
|
||||
<div ref="list" class="flex flex-col gap-2">
|
||||
<template v-for="group in [open, showResolved ? resolved : []]" :key="group === open ? 'open' : 'resolved'">
|
||||
<article
|
||||
v-for="t in group"
|
||||
:key="t.root.id"
|
||||
:data-id="t.root.id"
|
||||
class="relative rounded-md border p-3"
|
||||
:class="[
|
||||
t.root.id === active ? 'border-warning bg-warning-soft/40' : 'border-line bg-surface-raised',
|
||||
t.root.resolvedAt ? 'opacity-80' : '',
|
||||
t.root.canResolve ? 'pr-9' : '',
|
||||
]"
|
||||
data-testid="comment-thread"
|
||||
@click="emit('select', t.root.id)"
|
||||
>
|
||||
{{ $t("comments.delete") }}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<DwButton
|
||||
v-if="t.root.canResolve"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
:icon="t.root.resolvedAt ? 'restore' : 'check'"
|
||||
class="absolute top-2 right-2 !size-6"
|
||||
:aria-label="t.root.resolvedAt ? $t('comments.reopen') : $t('comments.resolve')"
|
||||
:title="t.root.resolvedAt ? $t('comments.reopen') : $t('comments.resolve')"
|
||||
:disabled="busy"
|
||||
data-testid="comment-resolve"
|
||||
@click.stop="setResolved(t, !t.root.resolvedAt)"
|
||||
/>
|
||||
<p v-if="t.root.quote" class="mb-1 line-clamp-2 border-l-2 border-warning pl-2 text-ui-sm text-ink-muted">
|
||||
{{ t.root.quote }}
|
||||
</p>
|
||||
<p v-if="t.root.resolvedAt" class="mb-1 text-ui-xs text-ink-muted">
|
||||
{{
|
||||
$t("comments.resolvedBy", {
|
||||
name: t.root.resolvedBy?.name || t.root.resolvedBy?.email || $t("page.someone"),
|
||||
})
|
||||
}}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-for="c in [t.root, ...t.replies]"
|
||||
:key="c.id"
|
||||
:data-id="c.id"
|
||||
class="group mt-2 first:mt-0"
|
||||
:class="c.parent ? 'border-t border-line pt-2' : ''"
|
||||
data-testid="comment"
|
||||
>
|
||||
<p class="text-ui-sm">
|
||||
<span class="font-semibold">{{ who(c) || $t("page.someone") }}</span>
|
||||
<span class="text-ink-muted"> · {{ when(c.created) }}</span>
|
||||
<span v-if="c.editedAt" class="text-ink-muted"> · {{ $t("comments.edited") }}</span>
|
||||
</p>
|
||||
<CommentBox
|
||||
v-if="editing === c.id"
|
||||
class="mt-1"
|
||||
:workspace="workspace"
|
||||
:placeholder="$t('comments.write')"
|
||||
:submit-label="$t('comments.save')"
|
||||
:busy="busy"
|
||||
:initial="c.body"
|
||||
autofocus
|
||||
@click.stop
|
||||
@submit="(body) => saveEdit(c, body)"
|
||||
@cancel="editing = ''"
|
||||
/>
|
||||
<p v-else class="mt-1 text-ui-md whitespace-pre-wrap">{{ c.body }}</p>
|
||||
|
||||
<div class="mt-1 flex flex-wrap items-center gap-1">
|
||||
<button
|
||||
v-for="r in c.reactions"
|
||||
:key="r.emoji"
|
||||
class="flex h-6 items-center gap-1 rounded-full border px-2 text-ui-sm"
|
||||
:class="r.mine ? 'border-primary bg-accent-soft' : 'border-line hover:border-line-strong'"
|
||||
:title="r.people.join(', ')"
|
||||
:aria-pressed="r.mine"
|
||||
:disabled="busy || !canComment"
|
||||
@click.stop="react(c, r.emoji)"
|
||||
>
|
||||
{{ r.emoji }}<span class="tabular-nums">{{ r.count }}</span>
|
||||
</button>
|
||||
<span v-if="canComment" class="relative">
|
||||
<DwButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="smile"
|
||||
class="!size-6 opacity-60 group-hover:opacity-100 focus-visible:opacity-100"
|
||||
:aria-label="$t('comments.react')"
|
||||
:title="$t('comments.react')"
|
||||
:aria-expanded="picker === c.id"
|
||||
@click.stop="picker = picker === c.id ? '' : c.id"
|
||||
/>
|
||||
<span
|
||||
v-if="picker === c.id"
|
||||
class="absolute left-0 top-full z-10 mt-1 flex gap-0.5 rounded-sm border border-line bg-surface-raised p-1 shadow-dialog"
|
||||
role="menu"
|
||||
>
|
||||
<button
|
||||
v-for="e in QUICK"
|
||||
:key="e"
|
||||
role="menuitem"
|
||||
class="grid size-7 place-items-center rounded-xs text-ui-lg hover:bg-surface-hover"
|
||||
:aria-label="e"
|
||||
@click.stop="react(c, e)"
|
||||
>
|
||||
{{ e }}
|
||||
</button>
|
||||
</span>
|
||||
</span>
|
||||
<span class="flex-1" />
|
||||
<button
|
||||
v-if="c.canEdit && editing !== c.id"
|
||||
class="text-ui-sm text-ink-muted hover:underline"
|
||||
:disabled="busy"
|
||||
@click.stop="editing = c.id"
|
||||
>
|
||||
{{ $t("comments.edit") }}
|
||||
</button>
|
||||
<button
|
||||
v-if="c.canDelete"
|
||||
class="text-ui-sm text-danger hover:underline"
|
||||
:disabled="busy"
|
||||
@click.stop="remove(c)"
|
||||
>
|
||||
{{ $t("comments.delete") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="canComment" class="mt-2 border-t border-line pt-2" @click.stop>
|
||||
<CommentBox
|
||||
v-if="replyTo === t.root.id"
|
||||
:workspace="workspace"
|
||||
:placeholder="$t('comments.reply')"
|
||||
:submit-label="$t('comments.send')"
|
||||
:busy="busy"
|
||||
autofocus
|
||||
@submit="(body, mentions) => reply(t, body, mentions)"
|
||||
@cancel="replyTo = ''"
|
||||
/>
|
||||
<button
|
||||
v-else
|
||||
class="flex items-center gap-1 text-ui-sm text-ink-muted hover:text-ink"
|
||||
data-testid="comment-reply"
|
||||
@click="replyTo = t.root.id"
|
||||
>
|
||||
<DwIcon name="reply" :size="14" />{{ $t("comments.reply") }}
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
|
||||
<button
|
||||
v-if="resolved.length"
|
||||
class="flex items-center gap-1 self-start text-ui-sm text-ink-muted hover:text-ink"
|
||||
:aria-expanded="showResolved"
|
||||
data-testid="comments-resolved"
|
||||
@click="showResolved = !showResolved"
|
||||
>
|
||||
<DwIcon name="check" :size="14" />
|
||||
{{
|
||||
showResolved
|
||||
? $t("comments.hideResolved")
|
||||
: $t("comments.showResolved", { n: resolved.length }, resolved.length)
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -385,6 +385,37 @@
|
||||
"send": "Comment",
|
||||
"cancel": "Cancel",
|
||||
"delete": "Delete",
|
||||
"hint": "Select some text and choose Comment to start a discussion."
|
||||
"hint": "Select some text and choose Comment to start a discussion.",
|
||||
"reply": "Reply",
|
||||
"resolve": "Resolve",
|
||||
"reopen": "Reopen",
|
||||
"resolvedBy": "Resolved by {name}",
|
||||
"edit": "Edit",
|
||||
"edited": "edited",
|
||||
"save": "Save",
|
||||
"react": "Add reaction",
|
||||
"showResolved": "Show {n} resolved thread | Show {n} resolved threads",
|
||||
"hideResolved": "Hide resolved threads"
|
||||
},
|
||||
"notifications": {
|
||||
"title": "Inbox",
|
||||
"unread": "Unread",
|
||||
"unreadCount": "{n} unread | {n} unread",
|
||||
"markAllRead": "Mark all as read",
|
||||
"empty": "Nothing new. Comments on pages you watch, replies, mentions and shares show up here.",
|
||||
"pageGone": "a page you can no longer open",
|
||||
"types": {
|
||||
"comment": "{actor} commented on {page}",
|
||||
"reply": "{actor} replied in {page}",
|
||||
"mention": "{actor} mentioned you in {page}",
|
||||
"share": "{actor} shared {page} with you",
|
||||
"resolved": "{actor} resolved a thread in {page}"
|
||||
},
|
||||
"settings": "Email",
|
||||
"emailDigest": "Email me about unread notifications",
|
||||
"emailDigestHint": "A summary every few minutes, only for what you have not seen in the app.",
|
||||
"watchHint": "You watch pages you create or comment on. Use the page menu to watch or mute a page.",
|
||||
"watch": "Watch page",
|
||||
"unwatch": "Stop watching"
|
||||
}
|
||||
}
|
||||
@@ -385,6 +385,37 @@
|
||||
"send": "Skomentuj",
|
||||
"cancel": "Anuluj",
|
||||
"delete": "Usuń",
|
||||
"hint": "Zaznacz fragment tekstu i wybierz Komentarz, aby rozpocząć dyskusję."
|
||||
"hint": "Zaznacz fragment tekstu i wybierz Komentarz, aby rozpocząć dyskusję.",
|
||||
"reply": "Odpowiedz",
|
||||
"resolve": "Rozwiąż",
|
||||
"reopen": "Otwórz ponownie",
|
||||
"resolvedBy": "Rozwiązane przez {name}",
|
||||
"edit": "Edytuj",
|
||||
"edited": "edytowano",
|
||||
"save": "Zapisz",
|
||||
"react": "Dodaj reakcję",
|
||||
"showResolved": "Pokaż {n} rozwiązany wątek | Pokaż {n} rozwiązane wątki | Pokaż {n} rozwiązanych wątków",
|
||||
"hideResolved": "Ukryj rozwiązane wątki"
|
||||
},
|
||||
"notifications": {
|
||||
"title": "Skrzynka",
|
||||
"unread": "Nieprzeczytane",
|
||||
"unreadCount": "{n} nieprzeczytane | {n} nieprzeczytane | {n} nieprzeczytanych",
|
||||
"markAllRead": "Oznacz wszystkie jako przeczytane",
|
||||
"empty": "Nic nowego. Komentarze na obserwowanych stronach, odpowiedzi, wzmianki i udostępnienia pojawią się tutaj.",
|
||||
"pageGone": "stronie, której już nie możesz otworzyć",
|
||||
"types": {
|
||||
"comment": "{actor} skomentował(a) {page}",
|
||||
"reply": "{actor} odpowiedział(a) na stronie {page}",
|
||||
"mention": "{actor} wspomniał(a) o Tobie na stronie {page}",
|
||||
"share": "{actor} udostępnił(a) Ci {page}",
|
||||
"resolved": "{actor} rozwiązał(a) wątek na stronie {page}"
|
||||
},
|
||||
"settings": "E-mail",
|
||||
"emailDigest": "Wysyłaj mi e-mail o nieprzeczytanych powiadomieniach",
|
||||
"emailDigestHint": "Podsumowanie co kilka minut, tylko o tym, czego nie widzisz w aplikacji.",
|
||||
"watchHint": "Obserwujesz strony, które tworzysz lub komentujesz. Menu strony pozwala obserwować lub wyciszyć stronę.",
|
||||
"watch": "Obserwuj stronę",
|
||||
"unwatch": "Przestań obserwować"
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export function createDocwellRouter(platform: Platform) {
|
||||
{ path: "p/:id", name: "page", component: () => import("./views/page/PageView.vue"), props: true },
|
||||
{ path: "s/:id", name: "space", component: () => import("./views/space/SpaceView.vue"), props: true },
|
||||
{ path: "s/:id/trash", name: "trash", component: () => import("./views/space/TrashView.vue"), props: true },
|
||||
{ path: "notifications", name: "notifications", component: () => import("./views/NotificationsView.vue") },
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { Notification } from "@docwell/api-client";
|
||||
import { defineStore } from "pinia";
|
||||
import { ref } from "vue";
|
||||
import { useApi } from "../api";
|
||||
|
||||
const POLL_MS = 60_000;
|
||||
|
||||
/** The signed-in user's notifications. The unread count is polled while the app is open. */
|
||||
export const useNotificationsStore = defineStore("notifications", () => {
|
||||
const api = useApi();
|
||||
const items = ref<Notification[]>([]);
|
||||
const unread = ref(0);
|
||||
const loaded = ref(false);
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
async function load() {
|
||||
const list = await api.notifications.list({ limit: 50 });
|
||||
items.value = list.items;
|
||||
unread.value = list.unread;
|
||||
loaded.value = true;
|
||||
}
|
||||
|
||||
async function refreshCount() {
|
||||
const list = await api.notifications.list({ unread: true, limit: 1 });
|
||||
unread.value = list.unread;
|
||||
}
|
||||
|
||||
async function markRead(ids: string[]) {
|
||||
const todo = ids.filter((id) => items.value.some((n) => n.id === id && !n.read));
|
||||
if (!todo.length) return;
|
||||
const res = await api.notifications.markRead({ ids: todo });
|
||||
for (const n of items.value) if (todo.includes(n.id)) n.read = true;
|
||||
unread.value = res.unread;
|
||||
}
|
||||
|
||||
async function markAllRead() {
|
||||
const res = await api.notifications.markRead({ all: true });
|
||||
for (const n of items.value) n.read = true;
|
||||
unread.value = res.unread;
|
||||
}
|
||||
|
||||
const onFocus = () => void refreshCount().catch(() => {});
|
||||
|
||||
/** Starts polling; safe to call more than once. */
|
||||
function start() {
|
||||
if (timer) return;
|
||||
onFocus();
|
||||
timer = setInterval(onFocus, POLL_MS);
|
||||
window.addEventListener("focus", onFocus);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
clearInterval(timer);
|
||||
timer = undefined;
|
||||
window.removeEventListener("focus", onFocus);
|
||||
items.value = [];
|
||||
unread.value = 0;
|
||||
loaded.value = false;
|
||||
}
|
||||
|
||||
return { items, unread, loaded, load, refreshCount, markRead, markAllRead, start, stop };
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Notification, NotificationSettings } from "@docwell/api-client";
|
||||
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon, type IconName } from "@docwell/ui";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../api";
|
||||
import { useFormErrors } from "../composables/useFormErrors";
|
||||
import { useNotificationsStore } from "../stores/notifications";
|
||||
|
||||
// The inbox: what happened on watched pages, replies, mentions and shares,
|
||||
// newest first, and whether unread ones also come by email.
|
||||
const api = useApi();
|
||||
const store = useNotificationsStore();
|
||||
const router = useRouter();
|
||||
const errors = useFormErrors();
|
||||
const { locale } = useI18n();
|
||||
|
||||
const settings = ref<NotificationSettings | null>(null);
|
||||
const busy = ref(false);
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await store.load();
|
||||
settings.value = await api.notifications.settings();
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
}
|
||||
});
|
||||
|
||||
const icons: Record<Notification["type"], IconName> = {
|
||||
comment: "comment",
|
||||
reply: "reply",
|
||||
mention: "at",
|
||||
share: "share",
|
||||
resolved: "check",
|
||||
};
|
||||
|
||||
async function open(n: Notification) {
|
||||
void store.markRead([n.id]).catch(() => {});
|
||||
if (!n.page) return;
|
||||
await router.push({ name: "page", params: { id: n.page.id }, query: n.comment ? { comment: n.comment } : {} });
|
||||
}
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
errors.reset();
|
||||
try {
|
||||
await action();
|
||||
} catch (e) {
|
||||
errors.show(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
const markAll = () => run(() => store.markAllRead());
|
||||
const setEmail = (on: boolean) =>
|
||||
run(async () => {
|
||||
settings.value = await api.notifications.setSettings({ email: on ? "digest" : "off" });
|
||||
});
|
||||
|
||||
const when = (s: string) =>
|
||||
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport defer to="#app-header">
|
||||
<DwBreadcrumbs :items="[{ label: $t('notifications.title') }]" :label="$t('page.breadcrumbs')" />
|
||||
</Teleport>
|
||||
|
||||
<article class="mx-auto max-w-doc px-4 pt-6 pb-16 sm:px-16 sm:pt-10">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<h1 class="font-serif text-doc-h1">{{ $t("notifications.title") }}</h1>
|
||||
<DwButton
|
||||
v-if="store.unread"
|
||||
size="sm"
|
||||
icon="check"
|
||||
:disabled="busy"
|
||||
data-testid="mark-all-read"
|
||||
@click="markAll"
|
||||
>
|
||||
{{ $t("notifications.markAllRead") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-4">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<ul v-if="store.items.length" class="mt-6 flex flex-col gap-1" data-testid="notifications">
|
||||
<li v-for="n in store.items" :key="n.id">
|
||||
<button
|
||||
class="flex w-full cursor-pointer items-start gap-3 rounded-md px-3 py-2.5 text-left hover:bg-surface-hover disabled:cursor-default"
|
||||
:class="n.read ? 'text-ink-muted' : ''"
|
||||
:disabled="!n.page"
|
||||
data-testid="notification"
|
||||
@click="open(n)"
|
||||
>
|
||||
<DwIcon :name="icons[n.type]" :size="18" class="mt-0.5 shrink-0 text-ink-muted" />
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block text-ui-md">
|
||||
<i18n-t :keypath="`notifications.types.${n.type}`" scope="global">
|
||||
<template #actor>
|
||||
<span class="font-semibold">{{ n.actor?.name || n.actor?.email || $t("page.someone") }}</span>
|
||||
</template>
|
||||
<template #page>
|
||||
<span class="font-semibold">{{
|
||||
n.page ? n.page.title || $t("home.untitled") : $t("notifications.pageGone")
|
||||
}}</span>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</span>
|
||||
<span v-if="n.excerpt && n.type !== 'share'" class="mt-0.5 line-clamp-2 block text-ui-sm text-ink-muted">
|
||||
{{ n.excerpt }}
|
||||
</span>
|
||||
<span class="mt-0.5 block text-ui-xs text-ink-faint">{{ when(n.created) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="!n.read"
|
||||
class="mt-2 size-2 shrink-0 rounded-full bg-primary"
|
||||
:aria-label="$t('notifications.unread')"
|
||||
/>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div
|
||||
v-else-if="store.loaded"
|
||||
class="mt-8 flex items-center gap-3 rounded-md border border-dashed border-line px-4 py-6 text-ink-muted"
|
||||
>
|
||||
<DwIcon name="bell" :size="20" class="text-spring" />
|
||||
{{ $t("notifications.empty") }}
|
||||
</div>
|
||||
|
||||
<section v-if="settings" class="mt-10 border-t border-line pt-6">
|
||||
<h2 class="dw-label">{{ $t("notifications.settings") }}</h2>
|
||||
<label class="mt-3 flex items-start gap-3 text-ui-md">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="mt-1 accent-primary"
|
||||
:checked="settings.email === 'digest'"
|
||||
:disabled="busy"
|
||||
data-testid="email-digest"
|
||||
@change="setEmail(($event.target as HTMLInputElement).checked)"
|
||||
/>
|
||||
<span>
|
||||
<span class="font-medium">{{ $t("notifications.emailDigest") }}</span>
|
||||
<span class="block text-ui-sm text-ink-muted">{{ $t("notifications.emailDigestHint") }}</span>
|
||||
</span>
|
||||
</label>
|
||||
<p class="mt-3 text-ui-sm text-ink-muted">{{ $t("notifications.watchHint") }}</p>
|
||||
</section>
|
||||
</article>
|
||||
</template>
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon, DwMenu, type MenuItem } from "@docwell/ui";
|
||||
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useApi, useToken } from "../../api";
|
||||
import PageHistory from "../../components/PageHistory.vue";
|
||||
import PageComments from "../../components/PageComments.vue";
|
||||
@@ -35,6 +35,7 @@ const spaces = useSpacesStore();
|
||||
const favorites = useFavoritesStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const config = useRuntimeConfig();
|
||||
@@ -56,21 +57,48 @@ const activeComment = ref("");
|
||||
const draft = ref<{ quote: string; anchor: Record<string, unknown> | null } | null>(null);
|
||||
const canComment = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "commenter"));
|
||||
|
||||
// Open threads only: resolved ones and replies light no text.
|
||||
const openThreads = computed(() => comments.value.filter((c) => !c.parent && !c.resolvedAt));
|
||||
|
||||
async function loadComments() {
|
||||
if (!page.value) return;
|
||||
const id = page.value.id;
|
||||
const list = await api.pages.comments(id).catch(() => null);
|
||||
if (list && page.value?.id === id) comments.value = list;
|
||||
// A notification links to ?comment=<id>: open the panel on its thread.
|
||||
const wanted = typeof route.query.comment === "string" ? route.query.comment : "";
|
||||
const hit = wanted && list?.find((c) => c.id === wanted);
|
||||
if (hit) {
|
||||
activeComment.value = hit.parent || hit.id;
|
||||
commentsOpen.value = true;
|
||||
}
|
||||
}
|
||||
function drawComments() {
|
||||
const editor = editorRef.value?.editor;
|
||||
if (!editor) return;
|
||||
setCommentMarks(
|
||||
editor,
|
||||
comments.value.map((c) => ({ id: c.id, anchor: (c.anchor as CommentAnchor | null) ?? null })),
|
||||
openThreads.value.map((c) => ({ id: c.id, anchor: (c.anchor as CommentAnchor | null) ?? null })),
|
||||
activeComment.value,
|
||||
);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.query.comment,
|
||||
() => void loadComments(),
|
||||
);
|
||||
|
||||
// Watching: new comments on the page land in the inbox.
|
||||
const watching = ref(false);
|
||||
async function loadWatch(id: string) {
|
||||
const st = await api.pages.watch(id).catch(() => null);
|
||||
if (st && page.value?.id === id) watching.value = st.watching;
|
||||
}
|
||||
const toggleWatch = () =>
|
||||
run(async () => {
|
||||
const st = await api.pages.setWatch(page.value!.id, !watching.value);
|
||||
watching.value = st.watching;
|
||||
});
|
||||
function startComment(sel: { from: number; to: number; text: string }) {
|
||||
const editor = editorRef.value?.editor;
|
||||
const anchor = editor ? encodeAnchor(editor, sel.from, sel.to) : null;
|
||||
@@ -189,6 +217,7 @@ async function load(id: string) {
|
||||
// Best effort: the recent list is a convenience.
|
||||
api.pages.visit(p.id).catch(() => {});
|
||||
void loadComments();
|
||||
void loadWatch(p.id);
|
||||
} catch {
|
||||
page.value = null;
|
||||
notFound.value = true;
|
||||
@@ -264,6 +293,11 @@ const exportAs = (format: "markdown" | "html") =>
|
||||
});
|
||||
|
||||
const menu = computed<MenuItem[]>(() => [
|
||||
{
|
||||
label: t(watching.value ? "notifications.unwatch" : "notifications.watch"),
|
||||
icon: watching.value ? "bell-off" : "bell",
|
||||
onSelect: toggleWatch,
|
||||
},
|
||||
{ label: t("page.exportMarkdown"), icon: "download", onSelect: () => exportAs("markdown") },
|
||||
{ label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") },
|
||||
]);
|
||||
@@ -361,7 +395,7 @@ const purge = () =>
|
||||
@click="commentsOpen = !commentsOpen"
|
||||
>
|
||||
<span class="sr-only sm:not-sr-only">{{ $t("comments.title") }}</span>
|
||||
<span v-if="comments.length" class="tabular-nums">{{ comments.length }}</span>
|
||||
<span v-if="openThreads.length" class="tabular-nums">{{ openThreads.length }}</span>
|
||||
</DwButton>
|
||||
<DwButton variant="ghost" size="sm" icon="share" data-testid="share-open" @click="shareOpen = true">
|
||||
<span class="sr-only sm:not-sr-only">{{ $t("share.button") }}</span>
|
||||
@@ -458,6 +492,7 @@ const purge = () =>
|
||||
<PageComments
|
||||
v-if="page && commentsOpen"
|
||||
:page="page.id"
|
||||
:workspace="page.workspace"
|
||||
:comments="comments"
|
||||
:draft="draft"
|
||||
:active="activeComment"
|
||||
|
||||
+239
-6
@@ -1677,7 +1677,7 @@ paths:
|
||||
get:
|
||||
operationId: listComments
|
||||
tags: [comments]
|
||||
summary: The page's inline comments, oldest first
|
||||
summary: The page's comments and replies, oldest first (threads are the ones without a parent)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
@@ -1689,7 +1689,8 @@ paths:
|
||||
post:
|
||||
operationId: createComment
|
||||
tags: [comments]
|
||||
summary: Comment on the page (commenter)
|
||||
summary: Start a thread on the page, or reply to one (commenter)
|
||||
description: The author starts watching the page. Watchers, the thread's people and mentioned people are notified.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -1700,11 +1701,13 @@ paths:
|
||||
required: [body]
|
||||
properties:
|
||||
body: { type: string, maxLength: 5000 }
|
||||
quote: { type: string, maxLength: 500, description: The commented text }
|
||||
quote: { type: string, maxLength: 500, description: The commented text (threads only) }
|
||||
anchor:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
description: The editor's encoding of the commented range (opaque to the server)
|
||||
description: The editor's encoding of the commented range, opaque to the server (threads only)
|
||||
parent: { type: string, description: The thread to reply to }
|
||||
mentions: { type: array, items: { type: string }, description: Ids of the people mentioned in body }
|
||||
responses:
|
||||
"201":
|
||||
description: Created
|
||||
@@ -1717,15 +1720,195 @@ paths:
|
||||
/api/v1/comments/{id}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
patch:
|
||||
operationId: updateComment
|
||||
tags: [comments]
|
||||
summary: Change a comment's text (its author)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [body]
|
||||
properties:
|
||||
body: { type: string, maxLength: 5000 }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Comment" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
delete:
|
||||
operationId: deleteComment
|
||||
tags: [comments]
|
||||
summary: Delete a comment (its author, or a space admin)
|
||||
summary: Delete a comment, and a thread's replies with it (its author, or a space admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"204": { description: Deleted }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/comments/{id}/resolve:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: resolveComment
|
||||
tags: [comments]
|
||||
summary: Resolve a thread, or open it again (commenter)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [resolved]
|
||||
properties:
|
||||
resolved: { type: boolean }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Comment" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/comments/{id}/reactions:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: reactToComment
|
||||
tags: [comments]
|
||||
summary: Add or remove the caller's emoji reaction (commenter)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [emoji, on]
|
||||
properties:
|
||||
emoji: { type: string, maxLength: 32 }
|
||||
on: { type: boolean }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Comment" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/watch:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getPageWatch
|
||||
tags: [notifications]
|
||||
summary: Whether the caller watches the page
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/WatchState" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
put:
|
||||
operationId: setPageWatch
|
||||
tags: [notifications]
|
||||
summary: Watch the page, or mute it
|
||||
description: Muting is remembered, so commenting later does not start watching again.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/WatchState" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/WatchState" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/notifications:
|
||||
get:
|
||||
operationId: listNotifications
|
||||
tags: [notifications]
|
||||
summary: The caller's newest notifications with the unread count
|
||||
security: [{ bearer: [] }]
|
||||
parameters:
|
||||
- { name: unread, in: query, description: Only unread ones, schema: { type: boolean } }
|
||||
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100 } }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NotificationList" }
|
||||
"401": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/notifications/read:
|
||||
post:
|
||||
operationId: markNotificationsRead
|
||||
tags: [notifications]
|
||||
summary: Mark notifications read (the listed ones, or all)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ids: { type: array, items: { type: string } }
|
||||
all: { type: boolean }
|
||||
responses:
|
||||
"200":
|
||||
description: The unread count afterwards
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [unread]
|
||||
properties:
|
||||
unread: { type: integer }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/notifications/settings:
|
||||
get:
|
||||
operationId: getNotificationSettings
|
||||
tags: [notifications]
|
||||
summary: The caller's notification preferences
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NotificationSettings" }
|
||||
put:
|
||||
operationId: setNotificationSettings
|
||||
tags: [notifications]
|
||||
summary: Change the caller's notification preferences
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NotificationSettings" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/NotificationSettings" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/admin/stats:
|
||||
get:
|
||||
operationId: getAdminStats
|
||||
@@ -2341,9 +2524,11 @@ components:
|
||||
pages: { type: array, items: { $ref: "#/components/schemas/PageNode" }, description: Pages under the shared page, in tree order (only when the link includes subpages) }
|
||||
Comment:
|
||||
type: object
|
||||
required: [id, page, author, body, quote, anchor, created, canDelete]
|
||||
required:
|
||||
[id, parent, page, author, body, quote, anchor, created, editedAt, resolvedAt, resolvedBy, reactions, canEdit, canDelete, canResolve]
|
||||
properties:
|
||||
id: { type: string }
|
||||
parent: { type: string, description: The thread's first comment for a reply; empty for a thread }
|
||||
page: { type: string }
|
||||
author: { $ref: "#/components/schemas/MemberUser" }
|
||||
body: { type: string }
|
||||
@@ -2352,7 +2537,55 @@ components:
|
||||
oneOf: [{ type: object, additionalProperties: true }, { type: "null" }]
|
||||
description: As sent when the comment was created; null when there was none
|
||||
created: { type: string }
|
||||
editedAt: { type: string, description: Empty when never edited }
|
||||
resolvedAt: { type: string, description: Empty unless the thread is resolved }
|
||||
resolvedBy:
|
||||
oneOf: [{ $ref: "#/components/schemas/MemberUser" }, { type: "null" }]
|
||||
reactions: { type: array, items: { $ref: "#/components/schemas/Reaction" }, description: Most used first }
|
||||
canEdit: { type: boolean }
|
||||
canDelete: { type: boolean }
|
||||
canResolve: { type: boolean, description: A thread the caller may resolve or reopen }
|
||||
Reaction:
|
||||
type: object
|
||||
required: [emoji, count, mine, people]
|
||||
properties:
|
||||
emoji: { type: string }
|
||||
count: { type: integer }
|
||||
mine: { type: boolean }
|
||||
people: { type: array, items: { type: string }, description: Names of the people who reacted }
|
||||
WatchState:
|
||||
type: object
|
||||
required: [watching]
|
||||
properties:
|
||||
watching: { type: boolean }
|
||||
NotificationType: { type: string, enum: [comment, reply, mention, share, resolved] }
|
||||
Notification:
|
||||
type: object
|
||||
required: [id, type, workspace, page, comment, actor, excerpt, created, read]
|
||||
properties:
|
||||
id: { type: string }
|
||||
type: { $ref: "#/components/schemas/NotificationType" }
|
||||
workspace: { type: string }
|
||||
page:
|
||||
oneOf: [{ $ref: "#/components/schemas/PageRef" }, { type: "null" }]
|
||||
description: Null when the page is gone or the caller lost access to it
|
||||
comment: { type: string, description: The comment it is about, if any }
|
||||
actor:
|
||||
oneOf: [{ $ref: "#/components/schemas/MemberUser" }, { type: "null" }]
|
||||
excerpt: { type: string }
|
||||
created: { type: string }
|
||||
read: { type: boolean }
|
||||
NotificationList:
|
||||
type: object
|
||||
required: [items, unread]
|
||||
properties:
|
||||
items: { type: array, items: { $ref: "#/components/schemas/Notification" } }
|
||||
unread: { type: integer }
|
||||
NotificationSettings:
|
||||
type: object
|
||||
required: [email]
|
||||
properties:
|
||||
email: { type: string, enum: [digest, "off"], description: Unread notifications by email every few minutes, or no emails }
|
||||
AdminStats:
|
||||
type: object
|
||||
required: [scope, users, organizations, workspaces, spaces, pages, attachments, storageBytes, rooms, editors, indexed]
|
||||
|
||||
Reference in new issue
Block a user