diff --git a/Database/pb_migrations/1764700000_verified_pages.js b/Database/pb_migrations/1764700000_verified_pages.js
new file mode 100644
index 0000000..d76dc1f
--- /dev/null
+++ b/Database/pb_migrations/1764700000_verified_pages.js
@@ -0,0 +1,62 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+///
+
+// Verified pages: an editor vouches that a page is correct, for a while.
+//
+// - pages.verified_by and verified_at: who verified the page and when; empty
+// when nobody has.
+// - pages.verified_until: when the verification runs out; empty for one that
+// does not expire.
+// - pages.verify_notified_at: when the verifier was told it ran out, so they
+// hear once; verifying again clears it.
+// - notifications gain the verify_expired type.
+
+migrate(
+ (app) => {
+ const users = app.findCollectionByNameOrId("users");
+ const pages = app.findCollectionByNameOrId("pages");
+ pages.fields.add(new RelationField({ name: "verified_by", collectionId: users.id, maxSelect: 1, cascadeDelete: false }));
+ pages.fields.add(new DateField({ name: "verified_at" }));
+ pages.fields.add(new DateField({ name: "verified_until" }));
+ pages.fields.add(new DateField({ name: "verify_notified_at" }));
+ pages.indexes.push("CREATE INDEX idx_pages_verified_until ON pages (verified_until)");
+ app.save(pages);
+
+ const notifications = app.findCollectionByNameOrId("notifications");
+ notifications.fields.getByName("type").values = [
+ "comment",
+ "reply",
+ "mention",
+ "share",
+ "resolved",
+ "reminder",
+ "join_request",
+ "join_approved",
+ "join_declined",
+ "verify_expired",
+ ];
+ app.save(notifications);
+ },
+ (app) => {
+ const pages = app.findCollectionByNameOrId("pages");
+ for (const name of ["verified_by", "verified_at", "verified_until", "verify_notified_at"]) {
+ pages.fields.removeByName(name);
+ }
+ pages.indexes = pages.indexes.filter((i) => !i.includes("idx_pages_verified_until"));
+ app.save(pages);
+ const notifications = app.findCollectionByNameOrId("notifications");
+ notifications.fields.getByName("type").values = [
+ "comment",
+ "reply",
+ "mention",
+ "share",
+ "resolved",
+ "reminder",
+ "join_request",
+ "join_approved",
+ "join_declined",
+ ];
+ app.save(notifications);
+ },
+);
diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md
index 7a9fda7..63722a2 100644
--- a/Docs-Site/guide/using-docwell.md
+++ b/Docs-Site/guide/using-docwell.md
@@ -15,6 +15,7 @@ Pages save as you type, and everyone with the page open sees changes and cursors
| To | Do this |
| --- | --- |
| Insert a heading, list, to-do list, table, callout, quote, code block, divider, image or file | Type `/` and pick from the menu (keep typing to filter); headings 4–6 are under **Other headings** |
+| Put blocks side by side | Type `/columns` and pick 2, 3 or 4 columns; drag the line between two columns to change their widths, and **+** at the right edge adds a column (Ctrl+Alt+→). Backspace in an empty column removes it. On phones the columns stack |
| Start a to-do list | Type `[] ` at the start of a line |
| Format text, colour or highlight it, align it, or add a link | Select it and use the toolbar that appears |
| Move, duplicate, turn into another kind, or delete a block | Point at it and drag the ⠿ grip in the margin, or click the grip for a menu |
@@ -32,6 +33,23 @@ Pages save as you type, and everyone with the page open sees changes and cursors
**History** in the page header lists saved versions; you can view any of them and restore it. Restoring keeps the
current text as a version too.
+### Suggesting edits
+
+Choose **Suggest edits** in the ⋯ menu to propose changes instead of making them. What you type is underlined in
+green and what you delete stays, struck through in red, until someone accepts or rejects it. Click a suggestion to
+see who made it and when, and to **Accept** or **Reject** it; the bar above the page counts the open suggestions and
+has **Accept all** and **Reject all**. Anyone who can edit the page can decide. Deleting your own suggested text
+simply removes it. Only text is tracked: splitting or joining paragraphs and formatting change directly. Suggesting
+mode is for you alone and ends when you leave the page (**Edit directly** in the same menu turns it off). Exports
+to Markdown, Word and PDF show the page without the open suggestions; HTML keeps them.
+
+### Verified pages
+
+Editors can choose **Verify page** in the ⋯ menu to say a page is correct, for a week, a month, three or six
+months, a year or with no end date. Everyone sees **Verified by …** under the title; once the time runs out it reads
+**Verification ran out**, and the person who verified it gets a notification (and an email, unless they turned that
+kind off). Click the badge to verify it again or remove the verification.
+
A synced page is read-only where it is shown: open it to edit it. People who cannot open that page see only its
title. **Account → Editor** sets, for this device, the text size, whether new pages start full width or titled with
today's date, whether properties and the pages that link here show, and line numbers in code blocks.
@@ -127,8 +145,9 @@ the **Comments** panel. People with the *commenter* role can comment without bei
admins can delete comments.
The **Inbox** lists your notifications. Under its settings you choose whether they also come by email, and which
-kinds (mentions, comments, replies, resolved threads, shared pages, reminders, people asking to join a workspace you
-manage).
+kinds (mentions, comments, replies, resolved threads, shared pages, reminders, verifications that ran out, people
+asking to join a workspace you manage). Emails and phone notifications are written in the language you last used
+Docwell in.
## Finding things
@@ -136,11 +155,13 @@ Press **Ctrl+K** (⌘K on a Mac) or click **Search** in the sidebar. With nothin
visited last; type to search titles and text in every space you can open. The filters narrow results by space,
tag, author or date. Star a page (☆ in the header) to keep it under **Favorites** in the sidebar.
-Search also reads the files attached to pages: the text of PDFs (not scanned ones, which have no text), Word
+Search also reads the files attached to pages: the text of PDFs, Word
(`.docx`), HTML and text files such as Markdown or CSV, up to 25 MB each, and their names. A match shows the file
with 📎 and the page it is on; it opens that page. Only files the page still links to are found, so a file removed
from its page drops out of search. Files are read once, a few seconds after they are uploaded; after an upgrade, the
-files already on the server are read in the background.
+files already on the server are read in the background. Scanned PDFs have no text of their own: a workspace admin
+can turn on **Read scanned PDFs for search** under *Workspace settings → AI*, and AI then writes out each one once
+(a few a minute), which uses the workspace's AI tokens.
## AI
diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts
index 87327bc..76b9492 100644
--- a/Packages/api-client/src/index.ts
+++ b/Packages/api-client/src/index.ts
@@ -222,6 +222,8 @@ export interface ClientOptions {
token?: () => string | null | undefined;
/** Called when the server rejects the token (401 on an authenticated call). */
onUnauthorized?: () => void;
+ /** The language the app shows (en, pl, …): sent as Accept-Language, so the server's messages match it. */
+ locale?: () => string | null | undefined;
fetch?: typeof fetch;
}
@@ -235,6 +237,8 @@ export function createClient(opts: ClientOptions) {
const headers: Record = { Accept: "application/json" };
const token = opts.token?.();
if (token) headers.Authorization = `Bearer ${token}`;
+ const locale = opts.locale?.();
+ if (locale) headers["Accept-Language"] = locale;
if (body !== undefined) headers["Content-Type"] = "application/json";
const res = await doFetch(base + path, {
@@ -258,6 +262,8 @@ export function createClient(opts: ClientOptions) {
const headers: Record = {};
const token = opts.token?.();
if (token) headers.Authorization = `Bearer ${token}`;
+ const locale = opts.locale?.();
+ if (locale) headers["Accept-Language"] = locale;
const res = await doFetch(base + path, { headers });
if (!res.ok) {
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
@@ -276,6 +282,8 @@ export function createClient(opts: ClientOptions) {
const headers: Record = { Accept: "text/event-stream", "Content-Type": "application/json" };
const token = opts.token?.();
if (token) headers.Authorization = `Bearer ${token}`;
+ const locale = opts.locale?.();
+ if (locale) headers["Accept-Language"] = locale;
const res = await doFetch(base + path, { method: "POST", headers, body: JSON.stringify(body), signal });
if (!res.ok || !res.body) {
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
@@ -291,6 +299,8 @@ export function createClient(opts: ClientOptions) {
const headers: Record = { Accept: "application/json" };
const token = opts.token?.();
if (token) headers.Authorization = `Bearer ${token}`;
+ const locale = opts.locale?.();
+ if (locale) headers["Accept-Language"] = locale;
const res = await doFetch(base + path, { method: "POST", headers, body: form });
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
if (!res.ok) {
@@ -786,6 +796,10 @@ export function createClient(opts: ClientOptions) {
unarchive: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
pin: (id: string) => request("PUT", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
unpin: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
+ /** Verifies the page for days days, or without end for 0 (editor). */
+ verify: (id: string, days: number) =>
+ request("PUT", `/api/v1/pages/${encodeURIComponent(id)}/verify`, { days }),
+ unverify: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/verify`),
/**
* A web page's title, description and picture, read by docwell-server.
* With a workspace, its GitHub, Linear and Figma tokens reach private items.
diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts
index a756068..5882352 100644
--- a/Packages/api-client/src/schema.d.ts
+++ b/Packages/api-client/src/schema.d.ts
@@ -1418,6 +1418,29 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/v1/pages/{id}/verify": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ get?: never;
+ /**
+ * Verify the page as the caller, for some days or without end (editor)
+ * @description Verifying again replaces the earlier verification. When it runs out, the caller gets a verify_expired notification.
+ */
+ put: operations["verifyPage"];
+ post?: never;
+ /** Take the page's verification off (editor) */
+ delete: operations["unverifyPage"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/pages/{id}/visit": {
parameters: {
query?: never;
@@ -3707,6 +3730,21 @@ export interface components {
journalDate: string;
createdBy: components["schemas"]["PageUser"];
lastEditedBy: components["schemas"]["PageUser"];
+ verification: components["schemas"]["PageVerification"];
+ };
+ /** @description Whether someone vouched for the page; at is empty when nobody has */
+ PageVerification: {
+ by: components["schemas"]["PageUser"];
+ /** @description When the page was verified; empty if it is not */
+ at: string;
+ /** @description When the verification runs out; empty when it does not */
+ until: string;
+ /** @description The verification ran out (until has passed) */
+ expired: boolean;
+ };
+ VerifyPage: {
+ /** @description How many days the verification lasts; 0 for one that does not run out */
+ days: number;
};
/**
* @description The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it
@@ -4361,10 +4399,10 @@ export interface components {
watching: boolean;
};
/**
- * @description The join_* types are about a workspace and have no page
+ * @description The join_* types are about a workspace and have no page; verify_expired tells the person who verified a page that it ran out
* @enum {string}
*/
- NotificationType: "comment" | "reply" | "mention" | "share" | "resolved" | "reminder" | "join_request" | "join_approved" | "join_declined";
+ NotificationType: "comment" | "reply" | "mention" | "share" | "resolved" | "reminder" | "join_request" | "join_approved" | "join_declined" | "verify_expired";
Notification: {
id: string;
type: components["schemas"]["NotificationType"];
@@ -4702,6 +4740,8 @@ export interface components {
ignored: string[];
/** @description Tokens the workspace may use per month; 0 is no cap */
monthlyTokenLimit: number;
+ /** @description Have a document-reading model write out scanned PDFs attached to pages */
+ readScans: boolean;
};
/**
* @description openai is any OpenAI-compatible API
@@ -7368,6 +7408,59 @@ export interface operations {
404: components["responses"]["Error"];
};
};
+ verifyPage: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["VerifyPage"];
+ };
+ };
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Page"];
+ };
+ };
+ 400: components["responses"]["Error"];
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
+ unverifyPage: {
+ 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"]["Page"];
+ };
+ };
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
recordPageVisit: {
parameters: {
query?: never;
diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue
index 54ee06d..45614fa 100644
--- a/Packages/editor/src/DocwellEditor.vue
+++ b/Packages/editor/src/DocwellEditor.vue
@@ -4,7 +4,7 @@ import type { Editor, JSONContent } from "@tiptap/core";
import { EditorContent, useEditor } from "@tiptap/vue-3";
import { BubbleMenu } from "@tiptap/vue-3/menus";
import { CellSelection } from "@tiptap/pm/tables";
-import { DwIcon, type IconName } from "@docwell/ui";
+import { DwButton, DwIcon, type IconName } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { aiActions, type AiAction, type AiHost } from "./ai";
import { copyBlockLink } from "./blocklinks";
@@ -17,6 +17,7 @@ import { englishLabels, type EditorLabels } from "./labels";
import type { MentionHost } from "./mention";
import { createLinkedPage, type PageHost } from "./pagelinks";
import type { CollabProvider } from "./provider";
+import { suggestionAt, suggestionsOf, type Suggestion, type SuggestionAuthor } from "./suggest";
import type { SyncedPageHost } from "./syncedpage";
import type * as Y from "yjs";
@@ -53,6 +54,8 @@ const props = withDefaults(
ai?: AiHost;
/** Edits this fragment of a document instead (a note on the canvas), without carets. */
fragment?: { doc: Y.Doc; fragment: Y.XmlFragment };
+ /** Suggesting mode: edits become suggestions made by this person. */
+ suggesting?: SuggestionAuthor | null;
}>(),
{ editable: true },
);
@@ -97,20 +100,70 @@ const editor = useEditor({
onOpenDate: props.journals ? (date) => emit("navigate", `/journal/${date}`) : undefined,
labels: props.labels,
onCommentSelect: (id) => emit("comment-select", id),
+ onSuggestionSelect: (id, el) => pickSuggestion(id, el),
onError: (e) => emit("error", e),
}),
editorProps: { attributes: { class: "dw-prose" } },
onUpdate: ({ editor }) => emit("update", editor.getJSON()),
- onTransaction: ({ editor }) => {
+ onCreate: ({ editor }) => {
+ if (props.suggesting) editor.commands.setSuggesting(props.suggesting);
+ suggestions.value = suggestionsOf(editor.state.doc);
+ },
+ onTransaction: ({ editor, transaction }) => {
+ if (transaction.docChanged) {
+ suggestions.value = suggestionsOf(editor.state.doc);
+ if (picked.value && !suggestions.value.some((s) => s.id === picked.value!.s.id)) picked.value = null;
+ }
const f = findKey.getState(editor.state);
found.value = { current: f?.current ?? -1, total: f?.matches.length ?? 0 };
},
onBlur: () => emit("blur"),
onSelectionUpdate: ({ editor }) => {
if (editor.state.selection.empty) panel.value = null;
+ // The card stays while the caret is in its suggestion (clicking it moves the caret there).
+ if (picked.value && suggestionAt(editor.state, editor.state.selection.head) !== picked.value.s.id)
+ picked.value = null;
},
});
+// Suggesting mode: the open suggestions, and the one whose card is showing.
+const suggestions = ref([]);
+const picked = ref<{ s: Suggestion; top: number; left: number } | null>(null);
+const root = ref(null);
+watch(
+ () => props.suggesting,
+ (a) => editor.value?.commands.setSuggesting(a ?? null),
+);
+function pickSuggestion(id: string, el: HTMLElement) {
+ // After the click's own selection change, which closes any open card.
+ void nextTick(() => {
+ const s = suggestions.value.find((x) => x.id === id);
+ const host = root.value?.getBoundingClientRect();
+ if (!s || !host) return;
+ const r = el.getBoundingClientRect();
+ picked.value = {
+ s,
+ top: r.bottom - host.top + 6,
+ left: Math.max(0, Math.min(r.left - host.left, host.width - 288)),
+ };
+ });
+}
+function decide(accept: boolean, id?: string) {
+ const c = editor.value?.chain().focus();
+ if (!c) return;
+ if (id) (accept ? c.acceptSuggestion(id) : c.rejectSuggestion(id)).run();
+ else (accept ? c.acceptAllSuggestions() : c.rejectAllSuggestions()).run();
+ picked.value = null;
+}
+const suggestionCount = computed(() =>
+ suggestions.value.length === 1
+ ? labels.value.suggest.one
+ : labels.value.suggest.count.replace("{n}", String(suggestions.value.length)),
+);
+const when = (at: number) =>
+ at ? new Intl.DateTimeFormat(labels.value.locale, { dateStyle: "medium", timeStyle: "short" }).format(at) : "";
+const short = (text: string) => (text.length > 120 ? text.slice(0, 117) + "…" : text);
+
watch(
() => props.editable,
(v) => editor.value?.setEditable(v),
@@ -436,7 +489,64 @@ defineExpose({ editor, openFind });
-
editor?.destroy());
+
+function setup(content: string | JSONContent) {
+ editor = new Editor({ extensions: docwellExtensions({}), content });
+ return editor;
+}
+
+const row = (e: Editor): JSONContent | undefined => (e.getJSON().content ?? []).find((n) => n.type === "columns");
+const widths = (e: Editor) => (row(e)?.content ?? []).map((c: JSONContent) => c.attrs?.width ?? null);
+/** The position just inside the paragraph of column i of the first row. */
+function inColumn(e: Editor, i: number): number {
+ let at = -1;
+ let seen = -1;
+ e.state.doc.descendants((n, pos) => {
+ if (at >= 0) return false;
+ if (n.type.name === "column" && ++seen === i) at = pos + 2;
+ return true;
+ });
+ return at;
+}
+
+describe("columns", () => {
+ it("inserts two to four columns from the slash menu and puts the caret in the first", () => {
+ const e = setup("");
+ const cmd = filterCommands(slashCommands(englishLabels), "3 columns")[0];
+ expect(cmd?.id).toBe("columns3");
+ cmd!.run(e, { from: 1, to: 1 });
+ expect(row(e)?.content).toHaveLength(3);
+ expect(e.state.selection.$from.node(-1).type.name).toBe("column");
+ e.commands.insertContent("Left");
+ expect(row(e)?.content?.[0]?.content?.[0]?.content?.[0]?.text).toBe("Left");
+ });
+
+ it("reads columns and their widths back from HTML", () => {
+ const e = setup(
+ '
A
' +
+ '
B
',
+ );
+ expect(widths(e)).toEqual([70, 30]);
+ expect(e.getHTML()).toContain('data-width="70"');
+ });
+
+ it("adds a column with an equal share and shrinks the others", () => {
+ const e = setup(
+ '
A
B
',
+ );
+ e.commands.setTextSelection(inColumn(e, 0));
+ expect(e.commands.addColumn()).toBe(true);
+ const w = widths(e) as number[];
+ expect(w).toHaveLength(3);
+ expect(w.reduce((s, x) => s + x, 0)).toBeCloseTo(100, 0);
+ expect(w[1]).toBeCloseTo(100 / 3, 0);
+ // The new column sits after the one with the caret, and the caret moves into it.
+ expect(row(e)?.content?.[2]?.content?.[0]?.content?.[0]?.text).toBe("B");
+ });
+
+ it("stops at four columns", () => {
+ const e = setup("");
+ e.commands.insertColumns(4);
+ e.commands.setTextSelection(inColumn(e, 0));
+ expect(e.commands.addColumn()).toBe(false);
+ });
+
+ it("removes an empty column on Backspace, and unwraps the last two", () => {
+ const e = setup(
+ '
A
' +
+ '
C
',
+ );
+ e.commands.setTextSelection(inColumn(e, 1));
+ e.commands.keyboardShortcut("Backspace");
+ expect(row(e)?.content).toHaveLength(2);
+ // Two columns, one emptied: Backspace there leaves the other's blocks on the page.
+ const e2 = setup(
+ '
A
',
+ );
+ e2.commands.setTextSelection(inColumn(e2, 1));
+ e2.commands.keyboardShortcut("Backspace");
+ expect(row(e2)).toBeUndefined();
+ // (The editor keeps an empty paragraph at the end of every page.)
+ expect(e2.getText({ blockSeparator: "|" })).toBe("A|");
+ });
+
+ it("unsets columns into their blocks in order", () => {
+ const e = setup(
+ '
A
B
C
',
+ );
+ e.commands.setTextSelection(inColumn(e, 1));
+ e.commands.unsetColumns();
+ expect(e.getText({ blockSeparator: "|" })).toBe("A|B|C|");
+ });
+});
diff --git a/Packages/editor/src/columns.ts b/Packages/editor/src/columns.ts
new file mode 100644
index 0000000..e328958
--- /dev/null
+++ b/Packages/editor/src/columns.ts
@@ -0,0 +1,340 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { mergeAttributes, Node, type Editor } from "@tiptap/core";
+import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
+import { TextSelection } from "@tiptap/pm/state";
+import type { EditorLabels } from "./labels";
+
+declare module "@tiptap/core" {
+ interface Commands {
+ columns: {
+ /** Puts a row of empty columns where the selection is. */
+ insertColumns: (count?: number) => ReturnType;
+ /** Adds an empty column after the one holding the selection. */
+ addColumn: () => ReturnType;
+ /** Turns the columns around the selection back into blocks, one column after another. */
+ unsetColumns: () => ReturnType;
+ };
+ }
+}
+
+export const minColumns = 2;
+export const maxColumns = 4;
+/** No column gets narrower than this share of the row (percent). */
+const minWidth = 10;
+
+/** A column's width in percent, or null for an equal share. */
+function cleanWidth(v: unknown): number | null {
+ const n = typeof v === "string" ? parseFloat(v) : typeof v === "number" ? v : NaN;
+ return Number.isFinite(n) && n > 0 && n <= 100 ? Math.round(n * 10) / 10 : null;
+}
+
+/** The widths of a row's columns in percent, equal shares filled in, adding up to 100. */
+export function columnWidths(row: PMNode): number[] {
+ const set = [] as (number | null)[];
+ row.forEach((c) => set.push(cleanWidth(c.attrs.width)));
+ const known = set.reduce((s, w) => s + (w ?? 0), 0);
+ const unknown = set.filter((w) => w === null).length;
+ const share = unknown ? Math.max(100 - known, unknown * minWidth) / unknown : 0;
+ const widths = set.map((w) => w ?? share);
+ const total = widths.reduce((s, w) => s + w, 0) || 1;
+ return widths.map((w) => (w * 100) / total);
+}
+
+/** The depth of the nearest row of columns around the selection, or -1. */
+function rowDepth(editor: Editor): number {
+ const { $from } = editor.state.selection;
+ for (let d = $from.depth; d > 0; d--) if ($from.node(d).type.name === "columns") return d;
+ return -1;
+}
+
+/** A column holding one empty paragraph. */
+function emptyColumn(editor: Editor, width: number | null = null): PMNode {
+ const { schema } = editor.state;
+ return schema.nodes.column!.create({ width }, schema.nodes.paragraph!.create());
+}
+
+/** Whether a column holds nothing but one empty paragraph. */
+function isEmptyColumn(col: PMNode): boolean {
+ return col.childCount === 1 && col.firstChild!.type.name === "paragraph" && col.firstChild!.content.size === 0;
+}
+
+/**
+ * Side-by-side columns: a row ("columns") of two to four columns, each
+ * holding ordinary blocks. Columns share the width equally until someone
+ * drags the line between two of them. On narrow screens they stack.
+ * Backspace in an empty column removes it, and a row left with one column
+ * turns back into plain blocks.
+ */
+export const Columns = Node.create<{ labels: EditorLabels | null }>({
+ name: "columns",
+ group: "block",
+ content: `column{${minColumns},${maxColumns}}`,
+ defining: true,
+ isolating: true,
+ draggable: true,
+
+ addOptions() {
+ return { labels: null };
+ },
+
+ parseHTML() {
+ return [{ tag: "div[data-type=columns]" }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "columns", class: "dw-columns" }), 0];
+ },
+
+ addCommands() {
+ return {
+ insertColumns:
+ (count = 2) =>
+ ({ editor, tr, dispatch }) => {
+ const n = Math.min(Math.max(Math.round(count), minColumns), maxColumns);
+ const row = editor.schema.nodes.columns!.create(
+ null,
+ Array.from({ length: n }, () => emptyColumn(editor)),
+ );
+ if (!dispatch) return true;
+ const from = tr.selection.from;
+ tr.replaceSelectionWith(row);
+ // The caret goes into the first column; the row starts at or just after from.
+ let start = -1;
+ tr.doc.nodesBetween(from, Math.min(from + row.nodeSize + 2, tr.doc.content.size), (node, pos) => {
+ if (start < 0 && node.type.name === "columns") start = pos;
+ return start < 0;
+ });
+ if (start >= 0) tr.setSelection(TextSelection.create(tr.doc, start + 3));
+ tr.scrollIntoView();
+ return true;
+ },
+ addColumn:
+ () =>
+ ({ editor, tr, dispatch }) => {
+ const d = rowDepth(editor);
+ if (d < 0) return false;
+ const { $from } = tr.selection;
+ const row = $from.node(d);
+ if (row.childCount >= maxColumns) return false;
+ if (!dispatch) return true;
+ const index = $from.index(d);
+ const rowPos = $from.before(d);
+ // The new column is an equal share; the others shrink to make room.
+ const widths = columnWidths(row);
+ const share = 100 / (row.childCount + 1);
+ const scale = (100 - share) / 100;
+ let pos = rowPos + 1;
+ row.forEach((col, _o, i) => {
+ tr.setNodeMarkup(tr.mapping.map(pos), undefined, { ...col.attrs, width: widths[i]! * scale });
+ pos += col.nodeSize;
+ });
+ let at = rowPos + 1;
+ for (let i = 0; i <= index; i++) at += row.child(i).nodeSize;
+ const mapped = tr.mapping.map(at);
+ tr.insert(mapped, emptyColumn(editor, share));
+ tr.setSelection(TextSelection.create(tr.doc, mapped + 2));
+ return true;
+ },
+ unsetColumns:
+ () =>
+ ({ editor, tr, dispatch }) => {
+ const d = rowDepth(editor);
+ if (d < 0) return false;
+ if (!dispatch) return true;
+ const { $from } = tr.selection;
+ const row = $from.node(d);
+ const blocks: PMNode[] = [];
+ row.forEach((col) => {
+ if (!isEmptyColumn(col)) col.forEach((b) => blocks.push(b));
+ });
+ if (!blocks.length) blocks.push(editor.schema.nodes.paragraph!.create());
+ const start = $from.before(d);
+ tr.replaceWith(start, start + row.nodeSize, Fragment.from(blocks));
+ tr.setSelection(TextSelection.near(tr.doc.resolve(start + 1)));
+ return true;
+ },
+ };
+ },
+
+ addKeyboardShortcuts() {
+ return {
+ // Backspace in an empty column removes it; one column left becomes plain blocks.
+ Backspace: ({ editor }) => {
+ const { $from, empty } = editor.state.selection;
+ if (!empty || $from.parentOffset > 0) return false;
+ const d = rowDepth(editor);
+ if (d < 0 || $from.depth !== d + 2) return false;
+ const row = $from.node(d);
+ const col = $from.node(d + 1);
+ if (!isEmptyColumn(col)) return false;
+ if (row.childCount <= minColumns) return editor.commands.unsetColumns();
+ const index = $from.index(d);
+ const colPos = $from.before(d + 1);
+ const tr = editor.state.tr.delete(colPos, colPos + col.nodeSize);
+ // The others share the freed width; the caret goes to the end of the column before.
+ const rowPos = $from.before(d);
+ const left = tr.doc.nodeAt(rowPos)!;
+ const widths = columnWidths(left);
+ let pos = rowPos + 1;
+ left.forEach((c, _o, i) => {
+ tr.setNodeMarkup(pos, undefined, { ...c.attrs, width: widths[i] });
+ pos += c.nodeSize;
+ });
+ const target = Math.max(index - 1, 0);
+ let end = rowPos + 1;
+ for (let i = 0; i <= target; i++) end += tr.doc.nodeAt(rowPos)!.child(i).nodeSize;
+ tr.setSelection(TextSelection.near(tr.doc.resolve(end - 1), -1));
+ editor.view.dispatch(tr.scrollIntoView());
+ return true;
+ },
+ "Mod-Alt-ArrowRight": ({ editor }) => editor.commands.addColumn(),
+ };
+ },
+});
+
+/** One column of a row; its width is a share of the row in percent. */
+export const Column = Node.create<{ labels: EditorLabels | null }>({
+ name: "column",
+ content: "block+",
+ isolating: true,
+
+ addOptions() {
+ return { labels: null };
+ },
+
+ addAttributes() {
+ return {
+ width: {
+ default: null,
+ parseHTML: (el) => cleanWidth(el.getAttribute("data-width")),
+ renderHTML: (attrs) => (attrs.width == null ? {} : { "data-width": String(cleanWidth(attrs.width)) }),
+ },
+ };
+ },
+
+ parseHTML() {
+ return [{ tag: "div[data-type=column]" }];
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "column", class: "dw-column" }), 0];
+ },
+
+ addNodeView() {
+ return ({ node, getPos, editor }) => {
+ const labels = this.options.labels;
+ const dom = document.createElement("div");
+ dom.className = "dw-column";
+ dom.setAttribute("data-type", "column");
+ const content = document.createElement("div");
+ content.className = "dw-column__body";
+ // The line on the right edge, dragged to share width with the next column.
+ const handle = document.createElement("div");
+ handle.className = "dw-column__resize";
+ handle.contentEditable = "false";
+ handle.setAttribute("role", "separator");
+ handle.setAttribute("aria-orientation", "vertical");
+ // The button that adds a column after this one.
+ const add = document.createElement("button");
+ add.type = "button";
+ add.className = "dw-column__add";
+ add.contentEditable = "false";
+ add.textContent = "+";
+ dom.append(content, handle, add);
+
+ const place = () => {
+ const pos = getPos();
+ if (typeof pos !== "number") return null;
+ const $pos = editor.state.doc.resolve(pos);
+ const row = $pos.parent;
+ if (row.type.name !== "columns") return null;
+ return { row, index: $pos.index(), rowPos: $pos.before() };
+ };
+ const draw = () => {
+ const p = place();
+ const widths = p ? columnWidths(p.row) : [100];
+ const w = p ? widths[p.index]! : 100;
+ dom.style.flexGrow = String(w);
+ const last = !p || p.index === p.row.childCount - 1;
+ handle.hidden = last;
+ add.hidden = !p || p.row.childCount >= maxColumns;
+ const resize = labels?.blocks.resizeColumn ?? "Drag to resize";
+ handle.title = resize;
+ handle.setAttribute("aria-label", resize);
+ const addLabel = labels?.blocks.addColumn ?? "Add a column";
+ add.title = addLabel;
+ add.setAttribute("aria-label", addLabel);
+ };
+ draw();
+
+ add.addEventListener("mousedown", (e) => e.preventDefault());
+ add.addEventListener("click", () => {
+ const pos = getPos();
+ if (typeof pos !== "number" || !editor.isEditable) return;
+ editor
+ .chain()
+ .setTextSelection(pos + 2)
+ .addColumn()
+ .focus()
+ .run();
+ });
+
+ handle.addEventListener("pointerdown", (e) => {
+ const p = place();
+ if (!p || !editor.isEditable || p.index >= p.row.childCount - 1) return;
+ e.preventDefault();
+ const rowEl = dom.parentElement;
+ const next = dom.nextElementSibling as HTMLElement | null;
+ if (!rowEl || !next) return;
+ const total = rowEl.getBoundingClientRect().width || 1;
+ const widths = columnWidths(p.row);
+ const pair = widths[p.index]! + widths[p.index + 1]!;
+ const startX = e.clientX;
+ const startW = widths[p.index]!;
+ let w = startW;
+ handle.setPointerCapture(e.pointerId);
+ dom.classList.add("is-resizing");
+ const move = (ev: PointerEvent) => {
+ w = Math.min(Math.max(startW + ((ev.clientX - startX) * 100) / total, minWidth), pair - minWidth);
+ dom.style.flexGrow = String(w);
+ next.style.flexGrow = String(pair - w);
+ };
+ const up = () => {
+ handle.removeEventListener("pointermove", move);
+ handle.removeEventListener("pointerup", up);
+ handle.removeEventListener("pointercancel", up);
+ dom.classList.remove("is-resizing");
+ const now = place();
+ if (!now || Math.abs(w - startW) < 0.5) return draw();
+ const all = columnWidths(now.row);
+ all[now.index] = w;
+ all[now.index + 1] = pair - w;
+ const tr = editor.state.tr;
+ let pos = now.rowPos + 1;
+ now.row.forEach((col, _o, i) => {
+ tr.setNodeMarkup(pos, undefined, { ...col.attrs, width: Math.round(all[i]! * 10) / 10 });
+ pos += col.nodeSize;
+ });
+ editor.view.dispatch(tr);
+ };
+ handle.addEventListener("pointermove", move);
+ handle.addEventListener("pointerup", up);
+ handle.addEventListener("pointercancel", up);
+ });
+
+ return {
+ dom,
+ contentDOM: content,
+ update: (n) => {
+ if (n.type !== node.type) return false;
+ draw();
+ return true;
+ },
+ stopEvent: (e) => handle.contains(e.target as globalThis.Node) || add.contains(e.target as globalThis.Node),
+ ignoreMutation: (m) =>
+ handle.contains(m.target) || add.contains(m.target) || (m.type === "attributes" && m.target === dom),
+ };
+ };
+ },
+});
diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css
index d98a398..bd3230e 100644
--- a/Packages/editor/src/editor.css
+++ b/Packages/editor/src/editor.css
@@ -2324,3 +2324,116 @@
grid-template-columns: 8rem minmax(0, 1fr);
}
}
+
+/* ---- Columns (columns.ts): blocks side by side, stacked on phones ---- */
+.dw-prose .dw-columns {
+ display: flex;
+ gap: 24px;
+ margin: 8px 0;
+}
+.dw-prose .dw-column {
+ position: relative;
+ flex: 1 1 0;
+ min-width: 0;
+}
+.dw-column__body > :first-child {
+ margin-top: 0;
+}
+.dw-column__body > :last-child {
+ margin-bottom: 0;
+}
+/* The line between two columns, in the middle of the gap. */
+.dw-column__resize {
+ position: absolute;
+ top: 0;
+ right: -14px;
+ bottom: 0;
+ width: 8px;
+ cursor: col-resize;
+ touch-action: none;
+ user-select: none;
+}
+.dw-column__resize::after {
+ content: "";
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 3px;
+ width: 2px;
+ border-radius: 1px;
+ background: var(--color-line);
+ opacity: 0;
+ transition: opacity 0.12s;
+}
+.dw-columns:hover .dw-column__resize::after {
+ opacity: 0.6;
+}
+.dw-column__resize:hover::after,
+.dw-column.is-resizing .dw-column__resize::after {
+ opacity: 1;
+ background: var(--color-accent);
+}
+.dw-column__add {
+ position: absolute;
+ top: 0;
+ right: -22px;
+ width: 20px;
+ height: 20px;
+ display: none;
+ place-items: center;
+ border: none;
+ border-radius: var(--radius-sm);
+ background: none;
+ color: var(--color-ink-muted);
+ font-size: 16px;
+ line-height: 1;
+ cursor: pointer;
+}
+.dw-column:last-child:hover > .dw-column__add:not([hidden]),
+.dw-column:last-child:focus-within > .dw-column__add:not([hidden]) {
+ display: grid;
+}
+.dw-column__add:hover {
+ background: var(--color-surface-hover);
+}
+.dw-prose[contenteditable="false"] .dw-column__resize,
+.dw-prose[contenteditable="false"] .dw-column__add {
+ display: none;
+}
+@media (max-width: 640px) {
+ .dw-prose .dw-columns {
+ flex-direction: column;
+ gap: 8px;
+ }
+ .dw-prose .dw-column {
+ flex-grow: 1 !important;
+ }
+ .dw-column__resize,
+ .dw-column__add {
+ display: none !important;
+ }
+}
+
+/* ---- Suggestions (suggest.ts): insertions underlined, deletions struck ---- */
+.dw-suggest-ins {
+ color: var(--dw-suggest-ins, #0e7a5c);
+ text-decoration: underline 2px color-mix(in srgb, currentColor 55%, transparent);
+ text-underline-offset: 3px;
+ background: color-mix(in srgb, currentColor 8%, transparent);
+ cursor: pointer;
+}
+.dw-suggest-del {
+ color: var(--dw-suggest-del, #b42318);
+ text-decoration: line-through 1.5px;
+ background: color-mix(in srgb, currentColor 7%, transparent);
+ cursor: pointer;
+}
+.dw-suggest-ins.dw-suggest-del {
+ color: var(--dw-suggest-del, #b42318);
+}
+.dark .dw-suggest-ins {
+ --dw-suggest-ins: #5fd8b1;
+}
+.dark .dw-suggest-del {
+ --dw-suggest-del: #ff8a7a;
+}
diff --git a/Packages/editor/src/extensions.ts b/Packages/editor/src/extensions.ts
index 2ea2d16..593736b 100644
--- a/Packages/editor/src/extensions.ts
+++ b/Packages/editor/src/extensions.ts
@@ -8,6 +8,7 @@ import StarterKit from "@tiptap/starter-kit";
import { BlockLinks } from "./blocklinks";
import { docwellAlign, docwellTables, docwellTasks, HeadingShortcuts } from "./blocks";
import { Callout } from "./callout";
+import { Column, Columns } from "./columns";
import { Database } from "./database";
import { DB_ORIGIN } from "./database/store";
import { DocwellCodeBlock } from "./codeblock";
@@ -27,6 +28,7 @@ import { MermaidBlock, type MermaidLoader } from "./mermaid";
import { PageLinks, type PageHost } from "./pagelinks";
import type { PdfLoader } from "./pdf";
import { SlashMenu, slashCommands } from "./slash";
+import { Suggestions } from "./suggest";
import type { CollabProvider } from "./provider";
import { TableMove } from "./tablemove";
import { TableOfContents } from "./toc";
@@ -86,6 +88,8 @@ export interface ExtensionOptions {
labels?: EditorLabels;
/** Clicking highlighted comment text calls this with the comment id. */
onCommentSelect?: (id: string) => void;
+ /** Clicking suggested text calls this with the suggestion id and the clicked element. */
+ onSuggestionSelect?: (id: string, el: HTMLElement) => void;
onError?: (e: unknown) => void;
}
@@ -131,6 +135,8 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
...docwellTables(),
TableMove.configure({ labels }),
Callout.configure({ labels }),
+ Columns.configure({ labels }),
+ Column.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
DateMention.configure({ labels, me: () => opts.mentions?.me, onOpen: opts.onOpenDate }),
@@ -139,6 +145,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
labels,
}),
CommentHighlights.configure({ onSelect: opts.onCommentSelect }),
+ Suggestions.configure({ onSelect: opts.onSuggestionSelect }),
docwellMath(labels, () => editor),
MermaidBlock.configure({ labels, load: opts.loadMermaid }),
TableOfContents.configure({ labels }),
diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts
index e9e54bf..34ce080 100644
--- a/Packages/editor/src/index.ts
+++ b/Packages/editor/src/index.ts
@@ -13,6 +13,7 @@ export { CollabProvider, type CollabProviderOptions, type CollabStatus } from ".
export { linkedPage, pagePath, type PageHost, type PageRef as LinkablePage } from "./pagelinks";
export { headingsOf, type Heading } from "./toc";
export { findMatches, type FindMatch } from "./find";
+export { isSuggesting, suggestionsOf, type Suggestion, type SuggestionAuthor } from "./suggest";
export { blockHash, linkedBlock, scrollToBlock } from "./blocklinks";
export { linkedRecord, openRecord, recordHash } from "./database/links";
export { followLink, isTargetHash } from "./hashlinks";
diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts
index e86c565..78b0ea3 100644
--- a/Packages/editor/src/labels.ts
+++ b/Packages/editor/src/labels.ts
@@ -111,6 +111,9 @@ export interface EditorLabels {
copyBlockLink: string;
calloutEmoji: string;
calloutColor: string;
+ /** The line between two columns and the button that adds one. */
+ resizeColumn: string;
+ addColumn: string;
pdfLoading: string;
/** One page of a PDF shown inline; {n} is its number. */
pdfPage: string;
@@ -127,6 +130,19 @@ export interface EditorLabels {
syncedDenied: string;
syncedSelf: string;
};
+ /** Suggesting mode (suggest.ts): the bar above the page and the card on a suggestion. count has {n} in it. */
+ suggest: {
+ mode: string;
+ hint: string;
+ one: string;
+ count: string;
+ accept: string;
+ reject: string;
+ acceptAll: string;
+ rejectAll: string;
+ adds: string;
+ removes: string;
+ };
/** The find and replace bar. count has {current} and {total} in it. */
find: {
find: string;
@@ -198,6 +214,10 @@ export const englishLabels: EditorLabels = {
ordered: { label: "Numbered list", description: "A list with numbers" },
todo: { label: "To-do list", description: "Tasks to tick off (or type [])" },
callout: { label: "Callout", description: "Set a note apart with an emoji and colour" },
+ columns: { label: "Columns", description: "Put blocks side by side" },
+ columns2: { label: "2 columns", description: "Two blocks side by side" },
+ columns3: { label: "3 columns", description: "Three blocks side by side" },
+ columns4: { label: "4 columns", description: "Four blocks side by side" },
table: { label: "Table", description: "Rows and columns" },
quote: { label: "Quote", description: "Set text apart as a quote" },
code: { label: "Code block", description: "Monospaced code" },
@@ -320,6 +340,8 @@ export const englishLabels: EditorLabels = {
copyBlockLink: "Copy link to this block",
calloutEmoji: "Change emoji",
calloutColor: "Change colour",
+ resizeColumn: "Drag to resize the columns",
+ addColumn: "Add a column",
pdfLoading: "Loading PDF…",
pdfPage: "Page {n}",
transcribe: "Transcribe",
@@ -327,6 +349,18 @@ export const englishLabels: EditorLabels = {
transcribing: "Transcribing…",
transcribeFailed: "The recording could not be transcribed.",
},
+ suggest: {
+ mode: "Suggesting",
+ hint: "Your edits show as suggestions until someone accepts them",
+ one: "1 suggestion",
+ count: "{n} suggestions",
+ accept: "Accept",
+ reject: "Reject",
+ acceptAll: "Accept all",
+ rejectAll: "Reject all",
+ adds: "Adds",
+ removes: "Removes",
+ },
find: {
find: "Find in page",
replace: "Replace with",
diff --git a/Packages/editor/src/slash.ts b/Packages/editor/src/slash.ts
index f7d74bf..d7a0d98 100644
--- a/Packages/editor/src/slash.ts
+++ b/Packages/editor/src/slash.ts
@@ -87,6 +87,14 @@ export function slashCommands(
block("callout", "callout", ["note", "info", "tip", "warning", "aside", "box"], (e, r) =>
e.chain().focus().deleteRange(r).setCallout().run(),
),
+ {
+ ...block("columns", "columns", ["layout", "side by side", "split", "grid", "multi-column"], () => {}),
+ children: ([2, 3, 4] as const).map((n) =>
+ block(`columns${n}`, "columns", ["columns", "layout", "side by side", String(n)], (e, r) =>
+ e.chain().focus().deleteRange(r).insertColumns(n).run(),
+ ),
+ ),
+ },
block("table", "table", ["grid", "rows", "columns", "spreadsheet"], (e, r) =>
e.chain().focus().deleteRange(r).insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
),
diff --git a/Packages/editor/src/suggest.test.ts b/Packages/editor/src/suggest.test.ts
new file mode 100644
index 0000000..7848306
--- /dev/null
+++ b/Packages/editor/src/suggest.test.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { Editor } from "@tiptap/core";
+import { afterEach, describe, expect, it } from "vitest";
+import { docwellExtensions } from "./extensions";
+import { suggestionsOf } from "./suggest";
+
+let editor: Editor | undefined;
+afterEach(() => editor?.destroy());
+
+const ana = { id: "ana", name: "Ana" };
+const ben = { id: "ben", name: "Ben" };
+
+function setup(html: string) {
+ editor = new Editor({ extensions: docwellExtensions({}), content: html });
+ return editor;
+}
+
+/** The first paragraph's text with suggestions shown as [+ins] and [-del]. */
+function shown(e: Editor): string {
+ let out = "";
+ e.state.doc.firstChild!.forEach((n) => {
+ const t = n.text ?? "";
+ const ins = n.marks.some((m) => m.type.name === "suggestInsert");
+ const del = n.marks.some((m) => m.type.name === "suggestDelete");
+ out += ins && del ? `[+-${t}]` : ins ? `[+${t}]` : del ? `[-${t}]` : t;
+ });
+ return out;
+}
+
+/** Types like the keyboard: one transaction per call, at the caret. */
+const type = (e: Editor, text: string) => e.view.dispatch(e.state.tr.insertText(text));
+const backspace = (e: Editor) => {
+ const { from } = e.state.selection;
+ e.view.dispatch(e.state.tr.delete(from - 1, from));
+};
+
+describe("suggesting mode", () => {
+ it("marks typed text as a suggestion and keeps adjacent typing in one", () => {
+ const e = setup("
");
+ e.commands.setSuggesting(ana);
+ e.commands.setTextSelection({ from: 7, to: 12 });
+ e.view.dispatch(e.state.tr.insertText("there"));
+ const [s] = suggestionsOf(e.state.doc);
+ // Same id for the deletion and the insertion of one replacement? Two suggestions are fine too.
+ const all = suggestionsOf(e.state.doc);
+ expect(all.map((x) => x.deleted + "|" + x.inserted).join(",")).toContain("world");
+ e.commands.setSuggesting(null);
+ expect(e.commands.acceptAllSuggestions()).toBe(true);
+ expect(shown(e)).toBe("Hello there");
+ expect(s).toBeDefined();
+
+ const f = setup("
Hello world
");
+ f.commands.setSuggesting(ana);
+ f.commands.setTextSelection({ from: 7, to: 12 });
+ f.view.dispatch(f.state.tr.insertText("there"));
+ f.commands.rejectAllSuggestions();
+ expect(shown(f)).toBe("Hello world");
+ });
+
+ it("accepts one suggestion by id and leaves the others", () => {
+ const e = setup("
");
+ type(e, "x");
+ expect(shown(e)).toBe("xHi");
+ e.commands.setSuggesting(ana);
+ // Backspace at the start of the second paragraph joins them: structure is not tracked.
+ e.commands.setTextSelection(6);
+ e.commands.joinBackward();
+ expect(e.state.doc.firstChild!.textContent).toBe("xHithere");
+ });
+
+ it("reads suggestions back from HTML", () => {
+ const e = setup(
+ '
abc
',
+ );
+ expect(shown(e)).toBe("a[+b][-c]");
+ expect(suggestionsOf(e.state.doc).map((s) => s.id)).toEqual(["s1", "s2"]);
+ expect(e.getHTML()).toContain(' {
+ suggestions: {
+ /** Turns suggesting mode on (as this person) or off. */
+ setSuggesting: (author: SuggestionAuthor | null) => ReturnType;
+ /** Keeps a suggestion: an insertion becomes plain text, a deletion's text goes. */
+ acceptSuggestion: (id: string) => ReturnType;
+ /** Drops a suggestion: an insertion's text goes, a deletion's text stays as it was. */
+ rejectSuggestion: (id: string) => ReturnType;
+ acceptAllSuggestions: () => ReturnType;
+ rejectAllSuggestions: () => ReturnType;
+ };
+ }
+}
+
+export interface SuggestionAuthor {
+ /** The user's id, which decides whose suggestions deleting really deletes. */
+ id: string;
+ name: string;
+}
+
+/** One suggestion: the text it inserts and the text it deletes. */
+export interface Suggestion {
+ id: string;
+ author: string;
+ name: string;
+ /** When it was made, in milliseconds since 1970. */
+ at: number;
+ inserted: string;
+ deleted: string;
+ /** Where it starts in the document. */
+ from: number;
+}
+
+const INSERT = "suggestInsert";
+const DELETE = "suggestDelete";
+/** Transactions with this meta are not turned into suggestions (accepting, rejecting, the mode itself). */
+const SKIP = "suggestionSkip";
+
+export const suggestKey = new PluginKey<{ author: SuggestionAuthor | null }>("suggestions");
+
+/** Whether suggesting mode is on in this editor. */
+export function isSuggesting(state: EditorState): boolean {
+ return !!suggestKey.getState(state)?.author;
+}
+
+const newId = () => Math.random().toString(36).slice(2, 10);
+
+function suggestionMark(name: string, tag: "ins" | "del") {
+ return Mark.create({
+ name,
+ inclusive: false,
+ excludes: "",
+ // Above underline and strikethrough, which also read and .
+ priority: 1100,
+
+ addAttributes() {
+ return {
+ id: { default: "", parseHTML: (el) => el.getAttribute("data-suggestion") ?? "" },
+ author: { default: "", parseHTML: (el) => el.getAttribute("data-author") ?? "" },
+ name: { default: "", parseHTML: (el) => el.getAttribute("data-name") ?? "" },
+ at: { default: 0, parseHTML: (el) => Number(el.getAttribute("data-at")) || 0 },
+ };
+ },
+
+ parseHTML() {
+ return [{ tag: `${tag}[data-suggestion]` }];
+ },
+
+ renderHTML({ mark, HTMLAttributes }) {
+ const a = mark.attrs as { id: string; author: string; name: string; at: number };
+ return [
+ tag,
+ mergeAttributes(
+ { class: tag === "ins" ? "dw-suggest-ins" : "dw-suggest-del" },
+ {
+ "data-suggestion": a.id,
+ "data-author": a.author,
+ "data-name": a.name,
+ "data-at": String(a.at),
+ title: a.name,
+ },
+ // The attributes above come from the mark itself.
+ Object.fromEntries(Object.entries(HTMLAttributes).filter(([k]) => k === "class" || k === "style")),
+ ),
+ 0,
+ ];
+ },
+ });
+}
+
+export const SuggestInsert = suggestionMark(INSERT, "ins");
+export const SuggestDelete = suggestionMark(DELETE, "del");
+
+/** The suggestion mark of this type on a node, if any. */
+const markOf = (node: PMNode, type: MarkType): PMMark | undefined => node.marks.find((m) => m.type === type);
+
+/** Each suggestion's ranges: [from, to, insert?] in document order. */
+function ranges(doc: PMNode, only?: string): Map {
+ const out = new Map();
+ doc.descendants((node, pos) => {
+ if (!node.isInline) return true;
+ for (const m of node.marks) {
+ if (m.type.name !== INSERT && m.type.name !== DELETE) continue;
+ const id = String(m.attrs.id);
+ if (only && id !== only) continue;
+ const list = out.get(id) ?? [];
+ const insert = m.type.name === INSERT;
+ const last = list[list.length - 1];
+ if (last && last.to === pos && last.insert === insert) last.to = pos + node.nodeSize;
+ else list.push({ from: pos, to: pos + node.nodeSize, insert });
+ out.set(id, list);
+ }
+ return false;
+ });
+ return out;
+}
+
+/** The page's open suggestions, in document order. */
+export function suggestionsOf(doc: PMNode): Suggestion[] {
+ const byId = new Map();
+ doc.descendants((node, pos) => {
+ if (!node.isInline) return true;
+ for (const m of node.marks) {
+ if (m.type.name !== INSERT && m.type.name !== DELETE) continue;
+ const id = String(m.attrs.id);
+ let s = byId.get(id);
+ if (!s) {
+ s = {
+ id,
+ author: String(m.attrs.author),
+ name: String(m.attrs.name),
+ at: Number(m.attrs.at) || 0,
+ inserted: "",
+ deleted: "",
+ from: pos,
+ };
+ byId.set(id, s);
+ }
+ const text = node.isText ? (node.text ?? "") : " ";
+ if (m.type.name === INSERT) s.inserted += text;
+ else s.deleted += text;
+ }
+ return false;
+ });
+ return [...byId.values()];
+}
+
+/** The suggestion id at a position, from the marks on either side. */
+export function suggestionAt(state: EditorState, pos: number): string | null {
+ const $pos = state.doc.resolve(pos);
+ for (const node of [$pos.nodeAfter, $pos.nodeBefore]) {
+ const m = node?.marks.find((x) => x.type.name === INSERT || x.type.name === DELETE);
+ if (m) return String(m.attrs.id);
+ }
+ return null;
+}
+
+/** Applies a choice to one suggestion (or every one): keep or drop its insertions and deletions. */
+function decide(tr: Transaction, accept: boolean, only?: string): boolean {
+ const all = ranges(tr.doc, only);
+ if (!all.size) return false;
+ const schema = tr.doc.type.schema;
+ const removals: { from: number; to: number }[] = [];
+ for (const list of all.values()) {
+ for (const r of list) {
+ const type = schema.marks[r.insert ? INSERT : DELETE]!;
+ // Accepting keeps insertions and drops deleted text; rejecting the opposite.
+ if (r.insert === accept) tr.removeMark(r.from, r.to, type);
+ else removals.push(r);
+ }
+ }
+ removals.sort((a, b) => b.from - a.from);
+ for (const r of removals) tr.delete(r.from, r.to);
+ tr.setMeta(SKIP, true);
+ return true;
+}
+
+/** Whether a fragment holds any text or other inline content. */
+function hasInline(f: Fragment): boolean {
+ let found = false;
+ f.descendants((n) => {
+ if (n.isInline) found = true;
+ return !found;
+ });
+ return found;
+}
+
+/**
+ * The deleted content as it goes back in: inline nodes get the deletion
+ * mark (keeping one they had), and the author's own suggested insertions
+ * are left out, since deleting them deletes them.
+ */
+function markDeleted(
+ f: Fragment,
+ type: MarkType,
+ insert: MarkType,
+ attrs: Record,
+ me: string,
+): Fragment {
+ const out: PMNode[] = [];
+ f.forEach((node) => {
+ if (node.isInline) {
+ const ins = markOf(node, insert);
+ if (ins && ins.attrs.author === me) return;
+ // Someone else's suggested insertion, deleted: their suggestion stays, now also marked deleted.
+ out.push(markOf(node, type) ? node : node.mark(type.create(attrs).addToSet(node.marks)));
+ return;
+ }
+ out.push(node.copy(markDeleted(node.content, type, insert, attrs, me)));
+ });
+ return Fragment.from(out);
+}
+
+/** The attributes to reuse: the author's suggestion of this kind right before or after pos, so it grows. */
+function neighbour(doc: PMNode, pos: number, type: MarkType, author: string): Record | null {
+ const $pos = doc.resolve(Math.min(Math.max(pos, 0), doc.content.size));
+ for (const node of [$pos.nodeBefore, $pos.nodeAfter]) {
+ const m = node && markOf(node, type);
+ if (m && m.attrs.author === author) return m.attrs;
+ }
+ return null;
+}
+
+/**
+ * Turns one transaction's edits into suggestions: deleted text comes back
+ * marked deleted, inserted text gets marked inserted. Returns null when
+ * there is nothing to track.
+ */
+function track(
+ tr: Transaction,
+ oldState: EditorState,
+ newState: EditorState,
+ author: SuggestionAuthor,
+): Transaction | null {
+ if (!tr.steps.length || !tr.steps.every((s) => s instanceof ReplaceStep)) return null;
+ const schema = newState.schema;
+ const insType = schema.marks[INSERT]!;
+ const delType = schema.marks[DELETE]!;
+ const fix = newState.tr;
+ const at = Date.now();
+ let caret: number | null = null;
+ const single = tr.steps.length === 1;
+
+ tr.steps.forEach((s, i) => {
+ const step = s as ReplaceStep & { from: number; to: number; slice: Slice };
+ const before = tr.docs[i]!;
+ const deleted = before.slice(step.from, step.to);
+ // Where the step's start ended up: through the later steps, then through our fixes.
+ const startInNew = fix.mapping.map(tr.mapping.slice(i + 1).map(step.from, -1), -1);
+ const insSize = step.slice.size;
+
+ // 1. Mark what was inserted (inline content only).
+ if (insSize > 0 && hasInline(step.slice.content)) {
+ const end = startInNew + insSize;
+ const attrs = neighbour(fix.doc, startInNew, insType, author.id) ??
+ neighbour(fix.doc, end, insType, author.id) ?? { id: newId(), author: author.id, name: author.name, at };
+ fix.doc.nodesBetween(startInNew, end, (node, pos) => {
+ if (!node.isInline) return true;
+ const from = Math.max(pos, startInNew);
+ const to = Math.min(pos + node.nodeSize, end);
+ // Text that was a deletion (pasted back from a struck range) is fresh text now.
+ if (markOf(node, delType)) fix.removeMark(from, to, delType);
+ fix.addMark(from, to, insType.create(attrs));
+ return false;
+ });
+ }
+
+ // 2. Put deleted text back, marked deleted. Joins of empty structure stay joined.
+ let back = 0;
+ if (deleted.size > 0 && hasInline(deleted.content)) {
+ // A deletion next to the author's own (Backspace held down) grows it.
+ const attrs = neighbour(fix.doc, startInNew, delType, author.id) ??
+ neighbour(fix.doc, startInNew + 1, delType, author.id) ?? {
+ id: newId(),
+ author: author.id,
+ name: author.name,
+ at,
+ };
+ const content = markDeleted(deleted.content, delType, insType, attrs, author.id);
+ if (hasInline(content)) {
+ const slice = new Slice(content, deleted.openStart, deleted.openEnd);
+ const sizeBefore = fix.doc.content.size;
+ fix.replace(startInNew, startInNew, slice);
+ back = fix.doc.content.size - sizeBefore;
+ }
+ }
+
+ if (single) {
+ const sel = oldState.selection;
+ if (insSize > 0) caret = startInNew + back + insSize;
+ // Backspace: the caret goes before the struck text, so the next one strikes further left.
+ else if (sel.empty && sel.head === step.to) caret = startInNew;
+ else caret = startInNew + back;
+ }
+ });
+
+ if (!fix.docChanged) return null;
+ if (caret !== null) {
+ const pos = Math.min(Math.max(caret, 0), fix.doc.content.size);
+ fix.setSelection(TextSelection.near(fix.doc.resolve(pos), insSizeDir(tr)));
+ }
+ fix.setMeta(SKIP, true);
+ return fix;
+}
+
+/** Search direction for the caret: backwards after a deletion, forwards after typing. */
+function insSizeDir(tr: Transaction): -1 | 1 {
+ const s = tr.steps[0] as ReplaceStep & { slice: Slice };
+ return s.slice.size > 0 ? 1 : -1;
+}
+
+export const Suggestions = Extension.create<{ onSelect?: (id: string, el: HTMLElement) => void }>({
+ name: "suggestions",
+
+ addOptions() {
+ return { onSelect: undefined };
+ },
+
+ addExtensions() {
+ return [SuggestInsert, SuggestDelete];
+ },
+
+ addCommands() {
+ return {
+ setSuggesting:
+ (author) =>
+ ({ tr, dispatch }) => {
+ if (dispatch) tr.setMeta(suggestKey, { author }).setMeta(SKIP, true).setMeta("addToHistory", false);
+ return true;
+ },
+ acceptSuggestion:
+ (id) =>
+ ({ tr }) =>
+ decide(tr, true, id),
+ rejectSuggestion:
+ (id) =>
+ ({ tr }) =>
+ decide(tr, false, id),
+ acceptAllSuggestions:
+ () =>
+ ({ tr }) =>
+ decide(tr, true),
+ rejectAllSuggestions:
+ () =>
+ ({ tr }) =>
+ decide(tr, false),
+ };
+ },
+
+ addProseMirrorPlugins() {
+ const onSelect = () => this.options.onSelect;
+ return [
+ new Plugin<{ author: SuggestionAuthor | null }>({
+ key: suggestKey,
+ state: {
+ init: () => ({ author: null }),
+ apply: (tr, value) => (tr.getMeta(suggestKey) as { author: SuggestionAuthor | null } | undefined) ?? value,
+ },
+ appendTransaction(trs, oldState, newState) {
+ const author = suggestKey.getState(newState)?.author;
+ if (!author) return null;
+ // One user edit at a time; remote changes, undo and our own fixes pass as they are.
+ if (trs.length !== 1) return null;
+ const tr = trs[0]!;
+ if (!tr.docChanged || tr.getMeta(SKIP)) return null;
+ if ((tr.getMeta(ySyncPluginKey) as { isChangeOrigin?: boolean } | undefined)?.isChangeOrigin) return null;
+ if (tr.getMeta("history$") || tr.getMeta("isUndoRedo")) return null;
+ return track(tr, oldState, newState, author);
+ },
+ props: {
+ attributes: (state): Record =>
+ suggestKey.getState(state)?.author ? { "data-suggesting": "true" } : {},
+ handleClick(_view, _pos, event) {
+ const el = (event.target as HTMLElement | null)?.closest?.("[data-suggestion]");
+ const id = el?.getAttribute("data-suggestion");
+ if (!el || !id) return false;
+ onSelect()?.(id, el);
+ return false;
+ },
+ },
+ }),
+ ];
+ },
+});
+
+/** Turns suggesting on or off from outside the editor. */
+export function setSuggesting(editor: Editor, author: SuggestionAuthor | null): void {
+ editor.commands.setSuggesting(author);
+}
diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts
index 75d6618..d2b4409 100644
--- a/Packages/ui/src/icons.ts
+++ b/Packages/ui/src/icons.ts
@@ -112,6 +112,7 @@ export const iconPaths = {
"arrow-up": ["M12 19V5", "M6 11l6-6 6 6"],
"arrow-down": ["M12 5v14", "M6 13l6 6 6-6"],
callout: ["M4 5h16v14H4z", "M8 10h.01", "M11 10h5", "M8 14h8"],
+ columns: ["M4 5h6v14H4z", "M14 5h6v14h-6z"],
palette: [
"M12 3a9 9 0 1 0 0 18c1 0 1.5-.7 1.5-1.5 0-1.2-1-1.5-1-2.5s.8-1.5 2-1.5H17a4 4 0 0 0 4-4c0-4.7-4-8.5-9-8.5z",
"M7.5 11h.01",
diff --git a/Phone-App/lib/api/docwell_api.dart b/Phone-App/lib/api/docwell_api.dart
index ca8da29..a044de4 100644
--- a/Phone-App/lib/api/docwell_api.dart
+++ b/Phone-App/lib/api/docwell_api.dart
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import '../l10n.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -278,6 +279,8 @@ class DocwellApi {
req.headers['Accept'] = 'application/json';
req.headers['Content-Type'] = 'application/json';
if (token != null) req.headers['Authorization'] = 'Bearer $token';
+ // The server writes its messages in the language the app shows.
+ req.headers['Accept-Language'] = appLanguage;
req.body = jsonEncode({'summarize': true});
final res = await http.Response.fromStream(
await _client.send(req).timeout(const Duration(minutes: 30)),
@@ -304,6 +307,8 @@ class DocwellApi {
req.headers['Accept'] = 'text/event-stream';
req.headers['Content-Type'] = 'application/json';
if (token != null) req.headers['Authorization'] = 'Bearer $token';
+ // The server writes its messages in the language the app shows.
+ req.headers['Accept-Language'] = appLanguage;
req.body = jsonEncode(body);
final res = await _client.send(req).timeout(const Duration(seconds: 30));
if (res.statusCode >= 300) {
@@ -354,6 +359,8 @@ class DocwellApi {
final req = http.Request(method, Uri.parse('$baseUrl$path'));
req.headers['Accept'] = 'application/json';
if (token != null) req.headers['Authorization'] = 'Bearer $token';
+ // The server writes its messages in the language the app shows.
+ req.headers['Accept-Language'] = appLanguage;
if (body != null) {
req.headers['Content-Type'] = 'application/json';
req.body = jsonEncode(body);
diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart
index fbe6991..8e8722e 100644
--- a/Phone-App/lib/api/generated/models.dart
+++ b/Phone-App/lib/api/generated/models.dart
@@ -702,6 +702,7 @@ class Page {
required this.journalDate,
required this.createdBy,
required this.lastEditedBy,
+ required this.verification,
});
factory Page.fromJson(Map json) => Page(
@@ -735,6 +736,9 @@ class Page {
lastEditedBy: PageUser.fromJson(
json['lastEditedBy'] as Map,
),
+ verification: PageVerification.fromJson(
+ json['verification'] as Map,
+ ),
);
final String id;
@@ -803,6 +807,8 @@ class Page {
final PageUser lastEditedBy;
+ final PageVerification verification;
+
Map toJson() => {
'id': id,
'workspace': workspace,
@@ -830,9 +836,58 @@ class Page {
'journalDate': journalDate,
'createdBy': createdBy.toJson(),
'lastEditedBy': lastEditedBy.toJson(),
+ 'verification': verification.toJson(),
};
}
+/// Whether someone vouched for the page; at is empty when nobody has
+class PageVerification {
+ const PageVerification({
+ required this.by,
+ required this.at,
+ required this.until,
+ required this.expired,
+ });
+
+ factory PageVerification.fromJson(Map json) =>
+ PageVerification(
+ by: PageUser.fromJson(json['by'] as Map),
+ at: json['at'] as String,
+ until: json['until'] as String,
+ expired: json['expired'] as bool,
+ );
+
+ final PageUser by;
+
+ /// When the page was verified; empty if it is not
+ final String at;
+
+ /// When the verification runs out; empty when it does not
+ final String until;
+
+ /// The verification ran out (until has passed)
+ final bool expired;
+
+ Map toJson() => {
+ 'by': by.toJson(),
+ 'at': at,
+ 'until': until,
+ 'expired': expired,
+ };
+}
+
+class VerifyPage {
+ const VerifyPage({required this.days});
+
+ factory VerifyPage.fromJson(Map json) =>
+ VerifyPage(days: (json['days'] as num).toInt());
+
+ /// How many days the verification lasts; 0 for one that does not run out
+ final int days;
+
+ Map toJson() => {'days': days};
+}
+
/// The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it
enum PageMode {
page('page'),
@@ -3861,7 +3916,7 @@ class WatchState {
Map toJson() => {'watching': watching};
}
-/// The join_* types are about a workspace and have no page
+/// The join_* types are about a workspace and have no page; verify_expired tells the person who verified a page that it ran out
enum NotificationType {
comment('comment'),
reply('reply'),
@@ -3871,7 +3926,8 @@ enum NotificationType {
reminder('reminder'),
joinRequest('join_request'),
joinApproved('join_approved'),
- joinDeclined('join_declined');
+ joinDeclined('join_declined'),
+ verifyExpired('verify_expired');
const NotificationType(this.value);
final String value;
@@ -5388,6 +5444,7 @@ class AiSettings {
required this.index,
required this.ignored,
required this.monthlyTokenLimit,
+ required this.readScans,
});
factory AiSettings.fromJson(Map json) => AiSettings(
@@ -5396,6 +5453,7 @@ class AiSettings {
index: json['index'] as bool,
ignored: (json['ignored'] as List).map((e) => e as String).toList(),
monthlyTokenLimit: (json['monthlyTokenLimit'] as num).toInt(),
+ readScans: json['readScans'] as bool,
);
final bool enabled;
@@ -5412,12 +5470,16 @@ class AiSettings {
/// Tokens the workspace may use per month; 0 is no cap
final int monthlyTokenLimit;
+ /// Have a document-reading model write out scanned PDFs attached to pages
+ final bool readScans;
+
Map toJson() => {
'enabled': enabled,
'useInstanceProfiles': useInstanceProfiles,
'index': index,
'ignored': ignored.map((e) => e).toList(),
'monthlyTokenLimit': monthlyTokenLimit,
+ 'readScans': readScans,
};
}
diff --git a/Phone-App/lib/l10n.dart b/Phone-App/lib/l10n.dart
index a5aff2a..bed0c76 100644
--- a/Phone-App/lib/l10n.dart
+++ b/Phone-App/lib/l10n.dart
@@ -141,6 +141,7 @@ const appStrings = >{
'notifShare': '{who} shared a page with you',
'notifResolved': '{who} resolved a thread',
'notifReminder': 'Reminder',
+ 'notifVerifyExpired': 'Your verification of this page ran out',
'notifJoinRequest': '{who} asks to join',
'notifJoinApproved': 'You can now open this workspace',
'notifJoinDeclined': 'Your request to join was declined',
@@ -288,6 +289,7 @@ const appStrings = >{
'notifShare': '{who} udostępnia Ci stronę',
'notifResolved': '{who} rozwiązuje wątek',
'notifReminder': 'Przypomnienie',
+ 'notifVerifyExpired': 'Twoja weryfikacja tej strony wygasła',
'notifJoinRequest': '{who} prosi o dołączenie',
'notifJoinApproved': 'Możesz już otworzyć ten obszar roboczy',
'notifJoinDeclined': 'Twoja prośba o dołączenie została odrzucona',
@@ -438,6 +440,7 @@ const appStrings = >{
'notifShare': '{who} hat eine Seite mit dir geteilt',
'notifResolved': '{who} hat einen Thread erledigt',
'notifReminder': 'Erinnerung',
+ 'notifVerifyExpired': 'Deine Verifizierung dieser Seite ist abgelaufen',
'notifJoinRequest': '{who} bittet um Beitritt',
'notifJoinApproved': 'Du kannst diesen Arbeitsbereich jetzt öffnen',
'notifJoinDeclined': 'Deine Anfrage zum Beitritt wurde abgelehnt',
@@ -589,6 +592,7 @@ const appStrings = >{
'notifShare': '{who} a partagé une page avec vous',
'notifResolved': '{who} a résolu une discussion',
'notifReminder': 'Rappel',
+ 'notifVerifyExpired': 'Votre vérification de cette page a expiré',
'notifJoinRequest': '{who} demande à rejoindre',
'notifJoinApproved': 'Vous pouvez maintenant ouvrir cet espace de travail',
'notifJoinDeclined': 'Votre demande pour rejoindre a été refusée',
@@ -738,6 +742,7 @@ const appStrings = >{
'notifShare': '{who} compartió una página contigo',
'notifResolved': '{who} resolvió un hilo',
'notifReminder': 'Recordatorio',
+ 'notifVerifyExpired': 'Tu verificación de esta página ha caducado',
'notifJoinRequest': '{who} pide unirse',
'notifJoinApproved': 'Ya puedes abrir este espacio de trabajo',
'notifJoinDeclined': 'Tu solicitud para unirte fue rechazada',
diff --git a/Phone-App/lib/screens/notifications_screen.dart b/Phone-App/lib/screens/notifications_screen.dart
index 12feebf..4465948 100644
--- a/Phone-App/lib/screens/notifications_screen.dart
+++ b/Phone-App/lib/screens/notifications_screen.dart
@@ -19,6 +19,7 @@ String notificationText(Notification n) {
NotificationType.share => tr('notifShare', {'who': who}),
NotificationType.resolved => tr('notifResolved', {'who': who}),
NotificationType.reminder => tr('notifReminder'),
+ NotificationType.verifyExpired => tr('notifVerifyExpired'),
NotificationType.joinRequest => tr('notifJoinRequest', {'who': who}),
NotificationType.joinApproved => tr('notifJoinApproved'),
NotificationType.joinDeclined => tr('notifJoinDeclined'),
diff --git a/Server/admin/src/session.ts b/Server/admin/src/session.ts
index 06484e9..bbeb9af 100644
--- a/Server/admin/src/session.ts
+++ b/Server/admin/src/session.ts
@@ -2,7 +2,7 @@
import { ApiError, createClient, createTokenStore, isManager, type User } from "@docwell/api-client";
import { computed, ref } from "vue";
-import { t } from "./i18n";
+import { i18n, t } from "./i18n";
// The admin panel is served by docwell-server itself, so the API is same-origin.
const tokens = createTokenStore("docwell.admin.token");
@@ -14,6 +14,7 @@ let restored = false;
export const api = createClient({
baseUrl: "",
token: tokens.get,
+ locale: () => i18n.global.locale.value,
onUnauthorized: () => signOut(),
});
diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go
index 94efb98..6c1777c 100644
--- a/Server/cmd/docwell-server/main.go
+++ b/Server/cmd/docwell-server/main.go
@@ -141,6 +141,7 @@ func run(log *slog.Logger) error {
reg.Register("notify.prune", "Deletes read notifications and sent reminders older than 90 days", 24*time.Hour, dirSvc.PruneNotifications)
reg.Register("analytics.prune", "Deletes page view counts older than 400 days", 24*time.Hour, dirSvc.PruneViews)
reg.Register("notify.reminders", "Sends reminders for dates in pages that are due", time.Minute, dirSvc.SendReminders)
+ reg.Register("notify.verifications", "Tells people when their verification of a page ran out", 15*time.Minute, dirSvc.SendVerificationReminders)
reg.Register("links.backfill", "Works out page links for pages saved before backlinks existed", 0, dirSvc.BackfillLinks)
index.Track(reg.Track)
indexCtx, stopIndex := context.WithCancel(context.Background())
@@ -149,6 +150,7 @@ func run(log *slog.Logger) error {
go reg.Every(indexCtx, "notify.digest", 5*time.Minute)
go reg.Every(indexCtx, "notify.prune", 24*time.Hour)
go reg.Every(indexCtx, "notify.reminders", time.Minute)
+ go reg.Every(indexCtx, "notify.verifications", 15*time.Minute)
_ = reg.Run("links.backfill")
dirSvc.UseSearch(index)
dirSvc.UseWebhooks(hooks)
@@ -177,6 +179,8 @@ func run(log *slog.Logger) error {
}
defer aiSvc.Close()
aiSvc.Track(reg.Track)
+ // Scanned PDFs attached to pages are read by AI where workspaces turn it on.
+ index.UseScans(aiSvc, ai.ErrScansOff)
reg.Register("ai.index", "Embeds changed pages of workspaces with AI indexing on", 30*time.Second,
func(ctx context.Context) error { return aiSvc.IndexPass(ctx, true) })
go aiSvc.Run(indexCtx, 30*time.Second, 10*time.Minute)
diff --git a/Server/internal/ai/profiles.go b/Server/internal/ai/profiles.go
index 1145562..a3b61d6 100644
--- a/Server/internal/ai/profiles.go
+++ b/Server/internal/ai/profiles.go
@@ -466,6 +466,9 @@ type Settings struct {
Ignored []string `json:"ignored"`
// MonthlyTokenLimit caps the tokens the workspace uses per month; 0 is no cap.
MonthlyTokenLimit int `json:"monthlyTokenLimit"`
+ // ReadScans has a document-reading model write out scanned PDFs attached
+ // to pages, once each, so search finds their text (scans.go).
+ ReadScans bool `json:"readScans"`
}
func defaultSettings() Settings {
diff --git a/Server/internal/ai/scans.go b/Server/internal/ai/scans.go
new file mode 100644
index 0000000..5d79000
--- /dev/null
+++ b/Server/internal/ai/scans.go
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ai
+
+import (
+ "context"
+ "errors"
+ "strings"
+)
+
+// Scanned PDFs attached to pages have no text layer, so search cannot read
+// them. A workspace that turns on Settings.ReadScans has its AI provider
+// write them out, once each, for the search index (search/scans.go). It
+// costs tokens, counted against the workspace's monthly limit like any
+// other use.
+
+// ErrScansOff is returned when the workspace does not read scanned PDFs (AI
+// or the setting is off, or no provider is set up).
+var ErrScansOff = errors.New("ai: the workspace does not read scanned PDFs")
+
+// ReadsScans reports whether a workspace reads scanned PDFs for search.
+func (s *Service) ReadsScans(ctx context.Context, wsID string) bool {
+ st, err := s.settings(ctx, wsID)
+ return err == nil && st.Enabled && st.ReadScans
+}
+
+// ReadScan writes out the text of a scanned PDF for the search index of a
+// workspace that reads scans. It runs as the server, not as a person.
+func (s *Service) ReadScan(ctx context.Context, wsID string, data []byte) (string, error) {
+ st, err := s.settings(ctx, wsID)
+ if err != nil {
+ return "", err
+ }
+ if !st.Enabled || !st.ReadScans {
+ return "", ErrScansOff
+ }
+ chain, err := s.chain(ctx, wsID, st)
+ if err != nil {
+ return "", err
+ }
+ if chain, err = s.limit(ctx, wsID, st, chain); err != nil {
+ return "", err
+ }
+ var out strings.Builder
+ _, err = s.chat(ctx, wsID, chain, ChatRequest{
+ System: ocrSystem, MaxTokens: 32000, PDF: data,
+ Messages: []Message{{Role: "user", Content: "Write out the text of this document."}},
+ }, func(d string) { out.WriteString(d) })
+ if errors.Is(err, errNoProfile) {
+ return "", ErrScansOff
+ }
+ if err != nil {
+ return "", err
+ }
+ return out.String(), nil
+}
diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go
index fa8407f..ab33cf1 100644
--- a/Server/internal/api/api.gen.go
+++ b/Server/internal/api/api.gen.go
@@ -503,15 +503,16 @@ func (e NotificationSettingsEmail) Valid() bool {
// Defines values for NotificationType.
const (
- NotificationTypeComment NotificationType = "comment"
- NotificationTypeJoinApproved NotificationType = "join_approved"
- NotificationTypeJoinDeclined NotificationType = "join_declined"
- NotificationTypeJoinRequest NotificationType = "join_request"
- NotificationTypeMention NotificationType = "mention"
- NotificationTypeReminder NotificationType = "reminder"
- NotificationTypeReply NotificationType = "reply"
- NotificationTypeResolved NotificationType = "resolved"
- NotificationTypeShare NotificationType = "share"
+ NotificationTypeComment NotificationType = "comment"
+ NotificationTypeJoinApproved NotificationType = "join_approved"
+ NotificationTypeJoinDeclined NotificationType = "join_declined"
+ NotificationTypeJoinRequest NotificationType = "join_request"
+ NotificationTypeMention NotificationType = "mention"
+ NotificationTypeReminder NotificationType = "reminder"
+ NotificationTypeReply NotificationType = "reply"
+ NotificationTypeResolved NotificationType = "resolved"
+ NotificationTypeShare NotificationType = "share"
+ NotificationTypeVerifyExpired NotificationType = "verify_expired"
)
// Valid indicates whether the value is a known member of the NotificationType enum.
@@ -535,6 +536,8 @@ func (e NotificationType) Valid() bool {
return true
case NotificationTypeShare:
return true
+ case NotificationTypeVerifyExpired:
+ return true
default:
return false
}
@@ -1339,6 +1342,9 @@ type AiSettings struct {
// MonthlyTokenLimit Tokens the workspace may use per month; 0 is no cap
MonthlyTokenLimit int `json:"monthlyTokenLimit"`
+ // ReadScans Have a document-reading model write out scanned PDFs attached to pages
+ ReadScans bool `json:"readScans"`
+
// UseInstanceProfiles After its own profiles
UseInstanceProfiles bool `json:"useInstanceProfiles"`
}
@@ -2060,7 +2066,7 @@ type Notification struct {
Page *PageRef `json:"page"`
Read bool `json:"read"`
- // Type The join_* types are about a workspace and have no page
+ // Type The join_* types are about a workspace and have no page; verify_expired tells the person who verified a page that it ran out
Type NotificationType `json:"type"`
Workspace string `json:"workspace"`
}
@@ -2083,7 +2089,7 @@ type NotificationSettings struct {
// NotificationSettingsEmail Unread notifications by email every few minutes
type NotificationSettingsEmail string
-// NotificationType The join_* types are about a workspace and have no page
+// NotificationType The join_* types are about a workspace and have no page; verify_expired tells the person who verified a page that it ran out
type NotificationType string
// OAuthProviderSettings defines model for OAuthProviderSettings.
@@ -2207,10 +2213,13 @@ type Page struct {
Space string `json:"space"`
// Tags Tag ids
- Tags []string `json:"tags"`
- Title string `json:"title"`
- Updated string `json:"updated"`
- Workspace string `json:"workspace"`
+ Tags []string `json:"tags"`
+ Title string `json:"title"`
+ Updated string `json:"updated"`
+
+ // Verification Whether someone vouched for the page; at is empty when nobody has
+ Verification PageVerification `json:"verification"`
+ Workspace string `json:"workspace"`
}
// PageAccess defines model for PageAccess.
@@ -2349,6 +2358,19 @@ type PageUser struct {
Name string `json:"name"`
}
+// PageVerification Whether someone vouched for the page; at is empty when nobody has
+type PageVerification struct {
+ // At When the page was verified; empty if it is not
+ At string `json:"at"`
+ By PageUser `json:"by"`
+
+ // Expired The verification ran out (until has passed)
+ Expired bool `json:"expired"`
+
+ // Until When the verification runs out; empty when it does not
+ Until string `json:"until"`
+}
+
// PageVersion defines model for PageVersion.
type PageVersion struct {
// Author Name (or email) of the last person who edited before it was taken
@@ -2852,6 +2874,12 @@ type UserList struct {
TotalItems int `json:"totalItems"`
}
+// VerifyPage defines model for VerifyPage.
+type VerifyPage struct {
+ // Days How many days the verification lasts; 0 for one that does not run out
+ Days int `json:"days"`
+}
+
// Version defines model for Version.
type Version struct {
Name string `json:"name"`
@@ -3627,6 +3655,9 @@ type MovePageJSONRequestBody MovePageJSONBody
// SetShareLinkJSONRequestBody defines body for SetShareLink for application/json ContentType.
type SetShareLinkJSONRequestBody SetShareLinkJSONBody
+// VerifyPageJSONRequestBody defines body for VerifyPage for application/json ContentType.
+type VerifyPageJSONRequestBody = VerifyPage
+
// SetPageWatchJSONRequestBody defines body for SetPageWatch for application/json ContentType.
type SetPageWatchJSONRequestBody = WatchState
diff --git a/Server/internal/auth/auth.go b/Server/internal/auth/auth.go
index 8ac9017..3fbd3ef 100644
--- a/Server/internal/auth/auth.go
+++ b/Server/internal/auth/auth.go
@@ -576,3 +576,10 @@ func BearerToken(r *http.Request) string {
}
return ""
}
+
+// SetLocale stores the language a person last used the app in, which their
+// emails and phone notifications are written in.
+func (s *Service) SetLocale(ctx context.Context, userID, lang string) error {
+ _, err := pocketbase.Update[UserRecord](ctx, s.pb, "users", userID, map[string]any{"locale": lang})
+ return err
+}
diff --git a/Server/internal/convert/columns.go b/Server/internal/convert/columns.go
new file mode 100644
index 0000000..ba3fd34
--- /dev/null
+++ b/Server/internal/convert/columns.go
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "golang.org/x/net/html"
+)
+
+// Side-by-side columns (Packages/editor/src/columns.ts): a "columns" row of
+// two to four "column" nodes, each with a width in percent or none for an
+// equal share. Exports to Markdown, Word and PDF put the columns one after
+// another; HTML keeps them side by side.
+
+const maxColumns = 4
+
+// newColumns is a row of columns around these bodies. Empty bodies are left
+// out; fewer than two left are returned as plain blocks, and anything past
+// the fourth joins the fourth.
+func newColumns(bodies [][]Node, widths []float64) []Node {
+ type col struct {
+ body []Node
+ width float64
+ }
+ var cols []col
+ for i, b := range bodies {
+ if len(b) == 0 {
+ continue
+ }
+ w := 0.0
+ if i < len(widths) {
+ w = widths[i]
+ }
+ cols = append(cols, col{b, w})
+ }
+ if len(cols) < 2 {
+ var out []Node
+ for _, c := range cols {
+ out = append(out, c.body...)
+ }
+ return out
+ }
+ if len(cols) > maxColumns {
+ last := &cols[maxColumns-1]
+ for _, c := range cols[maxColumns:] {
+ last.body = append(last.body, c.body...)
+ last.width += c.width
+ }
+ cols = cols[:maxColumns]
+ }
+ // Widths count only when every column has one; they are scaled to 100.
+ total := 0.0
+ for _, c := range cols {
+ if c.width <= 0 {
+ total = 0
+ break
+ }
+ total += c.width
+ }
+ row := Node{Type: "columns"}
+ for _, c := range cols {
+ n := Node{Type: "column", Attrs: map[string]any{"width": nil}, Content: c.body}
+ if total > 0 {
+ n.Attrs["width"] = float64(int(c.width*1000/total+0.5)) / 10
+ }
+ row.Content = append(row.Content, n)
+ }
+ return []Node{row}
+}
+
+// columnWidth is a column's width in percent, 0 when it has none.
+func columnWidth(n Node) float64 {
+ switch v := n.Attrs["width"].(type) {
+ case float64:
+ if v > 0 && v <= 100 {
+ return v
+ }
+ case string:
+ if f, err := strconv.ParseFloat(v, 64); err == nil && f > 0 && f <= 100 {
+ return f
+ }
+ }
+ return 0
+}
+
+// writeHTMLColumns writes a row as a flex box that docwell's own import
+// and editor read back.
+func writeHTMLColumns(b *strings.Builder, n Node, o Options) {
+ b.WriteString("
\n")
+ for _, c := range n.Content {
+ grow := 1.0
+ attr := ""
+ if w := columnWidth(c); w > 0 {
+ grow = w
+ attr = fmt.Sprintf(" data-width=\"%s\"", formatNumber(w))
+ }
+ fmt.Fprintf(b, "
\n", attr, formatNumber(grow))
+ for _, child := range c.Content {
+ writeHTML(b, child, o)
+ }
+ b.WriteString("
\n")
+ }
+ b.WriteString("
\n")
+}
+
+var cssWidth = regexp.MustCompile(`(?i)(?:^|;)\s*(?:width|flex-basis)\s*:\s*([0-9.]+)%`)
+
+// styleWidth is a percentage width from an element's style, 0 without one.
+func styleWidth(n *html.Node) float64 {
+ m := cssWidth.FindStringSubmatch(attrOf(n, "style"))
+ if m == nil {
+ return 0
+ }
+ f, _ := strconv.ParseFloat(m[1], 64)
+ return f
+}
+
+// confluenceCellWidth is the share Confluence's page layouts give a cell:
+// sidebars are narrow, the rest share what is left.
+func confluenceCellWidth(cell *html.Node) float64 {
+ if hasClass(cell, "aside") || hasClass(cell, "sidebar") {
+ return 30
+ }
+ return 0
+}
+
+// readColumns reads a row of columns from HTML: Docwell's own
+// (data-type="columns"), Notion's (div.column-list > div.column) and
+// Confluence's page layouts (div.columnLayout > div.cell). ok is false for
+// any other element.
+func (r *reader) readColumns(n *html.Node) (out []Node, ok bool) {
+ var isCol func(*html.Node) bool
+ width := styleWidth
+ switch {
+ case attrOf(n, "data-type") == "columns":
+ isCol = func(c *html.Node) bool { return attrOf(c, "data-type") == "column" }
+ width = func(c *html.Node) float64 {
+ if f, err := strconv.ParseFloat(attrOf(c, "data-width"), 64); err == nil {
+ return f
+ }
+ return 0
+ }
+ case hasClass(n, "column-list"):
+ isCol = func(c *html.Node) bool { return hasClass(c, "column") }
+ case hasClass(n, "columnLayout"):
+ isCol = func(c *html.Node) bool { return hasClass(c, "cell") }
+ width = confluenceCellWidth
+ default:
+ return nil, false
+ }
+ var bodies [][]Node
+ var widths []float64
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ if c.Type != html.ElementNode || !isCol(c) {
+ continue
+ }
+ bodies = append(bodies, r.blocks(c))
+ widths = append(widths, width(c))
+ }
+ // Sidebars have a width and the other cells none: they share the rest.
+ if hasClass(n, "columnLayout") {
+ fixed, open := 0.0, 0
+ for _, w := range widths {
+ if w > 0 {
+ fixed += w
+ } else {
+ open++
+ }
+ }
+ if fixed > 0 && open > 0 {
+ for i, w := range widths {
+ if w == 0 {
+ widths[i] = max(100-fixed, 10*float64(open)) / float64(open)
+ }
+ }
+ }
+ }
+ return newColumns(bodies, widths), true
+}
diff --git a/Server/internal/convert/columns_test.go b/Server/internal/convert/columns_test.go
new file mode 100644
index 0000000..0069445
--- /dev/null
+++ b/Server/internal/convert/columns_test.go
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "strings"
+ "testing"
+)
+
+func colTypes(doc Node) []string {
+ var out []string
+ for _, n := range doc.Content {
+ out = append(out, n.Type)
+ }
+ return out
+}
+
+func TestColumnsRoundTripThroughHTML(t *testing.T) {
+ doc := Node{Type: "doc", Content: []Node{{Type: "columns", Content: []Node{
+ {Type: "column", Attrs: map[string]any{"width": 70.0}, Content: []Node{cpara("Left")}},
+ {Type: "column", Attrs: map[string]any{"width": 30.0}, Content: []Node{cpara("Right")}},
+ }}}}
+ out := HTML(doc, Options{})
+ if !strings.Contains(out, `data-type="columns"`) || !strings.Contains(out, `data-width="70"`) {
+ t.Fatalf("html: %s", out)
+ }
+ back, err := FromHTML(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := colTypes(back); len(got) != 1 || got[0] != "columns" {
+ t.Fatalf("types: %v", got)
+ }
+ row := back.Content[0]
+ if len(row.Content) != 2 || columnWidth(row.Content[0]) != 70 || PlainText(row.Content[1]) != "Right" {
+ t.Fatalf("row: %+v", row)
+ }
+}
+
+func TestColumnsFlattenInMarkdown(t *testing.T) {
+ doc := Node{Type: "doc", Content: []Node{{Type: "columns", Content: []Node{
+ {Type: "column", Content: []Node{cpara("Left")}},
+ {Type: "column", Content: []Node{cpara("Right")}},
+ }}}}
+ md := Markdown(doc, Options{})
+ if !strings.Contains(md, "Left") || !strings.Contains(md, "Right") || strings.Index(md, "Left") > strings.Index(md, "Right") {
+ t.Fatalf("markdown: %q", md)
+ }
+}
+
+func TestNotionAndConfluenceColumns(t *testing.T) {
+ notion := `
`
+ doc, _ = FromHTML(conf)
+ if colTypes(doc)[0] != "columns" || columnWidth(doc.Content[0].Content[0]) != 70 || columnWidth(doc.Content[0].Content[1]) != 30 {
+ t.Fatalf("confluence: %+v", doc)
+ }
+ // A layout with one cell is just its blocks.
+ doc, _ = FromHTML(`
Only
`)
+ if got := colTypes(doc); len(got) != 1 || got[0] != "paragraph" {
+ t.Fatalf("single: %v", got)
+ }
+}
+
+func TestColumnsPastFourJoinTheFourth(t *testing.T) {
+ bodies := [][]Node{{cpara("1")}, {cpara("2")}, {cpara("3")}, {cpara("4")}, {cpara("5")}}
+ row := newColumns(bodies, nil)[0]
+ if len(row.Content) != 4 || len(row.Content[3].Content) != 2 {
+ t.Fatalf("row: %+v", row)
+ }
+}
+
+func cpara(s string) Node { return Node{Type: "paragraph", Content: []Node{{Type: "text", Text: s}}} }
diff --git a/Server/internal/convert/docx_export.go b/Server/internal/convert/docx_export.go
index c89fa38..4b84aed 100644
--- a/Server/internal/convert/docx_export.go
+++ b/Server/internal/convert/docx_export.go
@@ -26,7 +26,7 @@ type DOCXOptions struct {
// highlights, links and images are kept in a form FromDOCX reads back.
// Diagrams and embeds become links, formulas their LaTeX.
func DOCX(title string, doc Node, o DOCXOptions) ([]byte, error) {
- doc = expandDatabases(doc)
+ doc = withoutSuggestions(expandDatabases(doc))
w := &docxWriter{o: o}
if strings.TrimSpace(title) != "" {
w.para(paraProps{style: "Title"}, func() { w.text(title, runProps{}) })
diff --git a/Server/internal/convert/export.go b/Server/internal/convert/export.go
index 669de82..2036bc4 100644
--- a/Server/internal/convert/export.go
+++ b/Server/internal/convert/export.go
@@ -102,6 +102,8 @@ func writeHTML(b *strings.Builder, n Node, o Options) {
html.EscapeString(emoji), color, paletteBackground[color], html.EscapeString(emoji))
children()
b.WriteString("
\n")
+ case "columns":
+ writeHTMLColumns(b, n, o)
case "table":
b.WriteString("
\n\n")
children()
@@ -242,6 +244,9 @@ func writeHTMLText(b *strings.Builder, n Node, o Options) {
}
open = append(open, "")
close = append([]string{""}, close...)
+ case markSuggestInsert, markSuggestDelete:
+ op, cl := suggestionTags(m)
+ open, close = append(open, op), append([]string{cl}, close...)
case "link":
if href := o.file(m.attr("href")); safeURL.MatchString(href) {
open, close = append(open, ""), append([]string{""}, close...)
@@ -257,7 +262,7 @@ func writeHTMLText(b *strings.Builder, n Node, o Options) {
// Markdown renders the document as CommonMark (with ~~strikethrough~~).
func Markdown(doc Node, o Options) string {
- doc = expandDatabases(doc)
+ doc = withoutSuggestions(expandDatabases(doc))
w := &mdWriter{o: o}
w.blocks(doc.Content, "", "")
return strings.TrimRight(w.b.String(), "\n") + "\n"
diff --git a/Server/internal/convert/import.go b/Server/internal/convert/import.go
index 3f4af1f..4b11f4d 100644
--- a/Server/internal/convert/import.go
+++ b/Server/internal/convert/import.go
@@ -230,6 +230,10 @@ func (r *reader) block(n *html.Node) []Node {
h := Node{Type: "heading", Attrs: map[string]any{"level": float64(headingLevel[n.DataAtom])}}
h.Content = trimInline(r.inlineChildren(n, nil))
return aligned(n, []Node{h})
+ case atom.Div:
+ if cols, ok := r.readColumns(n); ok {
+ return cols
+ }
case atom.Aside:
if attrOf(n, "data-type") == "callout" {
body := n
@@ -476,9 +480,21 @@ func (r *reader) inline(n *html.Node, marks []mark) []Node {
marks = add(mark{Type: "bold"})
case atom.Em, atom.I:
marks = add(mark{Type: "italic"})
- case atom.S, atom.Del, atom.Strike:
+ case atom.Del:
+ if m, ok := suggestionMark(n, markSuggestDelete); ok {
+ marks = add(m)
+ } else {
+ marks = add(mark{Type: "strike"})
+ }
+ case atom.Ins:
+ if m, ok := suggestionMark(n, markSuggestInsert); ok {
+ marks = add(m)
+ } else {
+ marks = add(mark{Type: "underline"})
+ }
+ case atom.S, atom.Strike:
marks = add(mark{Type: "strike"})
- case atom.U, atom.Ins:
+ case atom.U:
marks = add(mark{Type: "underline"})
case atom.Code, atom.Kbd, atom.Samp:
marks = add(mark{Type: "code"})
diff --git a/Server/internal/convert/pdf.go b/Server/internal/convert/pdf.go
index 5535b32..c1568c7 100644
--- a/Server/internal/convert/pdf.go
+++ b/Server/internal/convert/pdf.go
@@ -42,7 +42,7 @@ const maxPDFImagePixels = 50_000_000
// heading and page numbers. Diagrams (stored as SVG) and Mermaid charts are
// not drawn: diagrams become a link to their file, Mermaid its source.
func PDF(title string, doc Node, o PDFOptions) (out []byte, err error) {
- doc = expandDatabases(doc)
+ doc = withoutSuggestions(expandDatabases(doc))
defer func() {
// fpdf panics on some input instead of failing; one bad page must
// not take the server down.
diff --git a/Server/internal/convert/suggest.go b/Server/internal/convert/suggest.go
new file mode 100644
index 0000000..2de39c6
--- /dev/null
+++ b/Server/internal/convert/suggest.go
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "html"
+ "strconv"
+ "strings"
+
+ xhtml "golang.org/x/net/html"
+)
+
+// Suggestions (Packages/editor/src/suggest.ts) are two marks on text:
+// suggestInsert on text someone proposes to add and suggestDelete on text
+// they propose to remove. HTML keeps them as / with their
+// details, so a page exported and imported again keeps its open
+// suggestions. Markdown, Word and PDF show the page as it stands until
+// someone accepts them: proposed text left out, proposed deletions kept.
+
+const (
+ markSuggestInsert = "suggestInsert"
+ markSuggestDelete = "suggestDelete"
+)
+
+// withoutSuggestions is the document with its open suggestions not taken:
+// inserted text dropped and deletion marks taken off.
+func withoutSuggestions(n Node) Node {
+ if len(n.Content) == 0 {
+ return n
+ }
+ out := make([]Node, 0, len(n.Content))
+ for _, c := range n.Content {
+ if hasMark(c, markSuggestInsert) {
+ continue
+ }
+ if hasMark(c, markSuggestDelete) {
+ c.Marks = withoutMark(c.Marks, markSuggestDelete)
+ }
+ out = append(out, withoutSuggestions(c))
+ }
+ n.Content = out
+ return n
+}
+
+func hasMark(n Node, typ string) bool {
+ for _, m := range n.Marks {
+ if m.Type == typ {
+ return true
+ }
+ }
+ return false
+}
+
+func withoutMark(marks []Mark, typ string) []Mark {
+ var out []Mark
+ for _, m := range marks {
+ if m.Type != typ {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+// suggestionTags are the opening and closing tags of a suggestion mark.
+func suggestionTags(m Mark) (string, string) {
+ tag, class := "ins", "dw-suggest-ins"
+ if m.Type == markSuggestDelete {
+ tag, class = "del", "dw-suggest-del"
+ }
+ open := "<" + tag + " class=\"" + class + "\" data-suggestion=\"" + html.EscapeString(m.attr("id")) +
+ "\" data-author=\"" + html.EscapeString(m.attr("author")) + "\" data-name=\"" + html.EscapeString(m.attr("name")) +
+ "\" data-at=\"" + suggestionTime(m) + "\">"
+ return open, "" + tag + ">"
+}
+
+// suggestionMark reads a suggestion from an or with data-suggestion.
+func suggestionMark(n *xhtml.Node, typ string) (Mark, bool) {
+ id := attrOf(n, "data-suggestion")
+ if strings.TrimSpace(id) == "" {
+ return Mark{}, false
+ }
+ at, _ := strconv.ParseFloat(attrOf(n, "data-at"), 64)
+ return Mark{Type: typ, Attrs: map[string]any{
+ "id": id, "author": attrOf(n, "data-author"), "name": attrOf(n, "data-name"), "at": at,
+ }}, true
+}
+
+// suggestionTime is when a suggestion was made, in milliseconds, as text.
+func suggestionTime(m Mark) string {
+ switch v := m.Attrs["at"].(type) {
+ case float64:
+ return strconv.FormatFloat(v, 'f', 0, 64)
+ case string:
+ if f, err := strconv.ParseFloat(v, 64); err == nil {
+ return strconv.FormatFloat(f, 'f', 0, 64)
+ }
+ }
+ return "0"
+}
diff --git a/Server/internal/convert/suggest_test.go b/Server/internal/convert/suggest_test.go
new file mode 100644
index 0000000..ed6f83a
--- /dev/null
+++ b/Server/internal/convert/suggest_test.go
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package convert
+
+import (
+ "strings"
+ "testing"
+)
+
+func suggestedDoc() Node {
+ ins := Mark{Type: markSuggestInsert, Attrs: map[string]any{"id": "s1", "author": "ana", "name": "Ana", "at": 5.0}}
+ del := Mark{Type: markSuggestDelete, Attrs: map[string]any{"id": "s2", "author": "ana", "name": "Ana", "at": 6.0}}
+ return Node{Type: "doc", Content: []Node{{Type: "paragraph", Content: []Node{
+ {Type: "text", Text: "The "},
+ {Type: "text", Text: "slow ", Marks: []Mark{ins}},
+ {Type: "text", Text: "quick ", Marks: []Mark{del, {Type: "bold"}}},
+ {Type: "text", Text: "fox"},
+ }}}}
+}
+
+func TestSuggestionsRoundTripThroughHTML(t *testing.T) {
+ out := HTML(suggestedDoc(), Options{})
+ if !strings.Contains(out, `slow `) {
+ t.Fatalf("html: %s", out)
+ }
+ back, err := FromHTML(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ p := back.Content[0]
+ if len(p.Content) != 4 || !hasMark(p.Content[1], markSuggestInsert) || !hasMark(p.Content[2], markSuggestDelete) || !hasMark(p.Content[2], "bold") {
+ t.Fatalf("back: %+v", p.Content)
+ }
+ if p.Content[1].Marks[0].attr("id") != "s1" || p.Content[1].Marks[0].attr("name") != "Ana" {
+ t.Fatalf("attrs: %+v", p.Content[1].Marks)
+ }
+ // Plain and stay underline and strikethrough.
+ plain, _ := FromHTML("
ab
")
+ if !hasMark(plain.Content[0].Content[0], "underline") || !hasMark(plain.Content[0].Content[1], "strike") {
+ t.Fatalf("plain: %+v", plain.Content[0].Content)
+ }
+}
+
+func TestExportsLeaveOpenSuggestionsOut(t *testing.T) {
+ md := Markdown(suggestedDoc(), Options{})
+ if strings.TrimSpace(md) != "The **quick** fox" {
+ t.Fatalf("markdown: %q", md)
+ }
+ if _, err := DOCX("", suggestedDoc(), DOCXOptions{}); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/Server/internal/directory/invites.go b/Server/internal/directory/invites.go
index 153b28d..8266853 100644
--- a/Server/internal/directory/invites.go
+++ b/Server/internal/directory/invites.go
@@ -18,6 +18,7 @@ import (
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/auth"
+ "docwell/server/internal/i18n"
"docwell/server/internal/mail"
"docwell/server/internal/store/pocketbase"
)
@@ -265,15 +266,17 @@ func (s *Service) sendInvite(ctx context.Context, id, token string) (Invite, err
if target == "" {
target = appName
}
+ // The invite is written in the inviter's language.
+ lang := i18n.Lang(ctx)
inviter := inv.InvitedBy
if inviter == "" {
- inviter = "Someone"
+ inviter = i18n.Sprintf(lang, "Someone")
}
expires := inv.Expires
if t, err := parsePBTime(inv.Expires); err == nil {
- expires = t.Format("2 January 2006")
+ expires = i18n.Date(lang, t)
}
- m, err := mail.Render(inv.Email, "invite", map[string]string{
+ m, err := mail.RenderIn(lang, inv.Email, "invite", map[string]string{
"AppName": appName, "Inviter": inviter, "Target": target, "Link": inv.Link, "Expires": expires,
})
if err != nil {
diff --git a/Server/internal/directory/notify.go b/Server/internal/directory/notify.go
index 0d7e729..8d9b125 100644
--- a/Server/internal/directory/notify.go
+++ b/Server/internal/directory/notify.go
@@ -15,6 +15,7 @@ import (
"docwell/server/internal/access"
"docwell/server/internal/apperr"
+ "docwell/server/internal/i18n"
"docwell/server/internal/mail"
"docwell/server/internal/push"
"docwell/server/internal/store/pocketbase"
@@ -45,7 +46,7 @@ const (
// 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, NotifyReminder: 6}
+var notifyRank = map[string]int{NotifyComment: 1, NotifyResolved: 2, NotifyReply: 3, NotifyShare: 4, NotifyMention: 5, NotifyReminder: 6, NotifyVerifyExpired: 7}
type watchRecord struct {
ID string `json:"id"`
@@ -162,8 +163,8 @@ type Pusher interface {
func (s *Service) UsePush(p Pusher) { s.push = p }
// pushMessage is the phone notification for one stored notification.
-func (s *Service) pushMessage(ctx context.Context, e event, kind string) push.Message {
- who := "Someone"
+func (s *Service) pushMessage(ctx context.Context, e event, kind, lang string) push.Message {
+ who := i18n.Sprintf(lang, "Someone")
if e.actor != "" {
if u, err := s.getUser(ctx, e.actor); err == nil {
who = u.Name
@@ -174,22 +175,24 @@ func (s *Service) pushMessage(ctx context.Context, e event, kind string) push.Me
}
title := strings.TrimSpace(e.page.Icon + " " + e.page.Title)
if strings.TrimSpace(e.page.Title) == "" {
- title = strings.TrimSpace(e.page.Icon + " Untitled")
+ title = strings.TrimSpace(e.page.Icon + " " + i18n.Sprintf(lang, "Untitled"))
}
var body string
switch kind {
case NotifyComment:
- body = who + " commented"
+ body = i18n.Sprintf(lang, "%s commented", who)
case NotifyReply:
- body = who + " replied"
+ body = i18n.Sprintf(lang, "%s replied", who)
case NotifyMention:
- body = who + " mentioned you"
+ body = i18n.Sprintf(lang, "%s mentioned you", who)
case NotifyShare:
- body = who + " shared this page with you"
+ body = i18n.Sprintf(lang, "%s shared this page with you", who)
case NotifyResolved:
- body = who + " resolved a thread"
+ body = i18n.Sprintf(lang, "%s resolved a thread", who)
case NotifyReminder:
- body = "Reminder"
+ body = i18n.Sprintf(lang, "Reminder")
+ case NotifyVerifyExpired:
+ body = i18n.Sprintf(lang, "Your verification of this page ran out")
}
if x := excerpt(e.excerpt); x != "" && kind != NotifyShare {
body += ": " + x
@@ -230,7 +233,7 @@ func (s *Service) send(ctx context.Context, e event) {
continue
}
if s.push != nil {
- s.push.Notify(userID, s.pushMessage(ctx, e, kind))
+ s.push.Notify(userID, s.pushMessage(ctx, e, kind, userLang(u.Locale)))
}
}
}
@@ -513,7 +516,7 @@ type NotificationSettings struct {
}
// notificationTypes are every type a notification can have, in menu order.
-var notificationTypes = []string{"mention", "comment", "reply", "resolved", "share", "reminder", "join_request"}
+var notificationTypes = []string{"mention", "comment", "reply", "resolved", "share", "reminder", "verify_expired", "join_request"}
// emailTypes is every notification type except the ones turned off.
func emailTypes(off []string) []string {
@@ -578,9 +581,9 @@ type digestItem struct {
Link string
}
-func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) {
+func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *people, lang string) (digestItem, bool) {
if n.Page == "" {
- return s.workspaceDigestLine(ctx, n, who)
+ return s.workspaceDigestLine(ctx, n, who, lang)
}
p, err := s.getPage(ctx, n.Page)
if err != nil || p.DeletedAt != "" {
@@ -588,22 +591,30 @@ func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *peo
}
actor := who.get(ctx, n.Actor).display()
if actor == "" {
- actor = "Someone"
+ actor = i18n.Sprintf(lang, "Someone")
}
title := p.Title
if title == "" {
- title = "Untitled"
+ title = i18n.Sprintf(lang, "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.Type == NotifyReminder {
- text = fmt.Sprintf("Reminder in “%s”", title)
+ var text string
+ switch n.Type {
+ case NotifyComment:
+ text = i18n.Sprintf(lang, "%s commented on “%s”", actor, title)
+ case NotifyReply:
+ text = i18n.Sprintf(lang, "%s replied in “%s”", actor, title)
+ case NotifyMention:
+ text = i18n.Sprintf(lang, "%s mentioned you in “%s”", actor, title)
+ case NotifyShare:
+ text = i18n.Sprintf(lang, "%s shared “%s”", actor, title)
+ case NotifyResolved:
+ text = i18n.Sprintf(lang, "%s resolved a thread in “%s”", actor, title)
+ case NotifyReminder:
+ text = i18n.Sprintf(lang, "Reminder in “%s”", title)
+ case NotifyVerifyExpired:
+ text = i18n.Sprintf(lang, "Your verification of “%s” ran out", title)
+ default:
+ return digestItem{}, false
}
if n.Excerpt != "" && n.Type != NotifyShare && n.Excerpt != p.Title {
text += ": " + n.Excerpt
@@ -616,23 +627,23 @@ func (s *Service) digestLine(ctx context.Context, n notificationRecord, who *peo
}
// workspaceDigestLine is the digest line of a notification without a page.
-func (s *Service) workspaceDigestLine(ctx context.Context, n notificationRecord, who *people) (digestItem, bool) {
+func (s *Service) workspaceDigestLine(ctx context.Context, n notificationRecord, who *people, lang string) (digestItem, bool) {
ws, err := s.getWorkspace(ctx, n.Workspace)
if err != nil {
return digestItem{}, false
}
actor := who.get(ctx, n.Actor).display()
if actor == "" {
- actor = "Someone"
+ actor = i18n.Sprintf(lang, "Someone")
}
base := strings.TrimRight(s.mailer.WebURL, "/")
switch n.Type {
case NotifyJoinRequest:
- return digestItem{Text: fmt.Sprintf("%s asks to join “%s”", actor, ws.Name), Link: base + "/w/" + url.PathEscape(ws.ID) + "/settings"}, true
+ return digestItem{Text: i18n.Sprintf(lang, "%s asks to join “%s”", actor, ws.Name), Link: base + "/w/" + url.PathEscape(ws.ID) + "/settings"}, true
case NotifyJoinApproved:
- return digestItem{Text: fmt.Sprintf("You can now open “%s”", ws.Name), Link: base + "/"}, true
+ return digestItem{Text: i18n.Sprintf(lang, "You can now open “%s”", ws.Name), Link: base + "/"}, true
case NotifyJoinDeclined:
- return digestItem{Text: fmt.Sprintf("Your request to join “%s” was declined", ws.Name), Link: base + "/"}, true
+ return digestItem{Text: i18n.Sprintf(lang, "Your request to join “%s” was declined", ws.Name), Link: base + "/"}, true
}
return digestItem{}, false
}
@@ -668,6 +679,7 @@ func (s *Service) SendDigests(ctx context.Context) error {
Status string `json:"status"`
NotifyEmail string `json:"notify_email"`
NotifyEmailOff []string `json:"notify_email_off"`
+ Locale string `json:"locale"`
}](ctx, s.pb, "users", userID)
if err == nil && u.NotifyEmail != "off" && u.Status != "disabled" {
var items []digestItem
@@ -676,12 +688,12 @@ func (s *Service) SendDigests(ctx context.Context) error {
if slices.Contains(u.NotifyEmailOff, n.Type) {
continue
}
- if it, ok := s.digestLine(ctx, n, who); ok {
+ if it, ok := s.digestLine(ctx, n, who, userLang(u.Locale)); ok {
items = append(items, it)
}
}
if len(items) > 0 {
- m, err := mail.Render(u.Email, "digest", map[string]any{
+ m, err := mail.RenderIn(userLang(u.Locale), u.Email, "digest", map[string]any{
"AppName": appName, "Name": u.Name, "Count": len(items), "Items": items,
"SettingsLink": strings.TrimRight(s.mailer.WebURL, "/") + "/notifications",
})
@@ -722,3 +734,12 @@ func (s *Service) PruneNotifications(ctx context.Context) error {
}
return s.pruneReminders(ctx)
}
+
+// userLang is the language to write to a person in: the one they last used
+// the app in, else English.
+func userLang(locale string) string {
+ if i18n.IsSupported(locale) {
+ return locale
+ }
+ return i18n.Default
+}
diff --git a/Server/internal/directory/notify_test.go b/Server/internal/directory/notify_test.go
index 3fc3f1f..caa7b11 100644
--- a/Server/internal/directory/notify_test.go
+++ b/Server/internal/directory/notify_test.go
@@ -70,7 +70,7 @@ func TestLinkIDs(t *testing.T) {
func TestEmailTypesLeaveOutTheOnesTurnedOff(t *testing.T) {
got := emailTypes([]string{"comment", "share"})
- want := []string{"mention", "reply", "resolved", "reminder", "join_request"}
+ want := []string{"mention", "reply", "resolved", "reminder", "verify_expired", "join_request"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("emailTypes = %v, want %v", got, want)
}
diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go
index 3798f06..59ca270 100644
--- a/Server/internal/directory/pages.go
+++ b/Server/internal/directory/pages.go
@@ -25,7 +25,7 @@ import (
// but stay readable (and read-only) until someone unarchives them.
// pageFields skips the large content columns.
-const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,default_mode,tags,journal_date,created,updated"
+const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,default_mode,tags,journal_date,verified_by,verified_at,verified_until,created,updated"
// pageDetailFields adds the page's property values.
const pageDetailFields = pageFields + ",properties"
@@ -54,8 +54,12 @@ type pageRecord struct {
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
JournalDate string `json:"journal_date"`
- Created string `json:"created"`
- Updated string `json:"updated"`
+ // Verification (verify.go): who vouched for the page, when, and until when.
+ VerifiedBy string `json:"verified_by"`
+ VerifiedAt string `json:"verified_at"`
+ VerifiedUntil string `json:"verified_until"`
+ Created string `json:"created"`
+ Updated string `json:"updated"`
}
// PageNode is one entry of a space's page tree.
@@ -120,6 +124,8 @@ type Page struct {
JournalDate string `json:"journalDate"`
CreatedBy PageUser `json:"createdBy"`
LastEditedBy PageUser `json:"lastEditedBy"`
+ // Verification is who vouched for the page and until when (verify.go).
+ Verification PageVerification `json:"verification"`
}
// PageUser is a person named on a page; Name is empty when the account is gone.
@@ -297,6 +303,7 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
FullWidth: p.FullWidth, Font: p.Font, DefaultMode: pageMode(p.DefaultMode),
Tags: nonNil(p.Tags), Properties: p.Properties, JournalDate: p.JournalDate,
CreatedBy: s.pageUser(ctx, p.Creator), LastEditedBy: s.pageUser(ctx, p.LastEditor),
+ Verification: s.verification(ctx, p, time.Now()),
}
if page.Properties == nil {
page.Properties = map[string]json.RawMessage{}
diff --git a/Server/internal/directory/verify.go b/Server/internal/directory/verify.go
new file mode 100644
index 0000000..47797c1
--- /dev/null
+++ b/Server/internal/directory/verify.go
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package directory
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "docwell/server/internal/access"
+ "docwell/server/internal/apperr"
+ "docwell/server/internal/store/pocketbase"
+)
+
+// ---- Verified pages --------------------------------------------------------
+//
+// An editor verifies a page to say it is correct, for some days or without
+// end. Everyone sees who verified it and until when. When a verification
+// runs out, the person who made it gets a "verify_expired" notification
+// (once; verifying again starts over). Editing the page keeps it verified.
+
+// NotifyVerifyExpired is the notification type of a verification that ran out.
+const NotifyVerifyExpired = "verify_expired"
+
+// maxVerifyDays is the longest a verification can last (about ten years).
+const maxVerifyDays = 3660
+
+// PageVerification is who verified a page and until when; At is empty when
+// nobody has, Until when it does not run out.
+type PageVerification struct {
+ By PageUser `json:"by"`
+ At string `json:"at"`
+ Until string `json:"until"`
+ Expired bool `json:"expired"`
+}
+
+// verification is a page's verification as of now.
+func (s *Service) verification(ctx context.Context, p pageRecord, now time.Time) PageVerification {
+ if p.VerifiedAt == "" {
+ return PageVerification{}
+ }
+ v := PageVerification{By: s.pageUser(ctx, p.VerifiedBy), At: p.VerifiedAt, Until: p.VerifiedUntil}
+ v.Expired = verificationExpired(p.VerifiedUntil, now)
+ return v
+}
+
+// verificationExpired reports whether a verification lasting until (a
+// PocketBase time, empty for no end) has run out at now.
+func verificationExpired(until string, now time.Time) bool {
+ if until == "" {
+ return false
+ }
+ t, err := parsePBTime(until)
+ return err == nil && !t.After(now)
+}
+
+// VerifyPage verifies a page as the caller for days days, or without end
+// for 0 (editor). It replaces an earlier verification.
+func (s *Service) VerifyPage(ctx context.Context, c access.Caller, id string, days int) (Page, error) {
+ if days < 0 || days > maxVerifyDays {
+ return Page{}, apperr.Invalid(fmt.Sprintf("days must be between 0 and %d", maxVerifyDays))
+ }
+ p, a, err := s.pageFor(ctx, c, id)
+ if err != nil {
+ return Page{}, err
+ }
+ if err := access.EditPages(a.role); err != nil {
+ return Page{}, err
+ }
+ if p.DeletedAt != "" || p.ArchivedAt != "" {
+ return Page{}, apperr.Invalid("trashed and archived pages cannot be verified")
+ }
+ now := time.Now()
+ until := ""
+ if days > 0 {
+ until = pbTime(now.AddDate(0, 0, days))
+ }
+ body := map[string]any{
+ "verified_by": c.ID, "verified_at": pbTime(now), "verified_until": until, "verify_notified_at": "",
+ }
+ if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, body); err != nil {
+ return Page{}, mapPB(err, "page not found")
+ }
+ return s.GetPage(ctx, c, p.ID)
+}
+
+// UnverifyPage takes a page's verification off (editor).
+func (s *Service) UnverifyPage(ctx context.Context, c access.Caller, id string) (Page, error) {
+ p, a, err := s.pageFor(ctx, c, id)
+ if err != nil {
+ return Page{}, err
+ }
+ if err := access.EditPages(a.role); err != nil {
+ return Page{}, err
+ }
+ if p.VerifiedAt != "" {
+ body := map[string]any{"verified_by": "", "verified_at": "", "verified_until": "", "verify_notified_at": ""}
+ if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, body); err != nil {
+ return Page{}, mapPB(err, "page not found")
+ }
+ }
+ return s.GetPage(ctx, c, p.ID)
+}
+
+// SendVerificationReminders tells each person whose verification of a page
+// ran out, once. Each page is marked first, so a failure loses a reminder
+// rather than sending it twice. Trashed pages are skipped (they are marked
+// too, so restoring one does not remind about the past). It is a background
+// job.
+func (s *Service) SendVerificationReminders(ctx context.Context) error {
+ rows, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
+ Filter: fmt.Sprintf("verified_at != '' && verified_until != '' && verify_notified_at = '' && verified_until <= '%s'", pbTime(time.Now())),
+ Sort: "verified_until",
+ Fields: pageFields,
+ })
+ if err != nil {
+ return err
+ }
+ for _, p := range rows {
+ if _, err := pocketbase.Update[struct{}](ctx, s.pb, "pages", p.ID, map[string]any{"verify_notified_at": pbTime(time.Now())}); err != nil {
+ return err
+ }
+ if p.DeletedAt != "" || !validID(p.VerifiedBy) {
+ continue
+ }
+ e := event{page: p, to: map[string]string{}}
+ e.add(p.VerifiedBy, NotifyVerifyExpired)
+ s.send(ctx, e)
+ }
+ return nil
+}
diff --git a/Server/internal/directory/verify_test.go b/Server/internal/directory/verify_test.go
new file mode 100644
index 0000000..7dc1388
--- /dev/null
+++ b/Server/internal/directory/verify_test.go
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package directory
+
+import (
+ "testing"
+ "time"
+)
+
+func TestVerificationRunsOutAtItsEnd(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ cases := []struct {
+ until string
+ want bool
+ }{
+ {"", false}, // no end
+ {pbTime(now.Add(time.Hour)), false},
+ {pbTime(now), true},
+ {pbTime(now.Add(-24 * time.Hour)), true},
+ {"not a time", false},
+ }
+ for _, c := range cases {
+ if got := verificationExpired(c.until, now); got != c.want {
+ t.Errorf("verificationExpired(%q) = %v, want %v", c.until, got, c.want)
+ }
+ }
+}
+
+func TestVerifyExpiredOutranksOtherReasons(t *testing.T) {
+ e := event{to: map[string]string{}}
+ e.add("u1", NotifyComment)
+ e.add("u1", NotifyVerifyExpired)
+ if e.to["u1"] != NotifyVerifyExpired {
+ t.Errorf("got %q", e.to["u1"])
+ }
+}
diff --git a/Server/internal/httpapi/ai.go b/Server/internal/httpapi/ai.go
index 0bfcdcf..c26e625 100644
--- a/Server/internal/httpapi/ai.go
+++ b/Server/internal/httpapi/ai.go
@@ -15,6 +15,7 @@ import (
"docwell/server/internal/apperr"
"docwell/server/internal/audit"
"docwell/server/internal/auth"
+ "docwell/server/internal/i18n"
)
// AIService is the AI layer (ADR-15).
@@ -323,7 +324,7 @@ func (a *api) streamError(w http.ResponseWriter, out *sse, err error) {
} else if r := err.Error(); r != "" && !strings.Contains(r, "context canceled") {
a.log.Warn("ai stream failed", "err", err)
}
- out.send("error", map[string]string{"message": msg})
+ out.send("error", map[string]string{"message": i18n.Translate(responseLang(w), msg)})
}
// mcpRoute serves the MCP endpoint. Its clients send API tokens (or
diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go
index fc6f948..0a42a19 100644
--- a/Server/internal/httpapi/auth.go
+++ b/Server/internal/httpapi/auth.go
@@ -9,14 +9,17 @@ import (
"log/slog"
"net/http"
"strings"
+ "sync"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/auth"
+ "docwell/server/internal/i18n"
)
// AuthService is the part of auth.Service the HTTP layer uses.
type AuthService interface {
+ SetLocale(ctx context.Context, userID, lang string) error
Methods(ctx context.Context) (auth.Methods, error)
Signup(ctx context.Context, in auth.SignupInput) (auth.Session, error)
Login(ctx context.Context, email, password, mfaID string) (auth.Session, error)
@@ -76,6 +79,8 @@ type api struct {
// wsIntegrations: GitHub, Linear, Figma and Slack per workspace.
wsIntegrations WorkspaceIntegrations
log *slog.Logger
+ // locales remembers which language was last stored per user (lang.go).
+ locales sync.Map
}
// requireUser lets in a signed-in user, or an API token acting as its owner
@@ -101,6 +106,7 @@ func (a *api) requireUser(next http.HandlerFunc) http.HandlerFunc {
return
}
r = r.WithContext(context.WithValue(ctx, ctxKey{}, u))
+ a.rememberLocale(r, u)
if r.Method == http.MethodGet || r.Method == http.MethodHead || a.audit == nil || unaudited[r.Pattern] {
next(w, r)
return
@@ -275,9 +281,14 @@ func (a *api) writeError(w http.ResponseWriter, err error) {
apperr.KindNotFound: http.StatusNotFound,
apperr.KindConflict: http.StatusConflict,
}[e.Kind]
- body := map[string]any{"error": e.Code, "message": e.Message}
+ lang := responseLang(w)
+ body := map[string]any{"error": e.Code, "message": i18n.Translate(lang, e.Message)}
if len(e.Fields) > 0 {
- body["fields"] = e.Fields
+ fields := make(map[string]string, len(e.Fields))
+ for k, v := range e.Fields {
+ fields[k] = i18n.Translate(lang, v)
+ }
+ body["fields"] = fields
}
writeJSON(w, status, body)
return
diff --git a/Server/internal/httpapi/lang.go b/Server/internal/httpapi/lang.go
new file mode 100644
index 0000000..f03d429
--- /dev/null
+++ b/Server/internal/httpapi/lang.go
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package httpapi
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "docwell/server/internal/auth"
+ "docwell/server/internal/i18n"
+)
+
+// Languages: the apps send the language they show in Accept-Language. Each
+// response says its language in Content-Language, error messages are
+// translated into it (writeError), and the request's context carries it for
+// text written while handling it (invite emails). A signed-in person's last
+// language is stored for the emails and notifications they get later.
+
+// withLang sets a request's language on its context and response.
+func withLang(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ lang := i18n.Match(r.Header.Get("Accept-Language"))
+ w.Header().Set("Content-Language", lang)
+ next.ServeHTTP(w, r.WithContext(i18n.WithLang(r.Context(), lang)))
+ })
+}
+
+// responseLang is the language withLang chose for a response.
+func responseLang(w http.ResponseWriter) string {
+ if l := w.Header().Get("Content-Language"); i18n.IsSupported(l) {
+ return l
+ }
+ return i18n.Default
+}
+
+// rememberLocale stores the language a signed-in person uses when it
+// changed (in the background; once per user and language per process).
+func (a *api) rememberLocale(r *http.Request, u auth.User) {
+ lang, ok := i18n.MatchOK(r.Header.Get("Accept-Language"))
+ if !ok || u.ID == "" || lang == u.Locale {
+ return
+ }
+ if prev, seen := a.locales.Load(u.ID); seen && prev == lang {
+ return
+ }
+ a.locales.Store(u.ID, lang)
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := a.auth.SetLocale(ctx, u.ID, lang); err != nil {
+ a.locales.Delete(u.ID)
+ a.log.Warn("remember locale", "user", u.ID, "err", err)
+ }
+ }()
+}
diff --git a/Server/internal/httpapi/router.go b/Server/internal/httpapi/router.go
index 2be98e7..d266c7d 100644
--- a/Server/internal/httpapi/router.go
+++ b/Server/internal/httpapi/router.go
@@ -65,7 +65,7 @@ type routeMux struct {
func (m *routeMux) Handle(pattern string, h http.Handler) {
m.patterns = append(m.patterns, pattern)
- m.ServeMux.Handle(pattern, h)
+ m.ServeMux.Handle(pattern, withLang(h))
}
func (m *routeMux) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request)) {
diff --git a/Server/internal/httpapi/spaces.go b/Server/internal/httpapi/spaces.go
index 833543e..eea2360 100644
--- a/Server/internal/httpapi/spaces.go
+++ b/Server/internal/httpapi/spaces.go
@@ -42,6 +42,8 @@ type SpaceService interface {
ListArchive(ctx context.Context, c access.Caller, spaceID string) ([]directory.ArchivedPage, error)
PinPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
UnpinPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
+ VerifyPage(ctx context.Context, c access.Caller, id string, days int) (directory.Page, error)
+ UnverifyPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
ListPinned(ctx context.Context, c access.Caller, spaceID string) ([]directory.PinnedPage, error)
}
@@ -123,6 +125,20 @@ func (a *api) spaceRoutes(mux *routeMux) {
p, err := a.dir.UnpinPage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, err)
}))
+ mux.HandleFunc("PUT /api/v1/pages/{id}/verify", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ var in struct {
+ Days int `json:"days"`
+ }
+ if !a.decode(w, r, &in) {
+ return
+ }
+ p, err := a.dir.VerifyPage(r.Context(), caller(r), r.PathValue("id"), in.Days)
+ a.respond(w, p, err)
+ }))
+ mux.HandleFunc("DELETE /api/v1/pages/{id}/verify", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ p, err := a.dir.UnverifyPage(r.Context(), caller(r), r.PathValue("id"))
+ a.respond(w, p, err)
+ }))
mux.HandleFunc("GET /api/v1/pages/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
p, err := a.dir.GetPage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, err)
diff --git a/Server/internal/i18n/catalog/de.json b/Server/internal/i18n/catalog/de.json
new file mode 100644
index 0000000..fe53e0b
--- /dev/null
+++ b/Server/internal/i18n/catalog/de.json
@@ -0,0 +1,262 @@
+{
+ "%q is not a domain.": "%q ist keine Domain.",
+ "%s asks to join “%s”": "%s möchte „%s“ beitreten",
+ "%s commented": "%s hat kommentiert",
+ "%s commented on “%s”": "%s hat „%s“ kommentiert",
+ "%s mentioned you": "%s hat dich erwähnt",
+ "%s mentioned you in “%s”": "%s hat dich in „%s“ erwähnt",
+ "%s replied": "%s hat geantwortet",
+ "%s replied in “%s”": "%s hat in „%s“ geantwortet",
+ "%s resolved a thread": "%s hat einen Thread erledigt",
+ "%s resolved a thread in “%s”": "%s hat einen Thread in „%s“ erledigt",
+ "%s shared this page with you": "%s hat diese Seite mit dir geteilt",
+ "%s shared “%s”": "%s hat „%s“ geteilt",
+ "A page can have at most 100 tags.": "Eine Seite kann höchstens 100 Tags haben.",
+ "A page cannot be moved inside itself.": "Eine Seite kann nicht in sich selbst verschoben werden.",
+ "A valid email is required.": "Eine gültige E-Mail-Adresse ist erforderlich.",
+ "AI is not available on this server": "KI ist auf diesem Server nicht verfügbar",
+ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "KI ist für diesen Arbeitsbereich nicht eingerichtet: Ein Admin muss in den Einstellungen des Arbeitsbereichs einen Anbieter hinzufügen.",
+ "AI is turned off in this workspace": "KI ist in diesem Arbeitsbereich ausgeschaltet",
+ "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Füge Text-, Markdown-, HTML-, Word- (.docx) oder PDF-Dateien hinzu.",
+ "Ask a question of up to 8 000 characters.": "Stelle eine Frage mit bis zu 8 000 Zeichen.",
+ "Ask for at most %d days, ending after they start.": "Wähle höchstens %d Tage, mit dem Ende nach dem Anfang.",
+ "At most 200 options.": "Höchstens 200 Optionen.",
+ "At most 2000 pages.": "Höchstens 2000 Seiten.",
+ "At most 50 rules.": "Höchstens 50 Regeln.",
+ "Bucket and endpoint are required for S3.": "Für S3 sind Bucket und Endpunkt erforderlich.",
+ "Choose a file.": "Wähle eine Datei.",
+ "Choose a language.": "Wähle eine Sprache.",
+ "Choose a notebook.": "Wähle ein Notizbuch.",
+ "Choose a space you can add pages to.": "Wähle einen Bereich, in dem du Seiten anlegen darfst.",
+ "Choose at least one file.": "Wähle mindestens eine Datei.",
+ "Choose digest or off.": "Wähle Zusammenfassung oder aus.",
+ "Choose the space highlights go to.": "Wähle den Bereich für die Markierungen.",
+ "Choose the space to import into.": "Wähle den Bereich, in den importiert wird.",
+ "Collection name is required.": "Ein Name für die Sammlung ist erforderlich.",
+ "Connect the bot token and choose a channel first.": "Verbinde zuerst das Bot-Token und wähle einen Kanal.",
+ "Connect the bot token first.": "Verbinde zuerst das Bot-Token.",
+ "Content must be a Tiptap document.": "Der Inhalt muss ein Tiptap-Dokument sein.",
+ "Dates look like 2026-11-14.": "Daten sehen so aus: 2026-11-14.",
+ "Dates look like 2026-11-16.": "Daten sehen so aus: 2026-11-16.",
+ "Dates must look like 2026-11-02 or 2026-11-02T15:04:05Z.": "Daten müssen so aussehen: 2026-11-02 oder 2026-11-02T15:04:05Z.",
+ "Default role must be editor, commenter or viewer.": "Die Standardrolle muss Bearbeiter, Kommentator oder Betrachter sein.",
+ "Description is too long (max 500).": "Die Beschreibung ist zu lang (max. 500).",
+ "Each option needs a name of at most 60 characters.": "Jede Option braucht einen Namen mit höchstens 60 Zeichen.",
+ "Endpoint must be an http(s) address.": "Der Endpunkt muss eine http(s)-Adresse sein.",
+ "Enter a web address (http or https).": "Gib eine Webadresse ein (http oder https).",
+ "Files can be up to 10 MB.": "Dateien dürfen bis zu 10 MB groß sein.",
+ "Font must be empty, serif or mono.": "Die Schrift muss leer, serif oder mono sein.",
+ "Format must be markdown or html.": "Das Format muss markdown oder html sein.",
+ "Format must be markdown, html, pdf or docx.": "Das Format muss markdown, html, pdf oder docx sein.",
+ "Google sign-in is not set up on this server": "Die Anmeldung mit Google ist auf diesem Server nicht eingerichtet",
+ "Icon is too long.": "Das Symbol ist zu lang.",
+ "Import at most %d pages at once.": "Importiere höchstens %d Seiten auf einmal.",
+ "Invalid option id.": "Ungültige Options-ID.",
+ "Invalid page id.": "Ungültige Seiten-ID.",
+ "Microsoft sign-in is not set up on this server": "Die Anmeldung mit Microsoft ist auf diesem Server nicht eingerichtet",
+ "Mode must be page or edgeless.": "Der Modus muss page oder edgeless sein.",
+ "Name and type are required.": "Name und Typ sind erforderlich.",
+ "Name is required.": "Ein Name ist erforderlich.",
+ "Name is too long (max 60).": "Der Name ist zu lang (max. 60).",
+ "Name is too long (max 80).": "Der Name ist zu lang (max. 80).",
+ "Name, kind and address are required.": "Name, Art und Adresse sind erforderlich.",
+ "No AI provider here can transcribe audio: a workspace admin can add a speech-to-text model to an OpenAI-compatible provider.": "Kein KI-Anbieter hier kann Audio verschriftlichen: Ein Admin des Arbeitsbereichs kann einem OpenAI-kompatiblen Anbieter ein Sprache-zu-Text-Modell hinzufügen.",
+ "No mail server is configured.": "Es ist kein Mailserver eingerichtet.",
+ "No speech was found in the recording.": "In der Aufnahme wurde keine Sprache gefunden.",
+ "Only audio and video files can be transcribed.": "Nur Audio- und Videodateien können verschriftlicht werden.",
+ "Parent page not found in this space.": "Die übergeordnete Seite wurde in diesem Bereich nicht gefunden.",
+ "Password must be at least 8 characters.": "Das Passwort muss mindestens 8 Zeichen lang sein.",
+ "Paste the app's Bot User OAuth Token (it starts with xoxb-).": "Füge das Bot User OAuth Token der App ein (es beginnt mit xoxb-).",
+ "Paste the app's Signing Secret (Basic Information → App Credentials).": "Füge das Signing Secret der App ein (Basic Information → App Credentials).",
+ "Paste your Readwise access token.": "Füge dein Readwise-Zugriffstoken ein.",
+ "Pick 1 to 365 days, or 0 for no end.": "Wähle 1 bis 365 Tage oder 0 für kein Ende.",
+ "Pick 7 to 90 days.": "Wähle 7 bis 90 Tage.",
+ "Pick a range of at most a year.": "Wähle einen Zeitraum von höchstens einem Jahr.",
+ "Pick an emoji.": "Wähle ein Emoji.",
+ "Pick another tag of this workspace.": "Wähle ein anderes Tag dieses Arbeitsbereichs.",
+ "Position must be a number.": "Die Position muss eine Zahl sein.",
+ "Readwise is not connected": "Readwise ist nicht verbunden",
+ "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Aufnahmen über 25 MB müssen mit ffmpeg zerteilt werden: Starte den Dienst docwell-media (DOCWELL_MEDIA_URL) oder installiere ffmpeg auf dem Server. MP3- und WAV-Dateien gehen auch ohne.",
+ "Recordings up to 1 GB can be transcribed.": "Aufnahmen bis 1 GB können verschriftlicht werden.",
+ "Reminder": "Erinnerung",
+ "Reminder in “%s”": "Erinnerung in „%s“",
+ "Role must be member or guest.": "Die Rolle muss Mitglied oder Gast sein.",
+ "Role must be user, admin or superadmin.": "Die Rolle muss Benutzer, Admin oder Superadmin sein.",
+ "Say what to do, in up to 2 000 characters.": "Sag, was zu tun ist, in bis zu 2 000 Zeichen.",
+ "Scope must be workspace, space or page.": "Der Umfang muss Arbeitsbereich, Bereich oder Seite sein.",
+ "Select at most 20 000 characters.": "Markiere höchstens 20 000 Zeichen.",
+ "Select some text first.": "Markiere zuerst etwas Text.",
+ "Someone": "Jemand",
+ "Something went wrong.": "Etwas ist schiefgelaufen.",
+ "Status must be active, disabled or invited.": "Der Status muss aktiv, deaktiviert oder eingeladen sein.",
+ "Template not found.": "Vorlage nicht gefunden.",
+ "That message is not in this chat.": "Diese Nachricht ist nicht in diesem Chat.",
+ "That page is not in this workspace.": "Diese Seite ist nicht in diesem Arbeitsbereich.",
+ "That space is not in this workspace.": "Dieser Bereich ist nicht in diesem Arbeitsbereich.",
+ "That thread is not on this page.": "Dieser Thread ist nicht auf dieser Seite.",
+ "The HTML file could not be read.": "Die HTML-Datei konnte nicht gelesen werden.",
+ "The MP3 file could not be read.": "Die MP3-Datei konnte nicht gelesen werden.",
+ "The Markdown could not be read.": "Das Markdown konnte nicht gelesen werden.",
+ "The PDF could not be read.": "Das PDF konnte nicht gelesen werden.",
+ "The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.": "Das PDF hat keine Textebene (gescannte Seiten). Um es zu lesen, füge einen Anthropic- oder OpenAI-Anbieter hinzu, dessen Modell PDF-Dateien liest.",
+ "The PDF has no text layer.": "Das PDF hat keine Textebene.",
+ "The WAV file could not be read.": "Die WAV-Datei konnte nicht gelesen werden.",
+ "The Word document could not be read.": "Das Word-Dokument konnte nicht gelesen werden.",
+ "The anchor is too large.": "Der Anker ist zu groß.",
+ "The comment is too long (max 5000).": "Der Kommentar ist zu lang (max. 5000).",
+ "The file has no text.": "Die Datei enthält keinen Text.",
+ "The file is larger than %d MB.": "Die Datei ist größer als %d MB.",
+ "The file is not UTF-8 text.": "Die Datei ist kein UTF-8-Text.",
+ "The file needs a name of up to 200 characters.": "Die Datei braucht einen Namen mit bis zu 200 Zeichen.",
+ "The filter is not valid JSON.": "Der Filter ist kein gültiges JSON.",
+ "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Der Mediendienst, der lange Aufnahmen zerteilt, ist nicht erreichbar. Versuche es später erneut oder frage einen Administrator.",
+ "The page is too large to save.": "Die Seite ist zu groß zum Speichern.",
+ "The recording has no sound to transcribe.": "Die Aufnahme hat keinen Ton zum Verschriftlichen.",
+ "The recording is larger than the media service accepts.": "Die Aufnahme ist größer, als der Mediendienst annimmt.",
+ "The token is too long.": "Das Token ist zu lang.",
+ "This chat is full; start a new one or fork it.": "Dieser Chat ist voll; starte einen neuen oder verzweige ihn.",
+ "This list has as many profiles as allowed.": "Diese Liste hat schon so viele Profile wie erlaubt.",
+ "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Dieser Arbeitsbereich hat seine KI-Tokens für diesen Monat aufgebraucht; ein Admin kann das Limit erhöhen.",
+ "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Dieser Arbeitsbereich hat seinen Anteil an der KI des Servers für diesen Monat aufgebraucht; füge einen eigenen Anbieter hinzu oder frage den Admin des Servers.",
+ "Title is too long (max 500).": "Der Titel ist zu lang (max. 500).",
+ "Unarchive the parent page first.": "Hole zuerst die übergeordnete Seite aus dem Archiv.",
+ "Unknown colour.": "Unbekannte Farbe.",
+ "Unknown option colour.": "Unbekannte Optionsfarbe.",
+ "Unknown property type.": "Unbekannter Eigenschaftstyp.",
+ "Unknown tag.": "Unbekanntes Tag.",
+ "Unknown time zone.": "Unbekannte Zeitzone.",
+ "Unknown writing action.": "Unbekannte Schreibaktion.",
+ "Untitled": "Ohne Titel",
+ "Use 0 for no limit, or a positive number.": "Nutze 0 für kein Limit oder eine positive Zahl.",
+ "Visibility must be always, hide_empty or never.": "Die Sichtbarkeit muss always, hide_empty oder never sein.",
+ "Visibility must be open or private.": "Die Sichtbarkeit muss offen oder privat sein.",
+ "Write something first.": "Schreib zuerst etwas.",
+ "You can now open “%s”": "Du kannst „%s“ jetzt öffnen",
+ "You have as many chats as allowed here; delete some first.": "Du hast hier schon so viele Chats wie erlaubt; lösche zuerst einige.",
+ "Your request to join “%s” was declined": "Deine Anfrage, „%s“ beizutreten, wurde abgelehnt",
+ "Your verification of this page ran out": "Deine Verifizierung dieser Seite ist abgelaufen",
+ "Your verification of “%s” ran out": "Deine Verifizierung von „%s“ ist abgelaufen",
+ "a group with this name already exists": "eine Gruppe mit diesem Namen gibt es schon",
+ "a space can have at most 12 pinned pages; unpin one first": "ein Bereich kann höchstens 12 angeheftete Seiten haben; löse zuerst eine",
+ "a superadmin account cannot join an organization": "ein Superadmin-Konto kann keiner Organisation beitreten",
+ "a tag with this name already exists": "ein Tag mit diesem Namen gibt es schon",
+ "a workspace can have at most 100 properties": "ein Arbeitsbereich kann höchstens 100 Eigenschaften haben",
+ "a workspace can have up to 20 webhooks": "ein Arbeitsbereich kann bis zu 20 Webhooks haben",
+ "admin role required": "Admin-Rolle erforderlich",
+ "an account with this email already exists; sign in to accept the invite": "ein Konto mit dieser E-Mail-Adresse gibt es schon; melde dich an, um die Einladung anzunehmen",
+ "an organization with this name already exists": "eine Organisation mit diesem Namen gibt es schon",
+ "attachment not found": "Anhang nicht gefunden",
+ "backup not found": "Sicherung nicht gefunden",
+ "calendar not found": "Kalender nicht gefunden",
+ "calendars are not available on this server": "Kalender sind auf diesem Server nicht verfügbar",
+ "chat not found": "Chat nicht gefunden",
+ "collection not found": "Sammlung nicht gefunden",
+ "comment not found": "Kommentar nicht gefunden",
+ "commenter role required": "Kommentator-Rolle erforderlich",
+ "could not find a free address for the journal space": "für den Journal-Bereich wurde keine freie Adresse gefunden",
+ "could not find a free space address; try another name": "keine freie Bereichsadresse gefunden; versuche einen anderen Namen",
+ "could not find a free workspace address; try another name": "keine freie Adresse für den Arbeitsbereich gefunden; versuche einen anderen Namen",
+ "days must be between 0 and %d": "die Tage müssen zwischen 0 und %d liegen",
+ "device not found": "Gerät nicht gefunden",
+ "editor role required": "Bearbeiter-Rolle erforderlich",
+ "file not found": "Datei nicht gefunden",
+ "give a space, or a workspace for its recent pages": "gib einen Bereich an, oder einen Arbeitsbereich für dessen letzte Seiten",
+ "grant not found": "Freigabe nicht gefunden",
+ "group not found": "Gruppe nicht gefunden",
+ "guests cannot change the workspace's properties, tags or collections": "Gäste können Eigenschaften, Tags und Sammlungen des Arbeitsbereichs nicht ändern",
+ "guests cannot invite people": "Gäste können niemanden einladen",
+ "import not found": "Import nicht gefunden",
+ "integrations are off on this server": "Integrationen sind auf diesem Server ausgeschaltet",
+ "invalid organization id": "ungültige Organisations-ID",
+ "invite not found": "Einladung nicht gefunden",
+ "link previews are off": "Linkvorschauen sind ausgeschaltet",
+ "match must be all or any.": "match muss all oder any sein.",
+ "member not found": "Mitglied nicht gefunden",
+ "move the page to the trash first": "verschiebe die Seite zuerst in den Papierkorb",
+ "no changes provided": "keine Änderungen angegeben",
+ "no job can be started with that name": "unter diesem Namen lässt sich kein Auftrag starten",
+ "no preview": "keine Vorschau",
+ "no user with that email": "kein Benutzer mit dieser E-Mail-Adresse",
+ "not found": "nicht gefunden",
+ "notification not found": "Benachrichtigung nicht gefunden",
+ "only a superadmin can create superadmins": "nur ein Superadmin kann Superadmins anlegen",
+ "only a superadmin can grant the superadmin role": "nur ein Superadmin kann die Superadmin-Rolle vergeben",
+ "only a thread's first comment can be resolved": "nur der erste Kommentar eines Threads kann erledigt werden",
+ "only organization admins can create workspaces": "nur Admins der Organisation können Arbeitsbereiche anlegen",
+ "only people with access to the whole space can add top-level pages": "nur wer Zugriff auf den ganzen Bereich hat, kann Seiten auf oberster Ebene anlegen",
+ "only superadmins manage the instance's AI profiles": "nur Superadmins verwalten die KI-Profile der Instanz",
+ "only the author can edit this comment": "nur der Autor kann diesen Kommentar bearbeiten",
+ "only the author or a space admin can delete this comment": "nur der Autor oder ein Admin des Bereichs kann diesen Kommentar löschen",
+ "only the collection's creator can change it": "nur wer die Sammlung angelegt hat, kann sie ändern",
+ "only the collection's creator can change who sees it": "nur wer die Sammlung angelegt hat, kann ändern, wer sie sieht",
+ "only the page's editors can see its views": "nur die Bearbeiter der Seite sehen ihre Aufrufe",
+ "organization is required": "eine Organisation ist erforderlich",
+ "organization not found": "Organisation nicht gefunden",
+ "organization still has members; move or remove them first": "die Organisation hat noch Mitglieder; verschiebe oder entferne sie zuerst",
+ "organization still has other members; move or remove them first": "die Organisation hat noch andere Mitglieder; verschiebe oder entferne sie zuerst",
+ "organization still has workspaces; delete them first": "die Organisation hat noch Arbeitsbereiche; lösche sie zuerst",
+ "page not found": "Seite nicht gefunden",
+ "profile not found": "Profil nicht gefunden",
+ "property not found": "Eigenschaft nicht gefunden",
+ "public links are turned off in this workspace": "öffentliche Links sind in diesem Arbeitsbereich ausgeschaltet",
+ "push notifications are off on this server": "Push-Benachrichtigungen sind auf diesem Server ausgeschaltet",
+ "request not found": "Anfrage nicht gefunden",
+ "restore the page from the trash first": "stelle die Seite zuerst aus dem Papierkorb wieder her",
+ "role must be admin, editor, commenter or viewer": "die Rolle muss Admin, Bearbeiter, Kommentator oder Betrachter sein",
+ "role must be editor, commenter or viewer": "die Rolle muss Bearbeiter, Kommentator oder Betrachter sein",
+ "role must be owner, admin, member or guest": "die Rolle muss Inhaber, Admin, Mitglied oder Gast sein",
+ "sign in to do this; API tokens cannot": "melde dich dafür an; API-Tokens können das nicht",
+ "space admin role required": "Admin-Rolle im Bereich erforderlich",
+ "space not found": "Bereich nicht gefunden",
+ "superadmin role required": "Superadmin-Rolle erforderlich",
+ "tag not found": "Tag nicht gefunden",
+ "that person already has an account here": "diese Person hat hier schon ein Konto",
+ "that person is a superadmin and already has access everywhere": "diese Person ist Superadmin und hat schon überall Zugriff",
+ "that person's account belongs to another organization": "das Konto dieser Person gehört zu einer anderen Organisation",
+ "that user is not a member of this workspace": "dieser Benutzer ist kein Mitglied dieses Arbeitsbereichs",
+ "that user is not in this workspace's organization": "dieser Benutzer ist nicht in der Organisation dieses Arbeitsbereichs",
+ "the Microsoft sign-in has expired; connect again": "die Microsoft-Anmeldung ist abgelaufen; verbinde dich erneut",
+ "the account is disabled": "das Konto ist deaktiviert",
+ "the job is already running": "der Auftrag läuft bereits",
+ "the page is in another workspace": "die Seite ist in einem anderen Arbeitsbereich",
+ "the workspace has more than %d %s": "der Arbeitsbereich hat mehr als %d Einträge (%s)",
+ "this API token can only read": "dieses API-Token darf nur lesen",
+ "this comment has as many different reactions as it can take": "dieser Kommentar hat schon so viele verschiedene Reaktionen wie möglich",
+ "this integration is not available on this server": "diese Integration ist auf diesem Server nicht verfügbar",
+ "this link does not exist or was turned off": "dieser Link existiert nicht oder wurde ausgeschaltet",
+ "too many files": "zu viele Dateien",
+ "too many notifications at once": "zu viele Benachrichtigungen auf einmal",
+ "trashed and archived pages cannot be pinned": "Seiten im Papierkorb oder Archiv können nicht angeheftet werden",
+ "trashed and archived pages cannot be verified": "Seiten im Papierkorb oder Archiv können nicht verifiziert werden",
+ "unarchive the page first": "hole die Seite zuerst aus dem Archiv",
+ "unknown service": "unbekannter Dienst",
+ "unknown tool": "unbekanntes Werkzeug",
+ "user is outside your organization": "der Benutzer ist nicht in deiner Organisation",
+ "user not found": "Benutzer nicht gefunden",
+ "validation failed": "Eingaben ungültig",
+ "version not found": "Version nicht gefunden",
+ "webhook not found": "Webhook nicht gefunden",
+ "webhooks are turned off on this server": "Webhooks sind auf diesem Server ausgeschaltet",
+ "workspace admin role required": "Admin-Rolle im Arbeitsbereich erforderlich",
+ "workspace admins already manage every page": "Admins des Arbeitsbereichs verwalten schon jede Seite",
+ "workspace admins already manage every space": "Admins des Arbeitsbereichs verwalten schon jeden Bereich",
+ "workspace member role required": "Mitgliedsrolle im Arbeitsbereich erforderlich",
+ "workspace not found": "Arbeitsbereich nicht gefunden",
+ "workspace owner role required": "Inhaber-Rolle im Arbeitsbereich erforderlich",
+ "you already belong to an organization": "du gehörst schon zu einer Organisation",
+ "you can add at most %d calendars": "du kannst höchstens %d Kalender hinzufügen",
+ "you can only create workspaces in your own organization": "du kannst Arbeitsbereiche nur in deiner eigenen Organisation anlegen",
+ "you can only delete your own organization": "du kannst nur deine eigene Organisation löschen",
+ "you can only rename your own organization": "du kannst nur deine eigene Organisation umbenennen",
+ "you cannot change a member ranked above you": "du kannst kein Mitglied ändern, das über dir steht",
+ "you cannot change your own role": "du kannst deine eigene Rolle nicht ändern",
+ "you cannot delete your own account": "du kannst dein eigenes Konto nicht löschen",
+ "you cannot disable your own account": "du kannst dein eigenes Konto nicht deaktivieren",
+ "you cannot grant a role above your own": "du kannst keine Rolle über deiner eigenen vergeben",
+ "you cannot manage a superadmin": "du kannst keinen Superadmin verwalten",
+ "you cannot manage this invite": "du kannst diese Einladung nicht verwalten",
+ "you cannot move users to another organization": "du kannst Benutzer nicht in eine andere Organisation verschieben",
+ "you cannot remove a member ranked above you": "du kannst kein Mitglied entfernen, das über dir steht",
+ "your account already belongs to another organization": "dein Konto gehört schon zu einer anderen Organisation",
+ "your account is not attached to an organization": "dein Konto gehört zu keiner Organisation"
+}
diff --git a/Server/internal/i18n/catalog/es.json b/Server/internal/i18n/catalog/es.json
new file mode 100644
index 0000000..f409a44
--- /dev/null
+++ b/Server/internal/i18n/catalog/es.json
@@ -0,0 +1,262 @@
+{
+ "%q is not a domain.": "%q no es un dominio.",
+ "%s asks to join “%s”": "%s pide unirse a «%s»",
+ "%s commented": "%s comentó",
+ "%s commented on “%s”": "%s comentó en «%s»",
+ "%s mentioned you": "%s te mencionó",
+ "%s mentioned you in “%s”": "%s te mencionó en «%s»",
+ "%s replied": "%s respondió",
+ "%s replied in “%s”": "%s respondió en «%s»",
+ "%s resolved a thread": "%s resolvió un hilo",
+ "%s resolved a thread in “%s”": "%s resolvió un hilo en «%s»",
+ "%s shared this page with you": "%s compartió esta página contigo",
+ "%s shared “%s”": "%s compartió «%s»",
+ "A page can have at most 100 tags.": "Una página puede tener como máximo 100 etiquetas.",
+ "A page cannot be moved inside itself.": "Una página no se puede mover dentro de sí misma.",
+ "A valid email is required.": "Se necesita un correo electrónico válido.",
+ "AI is not available on this server": "La IA no está disponible en este servidor",
+ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "La IA no está configurada en este espacio de trabajo: un administrador debe añadir un proveedor en su configuración.",
+ "AI is turned off in this workspace": "La IA está desactivada en este espacio de trabajo",
+ "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Añade archivos de texto, Markdown, HTML, Word (.docx) o PDF.",
+ "Ask a question of up to 8 000 characters.": "Haz una pregunta de hasta 8000 caracteres.",
+ "Ask for at most %d days, ending after they start.": "Pide como máximo %d días, con el final después del inicio.",
+ "At most 200 options.": "Como máximo 200 opciones.",
+ "At most 2000 pages.": "Como máximo 2000 páginas.",
+ "At most 50 rules.": "Como máximo 50 reglas.",
+ "Bucket and endpoint are required for S3.": "Para S3 se necesitan el bucket y el endpoint.",
+ "Choose a file.": "Elige un archivo.",
+ "Choose a language.": "Elige un idioma.",
+ "Choose a notebook.": "Elige un bloc de notas.",
+ "Choose a space you can add pages to.": "Elige un espacio en el que puedas añadir páginas.",
+ "Choose at least one file.": "Elige al menos un archivo.",
+ "Choose digest or off.": "Elige resumen o desactivado.",
+ "Choose the space highlights go to.": "Elige el espacio al que van los subrayados.",
+ "Choose the space to import into.": "Elige el espacio al que importar.",
+ "Collection name is required.": "La colección necesita un nombre.",
+ "Connect the bot token and choose a channel first.": "Primero conecta el token del bot y elige un canal.",
+ "Connect the bot token first.": "Primero conecta el token del bot.",
+ "Content must be a Tiptap document.": "El contenido debe ser un documento Tiptap.",
+ "Dates look like 2026-11-14.": "Las fechas se escriben así: 2026-11-14.",
+ "Dates look like 2026-11-16.": "Las fechas se escriben así: 2026-11-16.",
+ "Dates must look like 2026-11-02 or 2026-11-02T15:04:05Z.": "Las fechas deben escribirse 2026-11-02 o 2026-11-02T15:04:05Z.",
+ "Default role must be editor, commenter or viewer.": "El rol predeterminado debe ser editor, comentarista o lector.",
+ "Description is too long (max 500).": "La descripción es demasiado larga (máx. 500).",
+ "Each option needs a name of at most 60 characters.": "Cada opción necesita un nombre de como máximo 60 caracteres.",
+ "Endpoint must be an http(s) address.": "El endpoint debe ser una dirección http(s).",
+ "Enter a web address (http or https).": "Escribe una dirección web (http o https).",
+ "Files can be up to 10 MB.": "Los archivos pueden ocupar hasta 10 MB.",
+ "Font must be empty, serif or mono.": "La fuente debe estar vacía o ser serif o mono.",
+ "Format must be markdown or html.": "El formato debe ser markdown o html.",
+ "Format must be markdown, html, pdf or docx.": "El formato debe ser markdown, html, pdf o docx.",
+ "Google sign-in is not set up on this server": "El inicio de sesión con Google no está configurado en este servidor",
+ "Icon is too long.": "El icono es demasiado largo.",
+ "Import at most %d pages at once.": "Importa como máximo %d páginas a la vez.",
+ "Invalid option id.": "Identificador de opción no válido.",
+ "Invalid page id.": "Identificador de página no válido.",
+ "Microsoft sign-in is not set up on this server": "El inicio de sesión con Microsoft no está configurado en este servidor",
+ "Mode must be page or edgeless.": "El modo debe ser page o edgeless.",
+ "Name and type are required.": "Se necesitan el nombre y el tipo.",
+ "Name is required.": "Se necesita un nombre.",
+ "Name is too long (max 60).": "El nombre es demasiado largo (máx. 60).",
+ "Name is too long (max 80).": "El nombre es demasiado largo (máx. 80).",
+ "Name, kind and address are required.": "Se necesitan el nombre, el tipo y la dirección.",
+ "No AI provider here can transcribe audio: a workspace admin can add a speech-to-text model to an OpenAI-compatible provider.": "Ningún proveedor de IA puede transcribir audio aquí: un administrador del espacio puede añadir un modelo de voz a texto a un proveedor compatible con OpenAI.",
+ "No mail server is configured.": "No hay ningún servidor de correo configurado.",
+ "No speech was found in the recording.": "No se encontró voz en la grabación.",
+ "Only audio and video files can be transcribed.": "Solo se pueden transcribir archivos de audio y vídeo.",
+ "Parent page not found in this space.": "No se encontró la página superior en este espacio.",
+ "Password must be at least 8 characters.": "La contraseña debe tener al menos 8 caracteres.",
+ "Paste the app's Bot User OAuth Token (it starts with xoxb-).": "Pega el Bot User OAuth Token de la aplicación (empieza por xoxb-).",
+ "Paste the app's Signing Secret (Basic Information → App Credentials).": "Pega el Signing Secret de la aplicación (Basic Information → App Credentials).",
+ "Paste your Readwise access token.": "Pega tu token de acceso de Readwise.",
+ "Pick 1 to 365 days, or 0 for no end.": "Elige de 1 a 365 días, o 0 para que no termine.",
+ "Pick 7 to 90 days.": "Elige de 7 a 90 días.",
+ "Pick a range of at most a year.": "Elige un periodo de como máximo un año.",
+ "Pick an emoji.": "Elige un emoji.",
+ "Pick another tag of this workspace.": "Elige otra etiqueta de este espacio de trabajo.",
+ "Position must be a number.": "La posición debe ser un número.",
+ "Readwise is not connected": "Readwise no está conectado",
+ "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Las grabaciones de más de 25 MB necesitan ffmpeg para cortarse: ejecuta el servicio docwell-media (DOCWELL_MEDIA_URL) o instala ffmpeg en el servidor. Los archivos MP3 y WAV funcionan sin él.",
+ "Recordings up to 1 GB can be transcribed.": "Se pueden transcribir grabaciones de hasta 1 GB.",
+ "Reminder": "Recordatorio",
+ "Reminder in “%s”": "Recordatorio en «%s»",
+ "Role must be member or guest.": "El rol debe ser miembro o invitado.",
+ "Role must be user, admin or superadmin.": "El rol debe ser usuario, administrador o superadministrador.",
+ "Say what to do, in up to 2 000 characters.": "Di qué hacer, en hasta 2000 caracteres.",
+ "Scope must be workspace, space or page.": "El ámbito debe ser espacio de trabajo, espacio o página.",
+ "Select at most 20 000 characters.": "Selecciona como máximo 20 000 caracteres.",
+ "Select some text first.": "Primero selecciona algo de texto.",
+ "Someone": "Alguien",
+ "Something went wrong.": "Algo salió mal.",
+ "Status must be active, disabled or invited.": "El estado debe ser activo, desactivado o invitado.",
+ "Template not found.": "No se encontró la plantilla.",
+ "That message is not in this chat.": "Ese mensaje no está en este chat.",
+ "That page is not in this workspace.": "Esa página no está en este espacio de trabajo.",
+ "That space is not in this workspace.": "Ese espacio no está en este espacio de trabajo.",
+ "That thread is not on this page.": "Ese hilo no está en esta página.",
+ "The HTML file could not be read.": "No se pudo leer el archivo HTML.",
+ "The MP3 file could not be read.": "No se pudo leer el archivo MP3.",
+ "The Markdown could not be read.": "No se pudo leer el Markdown.",
+ "The PDF could not be read.": "No se pudo leer el PDF.",
+ "The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.": "El PDF no tiene capa de texto (páginas escaneadas). Para leerlo, añade un proveedor de Anthropic u OpenAI cuyo modelo lea archivos PDF.",
+ "The PDF has no text layer.": "El PDF no tiene capa de texto.",
+ "The WAV file could not be read.": "No se pudo leer el archivo WAV.",
+ "The Word document could not be read.": "No se pudo leer el documento de Word.",
+ "The anchor is too large.": "El ancla es demasiado grande.",
+ "The comment is too long (max 5000).": "El comentario es demasiado largo (máx. 5000).",
+ "The file has no text.": "El archivo no tiene texto.",
+ "The file is larger than %d MB.": "El archivo ocupa más de %d MB.",
+ "The file is not UTF-8 text.": "El archivo no es texto UTF-8.",
+ "The file needs a name of up to 200 characters.": "El archivo necesita un nombre de hasta 200 caracteres.",
+ "The filter is not valid JSON.": "El filtro no es un JSON válido.",
+ "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "No se puede acceder al servicio que corta las grabaciones largas. Inténtalo más tarde o pregunta a un administrador.",
+ "The page is too large to save.": "La página es demasiado grande para guardarla.",
+ "The recording has no sound to transcribe.": "La grabación no tiene sonido que transcribir.",
+ "The recording is larger than the media service accepts.": "La grabación es más grande de lo que acepta el servicio multimedia.",
+ "The token is too long.": "El token es demasiado largo.",
+ "This chat is full; start a new one or fork it.": "Este chat está lleno; empieza uno nuevo o bifúrcalo.",
+ "This list has as many profiles as allowed.": "Esta lista ya tiene tantos perfiles como se permite.",
+ "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Este espacio de trabajo ha gastado sus tokens de IA de este mes; un administrador puede subir el límite.",
+ "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Este espacio de trabajo ha gastado su parte de la IA del servidor de este mes; añade un proveedor propio o pregunta al administrador del servidor.",
+ "Title is too long (max 500).": "El título es demasiado largo (máx. 500).",
+ "Unarchive the parent page first.": "Primero desarchiva la página superior.",
+ "Unknown colour.": "Color desconocido.",
+ "Unknown option colour.": "Color de opción desconocido.",
+ "Unknown property type.": "Tipo de propiedad desconocido.",
+ "Unknown tag.": "Etiqueta desconocida.",
+ "Unknown time zone.": "Zona horaria desconocida.",
+ "Unknown writing action.": "Acción de escritura desconocida.",
+ "Untitled": "Sin título",
+ "Use 0 for no limit, or a positive number.": "Usa 0 para no tener límite, o un número positivo.",
+ "Visibility must be always, hide_empty or never.": "La visibilidad debe ser always, hide_empty o never.",
+ "Visibility must be open or private.": "La visibilidad debe ser abierta o privada.",
+ "Write something first.": "Primero escribe algo.",
+ "You can now open “%s”": "Ya puedes abrir «%s»",
+ "You have as many chats as allowed here; delete some first.": "Ya tienes tantos chats como se permite aquí; borra alguno primero.",
+ "Your request to join “%s” was declined": "Tu solicitud para unirte a «%s» fue rechazada",
+ "Your verification of this page ran out": "Tu verificación de esta página ha caducado",
+ "Your verification of “%s” ran out": "Tu verificación de «%s» ha caducado",
+ "a group with this name already exists": "ya existe un grupo con este nombre",
+ "a space can have at most 12 pinned pages; unpin one first": "un espacio puede tener como máximo 12 páginas fijadas; desfija una primero",
+ "a superadmin account cannot join an organization": "una cuenta de superadministrador no puede unirse a una organización",
+ "a tag with this name already exists": "ya existe una etiqueta con este nombre",
+ "a workspace can have at most 100 properties": "un espacio de trabajo puede tener como máximo 100 propiedades",
+ "a workspace can have up to 20 webhooks": "un espacio de trabajo puede tener hasta 20 webhooks",
+ "admin role required": "se necesita el rol de administrador",
+ "an account with this email already exists; sign in to accept the invite": "ya existe una cuenta con este correo; inicia sesión para aceptar la invitación",
+ "an organization with this name already exists": "ya existe una organización con este nombre",
+ "attachment not found": "no se encontró el adjunto",
+ "backup not found": "no se encontró la copia de seguridad",
+ "calendar not found": "no se encontró el calendario",
+ "calendars are not available on this server": "los calendarios no están disponibles en este servidor",
+ "chat not found": "no se encontró el chat",
+ "collection not found": "no se encontró la colección",
+ "comment not found": "no se encontró el comentario",
+ "commenter role required": "se necesita el rol de comentarista",
+ "could not find a free address for the journal space": "no se encontró una dirección libre para el espacio del diario",
+ "could not find a free space address; try another name": "no se encontró una dirección de espacio libre; prueba otro nombre",
+ "could not find a free workspace address; try another name": "no se encontró una dirección de espacio de trabajo libre; prueba otro nombre",
+ "days must be between 0 and %d": "los días deben estar entre 0 y %d",
+ "device not found": "no se encontró el dispositivo",
+ "editor role required": "se necesita el rol de editor",
+ "file not found": "no se encontró el archivo",
+ "give a space, or a workspace for its recent pages": "indica un espacio, o un espacio de trabajo para sus páginas recientes",
+ "grant not found": "no se encontró el permiso",
+ "group not found": "no se encontró el grupo",
+ "guests cannot change the workspace's properties, tags or collections": "los invitados no pueden cambiar las propiedades, etiquetas ni colecciones del espacio de trabajo",
+ "guests cannot invite people": "los invitados no pueden invitar a nadie",
+ "import not found": "no se encontró la importación",
+ "integrations are off on this server": "las integraciones están desactivadas en este servidor",
+ "invalid organization id": "identificador de organización no válido",
+ "invite not found": "no se encontró la invitación",
+ "link previews are off": "las vistas previas de enlaces están desactivadas",
+ "match must be all or any.": "match debe ser all o any.",
+ "member not found": "no se encontró el miembro",
+ "move the page to the trash first": "primero mueve la página a la papelera",
+ "no changes provided": "no se indicó ningún cambio",
+ "no job can be started with that name": "no se puede iniciar ninguna tarea con ese nombre",
+ "no preview": "sin vista previa",
+ "no user with that email": "no hay ningún usuario con ese correo",
+ "not found": "no encontrado",
+ "notification not found": "no se encontró la notificación",
+ "only a superadmin can create superadmins": "solo un superadministrador puede crear superadministradores",
+ "only a superadmin can grant the superadmin role": "solo un superadministrador puede dar el rol de superadministrador",
+ "only a thread's first comment can be resolved": "solo se puede resolver el primer comentario de un hilo",
+ "only organization admins can create workspaces": "solo los administradores de la organización pueden crear espacios de trabajo",
+ "only people with access to the whole space can add top-level pages": "solo quien tiene acceso a todo el espacio puede añadir páginas de primer nivel",
+ "only superadmins manage the instance's AI profiles": "solo los superadministradores gestionan los perfiles de IA de la instancia",
+ "only the author can edit this comment": "solo el autor puede editar este comentario",
+ "only the author or a space admin can delete this comment": "solo el autor o un administrador del espacio puede borrar este comentario",
+ "only the collection's creator can change it": "solo quien creó la colección puede cambiarla",
+ "only the collection's creator can change who sees it": "solo quien creó la colección puede cambiar quién la ve",
+ "only the page's editors can see its views": "solo los editores de la página ven sus visitas",
+ "organization is required": "se necesita una organización",
+ "organization not found": "no se encontró la organización",
+ "organization still has members; move or remove them first": "la organización aún tiene miembros; muévelos o quítalos primero",
+ "organization still has other members; move or remove them first": "la organización aún tiene otros miembros; muévelos o quítalos primero",
+ "organization still has workspaces; delete them first": "la organización aún tiene espacios de trabajo; bórralos primero",
+ "page not found": "no se encontró la página",
+ "profile not found": "no se encontró el perfil",
+ "property not found": "no se encontró la propiedad",
+ "public links are turned off in this workspace": "los enlaces públicos están desactivados en este espacio de trabajo",
+ "push notifications are off on this server": "las notificaciones push están desactivadas en este servidor",
+ "request not found": "no se encontró la solicitud",
+ "restore the page from the trash first": "primero restaura la página de la papelera",
+ "role must be admin, editor, commenter or viewer": "el rol debe ser administrador, editor, comentarista o lector",
+ "role must be editor, commenter or viewer": "el rol debe ser editor, comentarista o lector",
+ "role must be owner, admin, member or guest": "el rol debe ser propietario, administrador, miembro o invitado",
+ "sign in to do this; API tokens cannot": "inicia sesión para hacer esto; los tokens de API no pueden",
+ "space admin role required": "se necesita el rol de administrador del espacio",
+ "space not found": "no se encontró el espacio",
+ "superadmin role required": "se necesita el rol de superadministrador",
+ "tag not found": "no se encontró la etiqueta",
+ "that person already has an account here": "esa persona ya tiene una cuenta aquí",
+ "that person is a superadmin and already has access everywhere": "esa persona es superadministradora y ya tiene acceso a todo",
+ "that person's account belongs to another organization": "la cuenta de esa persona pertenece a otra organización",
+ "that user is not a member of this workspace": "ese usuario no es miembro de este espacio de trabajo",
+ "that user is not in this workspace's organization": "ese usuario no está en la organización de este espacio de trabajo",
+ "the Microsoft sign-in has expired; connect again": "el inicio de sesión de Microsoft caducó; vuelve a conectar",
+ "the account is disabled": "la cuenta está desactivada",
+ "the job is already running": "la tarea ya está en marcha",
+ "the page is in another workspace": "la página está en otro espacio de trabajo",
+ "the workspace has more than %d %s": "el espacio de trabajo tiene más de %d registros (%s)",
+ "this API token can only read": "este token de API solo puede leer",
+ "this comment has as many different reactions as it can take": "este comentario ya tiene tantas reacciones distintas como admite",
+ "this integration is not available on this server": "esta integración no está disponible en este servidor",
+ "this link does not exist or was turned off": "este enlace no existe o se desactivó",
+ "too many files": "demasiados archivos",
+ "too many notifications at once": "demasiadas notificaciones a la vez",
+ "trashed and archived pages cannot be pinned": "las páginas en la papelera o archivadas no se pueden fijar",
+ "trashed and archived pages cannot be verified": "las páginas en la papelera o archivadas no se pueden verificar",
+ "unarchive the page first": "primero desarchiva la página",
+ "unknown service": "servicio desconocido",
+ "unknown tool": "herramienta desconocida",
+ "user is outside your organization": "el usuario está fuera de tu organización",
+ "user not found": "no se encontró el usuario",
+ "validation failed": "los datos no son válidos",
+ "version not found": "no se encontró la versión",
+ "webhook not found": "no se encontró el webhook",
+ "webhooks are turned off on this server": "los webhooks están desactivados en este servidor",
+ "workspace admin role required": "se necesita el rol de administrador del espacio de trabajo",
+ "workspace admins already manage every page": "los administradores del espacio de trabajo ya gestionan todas las páginas",
+ "workspace admins already manage every space": "los administradores del espacio de trabajo ya gestionan todos los espacios",
+ "workspace member role required": "se necesita el rol de miembro del espacio de trabajo",
+ "workspace not found": "no se encontró el espacio de trabajo",
+ "workspace owner role required": "se necesita el rol de propietario del espacio de trabajo",
+ "you already belong to an organization": "ya perteneces a una organización",
+ "you can add at most %d calendars": "puedes añadir como máximo %d calendarios",
+ "you can only create workspaces in your own organization": "solo puedes crear espacios de trabajo en tu propia organización",
+ "you can only delete your own organization": "solo puedes borrar tu propia organización",
+ "you can only rename your own organization": "solo puedes cambiar el nombre de tu propia organización",
+ "you cannot change a member ranked above you": "no puedes cambiar a un miembro de rango superior",
+ "you cannot change your own role": "no puedes cambiar tu propio rol",
+ "you cannot delete your own account": "no puedes borrar tu propia cuenta",
+ "you cannot disable your own account": "no puedes desactivar tu propia cuenta",
+ "you cannot grant a role above your own": "no puedes dar un rol superior al tuyo",
+ "you cannot manage a superadmin": "no puedes gestionar a un superadministrador",
+ "you cannot manage this invite": "no puedes gestionar esta invitación",
+ "you cannot move users to another organization": "no puedes mover usuarios a otra organización",
+ "you cannot remove a member ranked above you": "no puedes quitar a un miembro de rango superior",
+ "your account already belongs to another organization": "tu cuenta ya pertenece a otra organización",
+ "your account is not attached to an organization": "tu cuenta no está vinculada a ninguna organización"
+}
diff --git a/Server/internal/i18n/catalog/fr.json b/Server/internal/i18n/catalog/fr.json
new file mode 100644
index 0000000..dbe49a7
--- /dev/null
+++ b/Server/internal/i18n/catalog/fr.json
@@ -0,0 +1,262 @@
+{
+ "%q is not a domain.": "%q n’est pas un domaine.",
+ "%s asks to join “%s”": "%s demande à rejoindre « %s »",
+ "%s commented": "%s a commenté",
+ "%s commented on “%s”": "%s a commenté « %s »",
+ "%s mentioned you": "%s vous a mentionné",
+ "%s mentioned you in “%s”": "%s vous a mentionné dans « %s »",
+ "%s replied": "%s a répondu",
+ "%s replied in “%s”": "%s a répondu dans « %s »",
+ "%s resolved a thread": "%s a résolu un fil",
+ "%s resolved a thread in “%s”": "%s a résolu un fil dans « %s »",
+ "%s shared this page with you": "%s a partagé cette page avec vous",
+ "%s shared “%s”": "%s a partagé « %s »",
+ "A page can have at most 100 tags.": "Une page peut avoir au plus 100 étiquettes.",
+ "A page cannot be moved inside itself.": "Une page ne peut pas être déplacée dans elle-même.",
+ "A valid email is required.": "Une adresse e-mail valide est requise.",
+ "AI is not available on this server": "L’IA n’est pas disponible sur ce serveur",
+ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "L’IA n’est pas configurée pour cet espace de travail : un administrateur doit ajouter un fournisseur dans ses paramètres.",
+ "AI is turned off in this workspace": "L’IA est désactivée dans cet espace de travail",
+ "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Ajoutez des fichiers texte, Markdown, HTML, Word (.docx) ou PDF.",
+ "Ask a question of up to 8 000 characters.": "Posez une question de 8 000 caractères au plus.",
+ "Ask for at most %d days, ending after they start.": "Demandez au plus %d jours, la fin après le début.",
+ "At most 200 options.": "200 options au plus.",
+ "At most 2000 pages.": "2000 pages au plus.",
+ "At most 50 rules.": "50 règles au plus.",
+ "Bucket and endpoint are required for S3.": "Le bucket et le point de terminaison sont requis pour S3.",
+ "Choose a file.": "Choisissez un fichier.",
+ "Choose a language.": "Choisissez une langue.",
+ "Choose a notebook.": "Choisissez un bloc-notes.",
+ "Choose a space you can add pages to.": "Choisissez un espace où vous pouvez ajouter des pages.",
+ "Choose at least one file.": "Choisissez au moins un fichier.",
+ "Choose digest or off.": "Choisissez résumé ou désactivé.",
+ "Choose the space highlights go to.": "Choisissez l’espace où vont les surlignages.",
+ "Choose the space to import into.": "Choisissez l’espace où importer.",
+ "Collection name is required.": "Le nom de la collection est requis.",
+ "Connect the bot token and choose a channel first.": "Connectez d’abord le jeton du bot et choisissez un canal.",
+ "Connect the bot token first.": "Connectez d’abord le jeton du bot.",
+ "Content must be a Tiptap document.": "Le contenu doit être un document Tiptap.",
+ "Dates look like 2026-11-14.": "Les dates s’écrivent ainsi : 2026-11-14.",
+ "Dates look like 2026-11-16.": "Les dates s’écrivent ainsi : 2026-11-16.",
+ "Dates must look like 2026-11-02 or 2026-11-02T15:04:05Z.": "Les dates doivent s’écrire 2026-11-02 ou 2026-11-02T15:04:05Z.",
+ "Default role must be editor, commenter or viewer.": "Le rôle par défaut doit être éditeur, commentateur ou lecteur.",
+ "Description is too long (max 500).": "La description est trop longue (500 max.).",
+ "Each option needs a name of at most 60 characters.": "Chaque option doit avoir un nom de 60 caractères au plus.",
+ "Endpoint must be an http(s) address.": "Le point de terminaison doit être une adresse http(s).",
+ "Enter a web address (http or https).": "Saisissez une adresse web (http ou https).",
+ "Files can be up to 10 MB.": "Les fichiers peuvent faire jusqu’à 10 Mo.",
+ "Font must be empty, serif or mono.": "La police doit être vide, serif ou mono.",
+ "Format must be markdown or html.": "Le format doit être markdown ou html.",
+ "Format must be markdown, html, pdf or docx.": "Le format doit être markdown, html, pdf ou docx.",
+ "Google sign-in is not set up on this server": "La connexion avec Google n’est pas configurée sur ce serveur",
+ "Icon is too long.": "L’icône est trop longue.",
+ "Import at most %d pages at once.": "Importez au plus %d pages à la fois.",
+ "Invalid option id.": "Identifiant d’option non valide.",
+ "Invalid page id.": "Identifiant de page non valide.",
+ "Microsoft sign-in is not set up on this server": "La connexion avec Microsoft n’est pas configurée sur ce serveur",
+ "Mode must be page or edgeless.": "Le mode doit être page ou edgeless.",
+ "Name and type are required.": "Le nom et le type sont requis.",
+ "Name is required.": "Le nom est requis.",
+ "Name is too long (max 60).": "Le nom est trop long (60 max.).",
+ "Name is too long (max 80).": "Le nom est trop long (80 max.).",
+ "Name, kind and address are required.": "Le nom, le type et l’adresse sont requis.",
+ "No AI provider here can transcribe audio: a workspace admin can add a speech-to-text model to an OpenAI-compatible provider.": "Aucun fournisseur d’IA ne peut transcrire l’audio ici : un administrateur de l’espace peut ajouter un modèle de reconnaissance vocale à un fournisseur compatible OpenAI.",
+ "No mail server is configured.": "Aucun serveur de messagerie n’est configuré.",
+ "No speech was found in the recording.": "Aucune parole n’a été trouvée dans l’enregistrement.",
+ "Only audio and video files can be transcribed.": "Seuls les fichiers audio et vidéo peuvent être transcrits.",
+ "Parent page not found in this space.": "Page parente introuvable dans cet espace.",
+ "Password must be at least 8 characters.": "Le mot de passe doit comporter au moins 8 caractères.",
+ "Paste the app's Bot User OAuth Token (it starts with xoxb-).": "Collez le Bot User OAuth Token de l’application (il commence par xoxb-).",
+ "Paste the app's Signing Secret (Basic Information → App Credentials).": "Collez le Signing Secret de l’application (Basic Information → App Credentials).",
+ "Paste your Readwise access token.": "Collez votre jeton d’accès Readwise.",
+ "Pick 1 to 365 days, or 0 for no end.": "Choisissez de 1 à 365 jours, ou 0 sans fin.",
+ "Pick 7 to 90 days.": "Choisissez de 7 à 90 jours.",
+ "Pick a range of at most a year.": "Choisissez une période d’un an au plus.",
+ "Pick an emoji.": "Choisissez un emoji.",
+ "Pick another tag of this workspace.": "Choisissez une autre étiquette de cet espace de travail.",
+ "Position must be a number.": "La position doit être un nombre.",
+ "Readwise is not connected": "Readwise n’est pas connecté",
+ "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Les enregistrements de plus de 25 Mo doivent être découpés avec ffmpeg : lancez le service docwell-media (DOCWELL_MEDIA_URL) ou installez ffmpeg sur le serveur. Les fichiers MP3 et WAV fonctionnent sans.",
+ "Recordings up to 1 GB can be transcribed.": "Les enregistrements jusqu’à 1 Go peuvent être transcrits.",
+ "Reminder": "Rappel",
+ "Reminder in “%s”": "Rappel dans « %s »",
+ "Role must be member or guest.": "Le rôle doit être membre ou invité.",
+ "Role must be user, admin or superadmin.": "Le rôle doit être utilisateur, administrateur ou superadministrateur.",
+ "Say what to do, in up to 2 000 characters.": "Dites quoi faire, en 2 000 caractères au plus.",
+ "Scope must be workspace, space or page.": "La portée doit être espace de travail, espace ou page.",
+ "Select at most 20 000 characters.": "Sélectionnez 20 000 caractères au plus.",
+ "Select some text first.": "Sélectionnez d’abord du texte.",
+ "Someone": "Quelqu’un",
+ "Something went wrong.": "Une erreur s’est produite.",
+ "Status must be active, disabled or invited.": "Le statut doit être actif, désactivé ou invité.",
+ "Template not found.": "Modèle introuvable.",
+ "That message is not in this chat.": "Ce message n’est pas dans cette discussion.",
+ "That page is not in this workspace.": "Cette page n’est pas dans cet espace de travail.",
+ "That space is not in this workspace.": "Cet espace n’est pas dans cet espace de travail.",
+ "That thread is not on this page.": "Ce fil n’est pas sur cette page.",
+ "The HTML file could not be read.": "Le fichier HTML n’a pas pu être lu.",
+ "The MP3 file could not be read.": "Le fichier MP3 n’a pas pu être lu.",
+ "The Markdown could not be read.": "Le Markdown n’a pas pu être lu.",
+ "The PDF could not be read.": "Le PDF n’a pas pu être lu.",
+ "The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.": "Le PDF n’a pas de couche de texte (pages numérisées). Pour le lire, ajoutez un fournisseur Anthropic ou OpenAI dont le modèle lit les PDF.",
+ "The PDF has no text layer.": "Le PDF n’a pas de couche de texte.",
+ "The WAV file could not be read.": "Le fichier WAV n’a pas pu être lu.",
+ "The Word document could not be read.": "Le document Word n’a pas pu être lu.",
+ "The anchor is too large.": "L’ancre est trop grande.",
+ "The comment is too long (max 5000).": "Le commentaire est trop long (5000 max.).",
+ "The file has no text.": "Le fichier ne contient pas de texte.",
+ "The file is larger than %d MB.": "Le fichier dépasse %d Mo.",
+ "The file is not UTF-8 text.": "Le fichier n’est pas du texte UTF-8.",
+ "The file needs a name of up to 200 characters.": "Le fichier doit avoir un nom de 200 caractères au plus.",
+ "The filter is not valid JSON.": "Le filtre n’est pas un JSON valide.",
+ "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Le service qui découpe les longs enregistrements est injoignable. Réessayez plus tard ou contactez un administrateur.",
+ "The page is too large to save.": "La page est trop volumineuse pour être enregistrée.",
+ "The recording has no sound to transcribe.": "L’enregistrement n’a pas de son à transcrire.",
+ "The recording is larger than the media service accepts.": "L’enregistrement dépasse la taille acceptée par le service multimédia.",
+ "The token is too long.": "Le jeton est trop long.",
+ "This chat is full; start a new one or fork it.": "Cette discussion est pleine ; commencez-en une nouvelle ou dupliquez-la.",
+ "This list has as many profiles as allowed.": "Cette liste a déjà autant de profils que permis.",
+ "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Cet espace de travail a épuisé ses jetons d’IA pour ce mois ; un administrateur peut relever la limite.",
+ "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Cet espace de travail a épuisé sa part de l’IA du serveur pour ce mois ; ajoutez son propre fournisseur ou contactez l’administrateur du serveur.",
+ "Title is too long (max 500).": "Le titre est trop long (500 max.).",
+ "Unarchive the parent page first.": "Désarchivez d’abord la page parente.",
+ "Unknown colour.": "Couleur inconnue.",
+ "Unknown option colour.": "Couleur d’option inconnue.",
+ "Unknown property type.": "Type de propriété inconnu.",
+ "Unknown tag.": "Étiquette inconnue.",
+ "Unknown time zone.": "Fuseau horaire inconnu.",
+ "Unknown writing action.": "Action d’écriture inconnue.",
+ "Untitled": "Sans titre",
+ "Use 0 for no limit, or a positive number.": "Utilisez 0 pour aucune limite, ou un nombre positif.",
+ "Visibility must be always, hide_empty or never.": "La visibilité doit être always, hide_empty ou never.",
+ "Visibility must be open or private.": "La visibilité doit être ouverte ou privée.",
+ "Write something first.": "Écrivez d’abord quelque chose.",
+ "You can now open “%s”": "Vous pouvez maintenant ouvrir « %s »",
+ "You have as many chats as allowed here; delete some first.": "Vous avez déjà autant de discussions que permis ici ; supprimez-en d’abord.",
+ "Your request to join “%s” was declined": "Votre demande pour rejoindre « %s » a été refusée",
+ "Your verification of this page ran out": "Votre vérification de cette page a expiré",
+ "Your verification of “%s” ran out": "Votre vérification de « %s » a expiré",
+ "a group with this name already exists": "un groupe portant ce nom existe déjà",
+ "a space can have at most 12 pinned pages; unpin one first": "un espace peut avoir au plus 12 pages épinglées ; détachez-en une d’abord",
+ "a superadmin account cannot join an organization": "un compte superadministrateur ne peut pas rejoindre une organisation",
+ "a tag with this name already exists": "une étiquette portant ce nom existe déjà",
+ "a workspace can have at most 100 properties": "un espace de travail peut avoir au plus 100 propriétés",
+ "a workspace can have up to 20 webhooks": "un espace de travail peut avoir jusqu’à 20 webhooks",
+ "admin role required": "rôle d’administrateur requis",
+ "an account with this email already exists; sign in to accept the invite": "un compte avec cette adresse e-mail existe déjà ; connectez-vous pour accepter l’invitation",
+ "an organization with this name already exists": "une organisation portant ce nom existe déjà",
+ "attachment not found": "pièce jointe introuvable",
+ "backup not found": "sauvegarde introuvable",
+ "calendar not found": "agenda introuvable",
+ "calendars are not available on this server": "les agendas ne sont pas disponibles sur ce serveur",
+ "chat not found": "discussion introuvable",
+ "collection not found": "collection introuvable",
+ "comment not found": "commentaire introuvable",
+ "commenter role required": "rôle de commentateur requis",
+ "could not find a free address for the journal space": "aucune adresse libre trouvée pour l’espace du journal",
+ "could not find a free space address; try another name": "aucune adresse d’espace libre ; essayez un autre nom",
+ "could not find a free workspace address; try another name": "aucune adresse d’espace de travail libre ; essayez un autre nom",
+ "days must be between 0 and %d": "le nombre de jours doit être compris entre 0 et %d",
+ "device not found": "appareil introuvable",
+ "editor role required": "rôle d’éditeur requis",
+ "file not found": "fichier introuvable",
+ "give a space, or a workspace for its recent pages": "indiquez un espace, ou un espace de travail pour ses pages récentes",
+ "grant not found": "autorisation introuvable",
+ "group not found": "groupe introuvable",
+ "guests cannot change the workspace's properties, tags or collections": "les invités ne peuvent pas modifier les propriétés, étiquettes ou collections de l’espace de travail",
+ "guests cannot invite people": "les invités ne peuvent pas inviter de personnes",
+ "import not found": "import introuvable",
+ "integrations are off on this server": "les intégrations sont désactivées sur ce serveur",
+ "invalid organization id": "identifiant d’organisation non valide",
+ "invite not found": "invitation introuvable",
+ "link previews are off": "les aperçus de liens sont désactivés",
+ "match must be all or any.": "match doit valoir all ou any.",
+ "member not found": "membre introuvable",
+ "move the page to the trash first": "mettez d’abord la page à la corbeille",
+ "no changes provided": "aucune modification fournie",
+ "no job can be started with that name": "aucune tâche ne peut être lancée sous ce nom",
+ "no preview": "pas d’aperçu",
+ "no user with that email": "aucun utilisateur avec cette adresse e-mail",
+ "not found": "introuvable",
+ "notification not found": "notification introuvable",
+ "only a superadmin can create superadmins": "seul un superadministrateur peut créer des superadministrateurs",
+ "only a superadmin can grant the superadmin role": "seul un superadministrateur peut attribuer ce rôle",
+ "only a thread's first comment can be resolved": "seul le premier commentaire d’un fil peut être résolu",
+ "only organization admins can create workspaces": "seuls les administrateurs de l’organisation peuvent créer des espaces de travail",
+ "only people with access to the whole space can add top-level pages": "seules les personnes ayant accès à tout l’espace peuvent ajouter des pages de premier niveau",
+ "only superadmins manage the instance's AI profiles": "seuls les superadministrateurs gèrent les profils d’IA de l’instance",
+ "only the author can edit this comment": "seul l’auteur peut modifier ce commentaire",
+ "only the author or a space admin can delete this comment": "seul l’auteur ou un administrateur de l’espace peut supprimer ce commentaire",
+ "only the collection's creator can change it": "seul le créateur de la collection peut la modifier",
+ "only the collection's creator can change who sees it": "seul le créateur de la collection peut changer qui la voit",
+ "only the page's editors can see its views": "seuls les éditeurs de la page voient ses vues",
+ "organization is required": "l’organisation est requise",
+ "organization not found": "organisation introuvable",
+ "organization still has members; move or remove them first": "l’organisation a encore des membres ; déplacez-les ou retirez-les d’abord",
+ "organization still has other members; move or remove them first": "l’organisation a encore d’autres membres ; déplacez-les ou retirez-les d’abord",
+ "organization still has workspaces; delete them first": "l’organisation a encore des espaces de travail ; supprimez-les d’abord",
+ "page not found": "page introuvable",
+ "profile not found": "profil introuvable",
+ "property not found": "propriété introuvable",
+ "public links are turned off in this workspace": "les liens publics sont désactivés dans cet espace de travail",
+ "push notifications are off on this server": "les notifications push sont désactivées sur ce serveur",
+ "request not found": "demande introuvable",
+ "restore the page from the trash first": "restaurez d’abord la page depuis la corbeille",
+ "role must be admin, editor, commenter or viewer": "le rôle doit être administrateur, éditeur, commentateur ou lecteur",
+ "role must be editor, commenter or viewer": "le rôle doit être éditeur, commentateur ou lecteur",
+ "role must be owner, admin, member or guest": "le rôle doit être propriétaire, administrateur, membre ou invité",
+ "sign in to do this; API tokens cannot": "connectez-vous pour faire ceci ; les jetons d’API ne le peuvent pas",
+ "space admin role required": "rôle d’administrateur de l’espace requis",
+ "space not found": "espace introuvable",
+ "superadmin role required": "rôle de superadministrateur requis",
+ "tag not found": "étiquette introuvable",
+ "that person already has an account here": "cette personne a déjà un compte ici",
+ "that person is a superadmin and already has access everywhere": "cette personne est superadministrateur et a déjà accès partout",
+ "that person's account belongs to another organization": "le compte de cette personne appartient à une autre organisation",
+ "that user is not a member of this workspace": "cet utilisateur n’est pas membre de cet espace de travail",
+ "that user is not in this workspace's organization": "cet utilisateur n’est pas dans l’organisation de cet espace de travail",
+ "the Microsoft sign-in has expired; connect again": "la connexion Microsoft a expiré ; reconnectez-vous",
+ "the account is disabled": "le compte est désactivé",
+ "the job is already running": "la tâche est déjà en cours",
+ "the page is in another workspace": "la page est dans un autre espace de travail",
+ "the workspace has more than %d %s": "l’espace de travail a plus de %d enregistrements (%s)",
+ "this API token can only read": "ce jeton d’API ne peut que lire",
+ "this comment has as many different reactions as it can take": "ce commentaire a déjà autant de réactions différentes que possible",
+ "this integration is not available on this server": "cette intégration n’est pas disponible sur ce serveur",
+ "this link does not exist or was turned off": "ce lien n’existe pas ou a été désactivé",
+ "too many files": "trop de fichiers",
+ "too many notifications at once": "trop de notifications à la fois",
+ "trashed and archived pages cannot be pinned": "les pages à la corbeille ou archivées ne peuvent pas être épinglées",
+ "trashed and archived pages cannot be verified": "les pages à la corbeille ou archivées ne peuvent pas être vérifiées",
+ "unarchive the page first": "désarchivez d’abord la page",
+ "unknown service": "service inconnu",
+ "unknown tool": "outil inconnu",
+ "user is outside your organization": "l’utilisateur est hors de votre organisation",
+ "user not found": "utilisateur introuvable",
+ "validation failed": "données non valides",
+ "version not found": "version introuvable",
+ "webhook not found": "webhook introuvable",
+ "webhooks are turned off on this server": "les webhooks sont désactivés sur ce serveur",
+ "workspace admin role required": "rôle d’administrateur de l’espace de travail requis",
+ "workspace admins already manage every page": "les administrateurs de l’espace de travail gèrent déjà chaque page",
+ "workspace admins already manage every space": "les administrateurs de l’espace de travail gèrent déjà chaque espace",
+ "workspace member role required": "rôle de membre de l’espace de travail requis",
+ "workspace not found": "espace de travail introuvable",
+ "workspace owner role required": "rôle de propriétaire de l’espace de travail requis",
+ "you already belong to an organization": "vous appartenez déjà à une organisation",
+ "you can add at most %d calendars": "vous pouvez ajouter au plus %d agendas",
+ "you can only create workspaces in your own organization": "vous ne pouvez créer des espaces de travail que dans votre organisation",
+ "you can only delete your own organization": "vous ne pouvez supprimer que votre organisation",
+ "you can only rename your own organization": "vous ne pouvez renommer que votre organisation",
+ "you cannot change a member ranked above you": "vous ne pouvez pas modifier un membre de rang supérieur",
+ "you cannot change your own role": "vous ne pouvez pas changer votre propre rôle",
+ "you cannot delete your own account": "vous ne pouvez pas supprimer votre propre compte",
+ "you cannot disable your own account": "vous ne pouvez pas désactiver votre propre compte",
+ "you cannot grant a role above your own": "vous ne pouvez pas attribuer un rôle supérieur au vôtre",
+ "you cannot manage a superadmin": "vous ne pouvez pas gérer un superadministrateur",
+ "you cannot manage this invite": "vous ne pouvez pas gérer cette invitation",
+ "you cannot move users to another organization": "vous ne pouvez pas déplacer des utilisateurs vers une autre organisation",
+ "you cannot remove a member ranked above you": "vous ne pouvez pas retirer un membre de rang supérieur",
+ "your account already belongs to another organization": "votre compte appartient déjà à une autre organisation",
+ "your account is not attached to an organization": "votre compte n’est rattaché à aucune organisation"
+}
diff --git a/Server/internal/i18n/catalog/pl.json b/Server/internal/i18n/catalog/pl.json
new file mode 100644
index 0000000..a680890
--- /dev/null
+++ b/Server/internal/i18n/catalog/pl.json
@@ -0,0 +1,262 @@
+{
+ "%q is not a domain.": "%q nie jest domeną.",
+ "%s asks to join “%s”": "%s prosi o dołączenie do „%s”",
+ "%s commented": "%s skomentował(a)",
+ "%s commented on “%s”": "%s skomentował(a) „%s”",
+ "%s mentioned you": "%s wspomniał(a) o tobie",
+ "%s mentioned you in “%s”": "%s wspomniał(a) o tobie w „%s”",
+ "%s replied": "%s odpowiedział(a)",
+ "%s replied in “%s”": "%s odpowiedział(a) w „%s”",
+ "%s resolved a thread": "%s rozwiązał(a) wątek",
+ "%s resolved a thread in “%s”": "%s rozwiązał(a) wątek w „%s”",
+ "%s shared this page with you": "%s udostępnił(a) ci tę stronę",
+ "%s shared “%s”": "%s udostępnił(a) „%s”",
+ "A page can have at most 100 tags.": "Strona może mieć najwyżej 100 tagów.",
+ "A page cannot be moved inside itself.": "Strony nie można przenieść do niej samej.",
+ "A valid email is required.": "Podaj prawidłowy adres e-mail.",
+ "AI is not available on this server": "AI nie jest dostępne na tym serwerze",
+ "AI is not set up for this workspace: an admin needs to add a provider in the workspace settings.": "AI nie jest skonfigurowane w tym obszarze roboczym: administrator musi dodać dostawcę w ustawieniach obszaru.",
+ "AI is turned off in this workspace": "AI jest wyłączone w tym obszarze roboczym",
+ "Add text, Markdown, HTML, Word (.docx) or PDF files.": "Dodaj pliki tekstowe, Markdown, HTML, Word (.docx) lub PDF.",
+ "Ask a question of up to 8 000 characters.": "Zadaj pytanie o długości do 8000 znaków.",
+ "Ask for at most %d days, ending after they start.": "Wybierz najwyżej %d dni, z końcem po początku.",
+ "At most 200 options.": "Najwyżej 200 opcji.",
+ "At most 2000 pages.": "Najwyżej 2000 stron.",
+ "At most 50 rules.": "Najwyżej 50 reguł.",
+ "Bucket and endpoint are required for S3.": "Dla S3 wymagane są bucket i endpoint.",
+ "Choose a file.": "Wybierz plik.",
+ "Choose a language.": "Wybierz język.",
+ "Choose a notebook.": "Wybierz notes.",
+ "Choose a space you can add pages to.": "Wybierz przestrzeń, do której możesz dodawać strony.",
+ "Choose at least one file.": "Wybierz co najmniej jeden plik.",
+ "Choose digest or off.": "Wybierz podsumowanie lub wyłącz.",
+ "Choose the space highlights go to.": "Wybierz przestrzeń, do której trafią zakreślenia.",
+ "Choose the space to import into.": "Wybierz przestrzeń, do której chcesz importować.",
+ "Collection name is required.": "Podaj nazwę kolekcji.",
+ "Connect the bot token and choose a channel first.": "Najpierw podłącz token bota i wybierz kanał.",
+ "Connect the bot token first.": "Najpierw podłącz token bota.",
+ "Content must be a Tiptap document.": "Treść musi być dokumentem Tiptap.",
+ "Dates look like 2026-11-14.": "Daty wyglądają tak: 2026-11-14.",
+ "Dates look like 2026-11-16.": "Daty wyglądają tak: 2026-11-16.",
+ "Dates must look like 2026-11-02 or 2026-11-02T15:04:05Z.": "Daty muszą wyglądać tak: 2026-11-02 lub 2026-11-02T15:04:05Z.",
+ "Default role must be editor, commenter or viewer.": "Domyślna rola musi być jedną z: edytor, komentujący, czytelnik.",
+ "Description is too long (max 500).": "Opis jest za długi (maks. 500).",
+ "Each option needs a name of at most 60 characters.": "Każda opcja potrzebuje nazwy o długości do 60 znaków.",
+ "Endpoint must be an http(s) address.": "Endpoint musi być adresem http(s).",
+ "Enter a web address (http or https).": "Wpisz adres internetowy (http lub https).",
+ "Files can be up to 10 MB.": "Pliki mogą mieć do 10 MB.",
+ "Font must be empty, serif or mono.": "Czcionka musi być pusta, serif lub mono.",
+ "Format must be markdown or html.": "Format musi być markdown lub html.",
+ "Format must be markdown, html, pdf or docx.": "Format musi być markdown, html, pdf lub docx.",
+ "Google sign-in is not set up on this server": "Logowanie przez Google nie jest skonfigurowane na tym serwerze",
+ "Icon is too long.": "Ikona jest za długa.",
+ "Import at most %d pages at once.": "Importuj najwyżej %d stron naraz.",
+ "Invalid option id.": "Nieprawidłowy identyfikator opcji.",
+ "Invalid page id.": "Nieprawidłowy identyfikator strony.",
+ "Microsoft sign-in is not set up on this server": "Logowanie przez Microsoft nie jest skonfigurowane na tym serwerze",
+ "Mode must be page or edgeless.": "Tryb musi być page lub edgeless.",
+ "Name and type are required.": "Podaj nazwę i typ.",
+ "Name is required.": "Podaj nazwę.",
+ "Name is too long (max 60).": "Nazwa jest za długa (maks. 60).",
+ "Name is too long (max 80).": "Nazwa jest za długa (maks. 80).",
+ "Name, kind and address are required.": "Podaj nazwę, rodzaj i adres.",
+ "No AI provider here can transcribe audio: a workspace admin can add a speech-to-text model to an OpenAI-compatible provider.": "Żaden dostawca AI nie potrafi tu przepisać nagrania: administrator obszaru może dodać model mowy na tekst do dostawcy zgodnego z OpenAI.",
+ "No mail server is configured.": "Nie skonfigurowano serwera poczty.",
+ "No speech was found in the recording.": "W nagraniu nie znaleziono mowy.",
+ "Only audio and video files can be transcribed.": "Przepisać można tylko pliki audio i wideo.",
+ "Parent page not found in this space.": "Nie znaleziono strony nadrzędnej w tej przestrzeni.",
+ "Password must be at least 8 characters.": "Hasło musi mieć co najmniej 8 znaków.",
+ "Paste the app's Bot User OAuth Token (it starts with xoxb-).": "Wklej Bot User OAuth Token aplikacji (zaczyna się od xoxb-).",
+ "Paste the app's Signing Secret (Basic Information → App Credentials).": "Wklej Signing Secret aplikacji (Basic Information → App Credentials).",
+ "Paste your Readwise access token.": "Wklej swój token dostępu Readwise.",
+ "Pick 1 to 365 days, or 0 for no end.": "Wybierz od 1 do 365 dni albo 0 bez końca.",
+ "Pick 7 to 90 days.": "Wybierz od 7 do 90 dni.",
+ "Pick a range of at most a year.": "Wybierz zakres najwyżej jednego roku.",
+ "Pick an emoji.": "Wybierz emoji.",
+ "Pick another tag of this workspace.": "Wybierz inny tag z tego obszaru roboczego.",
+ "Position must be a number.": "Pozycja musi być liczbą.",
+ "Readwise is not connected": "Readwise nie jest połączony",
+ "Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.": "Nagrania ponad 25 MB trzeba pociąć programem ffmpeg: uruchom usługę docwell-media (DOCWELL_MEDIA_URL) albo zainstaluj ffmpeg na serwerze. Pliki MP3 i WAV działają bez niego.",
+ "Recordings up to 1 GB can be transcribed.": "Przepisać można nagrania do 1 GB.",
+ "Reminder": "Przypomnienie",
+ "Reminder in “%s”": "Przypomnienie w „%s”",
+ "Role must be member or guest.": "Rola musi być: członek lub gość.",
+ "Role must be user, admin or superadmin.": "Rola musi być: użytkownik, administrator lub superadministrator.",
+ "Say what to do, in up to 2 000 characters.": "Napisz, co zrobić, w maksymalnie 2000 znaków.",
+ "Scope must be workspace, space or page.": "Zakres musi być: obszar roboczy, przestrzeń lub strona.",
+ "Select at most 20 000 characters.": "Zaznacz najwyżej 20 000 znaków.",
+ "Select some text first.": "Najpierw zaznacz tekst.",
+ "Someone": "Ktoś",
+ "Something went wrong.": "Coś poszło nie tak.",
+ "Status must be active, disabled or invited.": "Status musi być: aktywny, wyłączony lub zaproszony.",
+ "Template not found.": "Nie znaleziono szablonu.",
+ "That message is not in this chat.": "Tej wiadomości nie ma w tym czacie.",
+ "That page is not in this workspace.": "Tej strony nie ma w tym obszarze roboczym.",
+ "That space is not in this workspace.": "Tej przestrzeni nie ma w tym obszarze roboczym.",
+ "That thread is not on this page.": "Tego wątku nie ma na tej stronie.",
+ "The HTML file could not be read.": "Nie udało się odczytać pliku HTML.",
+ "The MP3 file could not be read.": "Nie udało się odczytać pliku MP3.",
+ "The Markdown could not be read.": "Nie udało się odczytać pliku Markdown.",
+ "The PDF could not be read.": "Nie udało się odczytać pliku PDF.",
+ "The PDF has no text layer (scanned pages). To read it, add an Anthropic or OpenAI provider whose model reads PDF files.": "PDF nie ma warstwy tekstowej (zeskanowane strony). Aby go odczytać, dodaj dostawcę Anthropic lub OpenAI z modelem czytającym pliki PDF.",
+ "The PDF has no text layer.": "PDF nie ma warstwy tekstowej.",
+ "The WAV file could not be read.": "Nie udało się odczytać pliku WAV.",
+ "The Word document could not be read.": "Nie udało się odczytać dokumentu Word.",
+ "The anchor is too large.": "Kotwica jest za duża.",
+ "The comment is too long (max 5000).": "Komentarz jest za długi (maks. 5000).",
+ "The file has no text.": "Plik nie zawiera tekstu.",
+ "The file is larger than %d MB.": "Plik jest większy niż %d MB.",
+ "The file is not UTF-8 text.": "Plik nie jest tekstem UTF-8.",
+ "The file needs a name of up to 200 characters.": "Plik potrzebuje nazwy o długości do 200 znaków.",
+ "The filter is not valid JSON.": "Filtr nie jest prawidłowym JSON-em.",
+ "The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.": "Usługa dzieląca długie nagrania jest nieosiągalna. Spróbuj później lub zapytaj administratora.",
+ "The page is too large to save.": "Strona jest za duża, by ją zapisać.",
+ "The recording has no sound to transcribe.": "Nagranie nie ma dźwięku do przepisania.",
+ "The recording is larger than the media service accepts.": "Nagranie jest większe, niż przyjmuje usługa multimediów.",
+ "The token is too long.": "Token jest za długi.",
+ "This chat is full; start a new one or fork it.": "Ten czat jest pełny; zacznij nowy albo go rozgałęź.",
+ "This list has as many profiles as allowed.": "Ta lista ma już maksymalną liczbę profili.",
+ "This workspace has used its AI tokens for this month; a workspace admin can raise the limit.": "Ten obszar roboczy wykorzystał tokeny AI na ten miesiąc; administrator obszaru może podnieść limit.",
+ "This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.": "Ten obszar roboczy wykorzystał swój udział w AI serwera na ten miesiąc; dodaj własnego dostawcę albo zapytaj administratora serwera.",
+ "Title is too long (max 500).": "Tytuł jest za długi (maks. 500).",
+ "Unarchive the parent page first.": "Najpierw przywróć z archiwum stronę nadrzędną.",
+ "Unknown colour.": "Nieznany kolor.",
+ "Unknown option colour.": "Nieznany kolor opcji.",
+ "Unknown property type.": "Nieznany typ właściwości.",
+ "Unknown tag.": "Nieznany tag.",
+ "Unknown time zone.": "Nieznana strefa czasowa.",
+ "Unknown writing action.": "Nieznana akcja pisania.",
+ "Untitled": "Bez tytułu",
+ "Use 0 for no limit, or a positive number.": "Wpisz 0, aby nie było limitu, lub liczbę dodatnią.",
+ "Visibility must be always, hide_empty or never.": "Widoczność musi być always, hide_empty lub never.",
+ "Visibility must be open or private.": "Widoczność musi być: otwarta lub prywatna.",
+ "Write something first.": "Najpierw coś napisz.",
+ "You can now open “%s”": "Możesz już otworzyć „%s”",
+ "You have as many chats as allowed here; delete some first.": "Masz już maksymalną liczbę czatów; najpierw usuń któryś.",
+ "Your request to join “%s” was declined": "Twoja prośba o dołączenie do „%s” została odrzucona",
+ "Your verification of this page ran out": "Twoja weryfikacja tej strony wygasła",
+ "Your verification of “%s” ran out": "Twoja weryfikacja strony „%s” wygasła",
+ "a group with this name already exists": "grupa o tej nazwie już istnieje",
+ "a space can have at most 12 pinned pages; unpin one first": "przestrzeń może mieć najwyżej 12 przypiętych stron; najpierw odepnij jedną",
+ "a superadmin account cannot join an organization": "konto superadministratora nie może dołączyć do organizacji",
+ "a tag with this name already exists": "tag o tej nazwie już istnieje",
+ "a workspace can have at most 100 properties": "obszar roboczy może mieć najwyżej 100 właściwości",
+ "a workspace can have up to 20 webhooks": "obszar roboczy może mieć do 20 webhooków",
+ "admin role required": "wymagana rola administratora",
+ "an account with this email already exists; sign in to accept the invite": "konto z tym adresem e-mail już istnieje; zaloguj się, aby przyjąć zaproszenie",
+ "an organization with this name already exists": "organizacja o tej nazwie już istnieje",
+ "attachment not found": "nie znaleziono załącznika",
+ "backup not found": "nie znaleziono kopii zapasowej",
+ "calendar not found": "nie znaleziono kalendarza",
+ "calendars are not available on this server": "kalendarze nie są dostępne na tym serwerze",
+ "chat not found": "nie znaleziono czatu",
+ "collection not found": "nie znaleziono kolekcji",
+ "comment not found": "nie znaleziono komentarza",
+ "commenter role required": "wymagana rola komentującego",
+ "could not find a free address for the journal space": "nie znaleziono wolnego adresu dla przestrzeni dziennika",
+ "could not find a free space address; try another name": "nie znaleziono wolnego adresu przestrzeni; spróbuj innej nazwy",
+ "could not find a free workspace address; try another name": "nie znaleziono wolnego adresu obszaru roboczego; spróbuj innej nazwy",
+ "days must be between 0 and %d": "liczba dni musi wynosić od 0 do %d",
+ "device not found": "nie znaleziono urządzenia",
+ "editor role required": "wymagana rola edytora",
+ "file not found": "nie znaleziono pliku",
+ "give a space, or a workspace for its recent pages": "podaj przestrzeń albo obszar roboczy, by zobaczyć jego ostatnie strony",
+ "grant not found": "nie znaleziono uprawnienia",
+ "group not found": "nie znaleziono grupy",
+ "guests cannot change the workspace's properties, tags or collections": "goście nie mogą zmieniać właściwości, tagów ani kolekcji obszaru roboczego",
+ "guests cannot invite people": "goście nie mogą zapraszać innych osób",
+ "import not found": "nie znaleziono importu",
+ "integrations are off on this server": "integracje są wyłączone na tym serwerze",
+ "invalid organization id": "nieprawidłowy identyfikator organizacji",
+ "invite not found": "nie znaleziono zaproszenia",
+ "link previews are off": "podglądy linków są wyłączone",
+ "match must be all or any.": "dopasowanie musi być all lub any.",
+ "member not found": "nie znaleziono członka",
+ "move the page to the trash first": "najpierw przenieś stronę do kosza",
+ "no changes provided": "nie podano żadnych zmian",
+ "no job can be started with that name": "nie można uruchomić zadania o tej nazwie",
+ "no preview": "brak podglądu",
+ "no user with that email": "brak użytkownika z tym adresem e-mail",
+ "not found": "nie znaleziono",
+ "notification not found": "nie znaleziono powiadomienia",
+ "only a superadmin can create superadmins": "tylko superadministrator może tworzyć superadministratorów",
+ "only a superadmin can grant the superadmin role": "tylko superadministrator może nadać rolę superadministratora",
+ "only a thread's first comment can be resolved": "rozwiązać można tylko pierwszy komentarz wątku",
+ "only organization admins can create workspaces": "tylko administratorzy organizacji mogą tworzyć obszary robocze",
+ "only people with access to the whole space can add top-level pages": "tylko osoby z dostępem do całej przestrzeni mogą dodawać strony najwyższego poziomu",
+ "only superadmins manage the instance's AI profiles": "tylko superadministratorzy zarządzają profilami AI instancji",
+ "only the author can edit this comment": "tylko autor może edytować ten komentarz",
+ "only the author or a space admin can delete this comment": "tylko autor lub administrator przestrzeni może usunąć ten komentarz",
+ "only the collection's creator can change it": "tylko twórca kolekcji może ją zmieniać",
+ "only the collection's creator can change who sees it": "tylko twórca kolekcji może zmienić, kto ją widzi",
+ "only the page's editors can see its views": "wyświetlenia strony widzą tylko jej edytorzy",
+ "organization is required": "organizacja jest wymagana",
+ "organization not found": "nie znaleziono organizacji",
+ "organization still has members; move or remove them first": "organizacja wciąż ma członków; najpierw ich przenieś lub usuń",
+ "organization still has other members; move or remove them first": "organizacja wciąż ma innych członków; najpierw ich przenieś lub usuń",
+ "organization still has workspaces; delete them first": "organizacja wciąż ma obszary robocze; najpierw je usuń",
+ "page not found": "nie znaleziono strony",
+ "profile not found": "nie znaleziono profilu",
+ "property not found": "nie znaleziono właściwości",
+ "public links are turned off in this workspace": "linki publiczne są wyłączone w tym obszarze roboczym",
+ "push notifications are off on this server": "powiadomienia push są wyłączone na tym serwerze",
+ "request not found": "nie znaleziono prośby",
+ "restore the page from the trash first": "najpierw przywróć stronę z kosza",
+ "role must be admin, editor, commenter or viewer": "rola musi być: administrator, edytor, komentujący lub czytelnik",
+ "role must be editor, commenter or viewer": "rola musi być: edytor, komentujący lub czytelnik",
+ "role must be owner, admin, member or guest": "rola musi być: właściciel, administrator, członek lub gość",
+ "sign in to do this; API tokens cannot": "zaloguj się, aby to zrobić; tokeny API nie mogą",
+ "space admin role required": "wymagana rola administratora przestrzeni",
+ "space not found": "nie znaleziono przestrzeni",
+ "superadmin role required": "wymagana rola superadministratora",
+ "tag not found": "nie znaleziono tagu",
+ "that person already has an account here": "ta osoba ma już tu konto",
+ "that person is a superadmin and already has access everywhere": "ta osoba jest superadministratorem i ma już dostęp wszędzie",
+ "that person's account belongs to another organization": "konto tej osoby należy do innej organizacji",
+ "that user is not a member of this workspace": "ten użytkownik nie jest członkiem tego obszaru roboczego",
+ "that user is not in this workspace's organization": "tego użytkownika nie ma w organizacji tego obszaru roboczego",
+ "the Microsoft sign-in has expired; connect again": "logowanie Microsoft wygasło; połącz ponownie",
+ "the account is disabled": "konto jest wyłączone",
+ "the job is already running": "zadanie już trwa",
+ "the page is in another workspace": "strona jest w innym obszarze roboczym",
+ "the workspace has more than %d %s": "obszar roboczy ma więcej niż %d rekordów (%s)",
+ "this API token can only read": "ten token API może tylko odczytywać",
+ "this comment has as many different reactions as it can take": "ten komentarz ma już maksymalną liczbę różnych reakcji",
+ "this integration is not available on this server": "ta integracja nie jest dostępna na tym serwerze",
+ "this link does not exist or was turned off": "ten link nie istnieje lub został wyłączony",
+ "too many files": "za dużo plików",
+ "too many notifications at once": "za dużo powiadomień naraz",
+ "trashed and archived pages cannot be pinned": "stron w koszu i w archiwum nie można przypinać",
+ "trashed and archived pages cannot be verified": "stron w koszu i w archiwum nie można weryfikować",
+ "unarchive the page first": "najpierw przywróć stronę z archiwum",
+ "unknown service": "nieznana usługa",
+ "unknown tool": "nieznane narzędzie",
+ "user is outside your organization": "użytkownik jest spoza twojej organizacji",
+ "user not found": "nie znaleziono użytkownika",
+ "validation failed": "dane są nieprawidłowe",
+ "version not found": "nie znaleziono wersji",
+ "webhook not found": "nie znaleziono webhooka",
+ "webhooks are turned off on this server": "webhooki są wyłączone na tym serwerze",
+ "workspace admin role required": "wymagana rola administratora obszaru roboczego",
+ "workspace admins already manage every page": "administratorzy obszaru roboczego już zarządzają każdą stroną",
+ "workspace admins already manage every space": "administratorzy obszaru roboczego już zarządzają każdą przestrzenią",
+ "workspace member role required": "wymagana rola członka obszaru roboczego",
+ "workspace not found": "nie znaleziono obszaru roboczego",
+ "workspace owner role required": "wymagana rola właściciela obszaru roboczego",
+ "you already belong to an organization": "należysz już do organizacji",
+ "you can add at most %d calendars": "możesz dodać najwyżej %d kalendarzy",
+ "you can only create workspaces in your own organization": "możesz tworzyć obszary robocze tylko w swojej organizacji",
+ "you can only delete your own organization": "możesz usunąć tylko swoją organizację",
+ "you can only rename your own organization": "możesz zmienić nazwę tylko swojej organizacji",
+ "you cannot change a member ranked above you": "nie możesz zmienić członka o wyższej randze",
+ "you cannot change your own role": "nie możesz zmienić swojej roli",
+ "you cannot delete your own account": "nie możesz usunąć swojego konta",
+ "you cannot disable your own account": "nie możesz wyłączyć swojego konta",
+ "you cannot grant a role above your own": "nie możesz nadać roli wyższej niż twoja",
+ "you cannot manage a superadmin": "nie możesz zarządzać superadministratorem",
+ "you cannot manage this invite": "nie możesz zarządzać tym zaproszeniem",
+ "you cannot move users to another organization": "nie możesz przenosić użytkowników do innej organizacji",
+ "you cannot remove a member ranked above you": "nie możesz usunąć członka o wyższej randze",
+ "your account already belongs to another organization": "twoje konto należy już do innej organizacji",
+ "your account is not attached to an organization": "twoje konto nie jest przypisane do organizacji"
+}
diff --git a/Server/internal/i18n/i18n.go b/Server/internal/i18n/i18n.go
new file mode 100644
index 0000000..66d2cd5
--- /dev/null
+++ b/Server/internal/i18n/i18n.go
@@ -0,0 +1,247 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// Package i18n translates the text docwell-server writes for people: error
+// messages in API responses, emails, and phone notifications. The server's
+// code stays in English; catalogs (catalog/.json) map each English
+// message to its translation. A message made with fmt.Sprintf is looked up
+// by its format ("you can add at most %d calendars"), and its arguments are
+// carried over into the translation, so call sites need no changes.
+//
+// The language of a request comes from its Accept-Language header (the apps
+// send the language they show); emails and notifications use the language
+// the person last used the app in.
+package i18n
+
+import (
+ "context"
+ "embed"
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Default is the language of the code and of anything not translated.
+const Default = "en"
+
+// Supported are the languages the server speaks, as in the apps.
+var Supported = []string{"en", "pl", "de", "fr", "es"}
+
+// IsSupported reports whether lang is one of Supported.
+func IsSupported(lang string) bool {
+ for _, l := range Supported {
+ if l == lang {
+ return true
+ }
+ }
+ return false
+}
+
+// Match picks the first supported language of an Accept-Language header,
+// by quality, or Default.
+func Match(header string) string {
+ lang, _ := MatchOK(header)
+ return lang
+}
+
+// MatchOK is Match, also saying whether the header named a supported language.
+func MatchOK(header string) (string, bool) {
+ type choice struct {
+ lang string
+ q float64
+ i int
+ }
+ var list []choice
+ for i, part := range strings.Split(header, ",") {
+ tag, params, _ := strings.Cut(strings.TrimSpace(part), ";")
+ q := 1.0
+ if v, ok := strings.CutPrefix(strings.TrimSpace(params), "q="); ok {
+ if f, err := strconv.ParseFloat(v, 64); err == nil {
+ q = f
+ }
+ }
+ base, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(tag)), "-")
+ if q > 0 && IsSupported(base) {
+ list = append(list, choice{base, q, i})
+ }
+ }
+ sort.SliceStable(list, func(a, b int) bool { return list[a].q > list[b].q })
+ if len(list) == 0 {
+ return Default, false
+ }
+ return list[0].lang, true
+}
+
+type ctxKey struct{}
+
+// WithLang is ctx carrying a request's language.
+func WithLang(ctx context.Context, lang string) context.Context {
+ return context.WithValue(ctx, ctxKey{}, lang)
+}
+
+// Lang is the language ctx carries, or Default.
+func Lang(ctx context.Context) string {
+ if l, ok := ctx.Value(ctxKey{}).(string); ok && IsSupported(l) {
+ return l
+ }
+ return Default
+}
+
+//go:embed catalog/*.json
+var files embed.FS
+
+// catalog is one language's translations.
+type catalog struct {
+ exact map[string]string
+ patterns []pattern
+}
+
+// pattern is a format key ("… %d …") matched against finished messages.
+type pattern struct {
+ re *regexp.Regexp
+ translation string
+}
+
+var (
+ loadOnce sync.Once
+ catalogs map[string]*catalog
+ loadErr error
+)
+
+// verb matches the fmt verbs catalogs use: %s %d %q %v, optionally indexed (%[2]s).
+var verb = regexp.MustCompile(`%(?:\[(\d+)\])?[sdqv]`)
+
+func load() {
+ catalogs = map[string]*catalog{}
+ for _, lang := range Supported {
+ if lang == Default {
+ continue
+ }
+ raw, err := files.ReadFile("catalog/" + lang + ".json")
+ if err != nil {
+ loadErr = err
+ return
+ }
+ var m map[string]string
+ if err := json.Unmarshal(raw, &m); err != nil {
+ loadErr = fmt.Errorf("i18n: catalog/%s.json: %w", lang, err)
+ return
+ }
+ c := &catalog{exact: m}
+ for key, tr := range m {
+ if verb.MatchString(key) {
+ c.patterns = append(c.patterns, pattern{re: compile(key), translation: tr})
+ }
+ }
+ // Longer formats first, so the most specific one wins.
+ sort.Slice(c.patterns, func(i, j int) bool {
+ return len(c.patterns[i].re.String()) > len(c.patterns[j].re.String())
+ })
+ catalogs[lang] = c
+ }
+}
+
+// compile turns a format key into a regexp that captures each verb's text.
+func compile(key string) *regexp.Regexp {
+ var b strings.Builder
+ b.WriteString("^")
+ last := 0
+ for _, m := range verb.FindAllStringIndex(key, -1) {
+ b.WriteString(regexp.QuoteMeta(key[last:m[0]]))
+ b.WriteString("(.+?)")
+ last = m[1]
+ }
+ b.WriteString(regexp.QuoteMeta(key[last:]))
+ b.WriteString("$")
+ return regexp.MustCompile(b.String())
+}
+
+func get(lang string) *catalog {
+ loadOnce.Do(load)
+ return catalogs[lang]
+}
+
+// Check reports a catalog that cannot be read (for tests and start-up).
+func Check() error {
+ loadOnce.Do(load)
+ return loadErr
+}
+
+// Translate is msg in lang: its catalog entry, or msg itself when there is
+// none. A message made from a format is matched by its format.
+func Translate(lang, msg string) string {
+ c := get(lang)
+ if c == nil || msg == "" {
+ return msg
+ }
+ if t, ok := c.exact[msg]; ok {
+ return t
+ }
+ for _, p := range c.patterns {
+ if m := p.re.FindStringSubmatch(msg); m != nil {
+ return fill(p.translation, m[1:])
+ }
+ }
+ return msg
+}
+
+// Sprintf formats key's translation in lang with args, like fmt.Sprintf on
+// the English key. Use it for text built here (emails, notifications).
+func Sprintf(lang, key string, args ...any) string {
+ format := key
+ if c := get(lang); c != nil {
+ if t, ok := c.exact[key]; ok {
+ format = t
+ }
+ }
+ return fmt.Sprintf(format, args...)
+}
+
+// fill puts captured argument texts into a translation's verbs: in order,
+// or by index for %[n]s.
+func fill(tr string, args []string) string {
+ next := 0
+ return verb.ReplaceAllStringFunc(tr, func(v string) string {
+ i := next
+ if m := verb.FindStringSubmatch(v); m[1] != "" {
+ n, _ := strconv.Atoi(m[1])
+ i = n - 1
+ } else {
+ next++
+ }
+ if i >= 0 && i < len(args) {
+ return args[i]
+ }
+ return v
+ })
+}
+
+// months are the month names of each language, in the form a date uses.
+var months = map[string][12]string{
+ "en": {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"},
+ "pl": {"stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września", "października", "listopada", "grudnia"},
+ "de": {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"},
+ "fr": {"janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"},
+ "es": {"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"},
+}
+
+// Date writes a day the way lang does: "2 January 2006", "2. Januar 2006",
+// "2 de enero de 2006".
+func Date(lang string, t time.Time) string {
+ names, ok := months[lang]
+ if !ok {
+ names = months[Default]
+ }
+ m := names[t.Month()-1]
+ switch lang {
+ case "de":
+ return fmt.Sprintf("%d. %s %d", t.Day(), m, t.Year())
+ case "es":
+ return fmt.Sprintf("%d de %s de %d", t.Day(), m, t.Year())
+ }
+ return fmt.Sprintf("%d %s %d", t.Day(), m, t.Year())
+}
diff --git a/Server/internal/i18n/i18n_test.go b/Server/internal/i18n/i18n_test.go
new file mode 100644
index 0000000..bd2fb3c
--- /dev/null
+++ b/Server/internal/i18n/i18n_test.go
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package i18n
+
+import (
+ "encoding/json"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestMatchPicksTheBestSupportedLanguage(t *testing.T) {
+ cases := map[string]string{
+ "": "en",
+ "pl": "pl",
+ "de-DE,de;q=0.9,en;q=0.8": "de",
+ "ja,fr-CA;q=0.8": "fr",
+ "en;q=0.5,es;q=0.9": "es",
+ "zh,ja": "en",
+ "pl;q=0": "en",
+ }
+ for header, want := range cases {
+ if got := Match(header); got != want {
+ t.Errorf("Match(%q) = %q, want %q", header, got, want)
+ }
+ }
+ if _, ok := MatchOK("zh"); ok {
+ t.Error("an unsupported language should not count as a choice")
+ }
+}
+
+func TestTranslate(t *testing.T) {
+ if err := Check(); err != nil {
+ t.Fatal(err)
+ }
+ if got := Translate("pl", "page not found"); got != "nie znaleziono strony" {
+ t.Errorf("exact: %q", got)
+ }
+ // A message made from a format keeps its arguments.
+ if got := Translate("de", "you can add at most 5 calendars"); got != "du kannst höchstens 5 Kalender hinzufügen" {
+ t.Errorf("format: %q", got)
+ }
+ if got := Translate("fr", `"bad..domain" is not a domain.`); got != `"bad..domain" n’est pas un domaine.` {
+ t.Errorf("quoted: %q", got)
+ }
+ // English, unknown messages and unknown languages pass through.
+ for _, c := range [][2]string{{"en", "page not found"}, {"pl", "a message nobody wrote"}, {"xx", "page not found"}} {
+ if got := Translate(c[0], c[1]); got != c[1] {
+ t.Errorf("Translate(%q, %q) = %q", c[0], c[1], got)
+ }
+ }
+}
+
+func TestSprintfAndDate(t *testing.T) {
+ if got := Sprintf("es", "%s commented on “%s”", "Ana", "Plan"); got != "Ana comentó en «Plan»" {
+ t.Errorf("Sprintf: %q", got)
+ }
+ if got := Sprintf("en", "%s commented on “%s”", "Ana", "Plan"); got != "Ana commented on “Plan”" {
+ t.Errorf("English: %q", got)
+ }
+ day := time.Date(2026, 12, 3, 0, 0, 0, 0, time.UTC)
+ for lang, want := range map[string]string{
+ "en": "3 December 2026", "pl": "3 grudnia 2026", "de": "3. Dezember 2026", "fr": "3 décembre 2026", "es": "3 de diciembre de 2026",
+ } {
+ if got := Date(lang, day); got != want {
+ t.Errorf("Date(%s) = %q, want %q", lang, got, want)
+ }
+ }
+}
+
+// TestCatalogsCoverEveryErrorMessage reads the server's code for the
+// messages errors carry (apperr calls, their fmt.Sprintf formats and field
+// maps, and mapPB's not-found messages) and checks that every language
+// translates each one, with the same placeholders.
+func TestCatalogsCoverEveryErrorMessage(t *testing.T) {
+ msgs := map[string]string{} // message -> where
+ root := ".."
+ err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() || !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") || strings.HasSuffix(p, ".gen.go") {
+ return err
+ }
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, p, nil, 0)
+ if err != nil {
+ return err
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ where := fset.Position(call.Pos()).String()
+ switch fn := call.Fun.(type) {
+ case *ast.SelectorExpr:
+ if id, ok := fn.X.(*ast.Ident); ok && id.Name == "apperr" {
+ for _, a := range call.Args {
+ collect(a, where, msgs)
+ }
+ }
+ case *ast.Ident:
+ if fn.Name == "mapPB" && len(call.Args) == 2 {
+ collect(call.Args[1], where, msgs)
+ }
+ }
+ return true
+ })
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(msgs) < 200 {
+ t.Fatalf("found only %d messages; is the walk reading the code?", len(msgs))
+ }
+ for _, lang := range Supported {
+ if lang == Default {
+ continue
+ }
+ raw, err := os.ReadFile("catalog/" + lang + ".json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cat map[string]string
+ if err := json.Unmarshal(raw, &cat); err != nil {
+ t.Fatal(err)
+ }
+ for m, where := range msgs {
+ if _, ok := cat[m]; !ok {
+ t.Errorf("%s: no %s translation of %q (%s)", lang, lang, m, where)
+ }
+ }
+ for k, v := range cat {
+ if a, b := len(verb.FindAllString(k, -1)), len(verb.FindAllString(v, -1)); a != b {
+ t.Errorf("%s: %q has %d placeholders, its translation %d", lang, k, a, b)
+ }
+ }
+ }
+}
+
+// collect adds the message texts in an argument: literals, Sprintf formats
+// and the values of field maps.
+func collect(e ast.Expr, where string, out map[string]string) {
+ switch x := e.(type) {
+ case *ast.BasicLit:
+ if x.Kind == token.STRING {
+ if s, err := strconv.Unquote(x.Value); err == nil {
+ out[s] = where
+ }
+ }
+ case *ast.CallExpr:
+ if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "Sprintf" && len(x.Args) > 0 {
+ collect(x.Args[0], where, out)
+ }
+ case *ast.CompositeLit:
+ for _, el := range x.Elts {
+ if kv, ok := el.(*ast.KeyValueExpr); ok {
+ collect(kv.Value, where, out)
+ }
+ }
+ }
+}
diff --git a/Server/internal/mail/mail.go b/Server/internal/mail/mail.go
index cfa3d54..db486ef 100644
--- a/Server/internal/mail/mail.go
+++ b/Server/internal/mail/mail.go
@@ -38,13 +38,21 @@ var (
// Render builds a message from the templates named name.html and name.txt.
// The first line of the text template is the subject.
-func Render(to, name string, data any) (Message, error) {
- var text, html bytes.Buffer
- if err := textTemplates.ExecuteTemplate(&text, name+".txt", data); err != nil {
- return Message{}, fmt.Errorf("mail: %s.txt: %w", name, err)
+func Render(to, name string, data any) (Message, error) { return RenderIn("", to, name, data) }
+
+// RenderIn is Render in a language: from name..html and
+// name..txt when there are such templates, else the English ones.
+func RenderIn(lang, to, name string, data any) (Message, error) {
+ textName, htmlName := name+".txt", name+".html"
+ if lang != "" && textTemplates.Lookup(name+"."+lang+".txt") != nil && htmlTemplates.Lookup(name+"."+lang+".html") != nil {
+ textName, htmlName = name+"."+lang+".txt", name+"."+lang+".html"
}
- if err := htmlTemplates.ExecuteTemplate(&html, name+".html", data); err != nil {
- return Message{}, fmt.Errorf("mail: %s.html: %w", name, err)
+ var text, html bytes.Buffer
+ if err := textTemplates.ExecuteTemplate(&text, textName, data); err != nil {
+ return Message{}, fmt.Errorf("mail: %s: %w", textName, err)
+ }
+ if err := htmlTemplates.ExecuteTemplate(&html, htmlName, data); err != nil {
+ return Message{}, fmt.Errorf("mail: %s: %w", htmlName, err)
}
subject, body, _ := strings.Cut(text.String(), "\n")
return Message{To: to, Subject: strings.TrimSpace(subject), HTML: html.String(), Text: strings.TrimSpace(body) + "\n"}, nil
diff --git a/Server/internal/mail/templates/digest.de.html b/Server/internal/mail/templates/digest.de.html
new file mode 100644
index 0000000..f650cc8
--- /dev/null
+++ b/Server/internal/mail/templates/digest.de.html
@@ -0,0 +1,11 @@
+
+ Recibes este correo porque tienes notificaciones sin leer. Desactiva estos correos en
+ tu configuración de notificaciones.
+
diff --git a/Server/internal/mail/templates/digest.es.txt b/Server/internal/mail/templates/digest.es.txt
new file mode 100644
index 0000000..217d712
--- /dev/null
+++ b/Server/internal/mail/templates/digest.es.txt
@@ -0,0 +1,9 @@
+{{.Count}} {{if eq .Count 1}}notificación nueva{{else}}notificaciones nuevas{{end}} en {{.AppName}}
+Hola{{if .Name}} {{.Name}}{{end}}:
+
+Esto es lo que pasó mientras no estabas:
+{{range .Items}}
+- {{.Text}}
+ {{.Link}}
+{{end}}
+Recibes este correo porque tienes notificaciones sin leer. Puedes desactivar estos correos en tu configuración de notificaciones: {{.SettingsLink}}
diff --git a/Server/internal/mail/templates/digest.fr.html b/Server/internal/mail/templates/digest.fr.html
new file mode 100644
index 0000000..f28841b
--- /dev/null
+++ b/Server/internal/mail/templates/digest.fr.html
@@ -0,0 +1,11 @@
+
Der Link gilt bis {{.Expires}}. Wenn du diese E-Mail nicht erwartet hast, kannst du sie ignorieren.
diff --git a/Server/internal/mail/templates/invite.de.txt b/Server/internal/mail/templates/invite.de.txt
new file mode 100644
index 0000000..a37b51b
--- /dev/null
+++ b/Server/internal/mail/templates/invite.de.txt
@@ -0,0 +1,6 @@
+{{.Inviter}} lädt dich zu {{.Target}} in {{.AppName}} ein
+{{.Inviter}} lädt dich ein, {{.Target}} in {{.AppName}} beizutreten.
+
+Einladung annehmen: {{.Link}}
+
+Der Link gilt bis {{.Expires}}. Wenn du diese E-Mail nicht erwartet hast, kannst du sie ignorieren.
diff --git a/Server/internal/mail/templates/invite.es.html b/Server/internal/mail/templates/invite.es.html
new file mode 100644
index 0000000..243d913
--- /dev/null
+++ b/Server/internal/mail/templates/invite.es.html
@@ -0,0 +1,4 @@
+
Hola:
+
{{.Inviter}} te invita a unirte a {{.Target}} en {{.AppName}}.
El enlace funciona hasta el {{.Expires}}. Si no esperabas este correo, puedes ignorarlo.
diff --git a/Server/internal/mail/templates/invite.es.txt b/Server/internal/mail/templates/invite.es.txt
new file mode 100644
index 0000000..97a13ae
--- /dev/null
+++ b/Server/internal/mail/templates/invite.es.txt
@@ -0,0 +1,6 @@
+{{.Inviter}} te invita a {{.Target}} en {{.AppName}}
+{{.Inviter}} te invita a unirte a {{.Target}} en {{.AppName}}.
+
+Acepta la invitación: {{.Link}}
+
+El enlace funciona hasta el {{.Expires}}. Si no esperabas este correo, puedes ignorarlo.
diff --git a/Server/internal/mail/templates/invite.fr.html b/Server/internal/mail/templates/invite.fr.html
new file mode 100644
index 0000000..5f91d89
--- /dev/null
+++ b/Server/internal/mail/templates/invite.fr.html
@@ -0,0 +1,4 @@
+
Bonjour,
+
{{.Inviter}} vous invite à rejoindre {{.Target}} sur {{.AppName}}.
Link działa do {{.Expires}}. Jeśli nie spodziewasz się tej wiadomości, możesz ją zignorować.
diff --git a/Server/internal/mail/templates/invite.pl.txt b/Server/internal/mail/templates/invite.pl.txt
new file mode 100644
index 0000000..99c59f0
--- /dev/null
+++ b/Server/internal/mail/templates/invite.pl.txt
@@ -0,0 +1,6 @@
+{{.Inviter}} zaprasza cię do {{.Target}} w {{.AppName}}
+{{.Inviter}} zaprasza cię do {{.Target}} w {{.AppName}}.
+
+Przyjmij zaproszenie: {{.Link}}
+
+Link działa do {{.Expires}}. Jeśli nie spodziewasz się tej wiadomości, możesz ją zignorować.
diff --git a/Server/internal/mail/templates/test.de.html b/Server/internal/mail/templates/test.de.html
new file mode 100644
index 0000000..5844183
--- /dev/null
+++ b/Server/internal/mail/templates/test.de.html
@@ -0,0 +1,2 @@
+
Dies ist eine Test-E-Mail von {{.AppName}}.
+
Der Mailversand funktioniert.
diff --git a/Server/internal/mail/templates/test.de.txt b/Server/internal/mail/templates/test.de.txt
new file mode 100644
index 0000000..088197b
--- /dev/null
+++ b/Server/internal/mail/templates/test.de.txt
@@ -0,0 +1,2 @@
+Test-E-Mail von {{.AppName}}
+Dies ist eine Test-E-Mail von {{.AppName}}. Der Mailversand funktioniert.
diff --git a/Server/internal/mail/templates/test.es.html b/Server/internal/mail/templates/test.es.html
new file mode 100644
index 0000000..d2c5908
--- /dev/null
+++ b/Server/internal/mail/templates/test.es.html
@@ -0,0 +1,2 @@
+
Este es un correo de prueba de {{.AppName}}.
+
El envío de correo funciona.
diff --git a/Server/internal/mail/templates/test.es.txt b/Server/internal/mail/templates/test.es.txt
new file mode 100644
index 0000000..6a62627
--- /dev/null
+++ b/Server/internal/mail/templates/test.es.txt
@@ -0,0 +1,2 @@
+Correo de prueba de {{.AppName}}
+Este es un correo de prueba de {{.AppName}}. El envío de correo funciona.
diff --git a/Server/internal/mail/templates/test.fr.html b/Server/internal/mail/templates/test.fr.html
new file mode 100644
index 0000000..e0c59be
--- /dev/null
+++ b/Server/internal/mail/templates/test.fr.html
@@ -0,0 +1,2 @@
+
Ceci est un e-mail de test de {{.AppName}}.
+
L’envoi des e-mails fonctionne.
diff --git a/Server/internal/mail/templates/test.fr.txt b/Server/internal/mail/templates/test.fr.txt
new file mode 100644
index 0000000..c42856c
--- /dev/null
+++ b/Server/internal/mail/templates/test.fr.txt
@@ -0,0 +1,2 @@
+E-mail de test de {{.AppName}}
+Ceci est un e-mail de test de {{.AppName}}. L’envoi des e-mails fonctionne.
diff --git a/Server/internal/mail/templates/test.pl.html b/Server/internal/mail/templates/test.pl.html
new file mode 100644
index 0000000..8738054
--- /dev/null
+++ b/Server/internal/mail/templates/test.pl.html
@@ -0,0 +1,2 @@
+
To jest wiadomość testowa z {{.AppName}}.
+
Wysyłanie poczty działa.
diff --git a/Server/internal/mail/templates/test.pl.txt b/Server/internal/mail/templates/test.pl.txt
new file mode 100644
index 0000000..a39ab07
--- /dev/null
+++ b/Server/internal/mail/templates/test.pl.txt
@@ -0,0 +1,2 @@
+{{.AppName}}: wiadomość testowa
+To jest wiadomość testowa z {{.AppName}}. Wysyłanie poczty działa.
diff --git a/Server/internal/pbschema/schema.json b/Server/internal/pbschema/schema.json
index 0fcbb85..3b0372f 100644
--- a/Server/internal/pbschema/schema.json
+++ b/Server/internal/pbschema/schema.json
@@ -1292,13 +1292,64 @@
"values": [
"edgeless"
]
+ },
+ {
+ "cascadeDelete": false,
+ "collectionId": "_pb_users_auth_",
+ "help": "",
+ "hidden": false,
+ "id": "relation1624678591",
+ "maxSelect": 1,
+ "minSelect": 0,
+ "name": "verified_by",
+ "presentable": false,
+ "required": false,
+ "system": false,
+ "type": "relation"
+ },
+ {
+ "help": "",
+ "hidden": false,
+ "id": "date894078913",
+ "max": "",
+ "min": "",
+ "name": "verified_at",
+ "presentable": false,
+ "required": false,
+ "system": false,
+ "type": "date"
+ },
+ {
+ "help": "",
+ "hidden": false,
+ "id": "date1278849778",
+ "max": "",
+ "min": "",
+ "name": "verified_until",
+ "presentable": false,
+ "required": false,
+ "system": false,
+ "type": "date"
+ },
+ {
+ "help": "",
+ "hidden": false,
+ "id": "date1654594970",
+ "max": "",
+ "min": "",
+ "name": "verify_notified_at",
+ "presentable": false,
+ "required": false,
+ "system": false,
+ "type": "date"
}
],
"id": "pbc_3945946014",
"indexes": [
"CREATE INDEX idx_pages_workspace ON pages (workspace, updated)",
"CREATE INDEX idx_pages_tree ON pages (space, parent, position)",
- "CREATE INDEX `idx_pages_journal` ON `pages` (space, journal_date)"
+ "CREATE INDEX `idx_pages_journal` ON `pages` (space, journal_date)",
+ "CREATE INDEX idx_pages_verified_until ON pages (verified_until)"
],
"listRule": null,
"name": "pages",
@@ -3149,7 +3200,8 @@
"reminder",
"join_request",
"join_approved",
- "join_declined"
+ "join_declined",
+ "verify_expired"
]
},
{
diff --git a/Server/internal/search/files.go b/Server/internal/search/files.go
index 89c6e4f..10282bf 100644
--- a/Server/internal/search/files.go
+++ b/Server/internal/search/files.go
@@ -13,12 +13,12 @@ package search
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
- "unicode/utf8"
"docwell/server/internal/store/pocketbase"
"docwell/server/internal/textract"
@@ -116,6 +116,7 @@ func (x *Index) CatchUpFiles(ctx context.Context) error {
return err
}
pages := map[string]bool{}
+ var scanned []attachmentRow
batch := x.idx.NewBatch()
for _, a := range res.Items {
if !textract.Supported(a.Name) {
@@ -127,13 +128,16 @@ func (x *Index) CatchUpFiles(ctx context.Context) error {
} else if old != nil {
continue
}
- text, ok := x.readFile(ctx, a)
+ text, ok, scan := x.readFile(ctx, a)
if ctx.Err() != nil {
return ctx.Err()
}
if !ok {
continue // a download that failed is tried again by a rebuild
}
+ if scan {
+ scanned = append(scanned, a) // remembered empty until AI reads it (scans.go)
+ }
ft := fileText{Name: a.Name, Text: text}
data, _ := json.Marshal(ft)
batch.SetInternal(fileTextKey(a.ID), data)
@@ -149,6 +153,9 @@ func (x *Index) CatchUpFiles(ctx context.Context) error {
if err := x.idx.Batch(batch); err != nil {
return err
}
+ if err := x.queueScans(ctx, scanned); err != nil {
+ return err
+ }
if err := x.reindexPages(ctx, pages); err != nil {
return err
}
@@ -161,33 +168,43 @@ func (x *Index) CatchUpFiles(ctx context.Context) error {
// readFile downloads an attachment and reads its text: "" when it has none
// or cannot be read, and ok false when the download failed (not remembered,
-// so a rebuild tries it again).
-func (x *Index) readFile(ctx context.Context, a attachmentRow) (text string, ok bool) {
- if a.File == "" || a.Size > maxFileBytes {
- return "", true
+// so a rebuild tries it again). scan is true for a PDF without a text layer,
+// which AI may read later (scans.go).
+func (x *Index) readFile(ctx context.Context, a attachmentRow) (text string, ok, scan bool) {
+ data, ok := x.download(ctx, a, maxFileBytes)
+ if !ok || data == nil {
+ return "", ok, false
+ }
+ text, err := textract.Text(a.Name, data)
+ if errors.Is(err, textract.ErrNoText) {
+ return "", true, true
+ }
+ if err != nil {
+ return "", true, false
+ }
+ return cleanText(text), true, false
+}
+
+// download fetches an attachment's file: nil when it is larger than limit
+// (or has no file), ok false when the download failed.
+func (x *Index) download(ctx context.Context, a attachmentRow, limit int64) (data []byte, ok bool) {
+ if a.File == "" || a.Size > limit {
+ return nil, true
}
res, err := x.pb.OpenFile(ctx, "attachments", a.ID, a.File, http.Header{})
if err != nil {
x.log.Warn("search: attachment download", "id", a.ID, "err", err)
- return "", false
+ return nil, false
}
defer func() { _ = res.Body.Close() }()
- data, err := io.ReadAll(io.LimitReader(res.Body, maxFileBytes+1))
+ data, err = io.ReadAll(io.LimitReader(res.Body, limit+1))
if err != nil {
- return "", false
+ return nil, false
}
- if len(data) > maxFileBytes {
- return "", true
+ if int64(len(data)) > limit {
+ return nil, true
}
- text, err = textract.Text(a.Name, data)
- if err != nil {
- return "", true
- }
- text = strings.Join(strings.Fields(text), " ")
- if utf8.RuneCountInString(text) > maxFileText {
- text = string([]rune(text)[:maxFileText])
- }
- return text, true
+ return data, true
}
// reindexPages indexes these pages again, now that more of their files
diff --git a/Server/internal/search/files_test.go b/Server/internal/search/files_test.go
index e121eab..2f73cb8 100644
--- a/Server/internal/search/files_test.go
+++ b/Server/internal/search/files_test.go
@@ -64,6 +64,18 @@ func (f *fakeFiles) server(t *testing.T) *pocketbase.Client {
defer f.mu.Unlock()
reply(w, map[string]any{"items": f.atts, "totalItems": len(f.atts), "totalPages": 1})
})
+ mux.HandleFunc("GET /api/collections/attachments/records/{id}", func(w http.ResponseWriter, r *http.Request) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, a := range f.atts {
+ if a.ID == r.PathValue("id") {
+ reply(w, a)
+ return
+ }
+ }
+ w.WriteHeader(http.StatusNotFound)
+ reply(w, map[string]any{"message": "not found"})
+ })
mux.HandleFunc("POST /api/files/token", func(w http.ResponseWriter, r *http.Request) {
reply(w, map[string]string{"token": "ft"})
})
diff --git a/Server/internal/search/scans.go b/Server/internal/search/scans.go
new file mode 100644
index 0000000..c0f1f21
--- /dev/null
+++ b/Server/internal/search/scans.go
@@ -0,0 +1,223 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package search
+
+// Scanned PDFs: a PDF attachment without a text layer goes on a queue
+// instead of being read. When its workspace has AI read scans (ai/scans.go),
+// ReadScans has the AI provider write it out, a few files per pass, and its
+// page is indexed again with the text. Files wait on the queue while the
+// workspace has it turned off, so turning it on later reads them too.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "strings"
+ "unicode/utf8"
+
+ "docwell/server/internal/store/pocketbase"
+)
+
+// ScanReader reads scanned PDFs for the index (the AI service).
+type ScanReader interface {
+ // ReadsScans reports whether a workspace has its scanned PDFs read.
+ ReadsScans(ctx context.Context, workspace string) bool
+ // ReadScan writes out a scanned PDF's text, or returns the reader's
+ // "turned off" error (see UseScans) when the workspace does not read them.
+ ReadScan(ctx context.Context, workspace string, data []byte) (string, error)
+}
+
+// scanHook is the scan reader and its "turned off" error.
+type scanHook struct {
+ r ScanReader
+ off error
+}
+
+// UseScans sets who reads scanned PDFs; without one they stay on the queue.
+// off is the reader's "turned off" error.
+func (x *Index) UseScans(r ScanReader, off error) {
+ x.scans.Store(&scanHook{r: r, off: off})
+}
+
+const scanQueueKey = "scanqueue"
+
+const (
+ maxScanQueue = 5000 // files waiting; the oldest are dropped past this
+ scansPerPass = 5 // files read per pass
+ maxScanTries = 3 // failed reads before a file is given up on
+ scanFileLimit = 20 << 20 // larger scans are not sent
+)
+
+// scanEntry is one scanned PDF waiting to be read.
+type scanEntry struct {
+ ID string `json:"id"`
+ Page string `json:"page"`
+ Workspace string `json:"workspace"`
+ Tries int `json:"tries,omitempty"`
+}
+
+func (x *Index) loadScans() ([]scanEntry, error) {
+ raw, err := x.idx.GetInternal([]byte(scanQueueKey))
+ if err != nil || len(raw) == 0 {
+ return nil, err
+ }
+ var q []scanEntry
+ if json.Unmarshal(raw, &q) != nil {
+ return nil, nil
+ }
+ return q, nil
+}
+
+func (x *Index) saveScans(q []scanEntry) error {
+ if len(q) > maxScanQueue {
+ q = q[len(q)-maxScanQueue:]
+ }
+ data, _ := json.Marshal(q)
+ return x.idx.SetInternal([]byte(scanQueueKey), data)
+}
+
+// queueScans adds scanned PDFs found by CatchUpFiles (x.mu held).
+func (x *Index) queueScans(ctx context.Context, found []attachmentRow) error {
+ if len(found) == 0 {
+ return nil
+ }
+ q, err := x.loadScans()
+ if err != nil {
+ return err
+ }
+ have := map[string]bool{}
+ for _, e := range q {
+ have[e.ID] = true
+ }
+ for _, a := range found {
+ if have[a.ID] || a.Page == "" {
+ continue
+ }
+ p, err := pocketbase.Get[pageRow](ctx, x.pb, "pages", a.Page)
+ if err != nil {
+ continue
+ }
+ q = append(q, scanEntry{ID: a.ID, Page: a.Page, Workspace: p.Workspace})
+ have[a.ID] = true
+ }
+ return x.saveScans(q)
+}
+
+// ScansWaiting is how many scanned PDFs wait to be read.
+func (x *Index) ScansWaiting() int {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ q, _ := x.loadScans()
+ return len(q)
+}
+
+// ReadScans reads a few queued scanned PDFs of workspaces that read scans,
+// and indexes their pages again.
+func (x *Index) ReadScans(ctx context.Context) error {
+ hook := x.scans.Load()
+ if hook == nil {
+ return nil
+ }
+ x.mu.Lock()
+ q, err := x.loadScans()
+ x.mu.Unlock()
+ if err != nil || len(q) == 0 {
+ return err
+ }
+ on := map[string]bool{}
+ done := map[string]bool{} // read, or gone: off the queue
+ failed := map[string]bool{} // tried again later, up to maxScanTries
+ read := map[string]fileText{}
+ pages := map[string]bool{}
+ n := 0
+ for _, e := range q {
+ if n >= scansPerPass || ctx.Err() != nil {
+ break
+ }
+ ok, seen := on[e.Workspace]
+ if !seen {
+ ok = hook.r.ReadsScans(ctx, e.Workspace)
+ on[e.Workspace] = ok
+ }
+ if !ok {
+ continue
+ }
+ n++
+ a, err := pocketbase.Get[attachmentRow](ctx, x.pb, "attachments", e.ID)
+ if err != nil {
+ if pocketbase.IsNotFound(err) {
+ done[e.ID] = true
+ } else {
+ failed[e.ID] = true
+ }
+ continue
+ }
+ data, ok := x.download(ctx, a, scanFileLimit)
+ if !ok {
+ failed[e.ID] = true
+ continue
+ }
+ if data == nil { // too large to send
+ done[e.ID] = true
+ continue
+ }
+ text, err := hook.r.ReadScan(ctx, e.Workspace, data)
+ switch {
+ case hook.off != nil && errors.Is(err, hook.off):
+ on[e.Workspace] = false
+ case err != nil:
+ x.log.Warn("search: reading a scanned PDF", "id", e.ID, "err", err)
+ failed[e.ID] = true
+ default:
+ read[e.ID] = fileText{Name: a.Name, Text: cleanText(text)}
+ done[e.ID] = true
+ if a.Page != "" {
+ pages[a.Page] = true
+ }
+ }
+ }
+ if len(done) == 0 && len(failed) == 0 {
+ return nil
+ }
+
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ // The queue may have grown meanwhile: apply the results to the current one.
+ cur, err := x.loadScans()
+ if err != nil {
+ return err
+ }
+ next := make([]scanEntry, 0, len(cur))
+ for _, e := range cur {
+ if done[e.ID] {
+ continue
+ }
+ if failed[e.ID] {
+ if e.Tries++; e.Tries >= maxScanTries {
+ continue
+ }
+ }
+ next = append(next, e)
+ }
+ batch := x.idx.NewBatch()
+ for id, ft := range read {
+ data, _ := json.Marshal(ft)
+ batch.SetInternal(fileTextKey(id), data)
+ }
+ if err := x.idx.Batch(batch); err != nil {
+ return err
+ }
+ if err := x.saveScans(next); err != nil {
+ return err
+ }
+ return x.reindexPages(ctx, pages)
+}
+
+// cleanText is file text as the index keeps it: spaces folded, length capped.
+func cleanText(text string) string {
+ text = strings.Join(strings.Fields(text), " ")
+ if utf8.RuneCountInString(text) > maxFileText {
+ text = string([]rune(text)[:maxFileText])
+ }
+ return text
+}
diff --git a/Server/internal/search/scans_test.go b/Server/internal/search/scans_test.go
new file mode 100644
index 0000000..6c46480
--- /dev/null
+++ b/Server/internal/search/scans_test.go
@@ -0,0 +1,152 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package search
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "log/slog"
+ "sync"
+ "testing"
+
+ "github.com/go-pdf/fpdf"
+)
+
+var errOff = errors.New("off")
+
+// fakeScanner reads every scan as the same text, for workspaces turned on.
+type fakeScanner struct {
+ mu sync.Mutex
+ on map[string]bool
+ fail error
+ reads int
+}
+
+func (s *fakeScanner) ReadsScans(_ context.Context, ws string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.on[ws]
+}
+
+func (s *fakeScanner) ReadScan(_ context.Context, ws string, _ []byte) (string, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.reads++
+ if !s.on[ws] {
+ return "", errOff
+ }
+ if s.fail != nil {
+ return "", s.fail
+ }
+ return "Signed lease agreement for the warehouse", nil
+}
+
+// scannedPDF is a PDF with a drawing and no text layer.
+func scannedPDF(t *testing.T) []byte {
+ t.Helper()
+ doc := fpdf.New("P", "mm", "A4", "")
+ doc.AddPage()
+ doc.Rect(20, 20, 80, 40, "F")
+ var buf bytes.Buffer
+ if err := doc.Output(&buf); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func TestScannedPDFsWaitForAI(t *testing.T) {
+ f := &fakeFiles{
+ pages: map[string]pageRow{"page00000000001": pageLinking("page00000000001", "Leases", "scan00000000001")},
+ atts: []attachmentRow{
+ {ID: "scan00000000001", Page: "page00000000001", File: "scan_abc.pdf", Name: "Lease.pdf", Size: 2000, Updated: "2026-11-01 10:00:00.000Z"},
+ },
+ files: map[string][]byte{"scan00000000001": scannedPDF(t)},
+ }
+ x, err := OpenMemory(f.server(t), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = x.Close() })
+ ctx := context.Background()
+ if err := x.CatchUp(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if err := x.CatchUpFiles(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if n := x.ScansWaiting(); n != 1 {
+ t.Fatalf("waiting %d, want 1", n)
+ }
+ find := func() []Hit {
+ t.Helper()
+ hits, _, err := x.Query(ctx, "w1", []string{"s1"}, "warehouse", Filter{}, 10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return hits
+ }
+
+ // Without a reader, or with the workspace turned off, the scan waits.
+ if err := x.ReadScans(ctx); err != nil {
+ t.Fatal(err)
+ }
+ sc := &fakeScanner{on: map[string]bool{}}
+ x.UseScans(sc, errOff)
+ if err := x.ReadScans(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if sc.reads != 0 || x.ScansWaiting() != 1 || len(find()) != 0 {
+ t.Fatalf("read while off: reads %d, waiting %d", sc.reads, x.ScansWaiting())
+ }
+
+ // Turned on: read once, indexed under its page, off the queue.
+ sc.on["w1"] = true
+ if err := x.ReadScans(ctx); err != nil {
+ t.Fatal(err)
+ }
+ hits := find()
+ if len(hits) != 1 || hits[0].File == nil || hits[0].File.Name != "Lease.pdf" {
+ t.Fatalf("hits %+v", hits)
+ }
+ if x.ScansWaiting() != 0 || sc.reads != 1 {
+ t.Fatalf("waiting %d, reads %d", x.ScansWaiting(), sc.reads)
+ }
+ // A later file pass does not queue it again.
+ if err := x.CatchUpFiles(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if x.ScansWaiting() != 0 {
+ t.Fatal("queued again")
+ }
+}
+
+func TestScannedPDFsAreGivenUpAfterFailures(t *testing.T) {
+ f := &fakeFiles{
+ pages: map[string]pageRow{"page00000000001": pageLinking("page00000000001", "Leases", "scan00000000001")},
+ atts: []attachmentRow{
+ {ID: "scan00000000001", Page: "page00000000001", File: "scan_abc.pdf", Name: "Lease.pdf", Size: 2000, Updated: "2026-11-01 10:00:00.000Z"},
+ },
+ files: map[string][]byte{"scan00000000001": scannedPDF(t)},
+ }
+ x, err := OpenMemory(f.server(t), slog.New(slog.NewTextHandler(io.Discard, nil)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = x.Close() })
+ ctx := context.Background()
+ if err := x.CatchUpFiles(ctx); err != nil {
+ t.Fatal(err)
+ }
+ sc := &fakeScanner{on: map[string]bool{"w1": true}, fail: errors.New("provider down")}
+ x.UseScans(sc, errOff)
+ for i := 1; i <= maxScanTries; i++ {
+ if err := x.ReadScans(ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if sc.reads != maxScanTries || x.ScansWaiting() != 0 {
+ t.Fatalf("reads %d, waiting %d", sc.reads, x.ScansWaiting())
+ }
+}
diff --git a/Server/internal/search/search.go b/Server/internal/search/search.go
index 528eaa2..ae54c5f 100644
--- a/Server/internal/search/search.go
+++ b/Server/internal/search/search.go
@@ -23,6 +23,7 @@ import (
"path/filepath"
"strings"
"sync"
+ "sync/atomic"
"time"
"unicode/utf8"
@@ -123,6 +124,9 @@ type Index struct {
mu sync.Mutex // serializes indexing passes
track func(name string, fn func() error) error
+
+ // scans reads scanned PDFs (scans.go); set once the AI service is up.
+ scans atomic.Pointer[scanHook]
}
// Track reports each indexing pass to fn (the admin panel's job list).
@@ -317,7 +321,7 @@ func (x *Index) Remove(id string) error { return x.idx.Delete(id) }
func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
tick := time.NewTicker(interval)
defer tick.Stop()
- lastSweep := time.Time{}
+ lastSweep, lastScans := time.Time{}, time.Time{}
for {
if err := x.tracked("search.index", func() error { return x.CatchUp(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: indexing failed", "err", err)
@@ -325,6 +329,12 @@ func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
if err := x.tracked("search.files", func() error { return x.CatchUpFiles(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: reading attachments failed", "err", err)
}
+ if x.scans.Load() != nil && time.Since(lastScans) >= time.Minute {
+ if err := x.tracked("search.scans", func() error { return x.ReadScans(ctx) }); err != nil && ctx.Err() == nil {
+ x.log.Warn("search: reading scanned PDFs failed", "err", err)
+ }
+ lastScans = time.Now()
+ }
if time.Since(lastSweep) >= sweepEvery {
if err := x.tracked("search.sweep", func() error { return x.Sweep(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: sweep failed", "err", err)
diff --git a/Server/internal/settings/settings.go b/Server/internal/settings/settings.go
index 59b98e3..c27eda4 100644
--- a/Server/internal/settings/settings.go
+++ b/Server/internal/settings/settings.go
@@ -19,6 +19,7 @@ import (
"docwell/server/internal/access"
"docwell/server/internal/apperr"
+ "docwell/server/internal/i18n"
"docwell/server/internal/mail"
"docwell/server/internal/store/pocketbase"
)
@@ -617,7 +618,7 @@ func (s *Service) TestEmail(ctx context.Context, c access.Caller, to string) err
if err != nil {
return err
}
- m, err := mail.Render(to, "test", map[string]string{"AppName": b.AppName})
+ m, err := mail.RenderIn(i18n.Lang(ctx), to, "test", map[string]string{"AppName": b.AppName})
if err != nil {
return err
}
diff --git a/Web-App/frontend/src/app.ts b/Web-App/frontend/src/app.ts
index 461ab8b..f509427 100644
--- a/Web-App/frontend/src/app.ts
+++ b/Web-App/frontend/src/app.ts
@@ -22,9 +22,11 @@ export async function createDocwellApp(platform: Platform, el: string | Element
const tokens = platform.tokenStore ? await platform.tokenStore() : createTokenStore();
const router = createDocwellRouter(platform);
const auth = useAuthStore(pinia);
+ const i18n = createDocwellI18n();
const api = createClient({
baseUrl: config.apiUrl,
token: tokens.get,
+ locale: () => i18n.global.locale.value,
onUnauthorized: () => {
auth.clear();
// During start-up the router guard decides where to go; public pages
@@ -41,7 +43,7 @@ export async function createDocwellApp(platform: Platform, el: string | Element
app.provide(configKey, config);
app.provide(apiKey, api);
app.provide(tokenKey, tokens.get);
- app.use(createDocwellI18n());
+ app.use(i18n);
app.use(router);
app.mount(el);
platform.onOpenRoute?.((route) => void router.push(route));
diff --git a/Web-App/frontend/src/components/PageVerify.vue b/Web-App/frontend/src/components/PageVerify.vue
new file mode 100644
index 0000000..da1fe38
--- /dev/null
+++ b/Web-App/frontend/src/components/PageVerify.vue
@@ -0,0 +1,105 @@
+
+
+
+
+