Add database relations and rollups, full-page records, and translate the admin panel and phone app
CI / go (Server) (push) Failing after 4m38s
CI / go (Web-App) (push) Successful in 12m18s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / frontend (push) Failing after 7m49s
CI / desktop (ubuntu-latest) (push) Successful in 1h25m30s
CI / mobile (push) Failing after 5m14s
CI / docker (push) Successful in 39m26s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

Databases (ADR-13 follow-ups):
- Relation properties link records to another database, on the same page
  or on any page the reader can open (read live and read-only, like synced
  pages). Cells list the linked titles; clicking one opens the record.
- Rollup properties work out counts, sums, averages, medians, min/max,
  ranges, earliest/latest dates and checked counts over related records.
  Neither is stored: views compute them before drawing (linked.ts), so they
  follow both databases live, and rollups sort and filter as numbers.
- Exports (Markdown, HTML, PDF, Word) resolve them for same-page databases.
- A record opens as a full page at /p/<page>/r/<database>/<record>, with
  "Open as full page" on the side panel and "Back to the page".

Edgeless mode (ADR-14 follow-ups):
- History previews show a version's canvas and count canvas changes.
- Comments can be anchored to canvas elements (anchor {element}); elements
  with open threads show a badge that opens the thread.
- Workspaces choose how new pages open (workspaces.default_page_mode); the
  per-device choice now defaults to following the workspace.
- Phones edit the canvas once a page is opened for editing; the page note
  shows the page title.

Languages:
- The admin panel speaks English, Polish, German, French and Spanish, with
  a picker sharing the web app's setting and a key parity test.
- The phone app speaks the same five, follows the phone's language (and
  Android's per-app language setting), and has its own parity test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-15 17:11:47 +01:00
1 parent e927653e4b
commit 0640004895
99 files changed
+4721 -564

No files matched your search

@@ -0,0 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// The view new pages of a workspace open in: text ("") or the edgeless
// canvas (ADR-14). Each page keeps its own default_mode after that.
migrate(
(app) => {
const ws = app.findCollectionByNameOrId("workspaces");
ws.fields.add(new SelectField({ name: "default_page_mode", maxSelect: 1, values: ["edgeless"] }));
app.save(ws);
},
(app) => {
const ws = app.findCollectionByNameOrId("workspaces");
ws.fields.removeByName("default_page_mode");
app.save(ws);
},
);
+4
View File
@@ -15,6 +15,10 @@ Superadmins and organization admins can sign in; organization admins see only th
| **Security** | The audit log (sign-ins and every change, with who, when and from where; searchable, exportable as CSV) and everyone's API tokens. |
| **Maintenance** | Create, download and delete backups; see the background jobs (search indexing) and run them by hand. |
The panel speaks English, Polish, German, French and Spanish: it follows the browser's language, and the picker
under your name in the sidebar chooses another on this device (the web app's picker uses the same setting where both
share an address).
Everything except Users, Organizations and Security is for superadmins only. Organization admins see their own organization's people, audit log and tokens.
## Sign-in providers
+27 -10
View File
@@ -43,7 +43,7 @@ choose **Group as database** in the list's ⠿ menu) to turn each item into a re
it together, and Ctrl+Z undoes database changes like any other.
- **Properties** are the columns: title, text, number, checkbox, select, multi-select, date, progress, link,
attachment, member, created time and created by. Click a column's name to rename it, change its type (values are
attachment, member, created time, created by, relation and rollup. Click a column's name to rename it, change its type (values are
converted), sort or filter by it, hide it, move it, or insert another next to it. Drag its edge to resize it, or its
name to move it.
- **Cells:** click a cell and type, or press Enter to edit it; arrow keys and Tab move between cells, Delete clears
@@ -54,9 +54,18 @@ it together, and Ctrl+Z undoes database changes like any other.
**calendar** that places records on a date property (drag them to another day). Click the active tab to rename,
duplicate, change or delete the view; which view you look at is yours alone.
- **Records as pages:** **Open** on a record, or a click on a card, opens it beside the page, with its properties on
top and room to write below. The link button there, or **Copy link to record** when you right-click a row, copies
a link that opens the page with that record open; it works for anyone who can open the page. On a public link,
the same buttons copy a link to the record on that public page.
top and room to write below. **Open as full page** (the arrow button) shows the record on its own, in the page's
place, with an address of its own (`/p/<page>/r/<database>/<record>`); **Back to the page** returns. The link
button, or **Copy link to record** when you right-click a row, copies a link that opens the page with that record
open; it works for anyone who can open the page. On a public link, the same buttons copy a link to the record on
that public page.
- **Relations** link records to records of another database, on the same page or on any page you can open (find it
by its title when you choose the database). A relation cell lists the linked records' titles; click one to open
it, or click the cell to link and unlink records. Changes in the other database show at once.
- **Rollups** sum up one property of the related records: count them or their values, sum, average, median, min,
max or range of numbers, earliest and latest dates, how many are checked, or just list the values. Choose the
relation, the property and the calculation in the column's **Rollup** menu. Rollups sort and filter like numbers
when they are numbers.
- **CSV:** the ⋯ menu exports the current view as a CSV file, or adds records from one; an empty database takes the
file's columns and guesses their types.
@@ -65,7 +74,9 @@ record. To drag a record with a finger, drag a row by its ⠿ grip, a board card
calendar entry by the entry itself. The formatting bar acts on an open record's notes while you are writing in them.
Columns are moved with **Move left** and **Move right** in their menu.
Exports (Markdown, HTML, PDF, Word) show a database as a table of its first view's columns. Search lists a matching
Exports (Markdown, HTML, PDF, Word) show a database as a table of its first view's columns, with relations and
rollups worked out from databases on the same page (a relation to another page's database shows how many records it
links to). Search lists a matching
record on its own, under the page that holds it, and opens it there. On a public link or in **History**, databases are
read-only.
@@ -74,8 +85,9 @@ read-only.
Every page can also be shown as a whiteboard. The two buttons next to the page's title in the header switch between
**Page** and **Edgeless**; the page's text becomes a note on an endless canvas, and typing in that note is typing in the
page. To have a page open as a canvas for everyone, choose **Open as canvas for everyone** in the page's ⋯ menu; a link
with `?mode=edgeless` (or `?mode=page`) opens one view either way. **Account settings → Editor** can make new pages
start as canvases.
with `?mode=edgeless` (or `?mode=page`) opens one view either way. Workspace admins choose how new pages of the
workspace open (**Workspace settings → New pages open as**), and **Account settings → Editor** can choose otherwise for
the pages you make on your device.
- **Tools** sit at the bottom: select (V), hand (H), note (N), text (T), shape (S: square, rounded rectangle,
ellipse, diamond or triangle, drawn plain or scribbled), connector (C: straight, curved or elbowed, stuck to what it
@@ -92,10 +104,15 @@ start as canvases.
- **Frames** carry what is inside them when they move. **Present** (in the tools, or the ⋯ menu) shows the frames
one after another, full screen; the arrow keys step and Escape ends.
- **Export:** the ⋯ menu saves the canvas as a PNG or SVG picture.
- **Comments:** select an element and choose **Comment** in the bar above it (people who may only comment can do this
too). Elements with open threads show a speech bubble with the number of threads; click it to open the thread, and
clicking a thread in the Comments panel brings its element into view.
Readers of a public link see the canvas read-only, and so does the mobile app: the canvas button in its title bar
switches between the text and the canvas. The canvas's text (shapes, notes, frames, mind maps) is found by search, and
**History** brings an old canvas back with the text.
Readers of a public link see the canvas read-only. In the mobile app, the canvas button in the title bar switches
between the text and the canvas; **Edit** works on the canvas too, with the same tools at the bottom (drag with one
finger, pinch to zoom). The canvas's text (shapes, notes, frames, mind maps) is found by search. In **History**, a
version with a canvas has a **Canvas** tab, **Changes** counts the canvas elements added, removed and changed, and
restoring brings the old canvas back with the text.
## Comments
+3
View File
@@ -348,6 +348,9 @@ export function createClient(opts: ClientOptions) {
create: (name: string, organization?: string) => post<Workspace>("/api/v1/workspaces", { name, organization }),
rename: (id: string, name: string) =>
request<Workspace>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { name }),
/** Changes how the workspace's new pages open: as text or as a canvas. */
setDefaultPageMode: (id: string, defaultPageMode: PageMode) =>
request<Workspace>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}`, { defaultPageMode }),
remove: (id: string) => request<void>("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}`),
members: (id: string) =>
request<WorkspaceMember[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/members`),
+9 -4
View File
@@ -566,8 +566,8 @@ export interface paths {
delete: operations["deleteWorkspace"];
options?: never;
head?: never;
/** Rename a workspace (workspace admin or above) */
patch: operations["renameWorkspace"];
/** Rename a workspace or change how its new pages open (workspace admin or above) */
patch: operations["updateWorkspace"];
trace?: never;
};
"/api/v1/workspaces/{id}/members": {
@@ -2536,6 +2536,8 @@ export interface components {
organizationName: string;
role: components["schemas"]["WorkspaceRole"];
created: string;
/** @description The view new pages of the workspace open in */
defaultPageMode: components["schemas"]["PageMode"];
};
WorkspaceMember: {
user: {
@@ -4295,7 +4297,7 @@ export interface operations {
404: components["responses"]["Error"];
};
};
renameWorkspace: {
updateWorkspace: {
parameters: {
query?: never;
header?: never;
@@ -4306,7 +4308,10 @@ export interface operations {
};
requestBody: {
content: {
"application/json": components["schemas"]["NameRequest"];
"application/json": {
name?: string;
defaultPageMode?: components["schemas"]["PageMode"];
};
};
};
responses: {
+25
View File
@@ -409,6 +409,31 @@
stroke: var(--dw-accent, #2f7d6d);
stroke-width: 1;
}
.dw-cv-badge {
pointer-events: all;
cursor: pointer;
}
.dw-cv-badge path {
fill: var(--dw-warning-soft, #fdf3d7);
stroke: var(--dw-warning, #9a7400);
stroke-width: 1.25;
}
.dw-cv-badge text {
fill: var(--dw-ink);
font-size: 11px;
font-weight: 600;
}
.dw-cv-badge-active path {
fill: var(--dw-warning, #9a7400);
}
.dw-cv-badge-active text {
fill: var(--dw-surface);
}
.dw-cv-commented {
fill: color-mix(in srgb, var(--dw-warning, #9a7400) 10%, transparent);
stroke: var(--dw-warning, #9a7400);
stroke-width: 2;
}
.dw-cv-guide {
stroke: var(--dw-c-pink, #b8327a);
stroke-width: 1;
+11
View File
@@ -218,6 +218,17 @@ describe("CanvasView", () => {
expect(host.querySelector(".dw-cv-shape")?.textContent).toBe("Choose");
expect(host.querySelector(".dw-cv-root")?.textContent).toBe("Root idea");
expect(host.querySelectorAll(".dw-cv-toolbar .dw-cv-btn").length).toBeGreaterThan(10);
// Comments on elements: a badge with the thread count, and the element's words to quote.
const shapeId = host.querySelector<HTMLElement>(".dw-cv-shape")!.dataset.id!;
view.setComments([
{ comment: "c1", element: shapeId },
{ comment: "c2", element: shapeId },
]);
const badge = host.querySelector<SVGElement>(".dw-cv-badge");
expect(badge?.dataset.comment).toBe("c1");
expect(badge?.textContent).toContain("2");
expect(view.elementText(shapeId)).toBe("Choose");
expect(view.elementText("page")).toBe("Page body");
const svg = await (await view.exportImage("svg")).text();
expect(svg).toMatch(/^<svg xmlns/);
for (const word of ["Choose", "Root idea", "My page", "Page body"]) expect(svg).toContain(word);
+1
View File
@@ -3,6 +3,7 @@
export {
CanvasView,
type CanvasOptions,
type ElementComment,
type CanvasFiles,
type CanvasLinks,
type NoteHandle,
+3
View File
@@ -66,6 +66,8 @@ export interface CanvasLabels {
copy: string;
editText: string;
openLink: string;
/** Starts a comment thread on the selected element. */
comment: string;
frameTitle: string;
groupTitle: string;
linkPrompt: string;
@@ -172,6 +174,7 @@ export const englishCanvasLabels: CanvasLabels = {
copy: "Copy",
editText: "Edit text",
openLink: "Open link",
comment: "Comment",
frameTitle: "Frame",
groupTitle: "Group",
linkPrompt: "Link address",
+15 -1
View File
@@ -417,7 +417,8 @@ export class CanvasUI {
refresh(): void {
this.buildBar();
const sel = this.v.editable && !this.v.editing && !this.v.isPresenting ? this.v.selection() : [];
const sel =
(this.v.editable || this.v.opts.onComment) && !this.v.editing && !this.v.isPresenting ? this.v.selection() : [];
const key = JSON.stringify([sel, this.v.activeNode, this.v.styles.shape.rough]);
if (key !== this.lastProps) {
this.lastProps = key;
@@ -455,6 +456,18 @@ export class CanvasUI {
p.hidden = false;
const v = this.v;
const l = v.labels;
const comment = v.opts.onComment;
const commentButton = () =>
this.button(icon("comment"), l.comment, () => {
const id = sel[0]!.id;
comment?.({ id, text: v.elementText(id).slice(0, 500) });
});
if (!v.editable) {
// Readers only comment.
if (comment && sel.length === 1) p.append(commentButton());
else p.hidden = true;
return;
}
const types = new Set(sel.map((e) => e.type));
const one = types.size === 1 ? sel[0]! : null;
const group: HTMLElement[] = [];
@@ -623,6 +636,7 @@ export class CanvasUI {
group.push(this.button(icon("open"), l.openLink, () => window.open(one.url, "_blank", "noopener,noreferrer")));
}
p.append(...group);
if (comment && sel.length === 1) p.append(commentButton());
if (group.length) p.append(this.sep());
const groups = sel.filter((e) => e.type === "group");
if (sel.length > 1 && !groups.length) p.append(this.button(icon("group"), l.group, () => v.group()));
+113 -1
View File
@@ -45,6 +45,7 @@ import { brushPath, brushSVG, connectorSVG, esc, livePaint, shapeSVG } from "./r
import { SurfaceStore, type ElementJSON } from "./store";
import { CanvasUI } from "./ui";
import { exportCanvas, type ExportKind } from "./export";
import { fragmentToJSON, plainText } from "./yxml";
/** A note mounted by the host: the page's text or a note body, as an editor. */
export interface NoteMount {
@@ -94,6 +95,16 @@ export interface CanvasOptions {
/** Tracks undo for canvas edits (off for read-only snapshots). */
undo?: boolean;
onError?: (e: unknown) => void;
/** Offers "Comment" on a selected element; called with its id and text. */
onComment?: (el: { id: string; text: string }) => void;
/** A comment badge on an element was clicked. */
onCommentSelect?: (comment: string) => void;
}
/** A comment thread on an element: drawn as a badge on its corner. */
export interface ElementComment {
comment: string;
element: string;
}
export type Tool = "select" | "hand" | "note" | "text" | "shape" | "connector" | "pen" | "eraser" | "frame" | "mindmap";
@@ -166,6 +177,8 @@ export class CanvasView {
private pointers = new Map<number, Point>();
private pinch: { dist: number; mid: Point; zoom: number; vx: number; vy: number } | null = null;
private presenting: { frames: string[]; at: number; bar: HTMLElement } | null = null;
private comments: ElementComment[] = [];
private activeComment = "";
// Missing in some test environments; sizes then come from the stored boxes.
private readonly resize =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver((entries) => this.onResize(entries));
@@ -700,6 +713,7 @@ export class CanvasView {
}
}
}
if (!this.presenting) this.drawComments(parts, poly);
if (this.marquee) {
const [x, y] = this.toScreen([this.marquee.x, this.marquee.y]);
parts.push(
@@ -964,6 +978,12 @@ export class CanvasView {
}
private onDown(e: PointerEvent): void {
const badge = e.target instanceof Element ? e.target.closest<SVGElement>("[data-comment]") : null;
if (badge?.dataset.comment) {
e.preventDefault();
this.opts.onCommentSelect?.(badge.dataset.comment);
return;
}
if (this.inEditor(e.target)) return;
if (e.button === 2) return;
// The canvas moves focus itself (to a new note or label); the browser's
@@ -999,7 +1019,16 @@ export class CanvasView {
return pan();
}
const target = e.target as Element;
if (!this.editable) return pan();
if (!this.editable) {
// Readers who may comment pick an element to comment on; anything else pans.
const h = this.opts.onComment && this.tool === "select" ? this.hit(target) : null;
if (h) {
const id = this.pick(h.id);
this.select([id]);
return;
}
return pan();
}
switch (this.tool) {
case "pen": {
@@ -2039,6 +2068,89 @@ export class CanvasView {
this.select([id]);
}
// ---- Comments on elements ----
/** Draws comment badges; a newly active comment brings its element into view. */
setComments(list: ElementComment[], active = ""): void {
this.comments = list;
const changed = active !== this.activeComment;
this.activeComment = active;
const hit = active ? list.find((c) => c.comment === active) : undefined;
if (changed && hit) this.reveal(hit.element);
this.drawOverlay();
}
/** Pans an element into the middle of the view when it is not wholly visible. */
reveal(id: string): void {
const el = this.get(id);
if (!el) return;
const b = this.outerBox(el);
const r = this.root.getBoundingClientRect();
const [x1, y1] = this.toScreen([b.x, b.y]);
const [x2, y2] = this.toScreen([b.x + b.w, b.y + b.h]);
if (x1 >= 0 && y1 >= 0 && x2 <= r.width && y2 <= r.height) return;
const from = { ...this.view };
const fits = b.w * from.zoom < r.width - 64 && b.h * from.zoom < r.height - 64;
if (fits) {
const [cx, cy] = center(b);
this.view = { zoom: from.zoom, x: r.width / 2 - cx * from.zoom, y: r.height / 2 - cy * from.zoom };
} else this.fit(b, false);
const to = { ...this.view };
this.view = from;
this.animateTo(to);
}
/** An element's words, quoted with a comment on it. */
elementText(id: string): string {
const e = this.get(id);
if (!e) return "";
switch (e.type) {
case "shape":
case "text":
return e.text;
case "frame":
return e.title;
case "connector":
return e.label;
case "image":
return e.alt;
case "embed":
return e.url;
case "mindmap": {
const root = rootOf(e.nodes);
return root ? (e.nodes[root]?.text ?? "") : "";
}
case "note": {
const body = e.page ? this.opts.doc.getXmlFragment("default") : this.store.body(e.id);
return body ? plainText(fragmentToJSON(body)).join(" ").trim() : "";
}
default:
return "";
}
}
private drawComments(parts: string[], poly: (b: Box, deg: number) => string): void {
if (!this.comments.length) return;
const by = new Map<string, ElementComment[]>();
for (const c of this.comments) {
// A comment on a group member shows on the group while it is closed.
const id = this.get(c.element) ? this.pick(c.element) : "";
if (!id) continue;
by.set(id, [...(by.get(id) ?? []), c]);
}
for (const [id, list] of by) {
const el = this.get(id)!;
const b = this.outerBox(el);
const active = list.find((c) => c.comment === this.activeComment);
if (active) parts.push(`<polygon class="dw-cv-commented" points="${poly(this.boxOf(el), el.rotate)}"/>`);
const [x, y] = this.toScreen([b.x + b.w, b.y]);
const target = (active ?? list[0]!).comment;
parts.push(
`<g class="dw-cv-badge${active ? " dw-cv-badge-active" : ""}" data-comment="${esc(target)}" transform="translate(${x} ${y})"><title>${esc(this.labels.comment)}</title><path d="M-1 -21h20a4 4 0 0 1 4 4v10a4 4 0 0 1-4 4h-12l-6 5v-5h-2a4 4 0 0 1-4-4v-10a4 4 0 0 1 4-4z"/><text x="9" y="-9.5" text-anchor="middle">${list.length}</text></g>`,
);
}
}
// ---- Export ----
/** The canvas (or the selection) as an SVG or PNG file. */
+29 -29
View File
@@ -146,7 +146,7 @@ img.ProseMirror-separator {
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(Ok,this.editor.getAttributes(kk)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new D({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=Sk(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=Gp({find:Ak,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:Ak,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(kk)}),joinPredicate:e,editor:this.editor})),[t]}}),Nk=/^\s*(\[([( |x])?\])\s$/,Pk=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,Fk=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},Ik=Jp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,A(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>op(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[NO(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=Pk;let l=e=>{let t=Fk(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Lu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[Gp({find:Nk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Lk=Jp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Tp.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(kO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(rk.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(fk.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(Mk.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Ik.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Lk.configure(this.options.taskList)),e}});var Rk=`&nbsp;`,zk=`\xA0`,Bk=Jp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,A(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===Rk||n[0].text===Rk||n[0].raw===zk||n[0].text===zk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Rk||r[0].text===zk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Rk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Vk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Hk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Uk=_p.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Hp({find:Vk,type:this.type})]},addPasteRules(){return[Yp({find:Hk,type:this.type})]}}),Wk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Gk=_p.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,A(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleLine truncated
`).length:0;c!==o&&(o=c,i.textContent=Array.from({length:c},(e,t)=>t+1).join(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),Fj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Ij(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Lj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-left":[`M14 6l-6 6 6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8Line truncated
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),Fj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Ij(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Lj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-left":[`M14 6l-6 6 6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8Line truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:pP(e)).join(`
`)}function hP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function gP(e,t){return t?e.split(t).join(`
`):e}function _P(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function vP(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>gP(t.renderChildren(e),n.cellLineSeparator)).join(`
@@ -158,16 +158,16 @@ img.ProseMirror-separator {
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=mP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`).length,u=e.split(`
`).slice(0,l).join(`
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=lP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(T.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>RM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>zM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return VM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>WM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>GM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return qM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>oN(e,t),mergeCells:()=>({state:e,dispatch:t})=>XM(e,t),splitCell:()=>({state:e,dispatch:t})=>ZM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>nN(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>nN(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>rN(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>XM(e,t)?!0:ZM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>$M(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>aN(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>aN(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&PM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=EM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:dP,"Mod-Backspace":dP,Delete:dP,"Mod-Delete":dP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[kN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],UN({allowTableNodeSelection:this.options.allowTableNodeSelection}),SP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),wP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(CP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(eP.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(tP.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(nP.configure(this.options.tableRow)),e}}),TP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function EP(){return[Lk.configure({HTMLAttributes:{class:`dw-tasks`}}),Ik.configure({nested:!0})]}function DP(){return[wP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var OP=TP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),kP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),AP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,jP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,MP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`)){if(!o){a.push(``);continue}let e=``;for(let s of o.split(/(\s+)/)){let o=e+s;if(!e||XF(o,t,r,i)<=n)e=o;else for(a.push(e.trimEnd()),e=s.trimStart();e&&XF(e,t,r,i)>n;){let o=e.length-1;for(;o>1&&XF(e.slice(0,o),t,r,i)>n;)o--;a.push(e.slice(0,o)),e=e.slice(o)}}a.push(e)}return a}function QF(e,t){let n=t===0?18:15,r=t===0?600:400,i=ZF(e||` `,n,260,KF,r),a=Math.max(...i.map(e=>XF(e,n,KF,r)),t===0?60:40);return{w:Math.ceil(a)+(t===0?32:24),h:i.length*Math.round(n*1.4)+(t===0?20:14)}}var $F=56,eI=14;function tI(e){let t=Object.entries(e).filter(([,t])=>!t.parent||!e[t.parent]);return t.sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)),t[0]?.[0]??null}function nI(e,t){return Object.entries(e).filter(([e,n])=>n.parent===t&&e!==t).sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)).map(([e])=>e)}function rI(e,t,n){let r=tI(e),i=new Map,a=[];if(!r)return{root:``,boxes:i,edges:a,bounds:{x:0,y:0,w:0,h:0}};let o=new Map,s=new Set,c=(t,r)=>{if(!(s.has(t)||r>50)){s.add(t),o.set(t,n(e[t].text,r));for(let n of nI(e,t))c(n,r+1)}};c(r,0);let l=t=>nI(e,t).filter(e=>o.has(e)),u=new Map,d=e=>{let t=u.get(e);if(t!==void 0)return t;let n=l(e),r=n.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,n.length-1),i=Math.max(o.get(e).h,r);return u.set(e,i),i},f=(e,t,n,r,a,s)=>{let c=o.get(e),u=a===1?t:t-c.w;i.set(e,{id:e,x:u,y:n-c.h/2,w:c.w,h:c.h,depth:r,dir:a,parent:s}),p(e,l(e),a===1?u+c.w+$F:u-$F,n,r+1,a)},p=(e,t,n,r,i,a)=>{let o=r-(t.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,t.length-1))/2;for(let r of t){let t=d(r);f(r,n,o+t/2,i,a,e),o+=t+eI}},m=o.get(r);i.set(r,{id:r,x:0,y:0,w:m.w,h:m.h,depth:0,dir:1,parent:``});let h=m.h/2,g=l(r);if(t===`right`)p(r,g,m.w+$F,h,1,1);else if(t===`left`)p(r,g,-56,h,1,-1);else{let e=Math.ceil(g.length/2);p(r,g.slice(0,e),m.w+$F,h,1,1),p(r,g.slice(e),-56,h,1,-1)}for(let e of i.values()){if(!e.parent)continue;let t=i.get(e.parent),n=e.dir===1?[t.x+t.w,t.y+t.h/2]:[t.x,t.y+t.h/2],r=e.dir===1?[e.x,e.y+e.h/2]:[e.x+e.w,e.y+e.h/2];a.push({from:n,to:r,child:e.id})}let _=1/0,v=1/0,y=-1/0,b=-1/0;for(let e of i.values())_=Math.min(_,e.x),v=Math.min(v,e.y),y=Math.max(y,e.x+e.w),b=Math.max(b,e.y+e.h);return{root:r,boxes:i,edges:a,bounds:{x:_,y:v,w:y-_,h:b-v}}}function iI(e,t,n,r){let i=e.boxes.get(n);if(!i)return null;if(r===`ArrowUp`||r===`ArrowDown`){let a=i.parent?nI(t,i.parent).filter(t=>e.boxes.get(t)?.dir===i.dir):[];return a[a.indexOf(n)+(r===`ArrowUp`?-1:1)]??null}let a=r===`ArrowRight`?1:-1;return i.parent?a===i.dir?nI(t,n)[0]??null:i.parent:nI(t,n).find(t=>e.boxes.get(t)?.dir===a)??null}function aI(e,t){let n=(e[0]+t[0])/2;return`M${e[0]} ${e[1]} C${n} ${e[1]} ${n} ${t[1]} ${t[0]} ${t[1]}`}function oI(e,t,n,r=e=>e){return e*r(.5-t*(.5-n))}function sI(e){return[-e[0],-e[1]]}function cI(e,t){return[e[0]+t[0],e[1]+t[1]]}function lI(e,t){return[e[0]-t[0],e[1]-t[1]]}function uI(e,t){return[e[0]*t,e[1]*t]}function dI(e,t){return[e[0]/t,e[1]/t]}function fI(e){return[e[1],-e[0]]}function pI(e,t){return e[0]*t[0]+e[1]*t[1]}function mI(e,t){return e[0]===t[0]&&e[1]===t[1]}function hI(e){return Math.hypot(e[0],e[1])}function gI(e){return e[0]*e[0]+e[1]*e[1]}function _I(e,t){return gI(lI(e,t))}function vI(e){return dI(e,hI(e))}function yI(e,t){return Math.hypot(e[1]-t[1],e[0]-t[0])}function bI(e,t,n){let r=Math.sin(n),i=Math.cos(n),a=e[0]-t[0],o=e[1]-t[1],s=a*i-o*r,c=a*r+o*i;return[s+t[0],c+t[1]]}function xI(e,t,n){return cI(e,uI(lI(t,e),n))}function SI(e,t,n){return cI(e,uI(t,n))}var{min:CI,PI:wI}=Math,TI=.275,EI=wI+1e-4;function DI(e,t={}){let{size:n=16,smoothing:r=.5,thinning:i=.5,simulatePressure:a=!0,easing:o=e=>e,start:s={},end:c={},last:l=!1}=t,{cap:u=!0,easing:d=e=>e*(2-e)}=s,{cap:f=!0,easing:p=e=>--e*e*e+1}=c;if(e.length===0||n<=0)return[];let m=e[e.length-1].runningLength,h=s.taper===!1?0:s.taper===!0?Math.max(n,m):s.taper,g=c.taper===!1?0:c.taper===!0?Math.max(n,m):c.taper,_=(n*r)**2,v=[],y=[],b=e.slice(0,10).reduce((e,t)=>{let r=t.pressure;if(a){let i=CI(1,t.distance/n);r=CI(1,e+(CI(1,1-i)-e)*(i*TI))}return(e+r)/2},e[0].pressure),x=oI(n,i,e[e.length-1].pressure,o),S,C=e[0].vector,ee=e[0].point,te=ee,ne=ee,re=te,ie=!1;for(let t=0;t<e.length;t++){let{pressure:r}=e[t],{point:s,vector:c,distance:l,runningLength:u}=e[t];if(t<e.length-1&&m-u<3)continue;if(i){if(a){let e=CI(1,l/n),t=CI(1,1-e);r=CI(1,b+(t-b)*(e*TI))}x=oI(n,i,r,o)}else x=n/2;S===void 0&&(S=x);let f=u<h?d(u/h):1,ae=m-u<g?p((m-u)/g):1;x=Math.max(.01,x*Math.min(f,ae));let oe=(t<e.length-1?e[t+1]:e[t]).vector,se=t<e.length-1?pI(c,oe):1,ce=pI(c,C)<0&&!ie,le=se!==null&&se<0;if(ce||le){let e=uI(fI(C),x);for(let t=0;t<=1;t+=.07692307692307693)ne=bI(lI(s,e),s,EI*t),v.push(ne),re=bI(cI(s,e),s,EI*-t),y.push(re);ee=ne,te=re,le&&(ie=!0);continue}if(ie=!1,t===e.length-1){let e=uI(fI(c),x);v.push(lI(s,e)),y.push(cI(s,e));continue}let ue=uI(fI(xI(oe,c,se)),x);ne=lI(s,ue),(t<=1||_I(ee,ne)>_)&&(v.push(ne),ee=ne),re=cI(s,ue),(t<=1||_I(te,re)>_)&&(y.push(re),te=re),b=r,C=c}let ae=e[0].point.slice(0,2),oe=e.length>1?e[e.length-1].point.slice(0,2):cI(e[0].point,[1,1]),se=[],ce=[];if(eLine truncated
`:n(e)).join(``),r=(e,i)=>{for(let a of e)if(a.type===`heading`){let e=Number(a.attrs?.level)||1;t.push({text:n(a),size:[0,26,21,18,16,16,16][e]??16,weight:650})}else if(a.type===`paragraph`)t.push({text:i+n(a),size:15,weight:400});else if(a.type===`listItem`||a.type===`taskItem`){let e=a.type===`taskItem`?a.attrs?.checked?`☑ `:`☐ `:`• `,[i,...o]=a.content??[];i&&t.push({text:e+n(i),size:15,weight:400}),r(o,` `)}else a.type===`codeBlock`?t.push({text:n(a),size:13,weight:400}):a.content?.length&&r(a.content,i)};return r(e,``),t}function uR(e,t,n,r,i,a,o=400,s=`start`){let c=Math.round(r*1.35);return n.map((n,l)=>`<text x="${e}" y="${t+r+l*c}" font-size="${r}" font-family="${PL(a)}" font-weight="${o}" fill="${i}" text-anchor="${s}" xml:space="preserve">${PL(n)}</text>`).join(``)}async function dR(e){if(e.startsWith(`data:`))return e;try{let t=await fetch(e,{credentials:`include`});if(!t.ok)return null;let n=await t.blob();return await new Promise(e=>{let t=new FileReader;t.onload=()=>e(typeof t.result==`string`?t.result:null),t.onerror=()=>e(null),t.readAsDataURL(n)})}catch{return null}}async function fR(e){let t=cR(e.root),n=e.elements.filter(e=>e.type!==`group`),r=HP(VP(n.map(t=>e.boxOf(t)))??{x:0,y:0,w:400,h:300},32),i=t(`ink`,`line`),a=[];for(let r of n){let n=e.boxOf(r),o=r.rotate?` rotate(${r.rotate} ${n.w/2} ${n.h/2})`:``,s=e=>`<g transform="translate(${n.x} ${n.y})${o}">${e}</g>`;switch(r.type){case`shape`:{let e=ZF(r.text,r.fontSize,Math.max(20,n.w-16)),i=Math.round(r.fontSize*1.35),o=n.h/2-e.length*i/2-r.fontSize*.25;a.push(s(HL(r,t)+(r.text?uR(n.w/2,o,e,r.fontSize,t(r.textColor,`line`),KF,400,`middle`):``)));break}case`text`:{let e=YF(r.font),i=r.w?ZF(r.text,r.fontSize,r.w,e):r.text.split(`
`),o=r.align===`center`?n.w/2:r.align===`right`?n.w:0,c=r.align===`center`?`middle`:r.align===`right`?`end`:`start`;a.push(s(uR(o,0,i,r.fontSize,t(r.color,`line`),e,r.bold?650:400,c)));break}case`connector`:{let n=e.routeOf(r);if(a.push(WL(r,n,t)),r.label){let e=Math.min(240,r.label.length*8+16);a.push(`<rect x="${n.mid[0]-e/2}" y="${n.mid[1]-12}" width="${e}" height="24" rx="4" fill="${t(`paper`,`line`)}"/>`+uR(n.mid[0],n.mid[1]-12+3,[r.label],13,i,KF,400,`middle`))}break}case`brush`:a.push(s(KL(r,t)));break;case`frame`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)===`none`?`none`:t(r.background,`fill`)}" stroke="${t(`gray`,`line`)}" stroke-width="1.5"/>`+uR(4,-24,[r.title],13,t(`gray`,`line`),KF,600)));break;case`note`:{let o=e.noteBody(r),c=o?lR(qL(o)):[],l=18,u=`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`;if(r.page&&e.pageTitle){let t=ZF(e.pageTitle,26,n.w-48,KF,650);u+=uR(24,l-4,t,26,i,KF,650),l+=t.length*35+8}for(let e of c){let t=ZF(e.text,e.size,n.w-48,KF,e.weight);if(u+=uR(24,l,t,e.size,i,KF,e.weight),l+=t.length*Math.round(e.size*1.35)+8,l>n.h-12)break}a.push(s(u));break}case`image`:{let i=await dR(e.resolve(r.src));a.push(s(i?`<image href="${PL(i)}" width="${n.w}" height="${n.h}" preserveAspectRatio="xMidYMid meet"/>`:`<rect width="${n.w}" height="${n.h}" fill="${t(`ink`,`fill`)}"/>`));break}case`embed`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(`paper`,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`+uR(16,16,ZF(r.url,13,n.w-32),13,t(`blue`,`line`),KF)));break;case`mindmap`:{let n=e.layoutOf(r),o=t(r.color,`line`),s=t(r.color,`fill`),c=n.edges.map(e=>`<path d="${aI(e.from,e.to)}" fill="none" stroke="${o}" stroke-width="2"/>`).join(``);for(let e of n.boxes.values()){let n=e.depth===0?18:15,a=e.depth===0?600:400,l=e.depth===0?o:e.depth===1?s:t(`paper`,`line`),u=e.depth===0?t(`paper`,`line`):i;c+=`<rect x="${e.x}" y="${e.y}" width="${e.w}" height="${e.h}" rx="${e.depth===0?10:8}" fill="${l}" stroke="${o}" stroke-width="${e.depth===0?0:1.5}"/>`;let d=ZF(r.nodes[e.id]?.text||` `,n,260,KF,a);c+=uR(e.x+e.w/2,e.y+(e.h-d.length*Math.round(n*1.4))/2-2,d,n,u,KF,a,`middle`)}a.push(`<g transform="translate(${r.x} ${r.y})">${c}</g>`);break}}}return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${Math.ceil(r.w)}" height="${Math.ceil(r.h)}" viewBox="${r.x} ${r.y} ${r.w} ${r.h}"><rect x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" fill="${t(`paper`,`line`)}"/>${a.join(``)}</svg>`,box:r}}async function pR(e,t){let{svg:n,box:r}=await fR(t),i=new Blob([n],{type:`image/svg+xml`});if(e===`svg`)return i;let a=Math.min(2,8192/Math.max(r.w,r.h,1)),o=URL.createObjectURL(i);try{let e=await new Promise((e,t)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>t(Error(`could not draw the canvas`)),n.src=o}),t=document.createElement(`canvas`);t.width=Math.ceil(r.w*a),t.height=Math.ceil(r.h*a);let n=t.getContext(`2d`);if(!n)throw Error(`could not draw the canvas`);return n.drawImage(e,0,0,t.width,t.height),await new Promise((e,n)=>t.toBlob(t=>t?e(t):n(Error(`could not draw the canvas`)),`image/png`))}finally{URL.revokeObjectURL(o)}}var mR=.1,hR=4,gR=`http://www.w3.org/2000/svg`,_R=e=>e instanceof HTMLElement&&(e.isContentEditable||e.tagName===`INPUT`||e.tagName===`TEXTAREA`),vR=class{opts;store;labels;root;styles;editable;tool=`select`;shapeKind;selected=new Set;activeNode=null;editing=null;entered=null;world;overlay;ui;view={x:0,y:0,zoom:1};rendered=new Map;measured=new Map;layouts=new Map;routes=new Map;previews=new Map;drag=null;guides=[];marquee=null;hover=null;raf=0;spaceDown=!1;pointers=new Map;pinch=null;presenting=null;resize=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>this.onResize(e));unsub;cleanups=[];saveTimer;constructor(e,t){this.opts=t,this.labels=t.labels??dF,this.editable=t.editable,this.styles=PF(t.styles),this.shapeKind=this.styles.shape.shape,this.store=new eR(t.doc,{undo:t.undo!==!1}),this.root=document.createElement(`div`),this.root.className=`dw-cv`,this.root.tabIndex=0,this.root.setAttribute(`role`,`application`),this.root.dataset.testid=`edgeless-canvas`,this.world=document.createElement(`div`),this.world.className=`dw-cv-world`,this.overlay=document.createElementNS(gR,`svg`),this.overlay.classList.add(`dw-cv-overlay`),this.root.append(this.world,this.overlay),e.append(this.root),this.ui=new sR(this),this.root.classList.toggle(`dw-cv-readonly`,!this.editable),this.unsub=this.store.onChange(()=>this.schedule()),this.listen(),this.render(),this.restoreView()||this.fit(void 0,!1),this.applyView()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.saveTimer),this.saveView(),this.unsub(),this.resize?.disconnect();for(let e of this.cleanups)e();for(let e of this.rendered.values())e.note?.destroy();this.rendered.clear(),this.ui.destroy(),this.store.destroy(),this.root.remove()}setEditable(e){if(e!==this.editable){this.editable=e,this.root.classList.toggle(`dw-cv-reLine truncated
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=lP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(T.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>RM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>zM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return VM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>WM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>GM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return qM(e,t&&(e=>{n&&fP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>oN(e,t),mergeCells:()=>({state:e,dispatch:t})=>XM(e,t),splitCell:()=>({state:e,dispatch:t})=>ZM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>nN(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>nN(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>rN(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>XM(e,t)?!0:ZM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>$M(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>aN(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>aN(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&PM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=EM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:dP,"Mod-Backspace":dP,Delete:dP,"Mod-Delete":dP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[kN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],UN({allowTableNodeSelection:this.options.allowTableNodeSelection}),SP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),wP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(CP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(eP.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(tP.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(nP.configure(this.options.tableRow)),e}}),TP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function EP(){return[Lk.configure({HTMLAttributes:{class:`dw-tasks`}}),Ik.configure({nested:!0})]}function DP(){return[wP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var OP=TP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),kP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),AP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,jP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,MP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`)){if(!o){a.push(``);continue}let e=``;for(let s of o.split(/(\s+)/)){let o=e+s;if(!e||XF(o,t,r,i)<=n)e=o;else for(a.push(e.trimEnd()),e=s.trimStart();e&&XF(e,t,r,i)>n;){let o=e.length-1;for(;o>1&&XF(e.slice(0,o),t,r,i)>n;)o--;a.push(e.slice(0,o)),e=e.slice(o)}}a.push(e)}return a}function QF(e,t){let n=t===0?18:15,r=t===0?600:400,i=ZF(e||` `,n,260,KF,r),a=Math.max(...i.map(e=>XF(e,n,KF,r)),t===0?60:40);return{w:Math.ceil(a)+(t===0?32:24),h:i.length*Math.round(n*1.4)+(t===0?20:14)}}var $F=56,eI=14;function tI(e){let t=Object.entries(e).filter(([,t])=>!t.parent||!e[t.parent]);return t.sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)),t[0]?.[0]??null}function nI(e,t){return Object.entries(e).filter(([e,n])=>n.parent===t&&e!==t).sort((e,t)=>e[1].pos-t[1].pos||(e[0]<t[0]?-1:1)).map(([e])=>e)}function rI(e,t,n){let r=tI(e),i=new Map,a=[];if(!r)return{root:``,boxes:i,edges:a,bounds:{x:0,y:0,w:0,h:0}};let o=new Map,s=new Set,c=(t,r)=>{if(!(s.has(t)||r>50)){s.add(t),o.set(t,n(e[t].text,r));for(let n of nI(e,t))c(n,r+1)}};c(r,0);let l=t=>nI(e,t).filter(e=>o.has(e)),u=new Map,d=e=>{let t=u.get(e);if(t!==void 0)return t;let n=l(e),r=n.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,n.length-1),i=Math.max(o.get(e).h,r);return u.set(e,i),i},f=(e,t,n,r,a,s)=>{let c=o.get(e),u=a===1?t:t-c.w;i.set(e,{id:e,x:u,y:n-c.h/2,w:c.w,h:c.h,depth:r,dir:a,parent:s}),p(e,l(e),a===1?u+c.w+$F:u-$F,n,r+1,a)},p=(e,t,n,r,i,a)=>{let o=r-(t.reduce((e,t)=>e+d(t),0)+eI*Math.max(0,t.length-1))/2;for(let r of t){let t=d(r);f(r,n,o+t/2,i,a,e),o+=t+eI}},m=o.get(r);i.set(r,{id:r,x:0,y:0,w:m.w,h:m.h,depth:0,dir:1,parent:``});let h=m.h/2,g=l(r);if(t===`right`)p(r,g,m.w+$F,h,1,1);else if(t===`left`)p(r,g,-56,h,1,-1);else{let e=Math.ceil(g.length/2);p(r,g.slice(0,e),m.w+$F,h,1,1),p(r,g.slice(e),-56,h,1,-1)}for(let e of i.values()){if(!e.parent)continue;let t=i.get(e.parent),n=e.dir===1?[t.x+t.w,t.y+t.h/2]:[t.x,t.y+t.h/2],r=e.dir===1?[e.x,e.y+e.h/2]:[e.x+e.w,e.y+e.h/2];a.push({from:n,to:r,child:e.id})}let _=1/0,v=1/0,y=-1/0,b=-1/0;for(let e of i.values())_=Math.min(_,e.x),v=Math.min(v,e.y),y=Math.max(y,e.x+e.w),b=Math.max(b,e.y+e.h);return{root:r,boxes:i,edges:a,bounds:{x:_,y:v,w:y-_,h:b-v}}}function iI(e,t,n,r){let i=e.boxes.get(n);if(!i)return null;if(r===`ArrowUp`||r===`ArrowDown`){let a=i.parent?nI(t,i.parent).filter(t=>e.boxes.get(t)?.dir===i.dir):[];return a[a.indexOf(n)+(r===`ArrowUp`?-1:1)]??null}let a=r===`ArrowRight`?1:-1;return i.parent?a===i.dir?nI(t,n)[0]??null:i.parent:nI(t,n).find(t=>e.boxes.get(t)?.dir===a)??null}function aI(e,t){let n=(e[0]+t[0])/2;return`M${e[0]} ${e[1]} C${n} ${e[1]} ${n} ${t[1]} ${t[0]} ${t[1]}`}function oI(e,t,n,r=e=>e){return e*r(.5-t*(.5-n))}function sI(e){return[-e[0],-e[1]]}function cI(e,t){return[e[0]+t[0],e[1]+t[1]]}function lI(e,t){return[e[0]-t[0],e[1]-t[1]]}function uI(e,t){return[e[0]*t,e[1]*t]}function dI(e,t){return[e[0]/t,e[1]/t]}function fI(e){return[e[1],-e[0]]}function pI(e,t){return e[0]*t[0]+e[1]*t[1]}function mI(e,t){return e[0]===t[0]&&e[1]===t[1]}function hI(e){return Math.hypot(e[0],e[1])}function gI(e){return e[0]*e[0]+e[1]*e[1]}function _I(e,t){return gI(lI(e,t))}function vI(e){return dI(e,hI(e))}function yI(e,t){return Math.hypot(e[1]-t[1],e[0]-t[0])}function bI(e,t,n){let r=Math.sin(n),i=Math.cos(n),a=e[0]-t[0],o=e[1]-t[1],s=a*i-o*r,c=a*r+o*i;return[s+t[0],c+t[1]]}function xI(e,t,n){return cI(e,uI(lI(t,e),n))}function SI(e,t,n){return cI(e,uI(t,n))}var{min:CI,PI:wI}=Math,TI=.275,EI=wI+1e-4;function DI(e,t={}){let{size:n=16,smoothing:r=.5,thinning:i=.5,simulatePressure:a=!0,easing:o=e=>e,start:s={},end:c={},last:l=!1}=t,{cap:u=!0,easing:d=e=>e*(2-e)}=s,{cap:f=!0,easing:p=e=>--e*e*e+1}=c;if(e.length===0||n<=0)return[];let m=e[e.length-1].runningLength,h=s.taper===!1?0:s.taper===!0?Math.max(n,m):s.taper,g=c.taper===!1?0:c.taper===!0?Math.max(n,m):c.taper,_=(n*r)**2,v=[],y=[],b=e.slice(0,10).reduce((e,t)=>{let r=t.pressure;if(a){let i=CI(1,t.distance/n);r=CI(1,e+(CI(1,1-i)-e)*(i*TI))}return(e+r)/2},e[0].pressure),x=oI(n,i,e[e.length-1].pressure,o),S,C=e[0].vector,ee=e[0].point,te=ee,ne=ee,re=te,ie=!1;for(let t=0;t<e.length;t++){let{pressure:r}=e[t],{point:s,vector:c,distance:l,runningLength:u}=e[t];if(t<e.length-1&&m-u<3)continue;if(i){if(a){let e=CI(1,l/n),t=CI(1,1-e);r=CI(1,b+(t-b)*(e*TI))}x=oI(n,i,r,o)}else x=n/2;S===void 0&&(S=x);let f=u<h?d(u/h):1,ae=m-u<g?p((m-u)/g):1;x=Math.max(.01,x*Math.min(f,ae));let oe=(t<e.length-1?e[t+1]:e[t]).vector,se=t<e.length-1?pI(c,oe):1,ce=pI(c,C)<0&&!ie,le=se!==null&&se<0;if(ce||le){let e=uI(fI(C),x);for(let t=0;t<=1;t+=.07692307692307693)ne=bI(lI(s,e),s,EI*t),v.push(ne),re=bI(cI(s,e),s,EI*-t),y.push(re);ee=ne,te=re,le&&(ie=!0);continue}if(ie=!1,t===e.length-1){let e=uI(fI(c),x);v.push(lI(s,e)),y.push(cI(s,e));continue}let ue=uI(fI(xI(oe,c,se)),x);ne=lI(s,ue),(t<=1||_I(ee,ne)>_)&&(v.push(ne),ee=ne),re=cI(s,ue),(t<=1||_I(te,re)>_)&&(y.push(re),te=re),b=r,C=c}let ae=e[0].point.slice(0,2),oe=e.length>1?e[e.length-1].point.slice(0,2):cI(e[0].point,[1,1]),se=[],ce=[];if(eLine truncated
`:n(e)).join(``),r=(e,i)=>{for(let a of e)if(a.type===`heading`){let e=Number(a.attrs?.level)||1;t.push({text:n(a),size:[0,26,21,18,16,16,16][e]??16,weight:650})}else if(a.type===`paragraph`)t.push({text:i+n(a),size:15,weight:400});else if(a.type===`listItem`||a.type===`taskItem`){let e=a.type===`taskItem`?a.attrs?.checked?`☑ `:`☐ `:`• `,[i,...o]=a.content??[];i&&t.push({text:e+n(i),size:15,weight:400}),r(o,` `)}else a.type===`codeBlock`?t.push({text:n(a),size:13,weight:400}):a.content?.length&&r(a.content,i)};return r(e,``),t}function dR(e,t,n,r,i,a,o=400,s=`start`){let c=Math.round(r*1.35);return n.map((n,l)=>`<text x="${e}" y="${t+r+l*c}" font-size="${r}" font-family="${PL(a)}" font-weight="${o}" fill="${i}" text-anchor="${s}" xml:space="preserve">${PL(n)}</text>`).join(``)}async function fR(e){if(e.startsWith(`data:`))return e;try{let t=await fetch(e,{credentials:`include`});if(!t.ok)return null;let n=await t.blob();return await new Promise(e=>{let t=new FileReader;t.onload=()=>e(typeof t.result==`string`?t.result:null),t.onerror=()=>e(null),t.readAsDataURL(n)})}catch{return null}}async function pR(e){let t=lR(e.root),n=e.elements.filter(e=>e.type!==`group`),r=HP(VP(n.map(t=>e.boxOf(t)))??{x:0,y:0,w:400,h:300},32),i=t(`ink`,`line`),a=[];for(let r of n){let n=e.boxOf(r),o=r.rotate?` rotate(${r.rotate} ${n.w/2} ${n.h/2})`:``,s=e=>`<g transform="translate(${n.x} ${n.y})${o}">${e}</g>`;switch(r.type){case`shape`:{let e=ZF(r.text,r.fontSize,Math.max(20,n.w-16)),i=Math.round(r.fontSize*1.35),o=n.h/2-e.length*i/2-r.fontSize*.25;a.push(s(HL(r,t)+(r.text?dR(n.w/2,o,e,r.fontSize,t(r.textColor,`line`),KF,400,`middle`):``)));break}case`text`:{let e=YF(r.font),i=r.w?ZF(r.text,r.fontSize,r.w,e):r.text.split(`
`),o=r.align===`center`?n.w/2:r.align===`right`?n.w:0,c=r.align===`center`?`middle`:r.align===`right`?`end`:`start`;a.push(s(dR(o,0,i,r.fontSize,t(r.color,`line`),e,r.bold?650:400,c)));break}case`connector`:{let n=e.routeOf(r);if(a.push(WL(r,n,t)),r.label){let e=Math.min(240,r.label.length*8+16);a.push(`<rect x="${n.mid[0]-e/2}" y="${n.mid[1]-12}" width="${e}" height="24" rx="4" fill="${t(`paper`,`line`)}"/>`+dR(n.mid[0],n.mid[1]-12+3,[r.label],13,i,KF,400,`middle`))}break}case`brush`:a.push(s(KL(r,t)));break;case`frame`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)===`none`?`none`:t(r.background,`fill`)}" stroke="${t(`gray`,`line`)}" stroke-width="1.5"/>`+dR(4,-24,[r.title],13,t(`gray`,`line`),KF,600)));break;case`note`:{let o=e.noteBody(r),c=o?uR(qL(o)):[],l=18,u=`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(r.background,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`;if(r.page&&e.pageTitle){let t=ZF(e.pageTitle,26,n.w-48,KF,650);u+=dR(24,l-4,t,26,i,KF,650),l+=t.length*35+8}for(let e of c){let t=ZF(e.text,e.size,n.w-48,KF,e.weight);if(u+=dR(24,l,t,e.size,i,KF,e.weight),l+=t.length*Math.round(e.size*1.35)+8,l>n.h-12)break}a.push(s(u));break}case`image`:{let i=await fR(e.resolve(r.src));a.push(s(i?`<image href="${PL(i)}" width="${n.w}" height="${n.h}" preserveAspectRatio="xMidYMid meet"/>`:`<rect width="${n.w}" height="${n.h}" fill="${t(`ink`,`fill`)}"/>`));break}case`embed`:a.push(s(`<rect width="${n.w}" height="${n.h}" rx="8" fill="${t(`paper`,`fill`)}" stroke="${t(`gray`,`fill`)}"/>`+dR(16,16,ZF(r.url,13,n.w-32),13,t(`blue`,`line`),KF)));break;case`mindmap`:{let n=e.layoutOf(r),o=t(r.color,`line`),s=t(r.color,`fill`),c=n.edges.map(e=>`<path d="${aI(e.from,e.to)}" fill="none" stroke="${o}" stroke-width="2"/>`).join(``);for(let e of n.boxes.values()){let n=e.depth===0?18:15,a=e.depth===0?600:400,l=e.depth===0?o:e.depth===1?s:t(`paper`,`line`),u=e.depth===0?t(`paper`,`line`):i;c+=`<rect x="${e.x}" y="${e.y}" width="${e.w}" height="${e.h}" rx="${e.depth===0?10:8}" fill="${l}" stroke="${o}" stroke-width="${e.depth===0?0:1.5}"/>`;let d=ZF(r.nodes[e.id]?.text||` `,n,260,KF,a);c+=dR(e.x+e.w/2,e.y+(e.h-d.length*Math.round(n*1.4))/2-2,d,n,u,KF,a,`middle`)}a.push(`<g transform="translate(${r.x} ${r.y})">${c}</g>`);break}}}return{svg:`<svg xmlns="http://www.w3.org/2000/svg" width="${Math.ceil(r.w)}" height="${Math.ceil(r.h)}" viewBox="${r.x} ${r.y} ${r.w} ${r.h}"><rect x="${r.x}" y="${r.y}" width="${r.w}" height="${r.h}" fill="${t(`paper`,`line`)}"/>${a.join(``)}</svg>`,box:r}}async function mR(e,t){let{svg:n,box:r}=await pR(t),i=new Blob([n],{type:`image/svg+xml`});if(e===`svg`)return i;let a=Math.min(2,8192/Math.max(r.w,r.h,1)),o=URL.createObjectURL(i);try{let e=await new Promise((e,t)=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>t(Error(`could not draw the canvas`)),n.src=o}),t=document.createElement(`canvas`);t.width=Math.ceil(r.w*a),t.height=Math.ceil(r.h*a);let n=t.getContext(`2d`);if(!n)throw Error(`could not draw the canvas`);return n.drawImage(e,0,0,t.width,t.height),await new Promise((e,n)=>t.toBlob(t=>t?e(t):n(Error(`could not draw the canvas`)),`image/png`))}finally{URL.revokeObjectURL(o)}}var hR=.1,gR=4,_R=`http://www.w3.org/2000/svg`,vR=e=>e instanceof HTMLElement&&(e.isContentEditable||e.tagName===`INPUT`||e.tagName===`TEXTAREA`),yR=class{opts;store;labels;root;styles;editable;tool=`select`;shapeKind;selected=new Set;activeNode=null;editing=null;entered=null;world;overlay;ui;view={x:0,y:0,zoom:1};rendered=new Map;measured=new Map;layouts=new Map;routes=new Map;previews=new Map;drag=null;guides=[];marquee=null;hover=null;raf=0;spaceDown=!1;pointers=new Map;pinch=null;presenting=null;comments=[];activeComment=``;resize=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>this.onResize(e));unsub;cleanups=[];saveTimer;constructor(e,t){this.opts=t,this.labels=t.labels??dF,this.editable=t.editable,this.styles=PF(t.styles),this.shapeKind=this.styles.shape.shape,this.store=new tR(t.doc,{undo:t.undo!==!1}),this.root=document.createElement(`div`),this.root.className=`dw-cv`,this.root.tabIndex=0,this.root.setAttribute(`role`,`application`),this.root.dataset.testid=`edgeless-canvas`,this.world=document.createElement(`div`),this.world.className=`dw-cv-world`,this.overlay=document.createElementNS(_R,`svg`),this.overlay.classList.add(`dw-cv-overlay`),this.root.append(this.world,this.overlay),e.append(this.root),this.ui=new cR(this),this.root.classList.toggle(`dw-cv-readonly`,!this.editable),this.unsub=this.store.onChange(()=>this.schedule()),this.listen(),this.render(),this.restoreView()||this.fit(void 0,!1),this.applyView()}destroy(){cancelAnimationFrame(this.raf),clearTimeout(this.saveTimer),this.saveView(),this.unsub(),this.resize?.disconnect();for(let e of this.cleanups)e();for(let e of this.rendered.values())e.note?.destroy();this.rendered.clear(),this.ui.destroy(),this.store.destroy(),this.root.remove()}setEditable(e){if(e!==this.editable){this.editable=e,this.roLine truncated
`||e===`\r`?(r.push(i),n.push(r),r=[],i=``,e===`\r`&&s[o+1]===`
`&&o++):i+=e,o++}return(i!==``||r.length)&&(r.push(i),n.push(r)),n}function Gz(e,t){return e.includes(t)||/["\r\n]/.test(e)||/^\s|\s$/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function Kz(e,t=`,`){return e.map(e=>e.map(e=>Gz(e,t)).join(t)).join(`\r
`)}function qz(e,t,n){return Kz([t.map(e=>e.name),...n.map(e=>t.map(t=>tz(e,t)))])}function Jz(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>$R(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function Yz(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:VR(),name:e,color:fz(n)},n.push(t)),t.id};switch(t.type){case`number`:return $R(r);case`progress`:{let e=$R(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return ZR(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function Xz(e,t=`,`){let n=Wz(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:VR(),name:e.trim()||`${t+1}`,type:t===0?`title`:Jz(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=Yz(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function Zz(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function Qz(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var $z=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function eB(e,t,n,r){let i=e.labels;if(!rz(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return Qz(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function tB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(Qz(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=nz(l.type),d=I(`div`,{class:`dw-db-pop__line`},Qz(n.column,$z(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:nz(t.type)[0]},s(),c()}),Qz(n.op,u.map(e=>({value:e,label:wR(i,e)})),i.filter,e=>{o[r]={...n,op:e},rz(e)||delete o[r].value,s(),c()}),eB(e,l,n,e=>{o[r]={...o[r],value:e},s()}),oB(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(sB(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:nz(e.type)[0]}),s(),c()}))};c()}function nB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},Qz(e.column,$z(a),i.sort,t=>{o[n]={...e,column:t},s()}),Qz(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),oB(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(sB(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function rB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>UR.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||SR(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?Qz(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function iB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?Qz(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||SR(i,e.tyLine truncated
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(NS.getState(this.editor.state)?.undoManager)?.addToScope(Oz(e))},addCommands(){let e=e=>{let t=VR(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(Uz(n,t,e,(e,t)=>OB(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??Rz(CB(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=jB(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=SB(this.options.labels),o={id:VR(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:VR(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:VR(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[HR(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(E.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new D({key:new Un(`databaseClipboard`),props:{transformCopied:t=>!e||!EB(t.content)?t:new p(TB(t.content,t=>{let n=Oz(e).get(String(t.attrs.id));return n instanceof Lb?t.type.create({...t.attrs,data:Hz(n,wB)}):t}),t.openStart,t.openEnd),transformPasted:e=>EB(e.content)?new p(TB(e.content,e=>{let t=VR();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?WR(e.attrs.data):null,a=Oz(n).get(String(e.attrs.id)),o=i??(a instanceof Lb?Hz(a,wB):Rz(CB(this.options.labels)));return Uz(n,t,AB(o),(e,t)=>OB(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(MS))||!e.some(e=>e.steps.some(e=>EB(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=Oz(n).get(String(t.attrs.id)),a=VR();i instanceof Lb&&Uz(n,a,AB(Hz(i,wB)),(e,t)=>OB(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??kR,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?Oz(o).get(p()):void 0;return e instanceof Lb?e:null},h=()=>{let t=m();return t?Lz(t):i.attrs.data?WR(i.attrs.data):Rz(CB(e.labels))},g=()=>({labels:a.database,colorNames:a.colors,locale:a.locale,files:e.files,people:e.people,store:c}),_=(t,n)=>{let r=e.rowExtensions;if(!r)return null;let i=m(),o=null;if(i&&(o=c?c.rowBody(n.id):kB(i,n.id),!o))return t.append(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),null;let s=new Vp({element:t,editable:!!c,extensions:r(o),content:o?void 0:{type:`doc`,content:n.body??[{type:`paragraph`}]},editorProps:{attributes:{class:`dw-prose dw-db-peek__prose`}}});return!o&&!n.body?.length&&t.replaceChildren(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),()=>s.destroy()},v=e.recordLink,y=v?t=>{let n=v(_B(p(),t));xB(n).then(t=>t&&e.onLinkCopied?.(n))}:void 0;f.addEventListener(yB,e=>{let t=e.detail,n=h();n.rows.some(e=>e.id===t.row)&&(t.found=!0,f.scrollIntoView?.({block:`start`}),b(t.row,n.rows.map(e=>e.id)))});let b=(e,t)=>{u?.close(),u=new Ez({ctx:{...g()},mountBody:_,copyLink:y},h(),e,t,()=>u=null)},x=()=>{let e=h();d?.update(e,{store:c}),u?.update(e,{store:c})},S=()=>{if(l?.(),l=null,c=null,!o)return;let t=m();if(!t&&s()){let a=i.attrs.data?WR(i.attrs.data):Rz(CB(e.labels)),s=p()?p():VR();Uz(o,s,a,(e,t)=>OB(n,e,t)),queueMicrotask(()=>{let e=typeof r==`function`?r():void 0;e!==void 0&&n.state.doc.nodeAt(e)?.type.name===`database`&&n.view.dispatch(n.state.tr.setNodeMarkup(e,void 0,{...i.attrs,id:s,data:null}).setMeta(`addToHistory`,!1))}),t=Oz(o).get(s)}let a=Oz(o),d=e=>{if(!e.keysChanged.has(p()))return;S(),x();let t=u?.row;t&&h().rows.some(e=>e.id===t)&&b(t,[t])};if(a.observe(d),t){s()&&(c=new Bz(o,t,()=>e.me?.()??null));let n=t,r=()=>x();n.observeDeep(r),l=()=>{a.unobserve(d),n.unobserveDeep(r)}}else l=()=>a.unobserve(d)};S(),d=new pB({...g(),openRow:b,undo:()=>n.commands.undo?.(),redo:()=>n.commands.redo?.(),notify:e.notify,copyLink:y},h()),f.append(d.dom);let C=s(),ee=()=>{s()!==C&&(C=s(),S(),x())};return n.on(`update`,ee),n.on(`transaction`,ee),{dom:f,update(e){if(e.type!==i.type)return!1;let t=e.attrs.id!==i.attrs.id;return i=e,t&&S(),x(),!0},ignoreMutation:()=>!0,stopEvent:e=>e.type!==`dragstart`||e.target!==f,destroy(){l?.(),u?.close(),d?.destroy(),n.off(`update`,ee),n.off(`transaction`,ee)}}}}});function OB(e,t,n){try{yw(e.schema,{type:`doc`,content:t},n)}catch{}}function kBLine truncated
`);return/\s/.test(n)}):!1}function QB(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function $B(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:QB(e)}function eV({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!ZB(r)}function tV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function nV({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function rV({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function iV({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function aV({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[kj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(jj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function oV(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function sV({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&oV(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=Oj(c,o,()=>{Mj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function cV({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=iV({editor:e,items:n}),v=aV({placLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=Oj(e.anchor,t,()=>{Mj(e.anchor,t,{placement:`bottom-start`,middleware:[kj(6),jj(),Aj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),jV===d&&(jV=null),n||e.onCancel?.())}let d=()=>u();return jV=d,n.focus(),e.multiline||n.select(),d}var NV=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function PV(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of NV){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function FV(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var IV=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function LV(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;MV({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(FV(t)),onCancel:()=>e(``)})})}async function RV(e,t,n,r){let i=await LV(e,t,t.blocks.embedUrl);i&&(PV(i)?e.chain().focus().insertEmbed(i).run():await BV(e,i,n,r))}async function zV(e,t,n,r){let i=await LV(e,t,t.blocks.linkUrl);i&&await BV(e,i,n,r)}async function BV(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var VV=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=FV(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=FV(e),i=PV(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${IV(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
`&&o++):i+=e,o++}return(i!==``||r.length)&&(r.push(i),n.push(r)),n}function cB(e,t){return e.includes(t)||/["\r\n]/.test(e)||/^\s|\s$/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function lB(e,t=`,`){return e.map(e=>e.map(e=>cB(e,t)).join(t)).join(`\r
`)}function uB(e,t,n){return lB([t.map(e=>e.name),...n.map(e=>t.map(t=>JR(e,t)))])}function dB(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>KR(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function fB(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:PR(),name:e,color:az(n)},n.push(t)),t.id};switch(t.type){case`number`:return KR(r);case`progress`:{let e=KR(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return WR(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function pB(e,t=`,`){let n=sB(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:PR(),name:e.trim()||`${t+1}`,type:t===0?`title`:dB(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=fB(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function mB(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function hB(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var gB=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function _B(e,t,n,r){let i=e.labels;if(!XR(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return hB(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function vB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(hB(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=YR(l.type),d=I(`div`,{class:`dw-db-pop__line`},hB(n.column,gB(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:YR(t.type)[0]},s(),c()}),hB(n.op,u.map(e=>({value:e,label:TR(i,e)})),i.filter,e=>{o[r]={...n,op:e},XR(e)||delete o[r].value,s(),c()}),_B(e,l,n,e=>{o[r]={...o[r],value:e},s()}),CB(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(wB(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:YR(e.type)[0]}),s(),c()}))};c()}function yB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},hB(e.column,gB(a),i.sort,t=>{o[n]={...e,column:t},s()}),hB(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),CB(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(wB(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function bB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>IR.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||CR(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?hB(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function xB(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?hB(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||CR(i,e.tyLine truncated
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(NS.getState(this.editor.state)?.undoManager)?.addToScope(Gz(e))},addCommands(){let e=e=>{let t=PR(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(oB(n,t,e,(e,t)=>GB(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??tB(BB(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=JB(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=zB(this.options.labels),o={id:PR(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:PR(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:PR(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[FR(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(E.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new D({key:new Un(`databaseClipboard`),props:{transformCopied:t=>!e||!UB(t.content)?t:new p(HB(t.content,t=>{let n=Gz(e).get(String(t.attrs.id));return n instanceof Lb?t.type.create({...t.attrs,data:aB(n,VB)}):t}),t.openStart,t.openEnd),transformPasted:e=>UB(e.content)?new p(HB(e.content,e=>{let t=PR();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?LR(e.attrs.data):null,a=Gz(n).get(String(e.attrs.id)),o=i??(a instanceof Lb?aB(a,VB):tB(BB(this.options.labels)));return oB(n,t,qB(o),(e,t)=>GB(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(MS))||!e.some(e=>e.steps.some(e=>UB(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=Gz(n).get(String(t.attrs.id)),a=PR();i instanceof Lb&&oB(n,a,qB(aB(i,VB)),(e,t)=>GB(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??AR,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?Gz(o).get(p()):void 0;return e instanceof Lb?e:null},h=()=>{let t=m();return t?eB(t):i.attrs.data?LR(i.attrs.data):tB(BB(e.labels))},g=e=>{let t=o?Gz(o).get(e):void 0;if(t instanceof Lb)return eB(t);let r=null;return n.state.doc.descendants(t=>!r&&(t.type.name===`database`&&t.attrs.id===e&&t.attrs.data&&(r=LR(t.attrs.data)),!0)),r},_=new Map,v=t=>{let n=e.linkedPages;if(!n)return null;let r=_.get(t);if(!r){let e=n.open(t),i=e.onChange(ne);e.doc.on(`update`,ne),r={provider:e,stop:()=>{i(),e.doc.off(`update`,ne),e.destroy()}},_.set(t,r)}return r.provider},y=t=>!t||t===e.linkedPages?.self,b=new Set,x=e=>{if(y(e.page))return b.add(e.database),e.database===p()?h():g(e.database);let t=v(e.page);if(!t?.synced)return null;let n=Gz(t.doc).get(e.database);return n instanceof Lb?eB(n):null},S=(e,t,n)=>{let r=[],i=e=>{for(let a of e.toArray())if(a instanceof ox){if(a.nodeName===`database`){let e=String(a.getAttribute(`id`)??``);e&&r.push({page:t,database:e,title:n(e)?.title??``})}else i(a)}};return i(e),r},C={local:()=>{let e=[];return n.state.doc.descendants(t=>(t.type.name===`database`&&t.attrs.id&&t.attrs.id!==p()&&e.push({page:``,database:String(t.attrs.id),title:g(String(t.attrs.id))?.title??``}),!0)),e},searchPages:e.pages?t=>e.pages.search(t).then(e=>e.filter(e=>!y(e.id)).map(e=>({id:e.id,title:e.title}))):void 0,databasesOn:e.linkedPages?e=>new Promise(t=>{let n=v(e),r=()=>{t(S(n.doc.getXmlFragment(`default`),e,e=>{let t=Gz(n.doc).get(e);return t instanceof Lb?eB(t):null}))};if(n.synced)return r();let i=setTimeout(()=>{a(),t([])},8e3),a=n.onChange(()=>{n.synced&&(clearTimeout(i),a(),r())})}):void 0,read:x,openRecord:(t,r)=>{y(t.page)?LB(n,t.database,r):e.onNavigate?.(`/p/${encodeURIComponent(t.page)}${PB(t.database,r)}`)}},ee=e=>{for(let t of e)if((t.path.length?[String(t.path[0])]:[...t.keysChanged??[]]).some(e=>e!==p()&&b.has(e)))return ne()};o&&Gz(o).observeDeep(ee);let te;function ne(){clearTimeout(te),te=setTimeout(()=>de(),60)}let re=()=>gz(h(),x,a.database),ie=()=>({labels:a.database,colorNames:a.colors,locale:a.locale,files:e.files,people:e.people,store:c,linked:C}),ae=(t,n)=>{let r=e.rowExtensions;if(!r)return null;let i=m(),o=null;if(i&&(o=c?c.rowBody(n.id):KB(i,n.id),!o))return t.append(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),null;let s=new Vp({element:t,editable:!!c,extensions:r(o),content:o?void 0:{type:`doLine truncated
`);return/\s/.test(n)}):!1}function hV(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function gV(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:hV(e)}function _V({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!mV(r)}function vV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function yV({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function bV({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function xV({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function SV({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[kj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(jj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function CV(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function wV({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&CV(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=Oj(c,o,()=>{Mj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function TV({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=xV({editor:e,items:n}),v=SV({placLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=Oj(e.anchor,t,()=>{Mj(e.anchor,t,{placement:`bottom-start`,middleware:[kj(6),jj(),Aj({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),JV===d&&(JV=null),n||e.onCancel?.())}let d=()=>u();return JV=d,n.focus(),e.multiline||n.select(),d}var XV=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function ZV(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of XV){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function QV(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var $V=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function eH(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;YV({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(QV(t)),onCancel:()=>e(``)})})}async function tH(e,t,n,r){let i=await eH(e,t,t.blocks.embedUrl);i&&(ZV(i)?e.chain().focus().insertEmbed(i).run():await rH(e,i,n,r))}async function nH(e,t,n,r){let i=await eH(e,t,t.blocks.linkUrl);i&&await rH(e,i,n,r)}async function rH(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var iH=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=QV(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=QV(e),i=ZV(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${$V(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
@@ -178,7 +178,7 @@ c5.3,-9.3,12,-14,20,-14
H400000v`+(40+e)+`H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},BH=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},rU=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120
c340,-704.7,510.7,-1060.3,512,-1067
l`+e/2.084+` -`+e+`
@@ -188,7 +188,7 @@ s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,
c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1
s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26
c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},VH=function(e,t){return`M983 `+(10+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},iU=function(e,t){return`M983 `+(10+e+t)+`
l`+e/3.13+` -`+e+`
c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+`
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
@@ -197,7 +197,7 @@ c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},HH=function(e,t){return`M424,`+(2398+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},aU=function(e,t){return`M424,`+(2398+e+t)+`
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
@@ -207,18 +207,18 @@ v`+(40+e)+`H1014.6
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+` `+t+`
h400000v`+(40+e)+`h-400000z`},UH=function(e,t){return`M473,`+(2713+e+t)+`
h400000v`+(40+e)+`h-400000z`},oU=function(e,t){return`M473,`+(2713+e+t)+`
c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+` -`+e+`
c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7
s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200
c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26
s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},WH=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},GH=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},sU=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},cU=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1
h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170
c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},KH=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=zH(t,RH);break;case`sqrtSize1`:r=BH(t,RH);break;case`sqrtSize2`:r=VH(t,RH);break;case`sqrtSize3`:r=HH(t,RH);break;case`sqrtSize4`:r=UH(t,RH);break;case`sqrtTall`:r=GH(t,RH,n)}return r},qH=function(e,t){switch(e){case`⎜`:return LH(`M291 0 H417 V`+t+` H291z`);case`∣`:return LH(`M145 0 H188 V`+t+` H145z`);case`∥`:return LH(`M145 0 H188 V`+t+` H145z`)+LH(`M367 0 H410 V`+t+` H367z`);case`⎟`:return LH(`M457 0 H583 V`+t+` H457z`);case`⎢`:return LH(`M319 0 H403 V`+t+` H319z`);case`⎥`:return LH(`M263 0 H347 V`+t+` H263z`);case`⎪`:return LH(`M384 0 H504 V`+t+` H384z`);case`⏐`:return LH(`M312 0 H355 V`+t+` H312z`);case`‖`:return LH(`M257 0 H300 V`+t+` H257z`)+LH(`M478 0 H521 V`+t+` H478z`);default:return``}},JH={doubleleftarrow:`M262 157
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},lU=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=nU(t,tU);break;case`sqrtSize1`:r=rU(t,tU);break;case`sqrtSize2`:r=iU(t,tU);break;case`sqrtSize3`:r=aU(t,tU);break;case`sqrtSize4`:r=oU(t,tU);break;case`sqrtTall`:r=cU(t,tU,n)}return r},uU=function(e,t){switch(e){case`⎜`:return eU(`M291 0 H417 V`+t+` H291z`);case`∣`:return eU(`M145 0 H188 V`+t+` H145z`);case`∥`:return eU(`M145 0 H188 V`+t+` H145z`)+eU(`M367 0 H410 V`+t+` H367z`);case`⎟`:return eU(`M457 0 H583 V`+t+` H457z`);case`⎢`:return eU(`M319 0 H403 V`+t+` H319z`);case`⎥`:return eU(`M263 0 H347 V`+t+` H263z`);case`⎪`:return eU(`M384 0 H504 V`+t+` H384z`);case`⏐`:return eU(`M312 0 H355 V`+t+` H312z`);case`‖`:return eU(`M257 0 H300 V`+t+` H257z`)+eU(`M478 0 H521 V`+t+` H478z`);default:return``}},dU={doubleleftarrow:`M262 157
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
@@ -264,10 +264,10 @@ m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:LH(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:LH(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:LH(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:LH(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:eU(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:eU(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:eU(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:eU(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:LH(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:eU(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
@@ -316,7 +316,7 @@ m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown
m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:LH(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:LH(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:LH(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:eU(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:eU(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:eU(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40
@@ -389,7 +389,7 @@ M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},YH=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},fU=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
H403z M403 1759 V0 H319 V1759 v`+t+` v1759 v84 h84z`;case`rbrack`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v1759 H0 v84 H347z
M347 1759 V0 H263 V1759 v`+t+` v1759 h84z`;case`vert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15
c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15
@@ -417,17 +417,17 @@ c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6
c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17
c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558
l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function XH(e){return`toText`in e}var ZH=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(XH(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},QH={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},$H={ex:!0,em:!0,mu:!0},eU=function(e){return typeof e!=`string`&&(e=e.unit),e in QH||e in $H||e===`ex`},tU=function(e,t){var n;if(e.unit in QH)n=QH[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},nU=function(e){return e.filter(e=>e).join(` `)},rU=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=iH(n)+`:`+r+`;`)}return t},iU=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},aU=function(e){var t=document.createElement(e);t.className=nU(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},oU=/[\s"'>/=\x00-\x1f]/,sU=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+sH(nU(this.classes))+`"`);var n=rU(this.style);n&&(t+=` style="`+sH(n)+`"`);for(var r of Object.keys(this.attributes)){if(oU.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+sH(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},cU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,iU.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return aU.call(this,`span`)}toMarkup(){return sU.call(this,`span`)}},lU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,iU.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return aU.call(this,`a`)}toMarkup(){return sU.call(this,`a`)}},uU=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+sH(this.src)+`"`+(` alt="`+sH(this.alt)+`"`),t=rU(this.style);return t&&(e+=` style="`+sH(t)+`"`),e+=`'/>`,e}},dU={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},fU=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=PH(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=dU[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=nU(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=sH(nU(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new pU([new mU(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=bW([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},kG=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new hU({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new hU({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=bW([],[new pU(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},AG=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],jG=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],MG=new Set(AG),NG=new Set(jG);function PG(e){return MG.has(e)}function FG(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function IG(e){var t=LG(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function LG(e){return e.type===`atom`||NG.has(e.type)?e:null}function RG(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var zG=e=>{if(e instanceof fU)return e;if(vU(e)&&e.children.length===1)return zG(e.children[0])},BG=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=FG(e.base,`accent`),n=r.base,e.base=n,i=_U($W(e,t)),e.base=r):(r=FG(e,`accent`),n=r.base);var a=$W(n,t.havingCrampedStyle()),o=r.isShifty&&uH(n),s=0;o&&(s=zG(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=OG(r,t),u=EW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=jW(`vec`,t),f=AW.vec[1]):(d=gW({type:`textord`,mode:r.mode,text:r.label},t),d=gU(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=EW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},VG=(e,t)=>{var n=e.isStretchy?TG(e.label):new Q(`mo`,[sG(e.label,e.mode)]),r=new Q(`mover`,[mG(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},HG=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=VW(t[0]),r=!HG.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:BG,mathmlBuilder:VG}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=$W(e.base,t),r=OG(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[EW({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=TG(e.label),r=new Q(`munder`,[mG(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var UG=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,Pq=`\\\\[a-zA-Z@]+`,Fq=`\\\\[^\ud800-\udfff]`,Iq=`(`+Pq+`)`+Nq+`*`,Lq=`\\\\(
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function pU(e){return`toText`in e}var mU=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(pU(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},hU={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},gU={ex:!0,em:!0,mu:!0},_U=function(e){return typeof e!=`string`&&(e=e.unit),e in hU||e in gU||e===`ex`},vU=function(e,t){var n;if(e.unit in hU)n=hU[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},yU=function(e){return e.filter(e=>e).join(` `)},bU=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=xH(n)+`:`+r+`;`)}return t},xU=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},SU=function(e){var t=document.createElement(e);t.className=yU(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},CU=/[\s"'>/=\x00-\x1f]/,wU=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+wH(yU(this.classes))+`"`);var n=bU(this.style);n&&(t+=` style="`+wH(n)+`"`);for(var r of Object.keys(this.attributes)){if(CU.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+wH(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},TU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,xU.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return SU.call(this,`span`)}toMarkup(){return wU.call(this,`span`)}},EU=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,xU.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return SU.call(this,`a`)}toMarkup(){return wU.call(this,`a`)}},DU=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+wH(this.src)+`"`+(` alt="`+wH(this.alt)+`"`),t=bU(this.style);return t&&(e+=` style="`+wH(t)+`"`),e+=`'/>`,e}},OU={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},kU=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=ZH(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=OU[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=yU(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=wH(yU(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new AU([new jU(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=LW([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=z(o),a>0&&(i.style.minWidth=z(a)),i},KG=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new MU({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new MU({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=LW([],[new AU(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},qG=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],JG=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],YG=new Set(qG),XG=new Set(JG);function ZG(e){return YG.has(e)}function QG(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function $G(e){var t=eK(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function eK(e){return e.type===`atom`||XG.has(e.type)?e:null}function tK(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new L(t,e);return r}var nK=e=>{if(e instanceof kU)return e;if(FU(e)&&e.children.length===1)return nK(e.children[0])},rK=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=QG(e.base,`accent`),n=r.base,e.base=n,i=PU(gG(e,t)),e.base=r):(r=QG(e,`accent`),n=r.base);var a=gG(n,t.havingCrampedStyle()),o=r.isShifty&&DH(n),s=0;o&&(s=nK(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=GG(r,t),u=UW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=JW(`vec`,t),f=qW.vec[1]):(d=NW({type:`textord`,mode:r.mode,text:r.label},t),d=NU(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=UW({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},iK=(e,t)=>{var n=e.isStretchy?HG(e.label):new Q(`mo`,[wG(e.label,e.mode)]),r=new Q(`mover`,[jG(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},aK=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=iG(t[0]),r=!aK.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:rK,mathmlBuilder:iK}),Z({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),Z({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=gG(e.base,t),r=GG(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[UW({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=HG(e.label),r=new Q(`munder`,[jG(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var oK=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
]`,Zq=`\\\\[a-zA-Z@]+`,Qq=`\\\\[^\ud800-\udfff]`,$q=`(`+Zq+`)`+Xq+`*`,eJ=`\\\\(
|[ \r ]+
?)[ \r ]*`,Rq=`[̀-ͯ]`,zq=RegExp(Rq+`+$`),Bq=`(`+Nq+`+)|`+(Lq+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(Rq+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(Rq+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+Iq)+(`|`+Fq+`)`),Vq=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(Bq,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new VK(`EOF`,new BK(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new VK(e[t],new BK(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new VK(r,new BK(this,t,this.tokenRegex.lastIndex))}},Hq=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new L(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},Uq=zK;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var Wq={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=Wq[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=Wq[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var Gq=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new L(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>Gq(e,!1,!0,!1)),$(`\\renewcommand`,e=>Gq(e,!0,!1,!1)),$(`\\providecommand`,e=>Gq(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),Mq[n],EU.math[n],EU.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(nJ,t[0])&&!EU[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=nJ[t[0]]+t.slice(1));var i=zq.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(EU[this.mode][t]){this.settings.strict&&this.mode===`math`&&JU.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=EU[this.mode][t].group,s=BK.range(e);a=PG(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(IH(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:BK.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!tJ[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=tJ[l][this.mode]||tJ[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:BK.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};rJ.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var iJ=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new rJ(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new VK(`\\df@tag`)])}]}return r},aJ=function(e,t,n){t.textContent=``;var r=lJ(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),aJ=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var oJ=function(e,t){return lJ(e,t).toMarkup()},sJ=function(e,t){return iJ(e,new gH(t))},cJ=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new fU(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},lJ=function(e,t){var n=new gH(t);try{return SG(iJ(e,n),e,n)}catch(t){return cJ(t,e,n)}},uJ={version:`0.18.10`,render:aJ,renderToString:oJ,ParseError:L,SETTINGS_SCHEMA:fH,__parse:sJ,__renderToDomTree:lJ,__renderToHTMLTree:function(e,t){var n=new gH(t);try{return CG(iJ(e,n),e,n)}catch(t){return cJ(t,e,n)}},__setFontMetrics:SU,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:cU,Anchor:lU,SymbolNode:fU,SvgNode:pU,PathNode:mU,LineNode:hU}},dJ=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{uJ.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),fJ=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},pJ=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:fJ,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{uJ.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),mJ=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[dJ.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),pJ.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function hJ(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;MV({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return mJ.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function gJ({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new Un,command:({editor:e,range:t,props:i})=>{var a,o;let sLine truncated
Idea --> Draft --> Review --> Published`,SJ=null;function CJ(e){return SJ??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),SJ}var wJ=0;async function TJ(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await CJ(r)).render(`dw-mermaid-${++wJ}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var EJ=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=xJ)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return TJ(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;MV({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void TJ(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),TJ(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void TJ(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),TJ(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function DJ(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function OJ(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().Line truncated
?)[ \r ]*`,tJ=`[̀-ͯ]`,nJ=RegExp(tJ+`+$`),rJ=`(`+Xq+`+)|`+(eJ+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(tJ+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(tJ+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+$q)+(`|`+Qq+`)`),iJ=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(rJ,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new iq(`EOF`,new rq(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new iq(e[t],new rq(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new iq(r,new rq(this,t,this.tokenRegex.lastIndex))}},aJ=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new L(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},oJ=nq;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var sJ={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=sJ[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=sJ[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var cJ=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new L(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>cJ(e,!1,!0,!1)),$(`\\renewcommand`,e=>cJ(e,!0,!1,!1)),$(`\\providecommand`,e=>cJ(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),Yq[n],UU.math[n],UU.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(yJ,t[0])&&!UU[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=yJ[t[0]]+t.slice(1));var i=nJ.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(UU[this.mode][t]){this.settings.strict&&this.mode===`math`&&dW.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=UU[this.mode][t].group,s=rq.range(e);a=ZG(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&($H(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:rq.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!vJ[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=vJ[l][this.mode]||vJ[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:rq.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};bJ.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var xJ=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new bJ(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new iq(`\\df@tag`)])}]}return r},SJ=function(e,t,n){t.textContent=``;var r=EJ(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),SJ=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var CJ=function(e,t){return EJ(e,t).toMarkup()},wJ=function(e,t){return xJ(e,new NH(t))},TJ=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new kU(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},EJ=function(e,t){var n=new NH(t);try{return zG(xJ(e,n),e,n)}catch(t){return TJ(t,e,n)}},DJ={version:`0.18.10`,render:SJ,renderToString:CJ,ParseError:L,SETTINGS_SCHEMA:kH,__parse:wJ,__renderToDomTree:EJ,__renderToHTMLTree:function(e,t){var n=new NH(t);try{return BG(xJ(e,n),e,n)}catch(t){return TJ(t,e,n)}},__setFontMetrics:zU,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:TU,Anchor:EU,SymbolNode:kU,SvgNode:AU,PathNode:jU,LineNode:MU}},OJ=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{DJ.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),kJ=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},AJ=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:kJ,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{DJ.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),jJ=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[OJ.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),AJ.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function MJ(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;YV({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return jJ.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function NJ({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new Un,command:({editor:e,range:t,props:i})=>{var a,o;let sLine truncated
Idea --> Draft --> Review --> Published`,zJ=null;function BJ(e){return zJ??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),zJ}var VJ=0;async function HJ(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await BJ(r)).render(`dw-mermaid-${++VJ}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var UJ=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=RJ)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return HJ(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;YV({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void HJ(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),HJ(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void HJ(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),HJ(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function WJ(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function GJ(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().Line truncated
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--shadow-dialog:var(--dw-shadow-dialog);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-varLine truncated
/*$vite$:1*/</style>
</head>
<body>
@@ -64,6 +64,9 @@ describe("EditorBridge", () => {
expect(canvas.querySelector(".dw-cv-pagenote")?.textContent).toContain("Hello");
expect(canvas.querySelector(".dw-cv-shape")?.textContent).toContain("Idea");
expect(canvas.querySelector(".dw-cv-note:not(.dw-cv-pagenote)")?.textContent).toContain("Sticky");
// Without a live page the canvas stays read-only, even when editing is allowed.
bridge.receive(JSON.stringify({ type: "setEditable", editable: true }));
expect(canvas.querySelector(".dw-cv-readonly")).not.toBeNull();
bridge.receive(JSON.stringify({ type: "setMode", mode: "page" }));
expect(document.querySelector(".dw-bridge-canvas")).toBeNull();
expect(el.hidden).toBe(false);
+11 -2
View File
@@ -76,6 +76,8 @@ export class EditorBridge {
private mode: "page" | "edgeless" = "page";
/** The content as the host sent it, with its canvas ("surface"). */
private lastContent: JSONContent | null = null;
/** The page's title, shown on its note on the canvas. */
private title = "";
constructor(
private readonly el: HTMLElement,
@@ -127,6 +129,8 @@ export class EditorBridge {
case "setEditable":
this.editable = msg.editable;
this.editor.setEditable(msg.editable);
// The canvas edits only the live page (it needs "connect" first).
this.canvas?.setEditable(msg.editable);
return;
case "setTheme":
document.documentElement.classList.toggle("dark", msg.dark);
@@ -159,6 +163,7 @@ export class EditorBridge {
return;
case "setMode":
this.mode = msg.mode === "edgeless" ? "edgeless" : "page";
if (typeof msg.title === "string") this.title = msg.title;
if (this.mode === "edgeless") this.openCanvas();
else this.closeCanvas();
return;
@@ -183,7 +188,10 @@ export class EditorBridge {
if (this.mode === "edgeless") this.openCanvas();
}
/** Draws the canvas over the text: the live page once connected, else the content. */
/**
* Draws the canvas over the text: the live page once connected (editable
* while the host allows editing), else the content read-only.
*/
private openCanvas(): void {
this.closeCanvas();
const el = document.createElement("div");
@@ -194,7 +202,8 @@ export class EditorBridge {
this.canvas = mountEdgeless(el, {
provider: this.provider ?? undefined,
content: this.provider ? undefined : (this.lastContent ?? this.editor.getJSON()),
editable: false,
editable: this.editable && !!this.provider,
pageTitle: () => this.title,
onNavigate: (path) => this.send({ type: "navigate", path }),
onError: (e) => this.send({ type: "error", message: e instanceof Error ? e.message : String(e) }),
});
+5 -2
View File
@@ -48,8 +48,11 @@ export type HostMessage =
| { type: "dismiss" }
/** Scrolls to a block ("#b-…") or opens a database record ("#r-…") of the page, once it shows it. */
| { type: "follow"; hash: string }
/** Shows the text, or the edgeless canvas read-only (ADR-14), of the content or live page. */
| { type: "setMode"; mode: "page" | "edgeless" }
/**
* Shows the text or the edgeless canvas (ADR-14). The canvas is editable
* once connected and editable, read-only on content alone.
*/
| { type: "setMode"; mode: "page" | "edgeless"; title?: string }
/** Edit the live document over docwell-server's /collab WebSocket. */
| { type: "connect"; url: string; page: string; token: string; user: { name: string; color: string } };
+17 -1
View File
@@ -3,7 +3,7 @@
// Edgeless mode for the web and desktop apps: the canvas, with every note a
// full Docwell editor (selection toolbar, tables, find) mounted in it.
import type { JSONContent } from "@tiptap/core";
import type { NoteHandle, StyleDefaults } from "@docwell/canvas";
import type { ElementComment, NoteHandle, StyleDefaults } from "@docwell/canvas";
import { createApp, h, onBeforeUnmount, onMounted, ref, shallowRef, watch, type App } from "vue";
import DocwellEditor from "./DocwellEditor.vue";
import { mountEdgeless, type Edgeless, type NoteSpec } from "./edgeless";
@@ -38,6 +38,11 @@ const props = withDefaults(
/** Keeps pan and zoom on this device under this key. */
viewKey?: string;
pageTitle?: string;
/** Shows "Comment" on a selected element, also when the canvas is read-only. */
canComment?: boolean;
/** Open comment threads on elements, drawn as badges. */
comments?: ElementComment[];
activeComment?: string;
}>(),
{ editable: true },
);
@@ -46,6 +51,9 @@ const emit = defineEmits<{
error: [err: unknown];
"block-link-copied": [url: string];
styles: [styles: StyleDefaults];
/** The reader asked to comment on an element. */
comment: [target: { element: string; text: string }];
"comment-select": [id: string];
}>();
const host = ref<HTMLElement | null>(null);
@@ -107,10 +115,18 @@ onMounted(() => {
viewKey: props.viewKey,
pageTitle: () => props.pageTitle ?? "",
onError: (e) => emit("error", e),
onComment: props.canComment ? (el) => emit("comment", { element: el.id, text: el.text }) : undefined,
onCommentSelect: (id) => emit("comment-select", id),
mountNote,
});
edgeless.value.view.setComments(props.comments ?? [], props.activeComment ?? "");
});
watch(
() => [props.comments, props.activeComment] as const,
([list, active]) => edgeless.value?.view.setComments(list ?? [], active ?? ""),
);
watch(
() => props.editable,
(on) => edgeless.value?.setEditable(on),
+3
View File
@@ -46,6 +46,8 @@ const props = withDefaults(
journals?: boolean;
/** Draws synced pages live; without it they show as links. */
syncedPages?: SyncedPageHost;
/** Opens a database record as a full page; without it records open beside the page only. */
recordPage?: (database: string, row: string) => void;
/** Edits this fragment of a document instead (a note on the canvas), without carets. */
fragment?: { doc: Y.Doc; fragment: Y.XmlFragment };
}>(),
@@ -88,6 +90,7 @@ const editor = useEditor({
codeLineNumbers: props.codeLineNumbers,
onNavigate: (path) => emit("navigate", path),
syncedPages: props.syncedPages,
recordPage: props.recordPage,
onOpenDate: props.journals ? (date) => emit("navigate", `/journal/${date}`) : undefined,
labels: props.labels,
onCommentSelect: (id) => emit("comment-select", id),
+21 -1
View File
@@ -26,6 +26,7 @@ import {
type SelectOption,
} from "./model";
import type { DbStore } from "./store";
import { relationPanel, renderRelation, type LinkedHost } from "./relationui";
/** What cells, views and panels need from the block. */
export interface DbContext {
@@ -41,6 +42,8 @@ export interface DbContext {
openRow: (id: string) => void;
/** Called while a cell is being edited (true) and after (false); the block holds back redraws meanwhile. */
setEditing: (on: boolean) => void;
/** Reads related databases for relations and rollups; without it they show counts. */
linked?: LinkedHost;
}
export const typeIcons: Record<ColumnType, IconName> = {
@@ -57,13 +60,15 @@ export const typeIcons: Record<ColumnType, IconName> = {
member: "users",
createdTime: "clock",
createdBy: "at",
relation: "relation",
rollup: "rollup",
};
/** Types whose cells edit as a line of text in place. */
export const inlineTypes: ColumnType[] = ["title", "text", "number", "link"];
/** Types that cannot be edited at all. */
export const readOnlyTypes: ColumnType[] = ["createdTime", "createdBy"];
export const readOnlyTypes: ColumnType[] = ["createdTime", "createdBy", "rollup"];
export function formatDay(iso: string, locale?: string): string {
const [y, m, d] = iso.split("-").map(Number);
@@ -175,6 +180,18 @@ export function renderCell(ctx: DbContext, row: Row, col: Column): Node {
{ class: "dw-db-tags" },
asList<Person>(v).map((p) => h("span", { class: "dw-db-person" }, h("span", { class: "dw-db-person__dot" }, (p?.name || "?").slice(0, 1).toUpperCase()), p?.name ?? "")),
);
case "relation":
return renderRelation(ctx, row, col);
case "rollup": {
const c = row.computed?.[col.id];
const v = c?.value;
if (typeof v !== "number") return h("span", { class: "dw-db-cell__text" }, c?.text ?? "");
// Numbers in the reader's format; percentages keep their sign, day counts their words.
const text = /^-?\d+(\.\d+)?%?$/.test(c!.text)
? v.toLocaleString(ctx.locale, { maximumFractionDigits: 2 }) + (c!.text.endsWith("%") ? "%" : "")
: c!.text;
return h("span", { class: "dw-db-cell__number" }, text);
}
}
}
@@ -283,6 +300,9 @@ export function editCell(ctx: DbContext, el: HTMLElement, row: Row, col: Column,
case "attachment":
panel((box) => attachmentPanel(ctx, box, row, col), "dw-db-pop--choices");
break;
case "relation":
panel((box, close) => relationPanel(ctx, box, row, col, close), "dw-db-pop--choices");
break;
default:
finish();
}
+175 -8
View File
@@ -13,13 +13,18 @@ import * as Y from "yjs";
import type { FileHost } from "../files";
import { englishLabels, type EditorLabels } from "../labels";
import type { MentionHost } from "../mention";
import type { PageHost } from "../pagelinks";
import type { SyncedPageHost } from "../syncedpage";
import type { CollabProvider } from "../provider";
import { computeLinked, type DatabaseChoice, type RelationTarget } from "./linked";
import type { LinkedHost } from "./relationui";
import { h } from "./dom";
import { cellText, defaultView, newId, normalize, titleColumn, type Column, type DbData, type Person, type Row } from "./model";
import { RowPeek } from "./peek";
import { blocksOf, DbStore, emptyDb, exportDb, readDb, seedDb } from "./store";
import { DatabaseView } from "./view";
import { typeLabel } from "./labels";
import { copyText, OPEN_RECORD, recordHash, type OpenRecordDetail } from "./links";
import { copyText, OPEN_RECORD, openRecord as openRecordIn, recordHash, type OpenRecordDetail } from "./links";
export interface DatabaseOptions {
labels: EditorLabels | null;
@@ -47,6 +52,14 @@ export interface DatabaseOptions {
recordLink?: (hash: string) => string;
/** Called after a link to a record was copied. */
onLinkCopied?: (url: string) => void;
/** Opens other pages read-only, for relations to their databases; self is this page. */
linkedPages?: SyncedPageHost;
/** Finds pages, for choosing another page's database in a relation. */
pages?: PageHost;
/** Opens an app route, e.g. a record on another page. */
onNavigate?: (path: string) => void;
/** Opens a record as a full page; without it records open beside the page only. */
recordPage?: (database: string, row: string) => void;
}
declare module "@tiptap/core" {
@@ -110,6 +123,10 @@ export const Database = Node.create<DatabaseOptions>({
notify: undefined,
recordLink: undefined,
onLinkCopied: undefined,
linkedPages: undefined,
pages: undefined,
onNavigate: undefined,
recordPage: undefined,
};
},
@@ -307,12 +324,137 @@ export const Database = Node.create<DatabaseOptions>({
const m = doc ? blocksOf(doc).get(id()) : undefined;
return m instanceof Y.Map ? m : null;
};
const snapshot = (): DbData => {
const rawSnapshot = (): DbData => {
const m = mapOf();
if (m) return readDb(m);
return node.attrs.data ? normalize(node.attrs.data) : emptyDb(dbDefaults(opts.labels));
};
// ---- Relations and rollups (linked.ts): reading the related databases ----
/** The database with this id on this page: live, or from its node's data. */
const readLocal = (dbId: string): DbData | null => {
const m = doc ? blocksOf(doc).get(dbId) : undefined;
if (m instanceof Y.Map) return readDb(m);
let data: DbData | null = null;
editor.state.doc.descendants((n) => {
if (data) return false;
if (n.type.name === "database" && n.attrs.id === dbId && n.attrs.data) data = normalize(n.attrs.data);
return true;
});
return data;
};
// Other pages are opened read-only once and followed live.
const remote = new Map<string, { provider: CollabProvider; stop: () => void }>();
const remotePage = (page: string) => {
const host = opts.linkedPages;
if (!host) return null;
let r = remote.get(page);
if (!r) {
const provider = host.open(page);
const off = provider.onChange(later);
provider.doc.on("update", later);
r = {
provider,
stop: () => {
off();
provider.doc.off("update", later);
provider.destroy();
},
};
remote.set(page, r);
}
return r.provider;
};
const isSelf = (page: string) => !page || page === opts.linkedPages?.self;
const watched = new Set<string>();
const readTarget = (t: RelationTarget): DbData | null => {
if (isSelf(t.page)) {
watched.add(t.database);
return t.database === id() ? rawSnapshot() : readLocal(t.database);
}
const p = remotePage(t.page);
if (!p?.synced) return null;
const m = blocksOf(p.doc).get(t.database);
return m instanceof Y.Map ? readDb(m) : null;
};
/** Database ids in a page's text, in order, with their titles. */
const databasesIn = (fragment: Y.XmlFragment, page: string, read: (id: string) => DbData | null): DatabaseChoice[] => {
const out: DatabaseChoice[] = [];
const walk = (el: Y.XmlFragment | Y.XmlElement) => {
for (const c of el.toArray()) {
if (!(c instanceof Y.XmlElement)) continue;
if (c.nodeName === "database") {
const dbId = String(c.getAttribute("id") ?? "");
if (dbId) out.push({ page, database: dbId, title: read(dbId)?.title ?? "" });
} else walk(c);
}
};
walk(fragment);
return out;
};
const linked: LinkedHost = {
local: () => {
const out: DatabaseChoice[] = [];
editor.state.doc.descendants((n) => {
if (n.type.name === "database" && n.attrs.id && n.attrs.id !== id())
out.push({ page: "", database: String(n.attrs.id), title: readLocal(String(n.attrs.id))?.title ?? "" });
return true;
});
return out;
},
searchPages: opts.pages
? (q) => opts.pages!.search(q).then((list) => list.filter((p) => !isSelf(p.id)).map((p) => ({ id: p.id, title: p.title })))
: undefined,
databasesOn: opts.linkedPages
? (page) =>
new Promise((resolve) => {
const p = remotePage(page)!;
const done = () => {
const read = (dbId: string) => {
const m = blocksOf(p.doc).get(dbId);
return m instanceof Y.Map ? readDb(m) : null;
};
resolve(databasesIn(p.doc.getXmlFragment("default"), page, read));
};
if (p.synced) return done();
const timer = setTimeout(() => {
off();
resolve([]);
}, 8000);
const off = p.onChange(() => {
if (!p.synced) return;
clearTimeout(timer);
off();
done();
});
})
: undefined,
read: readTarget,
openRecord: (t, row) => {
if (isSelf(t.page)) {
openRecordIn(editor, t.database, row);
return;
}
opts.onNavigate?.(`/p/${encodeURIComponent(t.page)}${recordHash(t.database, row)}`);
},
};
// Redraws when a related database on this page changes (this one redraws on its own).
const onBlocks = (events: Y.YEvent<Y.AbstractType<unknown>>[]) => {
for (const ev of events) {
const keys = ev.path.length ? [String(ev.path[0])] : [...((ev as Y.YMapEvent<unknown>).keysChanged ?? [])];
if (keys.some((k) => k !== id() && watched.has(k))) return later();
}
};
if (doc) blocksOf(doc).observeDeep(onBlocks);
let laterTimer: ReturnType<typeof setTimeout> | undefined;
function later() {
clearTimeout(laterTimer);
laterTimer = setTimeout(() => refresh(), 60);
}
const snapshot = (): DbData => computeLinked(rawSnapshot(), readTarget, labels.database);
const host = () => ({
labels: labels.database,
colorNames: labels.colors,
@@ -320,6 +462,7 @@ export const Database = Node.create<DatabaseOptions>({
files: opts.files,
people: opts.people,
store,
linked,
});
const mountBody = (el: HTMLElement, row: Row) => {
@@ -360,16 +503,36 @@ export const Database = Node.create<DatabaseOptions>({
const db = snapshot();
if (!db.rows.some((r) => r.id === detail.row)) return;
detail.found = true;
wrap.scrollIntoView?.({ block: "start" });
if (!detail.container) wrap.scrollIntoView?.({ block: "start" });
openRow(
detail.row,
db.rows.map((r) => r.id),
detail.container ? { container: detail.container, onLeave: detail.onClose } : undefined,
);
});
const openRow = (rowId: string, order: string[]) => {
peek?.close();
peek = new RowPeek({ ctx: { ...host() }, mountBody, copyLink }, snapshot(), rowId, order, () => (peek = null));
const recordPage = opts.recordPage;
// A record open as a full page stays one when the block rebinds.
let pageMode: { container: HTMLElement; onLeave?: () => void } | undefined;
const openRow = (rowId: string, order: string[], page?: { container: HTMLElement; onLeave?: () => void }) => {
peek?.close(false);
pageMode = page;
peek = new RowPeek(
{
ctx: { ...host() },
mountBody,
copyLink,
openPage: recordPage && !page ? (row) => recordPage(id(), row) : undefined,
page,
},
snapshot(),
rowId,
order,
() => {
peek = null;
pageMode = undefined;
},
);
};
const refresh = () => {
@@ -409,7 +572,7 @@ export const Database = Node.create<DatabaseOptions>({
refresh();
// An open record's body editor is bound to the old map's fragment.
const open = peek?.row;
if (open && snapshot().rows.some((r) => r.id === open)) openRow(open, [open]);
if (open && snapshot().rows.some((r) => r.id === open)) openRow(open, [open], pageMode);
};
blocks.observe(onKey);
if (m) {
@@ -465,7 +628,11 @@ export const Database = Node.create<DatabaseOptions>({
stopEvent: (e) => !(e.type === "dragstart" && (e.target as HTMLElement) === wrap),
destroy() {
stop?.();
peek?.close();
clearTimeout(laterTimer);
if (doc) blocksOf(doc).unobserveDeep(onBlocks);
for (const r of remote.values()) r.stop();
remote.clear();
peek?.close(false);
view?.destroy();
editor.off("update", onEditable);
editor.off("transaction", onEditable);
+44
View File
@@ -56,6 +56,48 @@ export const englishDatabaseLabels = {
typeMember: "Member",
typeCreatedTime: "Created time",
typeCreatedBy: "Created by",
typeRelation: "Relation",
typeRollup: "Rollup",
/** A relation whose database cannot be read (yet): how many records it links to. */
linkedCount: "{n} linked",
rollupDays: "{n} days",
relationTo: "Related database",
relationPick: "Choose a database",
relationThisPage: "On this page",
relationOtherPage: "On another page…",
relationSearchPage: "Find a page",
relationNoDatabases: "No databases on that page",
relationMissing: "The related database is not available.",
linkRecord: "Link a record",
searchRecords: "Search records",
noRecords: "No records",
openRelated: "Open record",
rollupSettings: "Rollup",
rollupRelation: "Relation",
rollupProperty: "Property",
rollupFn: "Calculate",
rollupRecords: "Records",
rollupNeedsRelation: "Add a relation property first.",
fnShowOriginal: "Show values",
fnCount: "Count records",
fnCountValues: "Count values",
fnCountUnique: "Count unique values",
fnCountEmpty: "Count empty",
fnCountNotEmpty: "Count not empty",
fnPercentNotEmpty: "Percent not empty",
fnSum: "Sum",
fnAverage: "Average",
fnMedian: "Median",
fnMin: "Min",
fnMax: "Max",
fnRange: "Range",
fnEarliest: "Earliest date",
fnLatest: "Latest date",
fnChecked: "Checked",
fnPercentChecked: "Percent checked",
openFullPage: "Open as full page",
backToPage: "Back to the page",
recordNotFound: "This record is not in the database any more.",
opContains: "contains",
opNotContains: "does not contain",
opIs: "is",
@@ -144,6 +186,8 @@ const typeKeys: Record<ColumnType, keyof DatabaseLabels> = {
member: "typeMember",
createdTime: "typeCreatedTime",
createdBy: "typeCreatedBy",
relation: "typeRelation",
rollup: "typeRollup",
};
export const typeLabel = (l: DatabaseLabels, t: ColumnType) => l[typeKeys[t]];
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { describe, expect, it } from "vitest";
import { englishDatabaseLabels } from "./labels";
import { computeLinked, rollupFnsFor } from "./linked";
import { cellText, normalize, viewRows, type DbData } from "./model";
const tasks: DbData = normalize({
title: "Tasks",
columns: [
{ id: "t", name: "Name", type: "title" },
{ id: "h", name: "Hours", type: "number" },
{ id: "c", name: "Done", type: "checkbox" },
{ id: "d", name: "Due", type: "date" },
],
rows: [
{ id: "k1", cells: { t: "Write", h: 2.5, c: true, d: "2026-11-02" } },
{ id: "k2", cells: { t: "Ship", h: 4, d: "2026-11-09" } },
{ id: "k3", cells: { t: "Rest" } },
],
views: [],
});
const projects = (fn: string, property = "h") =>
normalize({
title: "Projects",
columns: [
{ id: "t", name: "Name", type: "title" },
{ id: "rel", name: "Tasks", type: "relation", relation: { page: "", database: "tasks" } },
{ id: "r", name: "Roll", type: "rollup", rollup: { relation: "rel", property, fn } },
],
rows: [
{ id: "p1", cells: { t: "Launch", rel: ["k1", "k2", "missing"] } },
{ id: "p2", cells: { t: "Idle" } },
],
views: [{ id: "v", name: "", type: "table" }],
});
const linked = (db: DbData, found: DbData | null = tasks) =>
computeLinked(db, (t) => (t.database === "tasks" ? found : null), englishDatabaseLabels);
describe("relations and rollups", () => {
it("keeps their settings when read", () => {
const db = projects("sum");
expect(db.columns[1]).toMatchObject({ type: "relation", relation: { page: "", database: "tasks" } });
expect(db.columns[2]).toMatchObject({ type: "rollup", rollup: { relation: "rel", property: "h", fn: "sum" } });
});
it("shows the related records' titles, leaving out missing ones", () => {
const db = linked(projects("count"));
expect(cellText(db.rows[0]!, db.columns[1]!)).toBe("Write, Ship");
expect(db.rows[0]!.computed!.rel!.links).toEqual([
{ id: "k1", title: "Write" },
{ id: "k2", title: "Ship" },
]);
});
it("shows a count when the related database cannot be read", () => {
const db = linked(projects("count"), null);
expect(cellText(db.rows[0]!, db.columns[1]!)).toBe("3 linked");
});
it.each([
["sum", "h", "6.5"],
["average", "h", "3.25"],
["max", "h", "4"],
["count", "", "2"],
["percentChecked", "c", "50%"],
["earliest", "d", "2026-11-02"],
["range", "d", "7 days"],
["showOriginal", "", "Write, Ship"],
])("%s of %s", (fn, prop, want) => {
const db = linked(projects(fn, prop));
expect(cellText(db.rows[0]!, db.columns[2]!)).toBe(want);
});
it("sorts and filters rollups as numbers", () => {
const db = linked(projects("sum"));
const view = { ...db.views[0]!, sorts: [{ column: "r", desc: true }], filters: [{ column: "r", op: "gt" as const, value: 5 }] };
expect(viewRows(db, view).map((r) => r.id)).toEqual(["p1"]);
const empty = { ...db.views[0]!, filters: [{ column: "rel", op: "isEmpty" as const }] };
expect(viewRows(db, empty).map((r) => r.id)).toEqual(["p2"]);
});
it("offers functions that fit the property", () => {
expect(rollupFnsFor("number")[0]).toBe("sum");
expect(rollupFnsFor("date")[0]).toBe("earliest");
expect(rollupFnsFor("checkbox")).toContain("percentChecked");
});
});
+209
View File
@@ -0,0 +1,209 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Relations and rollups between databases. A relation column holds, per
// record, the ids of records in another database: on the same page, or on
// another page that is read live. A rollup column sums up one property of
// the related records (count, sum, earliest date…). Neither is stored as a
// result: before a view draws, computeLinked works out each record's titles
// and rollup values into row.computed, which cellText and cellValue read.
import type { DatabaseLabels as DbLabels } from "./labels";
import { asList, asNumber, cellText, cellValue, dateOf, isObject, type Column, type DbData, type Row } from "./model";
/** The database a relation points to; page "" is the page the relation is on. */
export interface RelationTarget {
page: string;
database: string;
}
export const rollupFns = [
"showOriginal",
"count",
"countValues",
"countUnique",
"countEmpty",
"countNotEmpty",
"percentNotEmpty",
"sum",
"average",
"median",
"min",
"max",
"range",
"earliest",
"latest",
"checked",
"percentChecked",
] as const;
export type RollupFn = (typeof rollupFns)[number];
export interface RollupConfig {
/** The relation column of this database whose records are rolled up. */
relation: string;
/** The column of the related database; "" rolls up the records themselves (their titles). */
property: string;
fn: RollupFn;
}
/** What a relation or rollup cell shows, worked out from the related database. */
export interface Computed {
text: string;
/** A number for counts and sums, a "YYYY-MM-DD" for dates, the titles' list otherwise. */
value: unknown;
/** The related records, for relation cells: their ids and titles (missing ones left out). */
links?: { id: string; title: string }[];
}
export function readTarget(v: unknown): RelationTarget | undefined {
if (!isObject(v) || typeof v.database !== "string" || !v.database) return undefined;
return { page: typeof v.page === "string" ? v.page : "", database: v.database };
}
export function readRollup(v: unknown): RollupConfig | undefined {
if (!isObject(v) || typeof v.relation !== "string") return undefined;
const fn = (rollupFns as readonly string[]).includes(String(v.fn)) ? (v.fn as RollupFn) : "count";
return { relation: v.relation, property: typeof v.property === "string" ? v.property : "", fn };
}
/** The functions that make sense for a property type, the first being the default. */
export function rollupFnsFor(type: Column["type"] | ""): RollupFn[] {
const counts: RollupFn[] = ["count", "countValues", "countUnique", "countEmpty", "countNotEmpty", "percentNotEmpty"];
switch (type) {
case "number":
case "progress":
return ["sum", "average", "median", "min", "max", "range", ...counts, "showOriginal"];
case "date":
case "createdTime":
return ["earliest", "latest", "range", ...counts, "showOriginal"];
case "checkbox":
return ["checked", "percentChecked", "count", "showOriginal"];
default:
return ["showOriginal", ...counts];
}
}
/** The ids a relation cell links to. */
export const relationIds = (v: unknown): string[] =>
asList<unknown>(v).filter((x): x is string => typeof x === "string" && !!x);
const fmt = (n: number) => (Number.isInteger(n) ? String(n) : String(Math.round(n * 100) / 100));
const days = (a: string, b: string) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
/** One rollup over the related records' values in a column. */
export function rollup(fn: RollupFn, related: Row[], col: Column | null, l: Pick<DbLabels, "rollupDays">): Computed {
const values = related.map((r) => (col ? cellValue(r, col) : r.id));
const texts = related.map((r) => (col ? cellText(r, col) : ""));
const filled = texts.filter((t, i) => (col?.type === "checkbox" ? values[i] === true : t !== ""));
const nums = col ? values.map(asNumber).filter((n): n is number => n !== null) : [];
const dates = col ? values.map(dateOf).filter(Boolean).sort() : [];
const num = (n: number | null): Computed => ({ text: n === null ? "" : fmt(n), value: n });
switch (fn) {
case "count":
return num(related.length);
case "countValues":
return num(filled.length);
case "countUnique":
return num(new Set(filled).size);
case "countEmpty":
return num(related.length - filled.length);
case "countNotEmpty":
return num(filled.length);
case "percentNotEmpty":
return related.length ? { text: `${fmt((filled.length / related.length) * 100)}%`, value: (filled.length / related.length) * 100 } : num(null);
case "sum":
return num(nums.length ? nums.reduce((a, b) => a + b, 0) : null);
case "average":
return num(nums.length ? nums.reduce((a, b) => a + b, 0) / nums.length : null);
case "median": {
if (!nums.length) return num(null);
const s = [...nums].sort((a, b) => a - b);
const m = Math.floor(s.length / 2);
return num(s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2);
}
case "min":
return num(nums.length ? Math.min(...nums) : null);
case "max":
return num(nums.length ? Math.max(...nums) : null);
case "range":
if (col && (col.type === "date" || col.type === "createdTime")) {
if (!dates.length) return num(null);
const d = days(dates[0]!, dates[dates.length - 1]!);
return { text: l.rollupDays.replace("{n}", String(d)), value: d };
}
return num(nums.length ? Math.max(...nums) - Math.min(...nums) : null);
case "earliest":
return { text: dates[0] ?? "", value: dates[0] ?? null };
case "latest":
return { text: dates[dates.length - 1] ?? "", value: dates[dates.length - 1] ?? null };
case "checked":
return num(values.filter((v) => v === true).length);
case "percentChecked":
return related.length
? { text: `${fmt((values.filter((v) => v === true).length / related.length) * 100)}%`, value: (values.filter((v) => v === true).length / related.length) * 100 }
: num(null);
case "showOriginal": {
const shown = texts.filter(Boolean);
return { text: shown.join(", "), value: shown };
}
}
}
/**
* The database with every relation and rollup cell worked out. find returns
* the related database, or null while it is not (yet) readable; then a
* relation shows how many records it links to.
*/
export function computeLinked(
db: DbData,
find: (t: RelationTarget) => DbData | null,
l: Pick<DbLabels, "linkedCount" | "rollupDays">,
): DbData {
const relations = db.columns.filter((c) => c.type === "relation" && c.relation);
const rollups = db.columns.filter((c) => c.type === "rollup" && c.rollup);
if (!relations.length && !rollups.length) return db;
const targets = new Map<string, DbData | null>();
for (const c of relations) targets.set(c.id, find(c.relation!));
const rows = db.rows.map((r) => {
const computed: Record<string, Computed> = {};
for (const c of relations) {
const ids = relationIds(r.cells[c.id]);
const target = targets.get(c.id);
if (!target) {
computed[c.id] = { text: ids.length ? l.linkedCount.replace("{n}", String(ids.length)) : "", value: ids };
continue;
}
const title = target.columns.find((x) => x.type === "title");
const byId = new Map(target.rows.map((x) => [x.id, x]));
const links = ids.flatMap((id) => {
const row = byId.get(id);
return row ? [{ id, title: title ? cellText(row, title) : "" }] : [];
});
computed[c.id] = { text: links.map((x) => x.title).join(", "), value: ids, links };
}
for (const c of rollups) {
const cfg = c.rollup!;
const rel = relations.find((x) => x.id === cfg.relation);
const target = rel ? targets.get(rel.id) : null;
if (!rel || !target) {
computed[c.id] = { text: "", value: null };
continue;
}
const byId = new Map(target.rows.map((x) => [x.id, x]));
const related = relationIds(r.cells[rel.id]).flatMap((id) => {
const row = byId.get(id);
return row ? [row] : [];
});
const prop = cfg.property ? (target.columns.find((x) => x.id === cfg.property) ?? null) : (target.columns.find((x) => x.type === "title") ?? null);
computed[c.id] = rollup(cfg.fn, related, prop, l);
}
return { ...r, computed };
});
return { ...db, rows };
}
/** Same-page databases a relation can point to, from the page's other database blocks. */
export interface DatabaseChoice {
page: string;
database: string;
title: string;
}
+11 -2
View File
@@ -23,6 +23,10 @@ export const OPEN_RECORD = "dw-open-record";
export interface OpenRecordDetail {
row: string;
/** Draws the record as a full page inside this element instead of beside the page. */
container?: HTMLElement;
/** Called when a record opened in a container is closed ("Back to the page"). */
onClose?: () => void;
/** Set by the block when it has the record and opened it. */
found?: boolean;
}
@@ -31,7 +35,12 @@ export interface OpenRecordDetail {
* Opens a record of the page's database. Returns false while the page does
* not show it (yet): the document may still be loading, or it was deleted.
*/
export function openRecord(editor: Editor, database: string, row: string): boolean {
export function openRecord(
editor: Editor,
database: string,
row: string,
page?: Pick<OpenRecordDetail, "container" | "onClose">,
): boolean {
let pos = -1;
editor.state.doc.descendants((n, p) => {
if (pos >= 0) return false;
@@ -41,7 +50,7 @@ export function openRecord(editor: Editor, database: string, row: string): boole
if (pos < 0) return false;
const dom = editor.view.nodeDOM(pos);
if (!(dom instanceof HTMLElement)) return false;
const detail: OpenRecordDetail = { row };
const detail: OpenRecordDetail = { row, ...page };
dom.dispatchEvent(new CustomEvent(OPEN_RECORD, { detail }));
return !!detail.found;
}
+35 -1
View File
@@ -6,6 +6,7 @@
import type { JSONContent } from "@tiptap/core";
import { isPaletteColor, palette, type PaletteColor } from "../colors";
import { readRollup, readTarget, relationIds, type Computed, type RelationTarget, type RollupConfig } from "./linked";
export const columnTypes = [
"title",
@@ -21,6 +22,8 @@ export const columnTypes = [
"member",
"createdTime",
"createdBy",
"relation",
"rollup",
] as const;
export type ColumnType = (typeof columnTypes)[number];
@@ -39,6 +42,10 @@ export interface Column {
type: ColumnType;
/** The choices of a select or multi-select column. */
options?: SelectOption[];
/** The database a relation column links to. */
relation?: RelationTarget;
/** What a rollup column sums up. */
rollup?: RollupConfig;
}
export interface Person {
@@ -63,6 +70,8 @@ export interface Row {
hasBody?: boolean;
/** The body as ProseMirror nodes, in snapshots read from JSON (see ADR-13). */
body?: JSONContent[];
/** Relation and rollup cells worked out from the related databases (linked.ts); never stored. */
computed?: Record<string, Computed>;
}
export const viewTypes = ["table", "kanban", "calendar"] as const;
@@ -155,6 +164,10 @@ export function normalize(raw: unknown): DbData {
const type = (columnTypes as readonly string[]).includes(String(c.type)) ? (c.type as ColumnType) : "text";
const col: Column = { id: c.id, name: typeof c.name === "string" ? c.name : "", type };
if (Array.isArray(c.options)) col.options = c.options.flatMap(option);
const target = type === "relation" ? readTarget(c.relation) : undefined;
if (target) col.relation = target;
const roll = type === "rollup" ? readRollup(c.rollup) : undefined;
if (roll) col.rollup = roll;
return [col];
});
if (!columns.some((c) => c.type === "title")) columns.unshift({ id: newId(), name: "", type: "title" });
@@ -222,6 +235,7 @@ export function titleColumn(db: DbData): Column {
export function cellValue(row: Row, col: Column): unknown {
if (col.type === "createdTime") return row.createdAt || null;
if (col.type === "createdBy") return row.createdBy ? [row.createdBy] : [];
if (col.type === "rollup") return row.computed?.[col.id]?.value ?? null;
return row.cells[col.id];
}
@@ -287,6 +301,9 @@ export function cellText(row: Row, col: Column): string {
return asList<Person>(v)
.map((p) => p?.name ?? "")
.join(", ");
case "relation":
case "rollup":
return row.computed?.[col.id]?.text ?? "";
}
}
@@ -309,6 +326,10 @@ export function filterOps(type: ColumnType): FilterOp[] {
return ["is", "before", "after", "isEmpty", "isNotEmpty"];
case "attachment":
return ["isEmpty", "isNotEmpty"];
case "relation":
return ["contains", "notContains", "isEmpty", "isNotEmpty"];
case "rollup":
return ["is", "isNot", "gt", "lt", "gte", "lte", "contains", "isEmpty", "isNotEmpty"];
default:
return ["contains", "notContains", "is", "isNot", "isEmpty", "isNotEmpty"];
}
@@ -319,13 +340,20 @@ export const opTakesValue = (op: FilterOp) => !["isEmpty", "isNotEmpty", "checke
export function matchesFilter(row: Row, col: Column, f: Filter): boolean {
const v = cellValue(row, col);
if (col.type === "relation") {
const empty = relationIds(v).length === 0;
if (f.op === "isEmpty") return empty;
if (f.op === "isNotEmpty") return !empty;
}
if (f.op === "isEmpty") return isEmptyValue(v) || cellText(row, col) === "";
if (f.op === "isNotEmpty") return !(isEmptyValue(v) || cellText(row, col) === "");
if (f.op === "checked") return v === true;
if (f.op === "unchecked") return v !== true;
// A filter without a value yet matches everything, as in a spreadsheet.
if (f.value === undefined || f.value === null || f.value === "") return true;
switch (col.type) {
// A rollup that counts or sums compares as a number.
const numeric = col.type === "rollup" && (typeof v === "number" || v === null) && ["is", "isNot", "gt", "lt", "gte", "lte"].includes(f.op);
switch (numeric ? "number" : col.type) {
case "number":
case "progress": {
const n = asNumber(v);
@@ -387,6 +415,12 @@ export function compareRows(a: Row, b: Row, col: Column): number {
return Number(cellValue(a, col) === true) - Number(cellValue(b, col) === true);
case "createdTime":
return a.createdAt - b.createdAt;
case "rollup": {
const x = cellValue(a, col);
const y = cellValue(b, col);
if (typeof x === "number" && typeof y === "number") return x - y;
return cellText(a, col).localeCompare(cellText(b, col), undefined, { numeric: true, sensitivity: "base" });
}
case "select": {
// Choices sort in their own order, like a status column.
const order = (r: Row) => col.options?.findIndex((o) => o.id === cellValue(r, col)) ?? -1;
+26 -9
View File
@@ -16,6 +16,10 @@ export interface PeekHost {
mountBody: (el: HTMLElement, row: Row) => (() => void) | null;
/** Copies a link to the record; without it there is no button. */
copyLink?: (row: string) => void;
/** Opens the record as a full page; without it there is no button. */
openPage?: (row: string) => void;
/** Draws the record as a full page in container instead of a panel over the page. */
page?: { container: HTMLElement; onLeave?: () => void };
}
export class RowPeek {
@@ -39,9 +43,9 @@ export class RowPeek {
) {
this.returnFocus = document.activeElement;
this.panel = h("div", { class: "dw-db-peek__panel", role: "dialog", "aria-modal": "true", tabIndex: -1 }, this.head, this.props, this.bodyEl);
this.dom = h("div", { class: "dw-db-peek" }, this.panel);
this.dom = h("div", { class: host.page ? "dw-db-peek dw-db-peek--page" : "dw-db-peek" }, this.panel);
this.dom.addEventListener("mousedown", (e) => {
if (e.target === this.dom) this.close();
if (e.target === this.dom && !this.host.page) this.close();
});
this.dom.addEventListener("keydown", (e) => {
if (e.key === "Escape" && !document.querySelector(".dw-db-pop, .dw-block-menu")) {
@@ -50,7 +54,11 @@ export class RowPeek {
this.close();
}
});
document.body.append(this.dom);
if (host.page) {
this.panel.removeAttribute("aria-modal");
this.panel.setAttribute("role", "region");
host.page.container.replaceChildren(this.dom);
} else document.body.append(this.dom);
this.draw(true);
this.panel.focus({ preventScroll: true });
}
@@ -103,17 +111,24 @@ export class RowPeek {
const next = iconButton("chevron-down", l.nextRow, () => this.show(this.order[i + 1]!));
prev.disabled = i <= 0;
next.disabled = i < 0 || i >= this.order.length - 1;
const page = this.host.page;
this.head.replaceChildren(
...(page ? [iconButton("chevron-left", l.backToPage, () => this.close())] : []),
h("span", { class: "dw-db-peek__db" }, icon("database", 14), this.db.title || l.untitled),
h("span", { class: "dw-db-peek__grow" }),
prev,
next,
iconButton(this.wide ? "width" : "width", this.wide ? l.collapse : l.expand, () => {
this.wide = !this.wide;
this.panel.classList.toggle("is-wide", this.wide);
}),
...(page
? []
: [
iconButton(this.wide ? "width" : "width", this.wide ? l.collapse : l.expand, () => {
this.wide = !this.wide;
this.panel.classList.toggle("is-wide", this.wide);
}),
]),
...(this.host.openPage ? [iconButton("open", l.openFullPage, () => this.host.openPage!(this.rowId))] : []),
...(this.host.copyLink ? [iconButton("link", l.copyLink, () => this.host.copyLink!(this.rowId))] : []),
iconButton("close", l.close, () => this.close()),
...(page ? [] : [iconButton("close", l.close, () => this.close())]),
);
const title = titleColumn(this.db);
@@ -184,11 +199,13 @@ export class RowPeek {
}
}
close() {
/** Closes the record; leave is false when the page itself goes away (no "back to the page"). */
close(leave = true) {
this.unmount?.();
this.unmount = null;
this.dom.remove();
this.onClose();
if (leave) this.host.page?.onLeave?.();
if (this.returnFocus instanceof HTMLElement && this.returnFocus.isConnected) this.returnFocus.focus({ preventScroll: true });
}
}
+265
View File
@@ -0,0 +1,265 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Panels for relations and rollups: which database a relation points to,
// which records a cell links to, and what a rollup calculates.
import type { DbContext } from "./cells";
import { h, popover } from "./dom";
import { fill, typeLabel, type DatabaseLabels } from "./labels";
import { relationIds, rollupFnsFor, type DatabaseChoice, type RelationTarget, type RollupConfig, type RollupFn } from "./linked";
import { cellText, titleColumn, type Column, type DbData, type Row } from "./model";
/** What relation cells and settings need from the block (index.ts fills it in). */
export interface LinkedHost {
/** The other databases on this page. */
local(): DatabaseChoice[];
/** Finds pages by title, for relations to another page's database. */
searchPages?(query: string): Promise<{ id: string; title: string }[]>;
/** The databases on another page (it is opened read-only to list them). */
databasesOn?(page: string): Promise<DatabaseChoice[]>;
/** The related database as it is now; null while it cannot be read. */
read(target: RelationTarget): DbData | null;
/** Opens a related record: beside this page, or on its own page. */
openRecord(target: RelationTarget, row: string): void;
}
const fnKey = (fn: RollupFn) => `fn${fn[0]!.toUpperCase()}${fn.slice(1)}` as keyof DatabaseLabels;
export const rollupFnLabel = (l: DatabaseLabels, fn: RollupFn) => l[fnKey(fn)];
function item(label: string, active: boolean, run: () => void, sub?: string): HTMLElement {
const el = h(
"div",
{ class: `dw-db-pop__item${active ? " is-active" : ""}`, role: "option", "aria-selected": String(active) },
h("span", {}, label),
sub ? h("small", { class: "dw-db-pop__sub" }, sub) : null,
);
el.addEventListener("mousedown", (e) => e.preventDefault());
el.addEventListener("click", run);
return el;
}
/** Picks the database a relation column points to. */
export function relationTargetPanel(ctx: DbContext, anchor: Element, col: Column, onDone?: () => void) {
const store = ctx.store;
const linked = ctx.linked;
if (!store || !linked) return;
const l = ctx.labels;
popover(
anchor,
(box, close) => {
const pick = (c: DatabaseChoice) => {
store.setRelation(col.id, { page: c.page, database: c.database });
close();
};
const current = col.relation;
const list = h("div", { class: "dw-db-pop__list", role: "listbox" });
const drawLocal = () => {
const local = linked.local();
list.replaceChildren(
h("div", { class: "dw-db-pop__heading" }, l.relationThisPage),
...(local.length
? local.map((c) =>
item(c.title || l.untitled, !!current && !current.page && current.database === c.database, () => pick(c)),
)
: [h("div", { class: "dw-db-pop__empty" }, l.relationNoDatabases)]),
);
};
drawLocal();
box.append(h("div", { class: "dw-db-pop__title" }, l.relationPick), list);
if (linked.searchPages && linked.databasesOn) {
const input = h("input", { class: "dw-db-input", placeholder: l.relationSearchPage, "aria-label": l.relationOtherPage });
const found = h("div", { class: "dw-db-pop__list", role: "listbox" });
let seq = 0;
input.addEventListener("input", async () => {
const q = input.value.trim();
const n = ++seq;
if (!q) return found.replaceChildren();
const pages = await linked.searchPages!(q).catch(() => []);
if (n !== seq) return;
found.replaceChildren(
...pages.slice(0, 8).map((p) =>
item(p.title || l.untitled, false, async () => {
const dbs = await linked.databasesOn!(p.id).catch(() => []);
if (n !== seq) return;
found.replaceChildren(
h("div", { class: "dw-db-pop__heading" }, p.title || l.untitled),
...(dbs.length
? dbs.map((c) =>
item(c.title || l.untitled, current?.page === c.page && current.database === c.database, () => pick(c)),
)
: [h("div", { class: "dw-db-pop__empty" }, l.relationNoDatabases)]),
);
}),
),
);
});
input.addEventListener("keydown", (e) => e.stopPropagation());
box.append(h("div", { class: "dw-db-pop__heading" }, l.relationOtherPage), input, found);
}
},
{ class: "dw-db-pop--choices", label: l.relationTo, onClose: onDone },
);
}
/** Links and unlinks records of the related database in one relation cell. */
export function relationPanel(ctx: DbContext, box: HTMLDivElement, row: Row, col: Column, close: () => void) {
const store = ctx.store!;
const l = ctx.labels;
const target = col.relation;
const related = target ? ctx.linked?.read(target) : null;
if (!target || !related) {
box.append(h("div", { class: "dw-db-pop__empty" }, target ? l.relationMissing : l.relationPick));
if (!target && ctx.linked) {
const btn = h("button", { type: "button", class: "dw-db__btn" }, l.relationTo);
btn.addEventListener("click", () => {
close();
relationTargetPanel(ctx, box, col);
});
box.append(btn);
}
return;
}
const title = titleColumn(related);
let ids = relationIds(row.cells[col.id]);
const chosen = h("div", { class: "dw-db-tags dw-db-pop__chosen" });
const input = h("input", { class: "dw-db-input", placeholder: l.searchRecords, "aria-label": l.linkRecord });
const list = h("div", { class: "dw-db-pop__list", role: "listbox" });
box.append(chosen, input, list);
const name = (r: Row) => cellText(r, title) || l.untitledRow;
const save = () => store.setCell(row.id, col.id, ids.length ? ids : null);
const toggle = (id: string) => {
ids = ids.includes(id) ? ids.filter((x) => x !== id) : [...ids, id];
save();
draw();
};
let active = 0;
let shown: Row[] = [];
const draw = () => {
const byId = new Map(related.rows.map((r) => [r.id, r]));
chosen.replaceChildren(
...ids.flatMap((id) => {
const r = byId.get(id);
if (!r) return [];
const t = h("span", { class: "dw-db-tag", dataset: { color: "gray" } }, name(r));
const x = h("button", { type: "button", class: "dw-db-tag__x", "aria-label": "×" }, "×");
x.addEventListener("mousedown", (e) => e.preventDefault());
x.addEventListener("click", () => toggle(id));
t.append(x);
return [t];
}),
);
const q = input.value.trim().toLowerCase();
shown = related.rows.filter((r) => !q || name(r).toLowerCase().includes(q)).slice(0, 50);
active = Math.min(active, Math.max(0, shown.length - 1));
list.replaceChildren(
...(shown.length
? shown.map((r, i) => {
const el = item(name(r), i === active, () => toggle(r.id));
if (ids.includes(r.id)) el.prepend(h("span", { class: "dw-db-pop__check" }, "✓"));
return el;
})
: [h("div", { class: "dw-db-pop__empty" }, l.noRecords)]),
);
};
input.addEventListener("input", () => {
active = 0;
draw();
});
input.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (shown.length) active = (active + (e.key === "ArrowDown" ? 1 : -1) + shown.length) % shown.length;
draw();
} else if (e.key === "Enter") {
e.preventDefault();
const r = shown[active];
if (r) toggle(r.id);
} else if (e.key === "Escape") {
e.preventDefault();
close();
}
});
draw();
input.focus({ preventScroll: true });
}
/** What a rollup column calculates: over which relation, which property, how. */
export function rollupPanel(ctx: DbContext, anchor: Element, col: Column, onDone?: () => void) {
const store = ctx.store;
if (!store) return;
const l = ctx.labels;
popover(
anchor,
(box) => {
const relations = ctx.db.columns.filter((c) => c.type === "relation");
if (!relations.length) {
box.append(h("div", { class: "dw-db-pop__empty" }, l.rollupNeedsRelation));
return;
}
const cfg: RollupConfig = col.rollup ?? { relation: relations[0]!.id, property: "", fn: "count" };
const select = (label: string, options: [string, string][], value: string, onChange: (v: string) => void) => {
const s = h("select", { class: "dw-db-input", "aria-label": label });
for (const [v, text] of options) s.append(h("option", { value: v }, text));
s.value = value;
s.addEventListener("change", () => onChange(s.value));
return h("label", { class: "dw-db-pop__field" }, h("span", {}, label), s);
};
const draw = () => {
const rel = relations.find((c) => c.id === cfg.relation) ?? relations[0]!;
const target = rel.relation ? ctx.linked?.read(rel.relation) : null;
const props: [string, string][] = [["", l.rollupRecords]];
for (const c of target?.columns ?? []) props.push([c.id, c.name || typeLabel(l, c.type)]);
const prop = target?.columns.find((c) => c.id === cfg.property);
const fns = rollupFnsFor(prop ? prop.type : "");
if (!fns.includes(cfg.fn)) cfg.fn = cfg.property ? fns[0]! : "count";
box.replaceChildren(
select(l.rollupRelation, relations.map((c) => [c.id, c.name || l.typeRelation]), rel.id, (v) => {
cfg.relation = v;
cfg.property = "";
cfg.fn = "count";
store.setRollup(col.id, { ...cfg });
draw();
}),
select(l.rollupProperty, props, cfg.property, (v) => {
cfg.property = v;
const t = target?.columns.find((c) => c.id === v);
cfg.fn = v ? rollupFnsFor(t ? t.type : "")[0]! : "count";
store.setRollup(col.id, { ...cfg });
draw();
}),
select(l.rollupFn, (cfg.property ? fns : (["count", "showOriginal"] as RollupFn[])).map((f) => [f, rollupFnLabel(l, f)]), cfg.fn, (v) => {
cfg.fn = v as RollupFn;
store.setRollup(col.id, { ...cfg });
}),
target ? h("span") : h("div", { class: "dw-db-pop__empty" }, l.relationMissing),
);
};
// A new rollup starts counting the first relation's records.
if (!col.rollup) store.setRollup(col.id, { ...cfg });
draw();
},
{ class: "dw-db-pop--choices", label: l.rollupSettings, onClose: onDone },
);
}
/** A relation cell: the linked records' titles, each opening its record. */
export function renderRelation(ctx: DbContext, row: Row, col: Column): HTMLElement {
const c = row.computed?.[col.id];
const wrap = h("span", { class: "dw-db-tags" });
if (c?.links && col.relation) {
const target = col.relation;
for (const link of c.links) {
const a = h("button", { type: "button", class: "dw-db-tag dw-db-rel", dataset: { color: "gray" }, title: ctx.labels.openRelated }, link.title || ctx.labels.untitledRow);
a.addEventListener("click", (e) => {
// A click on a chip opens the record; the cell itself edits.
e.stopPropagation();
ctx.linked?.openRecord(target, link.id);
});
wrap.append(a);
}
} else if (c?.text) wrap.append(h("span", { class: "dw-db-cell__text" }, c.text));
return wrap;
}
export const linkedCountText = (l: DatabaseLabels, n: number) => fill(l.linkedCount, n);
+25
View File
@@ -6,6 +6,7 @@
// manager tracks, so Ctrl+Z undoes it like typing.
import * as Y from "yjs";
import type { RelationTarget, RollupConfig } from "./linked";
import {
convertValue,
defaultView,
@@ -56,6 +57,8 @@ function columnToY(c: Column): YItem {
m.set("name", c.name);
m.set("type", c.type);
if (c.options) m.set("options", c.options);
if (c.relation) m.set("relation", c.relation);
if (c.rollup) m.set("rollup", c.rollup);
return m;
}
@@ -244,6 +247,26 @@ export class DbStore {
this.tx(() => this.find("columns", id)?.item.set("name", name));
}
/** Points a relation column at a database; its links to the old one are dropped. */
setRelation(id: string, target: RelationTarget) {
this.tx(() => {
const found = this.find("columns", id);
if (!found) return;
const old = found.item.get("relation") as RelationTarget | undefined;
found.item.set("relation", target);
if (old && (old.page !== target.page || old.database !== target.database)) {
for (const yr of this.list("rows").toArray()) {
const cells = yr.get("cells");
if (cells instanceof Y.Map) cells.delete(id);
}
}
});
}
setRollup(id: string, rollup: RollupConfig) {
this.tx(() => this.find("columns", id)?.item.set("rollup", rollup));
}
setOptions(id: string, options: SelectOption[]) {
this.tx(() => this.find("columns", id)?.item.set("options", options));
}
@@ -266,6 +289,8 @@ export class DbStore {
found.item.set("type", type);
if (type === "select" || type === "multiSelect") found.item.set("options", options);
else found.item.delete("options");
if (type !== "relation") found.item.delete("relation");
if (type !== "rollup") found.item.delete("rollup");
for (const yr of this.list("rows").toArray()) {
const cells = yr.get("cells");
if (!(cells instanceof Y.Map)) continue;
+18 -1
View File
@@ -32,6 +32,7 @@ import {
type View,
type ViewType,
} from "./model";
import { relationTargetPanel, rollupPanel } from "./relationui";
export interface ViewHost extends Omit<DbContext, "db" | "openRow" | "setEditing"> {
/** Opens a row as a page (peek.ts). */
@@ -662,10 +663,18 @@ export class DatabaseView {
id: t,
label: typeLabel(l, t),
icon: t === c.type ? "check" : typeIcons[t],
run: () => store.changeType(c.id, t),
run: () => {
store.changeType(c.id, t);
// A relation needs its database, a rollup what to calculate.
if (t === "relation" || t === "rollup") queueMicrotask(() => this.linkSettings(anchor, c.id));
},
})),
});
}
if (c.type === "relation")
actions.push({ id: "relationTo", label: l.relationTo, icon: "relation", run: () => this.linkSettings(anchor, c.id) });
if (c.type === "rollup")
actions.push({ id: "rollup", label: l.rollupSettings, icon: "rollup", run: () => this.linkSettings(anchor, c.id) });
actions.push(sortBy(false), sortBy(true), {
id: "filter",
label: l.filterBy,
@@ -692,6 +701,14 @@ export class DatabaseView {
openBlockMenu(anchor, actions, c.name || typeLabel(l, c.type));
}
/** Opens the settings of a relation or rollup column. */
private linkSettings(anchor: HTMLElement, id: string) {
const col = this.db.columns.find((x) => x.id === id);
const target = anchor.isConnected ? anchor : (this.dom.querySelector(`[data-col="${id}"]`) ?? this.dom);
if (col?.type === "relation") relationTargetPanel(this.ctx(), target, col);
else if (col?.type === "rollup") rollupPanel(this.ctx(), target, col);
}
private insertColumn(at: number) {
const store = this.host.store;
if (!store) return;
+6
View File
@@ -42,6 +42,10 @@ export interface EdgelessOptions extends NoteOptions {
onStyles?: (s: StyleDefaults) => void;
viewKey?: string;
pageTitle?: () => string;
/** Offers "Comment" on a selected element (also to readers). */
onComment?: (el: { id: string; text: string }) => void;
/** A comment badge on an element was clicked. */
onCommentSelect?: (comment: string) => void;
/**
* Makes a note's editor. The web app mounts its full editor (with the
* selection toolbar); without it a plain Tiptap editor is used.
@@ -153,6 +157,8 @@ export function mountEdgeless(el: HTMLElement, opts: EdgelessOptions): Edgeless
pageTitle: opts.pageTitle,
undo: live,
onError: opts.onError,
onComment: opts.onComment,
onCommentSelect: opts.onCommentSelect,
});
return {
view,
+53
View File
@@ -2061,6 +2061,44 @@
margin: 4px 2px;
color: var(--color-ink-faint);
}
/* Relations and rollups. */
.dw-db-pop__title {
margin: 2px 2px 4px;
font-weight: 600;
}
.dw-db-pop__heading {
margin: 6px 2px 2px;
color: var(--color-ink-muted);
font-size: 12px;
font-weight: 600;
}
.dw-db-pop__sub {
margin-left: auto;
color: var(--color-ink-faint);
}
.dw-db-pop__check {
width: 14px;
color: var(--color-accent);
}
.dw-db-pop__field {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 6px;
font-size: 12px;
color: var(--color-ink-muted);
}
.dw-db-rel {
border: 0;
cursor: pointer;
font: inherit;
text-decoration: underline;
text-decoration-color: color-mix(in srgb, currentColor 35%, transparent);
text-underline-offset: 2px;
}
.dw-db-rel:hover {
text-decoration-color: currentColor;
}
.dw-db-pop__add {
align-self: flex-start;
}
@@ -2118,6 +2156,21 @@
.dw-db-peek__panel.is-wide {
width: 100vw;
}
/* A record opened as a full page: in the page's place, not over it. */
.dw-db-peek--page {
position: static;
z-index: auto;
display: block;
background: none;
}
.dw-db-peek--page .dw-db-peek__panel {
width: 100%;
height: auto;
min-height: 100%;
overflow: visible;
box-shadow: none;
background: transparent;
}
.dw-db-peek__head {
position: sticky;
top: 0;
+7
View File
@@ -79,6 +79,8 @@ export interface ExtensionOptions {
loadPdf?: PdfLoader;
/** Whether code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers?: boolean;
/** Opens a database record as a full page (the host's record route). */
recordPage?: (database: string, row: string) => void;
/** Shows a database row's body read-only (a row in a synced page). */
rowFragmentReadOnly?: Y.XmlFragment;
labels?: EditorLabels;
@@ -177,6 +179,11 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
people: opts.mentions,
// Records are linked like blocks: the page address plus a #fragment.
recordLink: opts.blockLink,
// Relations read other pages' databases the way synced pages are read.
linkedPages: opts.syncedPages,
pages: opts.pages,
onNavigate: opts.onNavigate,
recordPage: opts.recordPage,
onLinkCopied: opts.onBlockLinkCopied,
me: () => {
const id = opts.mentions?.me;
+1
View File
@@ -19,6 +19,7 @@ export { followLink, isTargetHash } from "./hashlinks";
export { embedSource, type LinkHost, type LinkPreview } from "./embeds";
export { dateChoices, formatDate, type DateChoice } from "./dates";
export { default as DocwellEdgeless } from "./DocwellEdgeless.vue";
export type { ElementComment } from "@docwell/canvas";
export {
canvasLabels,
hasSurface,
+2
View File
@@ -129,6 +129,8 @@ export const iconPaths = {
sliders: ["M5 6h14", "M5 12h14", "M5 18h14", "M9 4v4", "M15 10v4", "M11 16v4"],
sort: ["M7 4v16", "M4 7l3-3 3 3", "M17 20V4", "M14 17l3 3 3-3"],
database: ["M4 5h16v14H4z", "M4 10h16", "M4 15h16", "M10 10v9"],
relation: ["M3 6h7v5H3z", "M14 13h7v5h-7z", "M10 8.5h2.5a2 2 0 0 1 2 2V13"],
rollup: ["M4 5h16", "M4 9h16", "M4 13h16", "M12 16v5", "M9 18l3 3 3-3"],
// Edgeless canvas.
edgeless: ["M4 5h16v14H4z", "M7 15l3-4 3 3 4-5", "M7 8.5h.01"],
cursor: ["M6 4l12 7-5.5 1.5L10 18z"],
@@ -4,7 +4,8 @@
<application
android:label="Docwell"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
android:icon="@mipmap/ic_launcher"
android:localeConfig="@xml/locales_config">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<!-- The languages Docwell speaks, for the per-app language setting (Android 13+). -->
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
<locale android:name="en" />
<locale android:name="pl" />
<locale android:name="de" />
<locale android:name="fr" />
<locale android:name="es" />
</locale-config>
+6
View File
@@ -344,6 +344,7 @@ class Workspace {
required this.organizationName,
required this.role,
required this.created,
required this.defaultPageMode,
});
factory Workspace.fromJson(Map<String, dynamic> json) => Workspace(
@@ -354,6 +355,7 @@ class Workspace {
organizationName: json['organizationName'] as String,
role: WorkspaceRole.fromJson(json['role'] as String),
created: json['created'] as String,
defaultPageMode: PageMode.fromJson(json['defaultPageMode'] as String),
);
final String id;
@@ -370,6 +372,9 @@ class Workspace {
final String created;
/// The view new pages of the workspace open in
final PageMode defaultPageMode;
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
@@ -378,6 +383,7 @@ class Workspace {
'organizationName': organizationName,
'role': role.toJson(),
'created': created,
'defaultPageMode': defaultPageMode.toJson(),
};
}
+10
View File
@@ -12,6 +12,8 @@ import 'screens/page_screen.dart';
import 'screens/share_screen.dart';
import 'session.dart';
import 'share.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'l10n.dart';
/// Makes a client for a server address (with its offline cache).
typedef ApiFactory = DocwellApi Function(String server);
@@ -160,6 +162,14 @@ class _DocwellAppState extends State<DocwellApp> {
final s = _session;
return MaterialApp(
title: 'Docwell',
// The phone's language where the app has it (lib/l10n.dart), else English.
supportedLocales: [for (final l in appLanguages) Locale(l)],
localizationsDelegates: GlobalMaterialLocalizations.delegates,
localeListResolutionCallback: (phone, _) {
final lang = pickLanguage(phone ?? const []);
setAppLanguage(lang);
return Locale(lang);
},
navigatorKey: _navigator,
theme: ThemeData(colorSchemeSeed: brand, useMaterial3: true),
darkTheme: ThemeData(
+5 -3
View File
@@ -125,9 +125,11 @@ class EditorBridge extends ChangeNotifier {
Future<void> focus() => _post({'type': 'focus'});
/// Shows the page's text, or its edgeless canvas (read-only), as the API's
/// PageMode names them: "page" or "edgeless".
Future<void> setMode(String mode) => _post({'type': 'setMode', 'mode': mode});
/// Shows the page's text or its edgeless canvas, as the API's PageMode
/// names them: "page" or "edgeless". The canvas can be edited once
/// [connect]ed and [setEditable]; on saved content it is read-only.
Future<void> setMode(String mode, {String? title}) =>
_post({'type': 'setMode', 'mode': mode, 'title': ?title});
/// Closes the topmost panel or menu over the text.
Future<void> dismiss() => _post({'type': 'dismiss'});
+17 -15
View File
@@ -12,6 +12,7 @@ import 'package:webview_flutter_android/webview_flutter_android.dart'
show AndroidWebViewController, MixedContentMode;
import 'bridge.dart';
import '../l10n.dart';
/// Where Packages/editor-bridge copies its build (`npm run build -w @docwell/editor-bridge`).
const editorAsset = 'assets/editor/index.html';
@@ -180,19 +181,20 @@ class EditorToolbar extends StatelessWidget {
final EditorBridge bridge;
static const _buttons = [
(EditorCommand.bold, Icons.format_bold, 'Bold'),
(EditorCommand.italic, Icons.format_italic, 'Italic'),
(EditorCommand.underline, Icons.format_underline, 'Underline'),
(EditorCommand.strike, Icons.format_strikethrough, 'Strikethrough'),
(EditorCommand.heading1, Icons.title, 'Heading'),
(EditorCommand.bulletList, Icons.format_list_bulleted, 'Bulleted list'),
(EditorCommand.orderedList, Icons.format_list_numbered, 'Numbered list'),
(EditorCommand.taskList, Icons.checklist, 'To-do list'),
(EditorCommand.callout, Icons.lightbulb_outline, 'Callout'),
(EditorCommand.table, Icons.table_chart_outlined, 'Table'),
(EditorCommand.blockquote, Icons.format_quote, 'Quote'),
(EditorCommand.codeBlock, Icons.code, 'Code block'),
// A getter, so the labels follow the language.
static List<(EditorCommand, IconData, String)> get _buttons => [
(EditorCommand.bold, Icons.format_bold, tr('bold')),
(EditorCommand.italic, Icons.format_italic, tr('italic')),
(EditorCommand.underline, Icons.format_underline, tr('underline')),
(EditorCommand.strike, Icons.format_strikethrough, tr('strike')),
(EditorCommand.heading1, Icons.title, tr('heading')),
(EditorCommand.bulletList, Icons.format_list_bulleted, tr('bulletList')),
(EditorCommand.orderedList, Icons.format_list_numbered, tr('orderedList')),
(EditorCommand.taskList, Icons.checklist, tr('taskList')),
(EditorCommand.callout, Icons.lightbulb_outline, tr('callout')),
(EditorCommand.table, Icons.table_chart_outlined, tr('table')),
(EditorCommand.blockquote, Icons.format_quote, tr('quote')),
(EditorCommand.codeBlock, Icons.code, tr('codeBlock')),
];
@override
@@ -207,14 +209,14 @@ class EditorToolbar extends StatelessWidget {
child: Row(
children: [
IconButton(
tooltip: 'Undo',
tooltip: tr('undo'),
icon: const Icon(Icons.undo),
onPressed: state.canUndo
? () => bridge.run(EditorCommand.undo)
: null,
),
IconButton(
tooltip: 'Redo',
tooltip: tr('redo'),
icon: const Icon(Icons.redo),
onPressed: state.canRedo
? () => bridge.run(EditorCommand.redo)
+560
View File
@@ -0,0 +1,560 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The app's own words in the interface languages Docwell has (the same five
// as the web app). The language follows the phone's; Android 13 and later
// can also pick one for this app alone in the system settings. Material's
// own words (Back, Paste…) come from flutter_localizations.
import 'package:flutter/widgets.dart';
/// Languages the app speaks, English first (the fallback).
const appLanguages = ['en', 'pl', 'de', 'fr', 'es'];
String _lang = 'en';
/// The language in use.
String get appLanguage => _lang;
/// Picks the first of the phone's languages the app has (English otherwise).
String pickLanguage(Iterable<Locale> phone) {
for (final l in phone) {
if (appLanguages.contains(l.languageCode)) return l.languageCode;
}
return 'en';
}
/// Sets the language for [tr].
void setAppLanguage(String lang) =>
_lang = appLanguages.contains(lang) ? lang : 'en';
/// The text for key in the current language, with {name} placeholders
/// filled in from args.
String tr(String key, [Map<String, Object> args = const {}]) {
var s = appStrings[_lang]?[key] ?? appStrings['en']![key] ?? key;
args.forEach((k, v) => s = s.replaceAll('{$k}', '$v'));
return s;
}
const appStrings = <String, Map<String, String>>{
'en': {
'untitled': 'Untitled',
'someone': 'Someone',
'retry': 'Retry',
'back': 'Back',
'cancel': 'Cancel',
'done': 'Done',
'edit': 'Edit',
'comments': 'Comments',
'search': 'Search',
'inbox': 'Inbox',
'account': 'Account',
'errNotFound': 'Not found, or you no longer have access.',
'errForbidden': "You don't have permission to do that.",
'errRefused': 'The server refused ({code}).',
'errOfflineNew':
"Can't reach the server, and this hasn't been opened before.",
'errOffline': "Can't reach the server.",
'offlineBanner': 'Offline: showing what was saved on this phone.',
'loginTitle': 'Sign in to Docwell',
'loginTotp': 'Two-step sign-in',
'server': 'Server address',
'email': 'Email',
'password': 'Password',
'totpHint':
'Enter the 6-digit code from your authenticator app, or a recovery code.',
'code': 'Code',
'verify': 'Verify',
'signIn': 'Sign in',
'loginWrong': 'Wrong email or password.',
'loginDisabled': 'This account is disabled.',
'loginBadCode': 'That code is not right. Try the next one.',
'loginMfa':
'This account signs in with an emailed code. Use the web app for now.',
'loginFailed': 'Sign-in failed.',
'loginBadServer': 'That server address is not valid.',
'loginOffline': "Can't reach the server. Check the address and connection.",
'pushTitle': 'Push notifications',
'pushHint': 'Mentions, replies and shares, through UnifiedPush.',
'pushNoDistributor':
'Install a UnifiedPush distributor such as ntfy to get notifications.',
'pushRefused': 'The server did not accept this phone: {error}',
'pushChannel': 'Comments and mentions',
'pushChannelHint': 'Replies, mentions and pages shared with you',
'signOut': 'Sign out',
'switchWorkspace': 'Switch workspace',
'noWorkspaces': 'No workspaces yet',
'noWorkspacesHint': 'Create one in the web app.',
'recent': 'Recent',
'spaces': 'Spaces',
'noSpaces': 'No spaces you can open yet.',
'newPage': 'New page',
'noPages': 'No pages yet.',
'fold': 'Fold',
'unfold': 'Unfold',
'searchIn': 'Search {workspace}',
'nothingFound': 'Nothing found.',
'inPage': 'in {title}',
'notifComment': '{who} commented',
'notifReply': '{who} replied',
'notifMention': '{who} mentioned you',
'notifShare': '{who} shared a page with you',
'notifResolved': '{who} resolved a thread',
'notifReminder': 'Reminder',
'markAllRead': 'Mark all read',
'allCaughtUp': "You're all caught up.",
'hideResolved': 'Hide resolved',
'showResolved': 'Resolved ({n})',
'noComments': 'No comments yet.',
'resolve': 'Resolve',
'reopen': 'Reopen',
'reply': 'Reply',
'commentOnPage': 'Comment on the page',
'replyTo': 'Reply to {name}',
'cancelReply': 'Cancel reply',
'send': 'Send',
'reconnecting': 'Reconnecting…',
'cantEdit': "You can't edit this page any more.",
'connecting': 'Connecting…',
'showAsPage': 'Show as page',
'showAsCanvas': 'Show as canvas',
'archived': 'This page is archived and read-only.',
'saveTitle': 'Save to Docwell',
'pageTitle': 'Page title',
'space': 'Space',
'noSpaceToAdd': "There's no space you can add pages to.",
'text': 'Text',
'saveAsPage': 'Save as a new page',
'bold': 'Bold',
'italic': 'Italic',
'underline': 'Underline',
'strike': 'Strikethrough',
'heading': 'Heading',
'bulletList': 'Bulleted list',
'orderedList': 'Numbered list',
'taskList': 'To-do list',
'callout': 'Callout',
'table': 'Table',
'quote': 'Quote',
'codeBlock': 'Code block',
'undo': 'Undo',
'redo': 'Redo',
},
'pl': {
'untitled': 'Bez tytułu',
'someone': 'Ktoś',
'retry': 'Spróbuj ponownie',
'back': 'Wstecz',
'cancel': 'Anuluj',
'done': 'Gotowe',
'edit': 'Edytuj',
'comments': 'Komentarze',
'search': 'Szukaj',
'inbox': 'Skrzynka',
'account': 'Konto',
'errNotFound': 'Nie znaleziono albo nie masz już dostępu.',
'errForbidden': 'Nie masz uprawnień, aby to zrobić.',
'errRefused': 'Serwer odmówił ({code}).',
'errOfflineNew':
'Brak połączenia z serwerem, a to nie było wcześniej otwierane.',
'errOffline': 'Brak połączenia z serwerem.',
'offlineBanner': 'Offline: widzisz to, co zapisano na tym telefonie.',
'loginTitle': 'Zaloguj się do Docwell',
'loginTotp': 'Logowanie dwuetapowe',
'server': 'Adres serwera',
'email': 'E-mail',
'password': 'Hasło',
'totpHint':
'Wpisz 6-cyfrowy kod z aplikacji uwierzytelniającej albo kod odzyskiwania.',
'code': 'Kod',
'verify': 'Potwierdź',
'signIn': 'Zaloguj',
'loginWrong': 'Nieprawidłowy e-mail lub hasło.',
'loginDisabled': 'To konto jest wyłączone.',
'loginBadCode': 'Ten kod jest nieprawidłowy. Spróbuj następnego.',
'loginMfa':
'To konto loguje się kodem wysyłanym e-mailem. Na razie użyj aplikacji internetowej.',
'loginFailed': 'Logowanie nie powiodło się.',
'loginBadServer': 'Ten adres serwera jest nieprawidłowy.',
'loginOffline': 'Brak połączenia z serwerem. Sprawdź adres i połączenie.',
'pushTitle': 'Powiadomienia push',
'pushHint': 'Wzmianki, odpowiedzi i udostępnienia przez UnifiedPush.',
'pushNoDistributor':
'Zainstaluj dystrybutor UnifiedPush, np. ntfy, aby dostawać powiadomienia.',
'pushRefused': 'Serwer nie przyjął tego telefonu: {error}',
'pushChannel': 'Komentarze i wzmianki',
'pushChannelHint': 'Odpowiedzi, wzmianki i udostępnione Ci strony',
'signOut': 'Wyloguj',
'switchWorkspace': 'Zmień obszar roboczy',
'noWorkspaces': 'Brak obszarów roboczych',
'noWorkspacesHint': 'Utwórz go w aplikacji internetowej.',
'recent': 'Ostatnie',
'spaces': 'Przestrzenie',
'noSpaces': 'Nie ma jeszcze przestrzeni, które możesz otworzyć.',
'newPage': 'Nowa strona',
'noPages': 'Nie ma jeszcze stron.',
'fold': 'Zwiń',
'unfold': 'Rozwiń',
'searchIn': 'Szukaj w {workspace}',
'nothingFound': 'Nic nie znaleziono.',
'inPage': 'w {title}',
'notifComment': '{who} dodaje komentarz',
'notifReply': '{who} odpowiada',
'notifMention': '{who} wspomina o Tobie',
'notifShare': '{who} udostępnia Ci stronę',
'notifResolved': '{who} rozwiązuje wątek',
'notifReminder': 'Przypomnienie',
'markAllRead': 'Oznacz wszystko jako przeczytane',
'allCaughtUp': 'Wszystko przeczytane.',
'hideResolved': 'Ukryj rozwiązane',
'showResolved': 'Rozwiązane ({n})',
'noComments': 'Nie ma jeszcze komentarzy.',
'resolve': 'Rozwiąż',
'reopen': 'Otwórz ponownie',
'reply': 'Odpowiedz',
'commentOnPage': 'Skomentuj stronę',
'replyTo': 'Odpowiedz: {name}',
'cancelReply': 'Anuluj odpowiedź',
'send': 'Wyślij',
'reconnecting': 'Ponowne łączenie…',
'cantEdit': 'Nie możesz już edytować tej strony.',
'connecting': 'Łączenie…',
'showAsPage': 'Pokaż jako stronę',
'showAsCanvas': 'Pokaż jako tablicę',
'archived': 'Ta strona jest zarchiwizowana i tylko do odczytu.',
'saveTitle': 'Zapisz w Docwell',
'pageTitle': 'Tytuł strony',
'space': 'Przestrzeń',
'noSpaceToAdd': 'Nie ma przestrzeni, do której możesz dodawać strony.',
'text': 'Tekst',
'saveAsPage': 'Zapisz jako nową stronę',
'bold': 'Pogrubienie',
'italic': 'Kursywa',
'underline': 'Podkreślenie',
'strike': 'Przekreślenie',
'heading': 'Nagłówek',
'bulletList': 'Lista punktowana',
'orderedList': 'Lista numerowana',
'taskList': 'Lista zadań',
'callout': 'Wyróżnienie',
'table': 'Tabela',
'quote': 'Cytat',
'codeBlock': 'Blok kodu',
'undo': 'Cofnij',
'redo': 'Ponów',
},
'de': {
'untitled': 'Ohne Titel',
'someone': 'Jemand',
'retry': 'Erneut versuchen',
'back': 'Zurück',
'cancel': 'Abbrechen',
'done': 'Fertig',
'edit': 'Bearbeiten',
'comments': 'Kommentare',
'search': 'Suchen',
'inbox': 'Posteingang',
'account': 'Konto',
'errNotFound': 'Nicht gefunden, oder du hast keinen Zugriff mehr.',
'errForbidden': 'Dazu fehlt dir die Berechtigung.',
'errRefused': 'Der Server hat abgelehnt ({code}).',
'errOfflineNew':
'Der Server ist nicht erreichbar, und dies wurde noch nie geöffnet.',
'errOffline': 'Der Server ist nicht erreichbar.',
'offlineBanner':
'Offline: Du siehst, was auf diesem Telefon gespeichert ist.',
'loginTitle': 'Bei Docwell anmelden',
'loginTotp': 'Anmeldung in zwei Schritten',
'server': 'Serveradresse',
'email': 'E-Mail',
'password': 'Passwort',
'totpHint':
'Gib den 6-stelligen Code aus deiner Authenticator-App oder einen Wiederherstellungscode ein.',
'code': 'Code',
'verify': 'Bestätigen',
'signIn': 'Anmelden',
'loginWrong': 'E-Mail oder Passwort ist falsch.',
'loginDisabled': 'Dieses Konto ist deaktiviert.',
'loginBadCode': 'Dieser Code stimmt nicht. Versuche den nächsten.',
'loginMfa':
'Dieses Konto meldet sich mit einem Code per E-Mail an. Nutze vorerst die Web-App.',
'loginFailed': 'Anmeldung fehlgeschlagen.',
'loginBadServer': 'Diese Serveradresse ist ungültig.',
'loginOffline':
'Der Server ist nicht erreichbar. Prüfe Adresse und Verbindung.',
'pushTitle': 'Push-Benachrichtigungen',
'pushHint': 'Erwähnungen, Antworten und Freigaben über UnifiedPush.',
'pushNoDistributor':
'Installiere einen UnifiedPush-Verteiler wie ntfy, um Benachrichtigungen zu bekommen.',
'pushRefused': 'Der Server hat dieses Telefon nicht angenommen: {error}',
'pushChannel': 'Kommentare und Erwähnungen',
'pushChannelHint': 'Antworten, Erwähnungen und mit dir geteilte Seiten',
'signOut': 'Abmelden',
'switchWorkspace': 'Arbeitsbereich wechseln',
'noWorkspaces': 'Noch keine Arbeitsbereiche',
'noWorkspacesHint': 'Erstelle einen in der Web-App.',
'recent': 'Zuletzt',
'spaces': 'Bereiche',
'noSpaces': 'Noch keine Bereiche, die du öffnen kannst.',
'newPage': 'Neue Seite',
'noPages': 'Noch keine Seiten.',
'fold': 'Einklappen',
'unfold': 'Ausklappen',
'searchIn': 'In {workspace} suchen',
'nothingFound': 'Nichts gefunden.',
'inPage': 'in {title}',
'notifComment': '{who} hat kommentiert',
'notifReply': '{who} hat geantwortet',
'notifMention': '{who} hat dich erwähnt',
'notifShare': '{who} hat eine Seite mit dir geteilt',
'notifResolved': '{who} hat einen Thread erledigt',
'notifReminder': 'Erinnerung',
'markAllRead': 'Alle als gelesen markieren',
'allCaughtUp': 'Du bist auf dem neuesten Stand.',
'hideResolved': 'Erledigte ausblenden',
'showResolved': 'Erledigt ({n})',
'noComments': 'Noch keine Kommentare.',
'resolve': 'Erledigen',
'reopen': 'Wieder öffnen',
'reply': 'Antworten',
'commentOnPage': 'Seite kommentieren',
'replyTo': '{name} antworten',
'cancelReply': 'Antwort abbrechen',
'send': 'Senden',
'reconnecting': 'Verbindet erneut…',
'cantEdit': 'Du kannst diese Seite nicht mehr bearbeiten.',
'connecting': 'Verbindet…',
'showAsPage': 'Als Seite zeigen',
'showAsCanvas': 'Als Tafel zeigen',
'archived': 'Diese Seite ist archiviert und schreibgeschützt.',
'saveTitle': 'In Docwell speichern',
'pageTitle': 'Seitentitel',
'space': 'Bereich',
'noSpaceToAdd': 'Es gibt keinen Bereich, in dem du Seiten anlegen kannst.',
'text': 'Text',
'saveAsPage': 'Als neue Seite speichern',
'bold': 'Fett',
'italic': 'Kursiv',
'underline': 'Unterstrichen',
'strike': 'Durchgestrichen',
'heading': 'Überschrift',
'bulletList': 'Aufzählung',
'orderedList': 'Nummerierte Liste',
'taskList': 'Aufgabenliste',
'callout': 'Hinweis',
'table': 'Tabelle',
'quote': 'Zitat',
'codeBlock': 'Codeblock',
'undo': 'Rückgängig',
'redo': 'Wiederholen',
},
'fr': {
'untitled': 'Sans titre',
'someone': 'Quelqu’un',
'retry': 'Réessayer',
'back': 'Retour',
'cancel': 'Annuler',
'done': 'Terminé',
'edit': 'Modifier',
'comments': 'Commentaires',
'search': 'Rechercher',
'inbox': 'Boîte de réception',
'account': 'Compte',
'errNotFound': 'Introuvable, ou vous n’y avez plus accès.',
'errForbidden': 'Vous n’avez pas l’autorisation de faire cela.',
'errRefused': 'Le serveur a refusé ({code}).',
'errOfflineNew':
'Impossible de joindre le serveur, et ceci n’a jamais été ouvert.',
'errOffline': 'Impossible de joindre le serveur.',
'offlineBanner':
'Hors ligne : affichage de ce qui est enregistré sur ce téléphone.',
'loginTitle': 'Se connecter à Docwell',
'loginTotp': 'Connexion en deux étapes',
'server': 'Adresse du serveur',
'email': 'E-mail',
'password': 'Mot de passe',
'totpHint':
'Saisissez le code à 6 chiffres de votre application d’authentification, ou un code de secours.',
'code': 'Code',
'verify': 'Valider',
'signIn': 'Se connecter',
'loginWrong': 'E-mail ou mot de passe incorrect.',
'loginDisabled': 'Ce compte est désactivé.',
'loginBadCode': 'Ce code est incorrect. Essayez le suivant.',
'loginMfa':
'Ce compte se connecte avec un code envoyé par e-mail. Utilisez l’application web pour l’instant.',
'loginFailed': 'La connexion a échoué.',
'loginBadServer': 'Cette adresse de serveur n’est pas valide.',
'loginOffline':
'Impossible de joindre le serveur. Vérifiez l’adresse et la connexion.',
'pushTitle': 'Notifications push',
'pushHint': 'Mentions, réponses et partages, via UnifiedPush.',
'pushNoDistributor':
'Installez un distributeur UnifiedPush comme ntfy pour recevoir les notifications.',
'pushRefused': 'Le serveur n’a pas accepté ce téléphone : {error}',
'pushChannel': 'Commentaires et mentions',
'pushChannelHint': 'Réponses, mentions et pages partagées avec vous',
'signOut': 'Se déconnecter',
'switchWorkspace': 'Changer d’espace de travail',
'noWorkspaces': 'Aucun espace de travail',
'noWorkspacesHint': 'Créez-en un dans l’application web.',
'recent': 'Récents',
'spaces': 'Espaces',
'noSpaces': 'Aucun espace que vous pouvez ouvrir pour l’instant.',
'newPage': 'Nouvelle page',
'noPages': 'Aucune page pour l’instant.',
'fold': 'Replier',
'unfold': 'Déplier',
'searchIn': 'Rechercher dans {workspace}',
'nothingFound': 'Aucun résultat.',
'inPage': 'dans {title}',
'notifComment': '{who} a commenté',
'notifReply': '{who} a répondu',
'notifMention': '{who} vous a mentionné',
'notifShare': '{who} a partagé une page avec vous',
'notifResolved': '{who} a résolu une discussion',
'notifReminder': 'Rappel',
'markAllRead': 'Tout marquer comme lu',
'allCaughtUp': 'Vous êtes à jour.',
'hideResolved': 'Masquer les résolues',
'showResolved': 'Résolues ({n})',
'noComments': 'Aucun commentaire pour l’instant.',
'resolve': 'Résoudre',
'reopen': 'Rouvrir',
'reply': 'Répondre',
'commentOnPage': 'Commenter la page',
'replyTo': 'Répondre à {name}',
'cancelReply': 'Annuler la réponse',
'send': 'Envoyer',
'reconnecting': 'Reconnexion…',
'cantEdit': 'Vous ne pouvez plus modifier cette page.',
'connecting': 'Connexion…',
'showAsPage': 'Afficher en page',
'showAsCanvas': 'Afficher en tableau',
'archived': 'Cette page est archivée et en lecture seule.',
'saveTitle': 'Enregistrer dans Docwell',
'pageTitle': 'Titre de la page',
'space': 'Espace',
'noSpaceToAdd': 'Aucun espace où vous pouvez ajouter des pages.',
'text': 'Texte',
'saveAsPage': 'Enregistrer comme nouvelle page',
'bold': 'Gras',
'italic': 'Italique',
'underline': 'Souligné',
'strike': 'Barré',
'heading': 'Titre',
'bulletList': 'Liste à puces',
'orderedList': 'Liste numérotée',
'taskList': 'Liste de tâches',
'callout': 'Encadré',
'table': 'Tableau',
'quote': 'Citation',
'codeBlock': 'Bloc de code',
'undo': 'Annuler',
'redo': 'Rétablir',
},
'es': {
'untitled': 'Sin título',
'someone': 'Alguien',
'retry': 'Reintentar',
'back': 'Atrás',
'cancel': 'Cancelar',
'done': 'Listo',
'edit': 'Editar',
'comments': 'Comentarios',
'search': 'Buscar',
'inbox': 'Bandeja de entrada',
'account': 'Cuenta',
'errNotFound': 'No se encontró, o ya no tienes acceso.',
'errForbidden': 'No tienes permiso para hacer eso.',
'errRefused': 'El servidor lo rechazó ({code}).',
'errOfflineNew':
'No se puede conectar con el servidor y esto no se ha abierto antes.',
'errOffline': 'No se puede conectar con el servidor.',
'offlineBanner': 'Sin conexión: se muestra lo guardado en este teléfono.',
'loginTitle': 'Entrar en Docwell',
'loginTotp': 'Inicio de sesión en dos pasos',
'server': 'Dirección del servidor',
'email': 'Correo',
'password': 'Contraseña',
'totpHint':
'Escribe el código de 6 cifras de tu aplicación de autenticación o un código de recuperación.',
'code': 'Código',
'verify': 'Verificar',
'signIn': 'Entrar',
'loginWrong': 'Correo o contraseña incorrectos.',
'loginDisabled': 'Esta cuenta está desactivada.',
'loginBadCode': 'Ese código no es correcto. Prueba con el siguiente.',
'loginMfa':
'Esta cuenta entra con un código enviado por correo. Por ahora usa la aplicación web.',
'loginFailed': 'No se pudo iniciar sesión.',
'loginBadServer': 'Esa dirección de servidor no es válida.',
'loginOffline':
'No se puede conectar con el servidor. Revisa la dirección y la conexión.',
'pushTitle': 'Notificaciones push',
'pushHint':
'Menciones, respuestas y páginas compartidas, mediante UnifiedPush.',
'pushNoDistributor':
'Instala un distribuidor de UnifiedPush como ntfy para recibir notificaciones.',
'pushRefused': 'El servidor no aceptó este teléfono: {error}',
'pushChannel': 'Comentarios y menciones',
'pushChannelHint': 'Respuestas, menciones y páginas compartidas contigo',
'signOut': 'Cerrar sesión',
'switchWorkspace': 'Cambiar de espacio de trabajo',
'noWorkspaces': 'Aún no hay espacios de trabajo',
'noWorkspacesHint': 'Crea uno en la aplicación web.',
'recent': 'Recientes',
'spaces': 'Espacios',
'noSpaces': 'Aún no hay espacios que puedas abrir.',
'newPage': 'Nueva página',
'noPages': 'Aún no hay páginas.',
'fold': 'Contraer',
'unfold': 'Desplegar',
'searchIn': 'Buscar en {workspace}',
'nothingFound': 'No se encontró nada.',
'inPage': 'en {title}',
'notifComment': '{who} comentó',
'notifReply': '{who} respondió',
'notifMention': '{who} te mencionó',
'notifShare': '{who} compartió una página contigo',
'notifResolved': '{who} resolvió un hilo',
'notifReminder': 'Recordatorio',
'markAllRead': 'Marcar todo como leído',
'allCaughtUp': 'Estás al día.',
'hideResolved': 'Ocultar resueltos',
'showResolved': 'Resueltos ({n})',
'noComments': 'Aún no hay comentarios.',
'resolve': 'Resolver',
'reopen': 'Reabrir',
'reply': 'Responder',
'commentOnPage': 'Comentar la página',
'replyTo': 'Responder a {name}',
'cancelReply': 'Cancelar respuesta',
'send': 'Enviar',
'reconnecting': 'Reconectando…',
'cantEdit': 'Ya no puedes editar esta página.',
'connecting': 'Conectando…',
'showAsPage': 'Mostrar como página',
'showAsCanvas': 'Mostrar como lienzo',
'archived': 'Esta página está archivada y es de solo lectura.',
'saveTitle': 'Guardar en Docwell',
'pageTitle': 'Título de la página',
'space': 'Espacio',
'noSpaceToAdd': 'No hay ningún espacio donde puedas añadir páginas.',
'text': 'Texto',
'saveAsPage': 'Guardar como página nueva',
'bold': 'Negrita',
'italic': 'Cursiva',
'underline': 'Subrayado',
'strike': 'Tachado',
'heading': 'Encabezado',
'bulletList': 'Lista con viñetas',
'orderedList': 'Lista numerada',
'taskList': 'Lista de tareas',
'callout': 'Destacado',
'table': 'Tabla',
'quote': 'Cita',
'codeBlock': 'Bloque de código',
'undo': 'Deshacer',
'redo': 'Rehacer',
},
};
+6 -6
View File
@@ -11,6 +11,7 @@ import 'package:unifiedpush_platform_interface/data/push_message.dart';
import 'package:unifiedpush_platform_interface/unifiedpush_platform_interface.dart';
import 'api/docwell_api.dart' hide PushMessage;
import 'l10n.dart';
/// Push notifications through UnifiedPush (Android). The phone's distributor
/// app (ntfy, NextPush, …) gives this app an endpoint; docwell-server sends
@@ -81,8 +82,7 @@ class PushService extends ChangeNotifier {
if (!ok) {
final all = await UnifiedPushPlatform.instance.getDistributors(const []);
if (all.isEmpty) {
problem =
'Install a UnifiedPush distributor such as ntfy to get notifications.';
problem = tr('pushNoDistributor');
notifyListeners();
return false;
}
@@ -129,7 +129,7 @@ class PushService extends ChangeNotifier {
await _storage.write(key: 'push_device', value: device.id);
notifyListeners();
} catch (err) {
problem = 'The server did not accept this phone: $err';
problem = tr('pushRefused', {'error': err});
notifyListeners();
}
}
@@ -152,11 +152,11 @@ class PushService extends ChangeNotifier {
id: DateTime.now().millisecondsSinceEpoch & 0x7fffffff,
title: msg['title'] as String? ?? 'Docwell',
body: msg['body'] as String? ?? '',
notificationDetails: const NotificationDetails(
notificationDetails: NotificationDetails(
android: AndroidNotificationDetails(
'activity',
'Comments and mentions',
channelDescription: 'Replies, mentions and pages shared with you',
tr('pushChannel'),
channelDescription: tr('pushChannelHint'),
importance: Importance.defaultImportance,
),
),
+14 -9
View File
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart' hide Notification, Page;
import '../api/docwell_api.dart';
import '../app.dart';
import 'widgets.dart';
import '../l10n.dart';
/// A page's comment threads with their replies. People who may comment can
/// start a thread, reply and resolve.
@@ -149,13 +150,15 @@ class _CommentsScreenState extends State<CommentsScreen> {
.length;
return Scaffold(
appBar: AppBar(
title: const Text('Comments'),
title: Text(tr('comments')),
actions: [
if (resolved > 0)
TextButton(
onPressed: () => setState(() => _showResolved = !_showResolved),
child: Text(
_showResolved ? 'Hide resolved' : 'Resolved ($resolved)',
_showResolved
? tr('hideResolved')
: tr('showResolved', {'n': resolved}),
),
),
],
@@ -175,7 +178,7 @@ class _CommentsScreenState extends State<CommentsScreen> {
child: Center(child: CircularProgressIndicator()),
)
else if (threads.isEmpty)
const ListTile(title: Text('No comments yet.')),
ListTile(title: Text(tr('noComments'))),
for (final t in threads)
Card(
margin: const EdgeInsets.fromLTRB(12, 8, 12, 0),
@@ -192,13 +195,15 @@ class _CommentsScreenState extends State<CommentsScreen> {
TextButton(
onPressed: () => _resolve(t),
child: Text(
t.resolvedAt.isEmpty ? 'Resolve' : 'Reopen',
t.resolvedAt.isEmpty
? tr('resolve')
: tr('reopen'),
),
),
if (_canComment && t.resolvedAt.isEmpty)
TextButton(
onPressed: () => setState(() => _replyTo = t),
child: const Text('Reply'),
child: Text(tr('reply')),
),
],
),
@@ -224,14 +229,14 @@ class _CommentsScreenState extends State<CommentsScreen> {
maxLines: 5,
decoration: InputDecoration(
hintText: _replyTo == null
? 'Comment on the page'
: 'Reply to ${_replyTo!.author.name}',
? tr('commentOnPage')
: tr('replyTo', {'name': _replyTo!.author.name}),
border: const OutlineInputBorder(),
isDense: true,
suffixIcon: _replyTo == null
? null
: IconButton(
tooltip: 'Cancel reply',
tooltip: tr('cancelReply'),
icon: const Icon(Icons.close),
onPressed: () =>
setState(() => _replyTo = null),
@@ -241,7 +246,7 @@ class _CommentsScreenState extends State<CommentsScreen> {
),
IconButton(
key: const Key('comment-send'),
tooltip: 'Send',
tooltip: tr('send'),
icon: const Icon(Icons.send),
onPressed: _busy ? null : _send,
),
+15 -18
View File
@@ -9,6 +9,7 @@ import 'page_screen.dart';
import 'search_screen.dart';
import 'space_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
/// The start screen: the current workspace's recent pages and spaces.
class HomeScreen extends StatefulWidget {
@@ -113,11 +114,8 @@ class _HomeScreenState extends State<HomeScreen> {
SwitchListTile(
key: const Key('push-toggle'),
secondary: const Icon(Icons.notifications_outlined),
title: const Text('Push notifications'),
subtitle: Text(
push.problem ??
'Mentions, replies and shares, through UnifiedPush.',
),
title: Text(tr('pushTitle')),
subtitle: Text(push.problem ?? tr('pushHint')),
value: push.enabled,
onChanged: (on) async {
await _togglePush(on);
@@ -127,7 +125,7 @@ class _HomeScreenState extends State<HomeScreen> {
ListTile(
key: const Key('sign-out'),
leading: const Icon(Icons.logout),
title: const Text('Sign out'),
title: Text(tr('signOut')),
onTap: () {
Navigator.of(context).pop();
widget.onSignOut();
@@ -149,7 +147,7 @@ class _HomeScreenState extends State<HomeScreen> {
title: workspaces == null || workspaces.length < 2
? Text(ws?.name ?? 'Docwell')
: PopupMenuButton<Workspace>(
tooltip: 'Switch workspace',
tooltip: tr('switchWorkspace'),
onSelected: (w) {
setState(() => _workspace = w);
_load();
@@ -169,13 +167,13 @@ class _HomeScreenState extends State<HomeScreen> {
actions: [
if (ws != null)
IconButton(
tooltip: 'Search',
tooltip: tr('search'),
icon: const Icon(Icons.search),
onPressed: () =>
_open(SearchScreen(session: widget.session, workspace: ws)),
),
IconButton(
tooltip: 'Inbox',
tooltip: tr('inbox'),
icon: Badge(
isLabelVisible: _unread > 0,
label: Text('$_unread'),
@@ -185,7 +183,7 @@ class _HomeScreenState extends State<HomeScreen> {
_open(NotificationsScreen(session: widget.session)),
),
IconButton(
tooltip: 'Account',
tooltip: tr('account'),
icon: const Icon(Icons.account_circle_outlined),
onPressed: _account,
),
@@ -204,26 +202,25 @@ class _HomeScreenState extends State<HomeScreen> {
child: Center(child: CircularProgressIndicator()),
)
else if (ws == null)
const ListTile(
title: Text('No workspaces yet'),
subtitle: Text('Create one in the web app.'),
ListTile(
title: Text(tr('noWorkspaces')),
subtitle: Text(tr('noWorkspacesHint')),
)
else ...[
if (_recent.isNotEmpty) ...[
const SectionTitle('Recent'),
SectionTitle(tr('recent')),
for (final p in _recent.take(5))
ListTile(
leading: PageIcon(p.icon),
title: Text(p.title.isEmpty ? 'Untitled' : p.title),
title: Text(p.title.isEmpty ? tr('untitled') : p.title),
subtitle: Text(p.spaceName),
onTap: () => _open(
PageScreen(session: widget.session, pageId: p.id),
),
),
],
const SectionTitle('Spaces'),
if (_spaces.isEmpty)
const ListTile(title: Text('No spaces you can open yet.')),
SectionTitle(tr('spaces')),
if (_spaces.isEmpty) ListTile(title: Text(tr('noSpaces'))),
for (final s in _spaces)
ListTile(
key: Key('space-${s.id}'),
+21 -26
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../api/docwell_api.dart';
import '../app.dart';
import '../l10n.dart';
/// Signs in: the server's address, email and password, then an
/// authenticator code for accounts with two-step sign-in.
@@ -34,11 +35,10 @@ class _LoginScreenState extends State<LoginScreen> {
String _challenge = '';
static const _messages = {
'invalid_credentials': 'Wrong email or password.',
'account_disabled': 'This account is disabled.',
'invalid_code': 'That code is not right. Try the next one.',
'mfa_required':
'This account signs in with an emailed code. Use the web app for now.',
'invalid_credentials': 'loginWrong',
'account_disabled': 'loginDisabled',
'invalid_code': 'loginBadCode',
'mfa_required': 'loginMfa',
};
/// The address as typed, with https:// added when the scheme is missing.
@@ -62,17 +62,14 @@ class _LoginScreenState extends State<LoginScreen> {
} else {
setState(
() => _error =
_messages[e.code] ??
(e.message.isNotEmpty ? e.message : 'Sign-in failed.'),
(_messages[e.code] != null ? tr(_messages[e.code]!) : null) ??
(e.message.isNotEmpty ? e.message : tr('loginFailed')),
);
}
} on FormatException {
setState(() => _error = 'That server address is not valid.');
setState(() => _error = tr('loginBadServer'));
} catch (_) {
setState(
() => _error =
"Can't reach the server. Check the address and connection.",
);
setState(() => _error = tr('loginOffline'));
} finally {
if (mounted) setState(() => _busy = false);
}
@@ -117,7 +114,7 @@ class _LoginScreenState extends State<LoginScreen> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
totp ? 'Two-step sign-in' : 'Sign in to Docwell',
totp ? tr('loginTotp') : tr('loginTitle'),
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 24),
@@ -127,8 +124,8 @@ class _LoginScreenState extends State<LoginScreen> {
controller: _server,
keyboardType: TextInputType.url,
autocorrect: false,
decoration: const InputDecoration(
labelText: 'Server address',
decoration: InputDecoration(
labelText: tr('server'),
hintText: 'docs.example.com',
border: OutlineInputBorder(),
),
@@ -139,8 +136,8 @@ class _LoginScreenState extends State<LoginScreen> {
controller: _email,
keyboardType: TextInputType.emailAddress,
autofillHints: const [AutofillHints.email],
decoration: const InputDecoration(
labelText: 'Email',
decoration: InputDecoration(
labelText: tr('email'),
border: OutlineInputBorder(),
),
),
@@ -151,15 +148,13 @@ class _LoginScreenState extends State<LoginScreen> {
obscureText: true,
autofillHints: const [AutofillHints.password],
onSubmitted: (_) => _submit(),
decoration: const InputDecoration(
labelText: 'Password',
decoration: InputDecoration(
labelText: tr('password'),
border: OutlineInputBorder(),
),
),
] else ...[
const Text(
'Enter the 6-digit code from your authenticator app, or a recovery code.',
),
Text(tr('totpHint')),
const SizedBox(height: 12),
TextField(
key: const Key('code'),
@@ -167,8 +162,8 @@ class _LoginScreenState extends State<LoginScreen> {
autofocus: true,
autofillHints: const [AutofillHints.oneTimeCode],
onSubmitted: (_) => _verify(),
decoration: const InputDecoration(
labelText: 'Code',
decoration: InputDecoration(
labelText: tr('code'),
border: OutlineInputBorder(),
),
),
@@ -185,7 +180,7 @@ class _LoginScreenState extends State<LoginScreen> {
const SizedBox(height: 20),
FilledButton(
onPressed: _busy ? null : (totp ? _verify : _submit),
child: Text(totp ? 'Verify' : 'Sign in'),
child: Text(totp ? tr('verify') : tr('signIn')),
),
if (totp)
TextButton(
@@ -195,7 +190,7 @@ class _LoginScreenState extends State<LoginScreen> {
_challenge = '';
_code.clear();
}),
child: const Text('Back'),
child: Text(tr('back')),
),
],
),
+12 -11
View File
@@ -6,18 +6,19 @@ import '../api/docwell_api.dart';
import '../app.dart';
import 'page_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
String notificationText(Notification n) {
final who = n.actor == null
? 'Someone'
? tr('someone')
: (n.actor!.name.isEmpty ? n.actor!.email : n.actor!.name);
return switch (n.type) {
NotificationType.comment => '$who commented',
NotificationType.reply => '$who replied',
NotificationType.mention => '$who mentioned you',
NotificationType.share => '$who shared a page with you',
NotificationType.resolved => '$who resolved a thread',
NotificationType.reminder => 'Reminder',
NotificationType.comment => tr('notifComment', {'who': who}),
NotificationType.reply => tr('notifReply', {'who': who}),
NotificationType.mention => tr('notifMention', {'who': who}),
NotificationType.share => tr('notifShare', {'who': who}),
NotificationType.resolved => tr('notifResolved', {'who': who}),
NotificationType.reminder => tr('notifReminder'),
};
}
@@ -82,10 +83,10 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
final list = _list;
return Scaffold(
appBar: AppBar(
title: const Text('Inbox'),
title: Text(tr('inbox')),
actions: [
if ((list?.unread ?? 0) > 0)
TextButton(onPressed: _readAll, child: const Text('Mark all read')),
TextButton(onPressed: _readAll, child: Text(tr('markAllRead'))),
],
),
body: RefreshIndicator(
@@ -100,7 +101,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
child: Center(child: CircularProgressIndicator()),
)
else if (list.items.isEmpty)
const ListTile(title: Text("You're all caught up.")),
ListTile(title: Text(tr('allCaughtUp'))),
for (final n in list?.items ?? <Notification>[])
ListTile(
key: Key('notification-${n.id}'),
@@ -111,7 +112,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
color: n.read ? null : Theme.of(context).colorScheme.primary,
),
title: Text(
'${notificationText(n)} · ${(n.page?.title ?? '').isNotEmpty ? n.page!.title : 'Untitled'}',
'${notificationText(n)} · ${(n.page?.title ?? '').isNotEmpty ? n.page!.title : tr('untitled')}',
style: TextStyle(fontWeight: n.read ? null : FontWeight.w600),
),
subtitle: Text(
+23 -16
View File
@@ -17,6 +17,7 @@ import '../editor/editor_screen.dart'
loadEditorPage;
import 'comments_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
/// A page in the shared editor (ADR-4). It opens read-only from the last
/// saved content, which is kept for reading offline; Edit joins the live
@@ -58,7 +59,7 @@ class _PageScreenState extends State<PageScreen> {
bool _editing = false;
bool _connected = false;
/// Showing the page as its edgeless canvas (read-only on phones).
/// Showing the page as its edgeless canvas.
bool _canvas = false;
bool get _canEdit {
@@ -126,7 +127,7 @@ class _PageScreenState extends State<PageScreen> {
await _bridge.setEditable(false);
await _bridge.setContent(_content);
}
if (_canvas) await _bridge.setMode('edgeless');
if (_canvas) await _bridge.setMode('edgeless', title: _pageTitle);
if (widget.target case final target?) await _bridge.follow(target);
if (widget.startEditing && _canEdit && !_editing) await _edit();
if (widget.openComment != null && mounted) _comments();
@@ -150,7 +151,8 @@ class _PageScreenState extends State<PageScreen> {
_connected = true;
}
await _bridge.setEditable(true);
await _bridge.focus();
// On the canvas, people pick what to change; the text has no cursor to put.
if (!_canvas) await _bridge.focus();
setState(() => _editing = true);
}
@@ -159,10 +161,15 @@ class _PageScreenState extends State<PageScreen> {
setState(() => _editing = false);
}
/// The title shown on the page's note on the canvas.
String get _pageTitle {
final t = _page?.title ?? '';
return t.isEmpty ? tr('untitled') : t;
}
Future<void> _toggleCanvas() async {
if (_editing) await _done();
final canvas = !_canvas;
await _bridge.setMode(canvas ? 'edgeless' : 'page');
await _bridge.setMode(canvas ? 'edgeless' : 'page', title: _pageTitle);
setState(() => _canvas = canvas);
}
@@ -202,9 +209,9 @@ class _PageScreenState extends State<PageScreen> {
}
String? get _status => switch (_bridge.collabStatus) {
'offline' => 'Reconnecting…',
'denied' => "You can't edit this page any more.",
'connecting' => 'Connecting…',
'offline' => tr('reconnecting'),
'denied' => tr('cantEdit'),
'connecting' => tr('connecting'),
_ => null,
};
@@ -213,7 +220,7 @@ class _PageScreenState extends State<PageScreen> {
final page = _page;
final title = page == null
? ''
: '${page.icon.isEmpty ? '' : '${page.icon} '}${page.title.isEmpty ? 'Untitled' : page.title}';
: '${page.icon.isEmpty ? '' : '${page.icon} '}${page.title.isEmpty ? tr('untitled') : page.title}';
return EditorBackHandler(
bridge: _bridge,
child: Scaffold(
@@ -223,7 +230,7 @@ class _PageScreenState extends State<PageScreen> {
if (page != null)
IconButton(
key: const Key('canvas'),
tooltip: _canvas ? 'Show as page' : 'Show as canvas',
tooltip: _canvas ? tr('showAsPage') : tr('showAsCanvas'),
icon: Icon(
_canvas ? Icons.article_outlined : Icons.dashboard_outlined,
),
@@ -231,16 +238,16 @@ class _PageScreenState extends State<PageScreen> {
),
if (page != null && !_offline)
IconButton(
tooltip: 'Comments',
tooltip: tr('comments'),
icon: const Icon(Icons.mode_comment_outlined),
onPressed: _comments,
),
if (_editing)
TextButton(onPressed: _done, child: const Text('Done'))
else if (_canEdit && !_canvas)
TextButton(onPressed: _done, child: Text(tr('done')))
else if (_canEdit)
IconButton(
key: const Key('edit'),
tooltip: 'Edit',
tooltip: tr('edit'),
icon: const Icon(Icons.edit_outlined),
onPressed: _bridge.isReady ? _edit : null,
),
@@ -250,8 +257,8 @@ class _PageScreenState extends State<PageScreen> {
children: [
if (_offline) const OfflineBanner(),
if (page?.archived == true)
const MaterialBanner(
content: Text('This page is archived and read-only.'),
MaterialBanner(
content: Text(tr('archived')),
actions: [SizedBox.shrink()],
),
if (_editing && _status != null)
+7 -4
View File
@@ -8,6 +8,7 @@ import '../api/docwell_api.dart';
import '../app.dart';
import 'page_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
/// Searches the workspace's pages as you type.
class SearchScreen extends StatefulWidget {
@@ -79,7 +80,7 @@ class _SearchScreenState extends State<SearchScreen> {
autofocus: true,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: 'Search ${widget.workspace.name}',
hintText: tr('searchIn', {'workspace': widget.workspace.name}),
border: InputBorder.none,
),
onChanged: _changed,
@@ -99,20 +100,22 @@ class _SearchScreenState extends State<SearchScreen> {
if (_query.text.trim().isNotEmpty &&
_hits.isEmpty &&
!_searching)
const ListTile(title: Text('Nothing found.')),
ListTile(title: Text(tr('nothingFound'))),
for (final h in _hits)
ListTile(
leading: h.record != null
? const Icon(Icons.table_chart_outlined)
: PageIcon(h.icon),
title: Text(switch (h.record?.title ?? h.title) {
'' => 'Untitled',
'' => tr('untitled'),
final t => t,
}),
subtitle: Text(
[
if (h.record != null)
'in ${h.title.isEmpty ? 'Untitled' : h.title}',
tr('inPage', {
'title': h.title.isEmpty ? tr('untitled') : h.title,
}),
h.spaceName,
h.snippet,
].where((s) => s.isNotEmpty).join(' · '),
+9 -8
View File
@@ -7,6 +7,7 @@ import '../app.dart';
import '../share.dart';
import 'page_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
final _url = RegExp(r'https?://[^\s<>"]+');
@@ -138,15 +139,15 @@ class _ShareScreenState extends State<ShareScreen> {
Widget build(BuildContext context) {
final targets = _targets;
return Scaffold(
appBar: AppBar(title: const Text('Save to Docwell')),
appBar: AppBar(title: Text(tr('saveTitle'))),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
TextField(
key: const Key('share-title'),
controller: _title,
decoration: const InputDecoration(
labelText: 'Page title',
decoration: InputDecoration(
labelText: tr('pageTitle'),
border: OutlineInputBorder(),
),
),
@@ -154,12 +155,12 @@ class _ShareScreenState extends State<ShareScreen> {
if (targets == null && _error == null)
const Center(child: CircularProgressIndicator())
else if (targets != null && targets.isEmpty)
const Text("There's no space you can add pages to.")
Text(tr('noSpaceToAdd'))
else if (targets != null)
DropdownButtonFormField<(Workspace, Space)>(
initialValue: _target,
decoration: const InputDecoration(
labelText: 'Space',
decoration: InputDecoration(
labelText: tr('space'),
border: OutlineInputBorder(),
),
items: [
@@ -175,7 +176,7 @@ class _ShareScreenState extends State<ShareScreen> {
onChanged: (t) => setState(() => _target = t),
),
const SizedBox(height: 16),
Text('Text', style: Theme.of(context).textTheme.labelLarge),
Text(tr('text'), style: Theme.of(context).textTheme.labelLarge),
const SizedBox(height: 4),
Text(
widget.shared.text,
@@ -193,7 +194,7 @@ class _ShareScreenState extends State<ShareScreen> {
FilledButton(
key: const Key('share-save'),
onPressed: _busy || _target == null ? null : _save,
child: const Text('Save as a new page'),
child: Text(tr('saveAsPage')),
),
],
),
+9 -4
View File
@@ -6,6 +6,7 @@ import '../api/docwell_api.dart';
import '../app.dart';
import 'page_screen.dart';
import 'widgets.dart';
import '../l10n.dart';
/// One page of the tree with how deep it sits.
typedef TreeRow = ({PageNode page, int depth});
@@ -108,7 +109,7 @@ class _SpaceScreenState extends State<SpaceScreen> {
appBar: AppBar(title: Text(widget.space.name)),
floatingActionButton: _canEdit && !_offline
? FloatingActionButton(
tooltip: 'New page',
tooltip: tr('newPage'),
onPressed: _newPage,
child: const Icon(Icons.add),
)
@@ -126,7 +127,7 @@ class _SpaceScreenState extends State<SpaceScreen> {
child: Center(child: CircularProgressIndicator()),
)
else if (pages.isEmpty)
const ListTile(title: Text('No pages yet.')),
ListTile(title: Text(tr('noPages'))),
for (final r in visible)
ListTile(
key: Key('page-${r.page.id}'),
@@ -136,7 +137,9 @@ class _SpaceScreenState extends State<SpaceScreen> {
),
leading: hasChildren.contains(r.page.id)
? IconButton(
tooltip: _open.contains(r.page.id) ? 'Fold' : 'Unfold',
tooltip: _open.contains(r.page.id)
? tr('fold')
: tr('unfold'),
icon: Icon(
_open.contains(r.page.id)
? Icons.expand_more
@@ -147,7 +150,9 @@ class _SpaceScreenState extends State<SpaceScreen> {
}),
)
: SizedBox(width: 48, child: PageIcon(r.page.icon)),
title: Text(r.page.title.isEmpty ? 'Untitled' : r.page.title),
title: Text(
r.page.title.isEmpty ? tr('untitled') : r.page.title,
),
onTap: () => _openPage(r.page.id),
),
],
+10 -7
View File
@@ -5,18 +5,21 @@ import 'dart:io';
import 'package:flutter/material.dart';
import '../api/docwell_api.dart';
import '../l10n.dart';
/// A short, human explanation of a failed request.
String describeError(Object e) {
if (e is DocwellApiException) {
if (e.status == 404) return 'Not found, or you no longer have access.';
if (e.status == 403) return "You don't have permission to do that.";
return e.message.isNotEmpty ? e.message : 'The server refused (${e.code}).';
if (e.status == 404) return tr('errNotFound');
if (e.status == 403) return tr('errForbidden');
return e.message.isNotEmpty
? e.message
: tr('errRefused', {'code': e.code});
}
if (e is SocketException || e is HttpException) {
return "Can't reach the server, and this hasn't been opened before.";
return tr('errOfflineNew');
}
return "Can't reach the server.";
return tr('errOffline');
}
class OfflineBanner extends StatelessWidget {
@@ -26,7 +29,7 @@ class OfflineBanner extends StatelessWidget {
Widget build(BuildContext context) => MaterialBanner(
key: const Key('offline'),
leading: const Icon(Icons.cloud_off_outlined),
content: const Text('Offline: showing what was saved on this phone.'),
content: Text(tr('offlineBanner')),
actions: const [SizedBox.shrink()],
);
}
@@ -44,7 +47,7 @@ class ErrorTile extends StatelessWidget {
children: [
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 12),
FilledButton(onPressed: onRetry, child: const Text('Retry')),
FilledButton(onPressed: onRetry, child: Text(tr('retry'))),
],
),
);
+13
View File
@@ -171,6 +171,11 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.1"
flutter_localizations:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_secure_storage:
dependency: "direct main"
description:
@@ -271,6 +276,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
intl:
dependency: transitive
description:
name: intl
sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5"
url: "https://pub.dev"
source: hosted
version: "0.20.2"
jni:
dependency: transitive
description:
+3
View File
@@ -30,6 +30,9 @@ environment:
dependencies:
flutter:
sdk: flutter
# Material's own words (Back, Paste…) in the app's languages.
flutter_localizations:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:docwell_mobile/l10n.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
List<String> placeholders(String s) =>
RegExp(r'\{(\w+)\}').allMatches(s).map((m) => m[1]!).toList()..sort();
void main() {
final english = appStrings['en']!;
test('has every language the app offers', () {
expect(appStrings.keys.toSet(), appLanguages.toSet());
});
for (final lang in appLanguages.where((l) => l != 'en')) {
test('$lang has every English text, with the same placeholders', () {
final other = appStrings[lang]!;
expect(other.keys.toSet(), english.keys.toSet());
for (final e in english.entries) {
expect(
placeholders(other[e.key]!),
placeholders(e.value),
reason: '$lang: ${e.key}',
);
}
});
}
test('follows the first phone language it has', () {
expect(pickLanguage(const [Locale('pt'), Locale('de', 'AT')]), 'de');
expect(pickLanguage(const [Locale('ja')]), 'en');
setAppLanguage('pl');
expect(tr('replyTo', {'name': 'Ann'}), 'Odpowiedz: Ann');
setAppLanguage('xx');
expect(appLanguage, 'en');
expect(tr('untitled'), 'Untitled');
});
}
+1
View File
@@ -39,6 +39,7 @@ const workspace = {
'organizationName': 'Acme',
'role': 'owner',
'created': '2026-10-01 09:00:00.000Z',
'defaultPageMode': 'page',
};
const space = {
+5 -1
View File
@@ -7,20 +7,24 @@
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build && node -e \"require('fs').writeFileSync('../internal/admin/dist/.gitkeep','')\"",
"typecheck": "vue-tsc --noEmit"
"typecheck": "vue-tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@docwell/api-client": "*",
"@docwell/ui": "*",
"vue": "^3.5.44",
"vue-i18n": "^11.4.16",
"vue-router": "^5.4.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@vitejs/plugin-vue": "^6.0.10",
"jsdom": "^30.1.3",
"tailwindcss": "^4.3.3",
"typescript": "~5.9.3",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"vue-tsc": "^3.3.14"
}
}
+36 -13
View File
@@ -2,26 +2,31 @@
<script setup lang="ts">
import { DwBadge, DwButton, DwLogo, useTheme } from "@docwell/ui";
import { useRouter } from "vue-router";
import { computed } from "vue";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { localeNames, storedLocale, storeLocale, supportedLocales, type Locale } from "./i18n";
import { currentUser, isSuperadmin, signOut } from "./session";
useTheme();
const router = useRouter();
const { t, locale } = useI18n();
const language = ref<Locale | "">(storedLocale());
const pickLanguage = () => (locale.value = storeLocale(language.value));
// Org admins manage their own organization; instance-wide settings are for
// superadmins only.
const nav = computed(() => [
{ to: "/", label: "Overview" },
{ to: "/users", label: "Users" },
{ to: "/organizations", label: isSuperadmin.value ? "Organizations" : "Organization" },
{ to: "/security", label: "Security" },
{ to: "/", label: t("nav.overview") },
{ to: "/users", label: t("nav.users") },
{ to: "/organizations", label: t(isSuperadmin.value ? "nav.organizations" : "nav.organization") },
{ to: "/security", label: t("nav.security") },
...(isSuperadmin.value
? [
{ to: "/authentication", label: "Authentication" },
{ to: "/branding", label: "Branding" },
{ to: "/storage", label: "Storage" },
{ to: "/email", label: "Email" },
{ to: "/maintenance", label: "Maintenance" },
{ to: "/authentication", label: t("nav.authentication") },
{ to: "/branding", label: t("nav.branding") },
{ to: "/storage", label: t("nav.storage") },
{ to: "/email", label: t("nav.email") },
{ to: "/maintenance", label: t("nav.maintenance") },
]
: []),
]);
@@ -38,7 +43,7 @@ function logout() {
<aside class="flex flex-col border-b border-line bg-surface-sunken md:w-56 md:border-r md:border-b-0">
<div class="flex h-12 items-center gap-2 px-4">
<DwLogo class="h-6" />
<DwBadge tone="accent">Admin</DwBadge>
<DwBadge tone="accent">{{ $t("shell.badge") }}</DwBadge>
</div>
<nav class="flex gap-px overflow-x-auto px-2 pb-2 md:flex-1 md:flex-col">
<RouterLink
@@ -55,9 +60,27 @@ function logout() {
<div class="truncate font-medium text-ink">{{ currentUser.name }}</div>
<div class="truncate text-ui-sm text-ink-muted">{{ currentUser.email }}</div>
<div class="mt-1 text-ui-sm text-ink-muted" data-testid="role">
{{ isSuperadmin ? "Superadmin" : `Admin · ${currentUser.organizationName || "no organization"}` }}
{{
isSuperadmin
? $t("shell.superadmin")
: $t("shell.adminOf", { org: currentUser.organizationName || $t("shell.noOrganization") })
}}
</div>
<DwButton variant="ghost" size="sm" icon="sign-out" class="mt-2 -ml-2" @click="logout">Sign out</DwButton>
<label class="mt-2 flex items-center gap-2 text-ui-sm text-ink-muted">
<span class="sr-only">{{ $t("common.language") }}</span>
<select
v-model="language"
class="dw-input h-control-sm min-w-0 flex-1"
data-testid="admin-language"
@change="pickLanguage"
>
<option value="">{{ $t("common.browserLanguage") }}</option>
<option v-for="l in supportedLocales" :key="l" :value="l">{{ localeNames[l] }}</option>
</select>
</label>
<DwButton variant="ghost" size="sm" icon="sign-out" class="mt-2 -ml-2" @click="logout">{{
$t("shell.signOut")
}}</DwButton>
</div>
</aside>
<main class="min-w-0 flex-1 bg-surface p-4 sm:p-8">
+20 -16
View File
@@ -3,6 +3,7 @@
import type { Invite, Organization, Role } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import { api, errorMessage, isSuperadmin } from "../session";
// Invite people by email into an organization. The person picks their own
@@ -18,7 +19,8 @@ const busy = ref(false);
const copied = ref(false);
const roles = computed<Role[]>(() => (isSuperadmin.value ? ["user", "admin", "superadmin"] : ["user", "admin"]));
const roleLabel: Record<string, string> = { user: "User", admin: "Admin", superadmin: "Superadmin" };
const { t } = useI18n();
const roleLabel = (r: string) => t(`roles.${r}`);
async function load() {
invites.value = (await api.invites.list()).filter((i) => !i.workspace);
@@ -63,35 +65,35 @@ async function copy(link: string) {
<template>
<section class="mt-6 dw-card" data-testid="invites">
<h2 class="text-ui-lg">Invite people</h2>
<h2 class="text-ui-lg">{{ $t("invites.title") }}</h2>
<form class="mt-3 flex flex-wrap gap-2" @submit.prevent="invite">
<input
v-model="form.email"
type="email"
required
placeholder="name@example.com"
aria-label="Email to invite"
:aria-label="$t('invites.emailLabel')"
class="dw-input min-w-56 flex-1"
/>
<select v-model="form.role" aria-label="Role" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel[r] }}</option>
<select v-model="form.role" :aria-label="$t('common.role')" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel(r) }}</option>
</select>
<select v-if="isSuperadmin" v-model="form.organization" aria-label="Organization" class="dw-input">
<option value="">No organization</option>
<select v-if="isSuperadmin" v-model="form.organization" :aria-label="$t('common.organization')" class="dw-input">
<option value="">{{ $t("common.noOrganization") }}</option>
<option v-for="o in props.orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
<DwButton type="submit" variant="primary" :disabled="busy || !form.email">Send invite</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy || !form.email">{{ $t("invites.send") }}</DwButton>
</form>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-3">{{ error }}</DwCallout>
<DwCallout v-else-if="result" :tone="result.mailed ? 'success' : 'warning'" size="ui" class="mt-3">
<span class="flex flex-wrap items-center gap-2">
{{
result.mailed
? `An invitation is on its way to ${result.email}.`
: `${result.email} is invited, but the email could not be sent. Send them the link yourself.`
? $t("invites.mailed", { email: result.email })
: $t("invites.notMailed", { email: result.email })
}}
<button v-if="result.link && !result.mailed" class="dw-link" @click="copy(result.link)">
{{ copied ? "Copied" : "Copy link" }}
{{ copied ? $t("invites.copied") : $t("invites.copyLink") }}
</button>
</span>
</DwCallout>
@@ -101,14 +103,16 @@ async function copy(link: string) {
<div class="min-w-0">
<p class="truncate font-medium">{{ i.email }}</p>
<p class="truncate text-ui-sm text-ink-muted">
{{ roleLabel[i.role] }}<template v-if="i.organizationName"> · {{ i.organizationName }}</template> · invited
by {{ i.invitedBy || "someone" }}
{{ roleLabel(i.role) }}<template v-if="i.organizationName"> · {{ i.organizationName }}</template> ·
{{ $t("invites.invitedBy", { name: i.invitedBy || $t("invites.someone") }) }}
</p>
</div>
<div class="flex items-center gap-2">
<DwBadge v-if="i.status === 'expired'" tone="danger">Expired</DwBadge>
<DwButton variant="ghost" size="sm" :disabled="busy" @click="resend(i)">Resend</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="revoke(i)">Revoke</DwButton>
<DwBadge v-if="i.status === 'expired'" tone="danger">{{ $t("invites.expired") }}</DwBadge>
<DwButton variant="ghost" size="sm" :disabled="busy" @click="resend(i)">{{ $t("invites.resend") }}</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="revoke(i)">{{
$t("common.revoke")
}}</DwButton>
</div>
</li>
</ul>
+86
View File
@@ -0,0 +1,86 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { watch } from "vue";
import { createI18n } from "vue-i18n";
import de from "./locales/de.json";
import en from "./locales/en.json";
import es from "./locales/es.json";
import fr from "./locales/fr.json";
import pl from "./locales/pl.json";
export const supportedLocales = ["en", "de", "es", "fr", "pl"] as const;
export type Locale = (typeof supportedLocales)[number];
/** Each language's name in that language, for the picker. */
export const localeNames: Record<Locale, string> = {
en: "English",
de: "Deutsch",
es: "Español",
fr: "Français",
pl: "Polski",
};
// The language picked on this device; none means follow the browser. The
// same key as the web app, so both follow one choice where they share an origin.
const storageKey = "docwell.locale";
const isLocale = (v: string | null | undefined): v is Locale =>
!!v && (supportedLocales as readonly string[]).includes(v);
/** The language picked on this device, or "" to follow the browser. */
export function storedLocale(): Locale | "" {
try {
const v = localStorage.getItem(storageKey);
return isLocale(v) ? v : "";
} catch {
return "";
}
}
/** Remembers the picked language ("" forgets it) and returns the one to show. */
export function storeLocale(choice: Locale | ""): Locale {
try {
if (choice) localStorage.setItem(storageKey, choice);
else localStorage.removeItem(storageKey);
} catch {
// Private mode: the choice lasts until the page is closed.
}
return choice || browserLocale();
}
/** The first of the browser's languages the app has, else English. */
export function browserLocale(languages: readonly string[] = navigator.languages ?? [navigator.language]): Locale {
for (const tag of languages) {
const base = tag.slice(0, 2).toLowerCase();
if (isLocale(base)) return base;
}
return "en";
}
function createAdminI18n() {
const i18n = createI18n({
legacy: false,
locale: storedLocale() || browserLocale(),
fallbackLocale: "en",
messages: { en, de, es, fr, pl },
pluralRules: {
// Polish: 1 strona, 2-4 strony (but 12-14 stron), otherwise stron.
pl: (n: number) => {
if (n === 1) return 0;
const ones = n % 10;
const tens = n % 100;
return ones >= 2 && ones <= 4 && (tens < 12 || tens > 14) ? 1 : 2;
},
// French: 0 and 1 are singular (0 page, 1 page, 2 pages).
fr: (n: number) => (n <= 1 ? 0 : 1),
},
});
// Screen readers, hyphenation and spell checking follow the page's language.
watch(i18n.global.locale, (l) => (document.documentElement.lang = l), { immediate: true });
return i18n;
}
export const i18n = createAdminI18n();
/** Translates outside components (messages built in scripts). */
export const t = i18n.global.t;
+272
View File
@@ -0,0 +1,272 @@
{
"common": {
"save": "Speichern",
"saved": "Gespeichert.",
"cancel": "Abbrechen",
"create": "Erstellen",
"delete": "Löschen",
"edit": "Bearbeiten",
"rename": "Umbenennen",
"revoke": "Widerrufen",
"download": "Herunterladen",
"remove": "Entfernen",
"actions": "Aktionen",
"name": "Name",
"email": "E-Mail",
"password": "Passwort",
"role": "Rolle",
"status": "Status",
"organization": "Organisation",
"noOrganization": "Keine Organisation",
"previous": "Zurück",
"next": "Weiter",
"pageOf": "Seite {page} von {total}",
"unchanged": "Unverändert",
"language": "Sprache",
"browserLanguage": "Sprache des Browsers",
"cantReach": "Der Server ist nicht erreichbar.",
"checkForm": "Bitte prüfe das Formular.",
"requestFailed": "Anfrage fehlgeschlagen ({code})."
},
"roles": {
"user": "Nutzer",
"admin": "Admin",
"superadmin": "Superadmin"
},
"userStatus": {
"active": "Aktiv",
"invited": "Eingeladen",
"disabled": "Deaktiviert"
},
"nav": {
"overview": "Übersicht",
"users": "Nutzer",
"organizations": "Organisationen",
"organization": "Organisation",
"security": "Sicherheit",
"authentication": "Anmeldung",
"branding": "Erscheinungsbild",
"storage": "Speicher",
"email": "E-Mail",
"maintenance": "Wartung"
},
"shell": {
"badge": "Admin",
"superadmin": "Superadmin",
"adminOf": "Admin · {org}",
"noOrganization": "keine Organisation",
"signOut": "Abmelden"
},
"login": {
"title": "Am Admin-Bereich anmelden",
"hint": "Nutze ein Konto als Organisations-Admin oder Superadmin.",
"totpHint": "Gib den 6-stelligen Code aus deiner Authenticator-App oder einen Wiederherstellungscode ein.",
"code": "Authenticator-Code",
"submit": "Anmelden",
"failed": "Anmeldung fehlgeschlagen.",
"errors": {
"invalid_credentials": "E-Mail oder Passwort ist falsch.",
"forbidden": "Nur Organisations-Admins und Superadmins können den Admin-Bereich nutzen.",
"account_disabled": "Dieses Konto ist deaktiviert.",
"mfa_required": "Dieses Konto nutzt die Anmeldung in zwei Schritten. Melde dich zuerst in der Web-App an; der Admin-Bereich unterstützt das noch nicht.",
"invalid_code": "Dieser Code stimmt nicht oder wurde schon benutzt.",
"invalid_token": "Das hat zu lange gedauert. Melde dich erneut an."
}
},
"overview": {
"title": "Übersicht",
"instance": "Der ganze Server.",
"org": "Deine Organisation.",
"users": "Nutzer",
"organizations": "Organisationen",
"workspaces": "Arbeitsbereiche",
"spaces": "Bereiche",
"pages": "Seiten",
"files": "Dateien",
"openNow": "Gerade geöffnet",
"openNowValue": "{rooms} Seite(n) · {editors} Bearbeitende",
"searchIndex": "Suchindex",
"indexed": "{n} Seite(n)",
"system": "System",
"version": "Version",
"upFor": "Läuft seit",
"database": "Datenbank",
"connected": "Verbunden · {ms} ms",
"unavailable": "Nicht verfügbar",
"memory": "Speicher",
"memoryValue": "{mb} MB · {goroutines} Goroutinen",
"days": "{d} T {h} Std",
"hours": "{h} Std {m} Min",
"minutes": "{m} Min"
},
"users": {
"title": "Nutzer",
"everyone": "Alle auf diesem Server.",
"membersOf": "Mitglieder von {org}.",
"new": "Neuer Nutzer",
"search": "Name oder E-Mail suchen",
"searchLabel": "Nutzer suchen",
"filterOrg": "Nach Organisation filtern",
"allOrgs": "Alle Organisationen",
"editTitle": "{email} bearbeiten",
"newPassword": "Neues Passwort (optional)",
"ownRole": "Du kannst deine eigene Rolle nicht ändern.",
"createUser": "Nutzer erstellen",
"resetPassword": "Passwort zurücksetzen",
"turnOffTotp": "Zwei Schritte ausschalten",
"none": "Keine Nutzer gefunden.",
"resetSent": "Ein Link zum Zurücksetzen des Passworts ist unterwegs an {email}.",
"confirmTotp": "Anmeldung in zwei Schritten für {email} ausschalten? Bis sie wieder eingerichtet ist, genügt das Passwort.",
"totpOff": "Die Anmeldung in zwei Schritten ist für {email} aus.",
"confirmDelete": "{email} löschen? Das lässt sich nicht rückgängig machen."
},
"invites": {
"title": "Personen einladen",
"emailLabel": "E-Mail zum Einladen",
"send": "Einladung senden",
"mailed": "Eine Einladung ist unterwegs an {email}.",
"notMailed": "{email} ist eingeladen, aber die E-Mail konnte nicht gesendet werden. Schicke den Link selbst.",
"copied": "Kopiert",
"copyLink": "Link kopieren",
"invitedBy": "eingeladen von {name}",
"someone": "jemandem",
"expired": "Abgelaufen",
"resend": "Erneut senden"
},
"orgs": {
"titleAll": "Organisationen",
"titleOne": "Organisation",
"hintAll": "Alle Organisationen auf diesem Server. Admins einer Organisation verwalten nur ihre eigene.",
"hintOne": "Deine Organisation. Du verwaltest ihre Mitglieder und alle ihre Arbeitsbereiche.",
"new": "Neue Organisation",
"none": "Noch keine Organisationen.",
"members": "{n} Mitglied | {n} Mitglieder",
"workspaces": "{n} Arbeitsbereich | {n} Arbeitsbereiche",
"confirmDeleteMine": "{name} löschen? Du wirst ein normaler Nutzer und verlierst den Zugang zum Admin-Bereich.",
"confirmDelete": "{name} löschen? Das lässt sich nicht rückgängig machen."
},
"security": {
"title": "Sicherheit",
"hintAll": "Wer was geändert hat, Anmeldungen und API-Tokens.",
"hintOrg": "Wer was geändert hat, Anmeldungen und API-Tokens in deiner Organisation.",
"auditLog": "Protokoll",
"searchPlaceholder": "Aktion, E-Mail, ID oder IP",
"searchLabel": "Protokoll durchsuchen",
"since": "Seit",
"search": "Suchen",
"time": "Zeit",
"action": "Aktion",
"who": "Wer",
"target": "Ziel",
"ip": "IP",
"nothing": "Keine Treffer.",
"newer": "Neuer",
"older": "Älter",
"tokens": "API-Tokens",
"tokensHint": "Personen erstellen sie in ihrem Konto. Widerrufe alle, die nicht mehr funktionieren sollen.",
"lastUsed": "zuletzt benutzt {when}",
"neverUsed": "nie benutzt",
"expires": "läuft ab {when}",
"noTokens": "Keine Tokens.",
"thisUser": "diesem Nutzer",
"confirmRevoke": "„{name}“ von {email} widerrufen? Skripte, die es nutzen, funktionieren dann nicht mehr."
},
"auth": {
"title": "Anmeldung",
"hint": "Wer ein Konto erstellen kann und wie man sich anmeldet.",
"signup": "Registrierung",
"anyone": "Jeder kann ein Konto erstellen",
"anyoneHint": "Aus: Nur eingeladene Personen können beitreten. Das allererste Konto kann sich immer registrieren.",
"domains": "Erlaubte E-Mail-Domains",
"domainsHint": "Eine pro Zeile. Leer erlaubt jede Domain. Einladungen ignorieren diese Liste. Konten über einen Anmeldeanbieter folgen diesen Regeln auch.",
"methods": "Anmeldemethoden",
"methodsHint": "E-Mail und Passwort sind immer an. Die Anmeldung in zwei Schritten kann jede Person in ihrem Konto einrichten.",
"magicLink": "Anmeldelinks per E-Mail",
"magicLinkHint": "Statt das Passwort einzugeben, kann man einen Link und einen Einmalcode anfordern. Braucht funktionierende E-Mail.",
"providers": "Anmeldeanbieter",
"providersHint": "Registriere Docwell beim Anbieter mit dieser Rückrufadresse und gib dann Client-ID und Secret ein:",
"clientId": "Client-ID",
"clientSecret": "Client-Secret",
"secretSaved": "Gespeichert; zum Ersetzen eintippen",
"buttonLabel": "Beschriftung der Schaltfläche",
"singleSignOn": "Single Sign-on",
"authUrl": "Autorisierungs-URL",
"tokenUrl": "Token-URL",
"userInfoUrl": "Nutzerinfo-URL",
"consoles": {
"google": "Google Cloud Console → APIs & Dienste → Anmeldedaten",
"github": "GitHub → Settings → Developer settings → OAuth Apps",
"microsoft": "Microsoft Entra Admin Center → App-Registrierungen",
"oidc": "Dein Identitätsanbieter (Keycloak, Authentik, Okta, …)"
}
},
"branding": {
"title": "Erscheinungsbild",
"hint": "Wie sich dieser Server auf den Anmeldeseiten und in E-Mails zeigt.",
"accent": "Akzentfarbe",
"pickAccent": "Akzentfarbe wählen",
"useDefault": "Standard verwenden",
"logo": "Logo",
"currentLogo": "Aktuelles Logo",
"defaultLogo": "Das Docwell-Logo.",
"upload": "Hochladen…",
"badType": "Nutze ein PNG-, JPEG-, WebP- oder SVG-Bild.",
"tooBig": "Das Logo muss kleiner als 190 KB sein."
},
"storage": {
"title": "Speicher",
"hint": "Wo Bilder und Anhänge liegen.",
"warning": "Ein Wechsel verschiebt vorhandene Dateien nicht. Vorher hochgeladene Dateien bleiben, wo sie waren, und lassen sich erst öffnen, wenn sie kopiert wurden.",
"keep": "Dateien speichern",
"disk": "Auf der Festplatte von docwell-db",
"s3": "In einem S3-kompatiblen Bucket",
"endpoint": "Endpunkt",
"bucket": "Bucket",
"region": "Region",
"accessKey": "Zugriffsschlüssel",
"secret": "Secret",
"pathStyle": "Pfadbasierte Adressierung (MinIO und manche andere Server brauchen sie)",
"test": "Gespeicherten Bucket testen",
"reachable": "Der Bucket ist erreichbar."
},
"email": {
"title": "E-Mail",
"hint": "Docwell sendet Bestätigungen, Passwort-Links, Einladungen und Anmelde-E-Mails über diesen Server.",
"envNote": "Ist DOCWELL_SMTP_HOST für docwell-server gesetzt, werden diese Umgebungswerte bei jedem Start wieder übernommen.",
"enabled": "E-Mails über einen SMTP-Server senden",
"host": "Host",
"port": "Port",
"username": "Nutzername",
"tls": "TLS von Anfang an nutzen (meist Port 465; Port 587 wechselt von selbst)",
"senderName": "Name des Absenders",
"senderAddress": "Adresse des Absenders",
"test": "Test",
"testHint": "Sendet eine kurze E-Mail mit den gespeicherten Einstellungen.",
"testTo": "Test senden an",
"sendTest": "Test-E-Mail senden",
"sent": "An {email} gesendet. Prüfe den Posteingang (und den Spam-Ordner)."
},
"maintenance": {
"title": "Wartung",
"backups": "Sicherungen",
"backupsHint": "Eine Sicherung enthält die ganze Datenbank mit ihren Dateien. Zum Wiederherstellen Docwell anhalten und die Daten von docwell-db durch den Inhalt des Archivs ersetzen.",
"creating": "Wird erstellt…",
"create": "Sicherung erstellen",
"file": "Datei",
"size": "Größe",
"created": "Erstellt",
"noBackups": "Noch keine Sicherungen.",
"confirmDelete": "Sicherung {key} löschen?",
"jobs": "Hintergrundaufgaben",
"jobsHint": "Gezählt seit dem Start des Servers.",
"job": "Aufgabe",
"runs": "Läufe",
"lastRun": "Letzter Lauf",
"every": "alle {every}",
"failedCount": "({n} fehlgeschlagen)",
"running": "Läuft",
"failed": "Fehlgeschlagen",
"ok": "OK",
"runNow": "Jetzt ausführen"
}
}
+272
View File
@@ -0,0 +1,272 @@
{
"common": {
"save": "Save",
"saved": "Saved.",
"cancel": "Cancel",
"create": "Create",
"delete": "Delete",
"edit": "Edit",
"rename": "Rename",
"revoke": "Revoke",
"download": "Download",
"remove": "Remove",
"actions": "Actions",
"name": "Name",
"email": "Email",
"password": "Password",
"role": "Role",
"status": "Status",
"organization": "Organization",
"noOrganization": "No organization",
"previous": "Previous",
"next": "Next",
"pageOf": "Page {page} of {total}",
"unchanged": "Unchanged",
"language": "Language",
"browserLanguage": "Browser language",
"cantReach": "Can't reach the server.",
"checkForm": "Please check the form.",
"requestFailed": "Request failed ({code})."
},
"roles": {
"user": "User",
"admin": "Admin",
"superadmin": "Superadmin"
},
"userStatus": {
"active": "Active",
"invited": "Invited",
"disabled": "Disabled"
},
"nav": {
"overview": "Overview",
"users": "Users",
"organizations": "Organizations",
"organization": "Organization",
"security": "Security",
"authentication": "Authentication",
"branding": "Branding",
"storage": "Storage",
"email": "Email",
"maintenance": "Maintenance"
},
"shell": {
"badge": "Admin",
"superadmin": "Superadmin",
"adminOf": "Admin · {org}",
"noOrganization": "no organization",
"signOut": "Sign out"
},
"login": {
"title": "Sign in to the admin panel",
"hint": "Use an organization admin or superadmin account.",
"totpHint": "Enter the 6-digit code from your authenticator app, or a recovery code.",
"code": "Authenticator code",
"submit": "Sign in",
"failed": "Sign-in failed.",
"errors": {
"invalid_credentials": "Wrong email or password.",
"forbidden": "Only organization admins and superadmins can use the admin panel.",
"account_disabled": "This account is disabled.",
"mfa_required": "This account uses two-step sign-in. Sign in to the web app first; MFA for the admin panel is not supported yet.",
"invalid_code": "That code is not right, or was already used.",
"invalid_token": "That took too long. Sign in again."
}
},
"overview": {
"title": "Overview",
"instance": "The whole server.",
"org": "Your organization.",
"users": "Users",
"organizations": "Organizations",
"workspaces": "Workspaces",
"spaces": "Spaces",
"pages": "Pages",
"files": "Files",
"openNow": "Open now",
"openNowValue": "{rooms} page(s) · {editors} editor(s)",
"searchIndex": "Search index",
"indexed": "{n} page(s)",
"system": "System",
"version": "Version",
"upFor": "Up for",
"database": "Database",
"connected": "Connected · {ms} ms",
"unavailable": "Unavailable",
"memory": "Memory",
"memoryValue": "{mb} MB · {goroutines} goroutines",
"days": "{d} d {h} h",
"hours": "{h} h {m} min",
"minutes": "{m} min"
},
"users": {
"title": "Users",
"everyone": "Everyone on this server.",
"membersOf": "Members of {org}.",
"new": "New user",
"search": "Search name or email",
"searchLabel": "Search users",
"filterOrg": "Filter by organization",
"allOrgs": "All organizations",
"editTitle": "Edit {email}",
"newPassword": "New password (optional)",
"ownRole": "You cannot change your own role.",
"createUser": "Create user",
"resetPassword": "Reset password",
"turnOffTotp": "Turn off two-step",
"none": "No users found.",
"resetSent": "A password reset link is on its way to {email}.",
"confirmTotp": "Turn off two-step sign-in for {email}? They will sign in with their password alone until they set it up again.",
"totpOff": "Two-step sign-in is off for {email}.",
"confirmDelete": "Delete {email}? This cannot be undone."
},
"invites": {
"title": "Invite people",
"emailLabel": "Email to invite",
"send": "Send invite",
"mailed": "An invitation is on its way to {email}.",
"notMailed": "{email} is invited, but the email could not be sent. Send them the link yourself.",
"copied": "Copied",
"copyLink": "Copy link",
"invitedBy": "invited by {name}",
"someone": "someone",
"expired": "Expired",
"resend": "Resend"
},
"orgs": {
"titleAll": "Organizations",
"titleOne": "Organization",
"hintAll": "Every organization on this server. Admins of an organization manage only their own.",
"hintOne": "Your organization. You manage its members and all of its workspaces.",
"new": "New organization",
"none": "No organizations yet.",
"members": "{n} member | {n} members",
"workspaces": "{n} workspace | {n} workspaces",
"confirmDeleteMine": "Delete {name}? You will become a regular user and lose access to the admin panel.",
"confirmDelete": "Delete {name}? This cannot be undone."
},
"security": {
"title": "Security",
"hintAll": "Who changed what, sign-ins, and API tokens.",
"hintOrg": "Who changed what, sign-ins, and API tokens in your organization.",
"auditLog": "Audit log",
"searchPlaceholder": "Action, email, id or IP",
"searchLabel": "Search the audit log",
"since": "Since",
"search": "Search",
"time": "Time",
"action": "Action",
"who": "Who",
"target": "Target",
"ip": "IP",
"nothing": "Nothing matches.",
"newer": "Newer",
"older": "Older",
"tokens": "API tokens",
"tokensHint": "People create these in their account. Revoke any that should not work any more.",
"lastUsed": "last used {when}",
"neverUsed": "never used",
"expires": "expires {when}",
"noTokens": "No tokens.",
"thisUser": "this user",
"confirmRevoke": "Revoke “{name}” of {email}? Scripts using it stop working."
},
"auth": {
"title": "Authentication",
"hint": "Who can create an account, and how people sign in.",
"signup": "Sign-up",
"anyone": "Anyone can create an account",
"anyoneHint": "Off: only invited people can join. The very first account can always sign up.",
"domains": "Allowed email domains",
"domainsHint": "One per line. Empty allows every domain. Invites ignore this list. Accounts created by a sign-in provider follow these rules too.",
"methods": "Sign-in methods",
"methodsHint": "Email and password is always on. People can add two-step sign-in in their account.",
"magicLink": "Sign-in links by email",
"magicLinkHint": "People can ask for a link and a one-time code instead of typing their password. Needs working email.",
"providers": "Sign-in providers",
"providersHint": "Register Docwell with the provider, using this callback address, then enter the client ID and secret:",
"clientId": "Client ID",
"clientSecret": "Client secret",
"secretSaved": "Saved; type to replace",
"buttonLabel": "Button label",
"singleSignOn": "Single sign-on",
"authUrl": "Authorization URL",
"tokenUrl": "Token URL",
"userInfoUrl": "User info URL",
"consoles": {
"google": "Google Cloud console → APIs & Services → Credentials",
"github": "GitHub → Settings → Developer settings → OAuth Apps",
"microsoft": "Microsoft Entra admin center → App registrations",
"oidc": "Your identity provider (Keycloak, Authentik, Okta, …)"
}
},
"branding": {
"title": "Branding",
"hint": "How this server presents itself on the sign-in pages and in emails.",
"accent": "Accent colour",
"pickAccent": "Pick the accent colour",
"useDefault": "Use default",
"logo": "Logo",
"currentLogo": "Current logo",
"defaultLogo": "The Docwell logo.",
"upload": "Upload…",
"badType": "Use a PNG, JPEG, WebP or SVG image.",
"tooBig": "The logo must be smaller than 190 KB."
},
"storage": {
"title": "Storage",
"hint": "Where images and attachments are kept.",
"warning": "Switching storage does not move existing files. Files uploaded before the switch stay where they were and cannot be opened until they are copied over.",
"keep": "Keep files",
"disk": "On docwell-db's disk",
"s3": "In an S3-compatible bucket",
"endpoint": "Endpoint",
"bucket": "Bucket",
"region": "Region",
"accessKey": "Access key",
"secret": "Secret",
"pathStyle": "Path-style addressing (MinIO and some other servers need it)",
"test": "Test the saved bucket",
"reachable": "The bucket is reachable."
},
"email": {
"title": "Email",
"hint": "Docwell sends verification, password reset, invite and sign-in emails through this server.",
"envNote": "If DOCWELL_SMTP_HOST is set for docwell-server, those environment values are applied again whenever it starts.",
"enabled": "Send email through an SMTP server",
"host": "Host",
"port": "Port",
"username": "Username",
"tls": "Use TLS from the start (usually port 465; port 587 upgrades on its own)",
"senderName": "Sender name",
"senderAddress": "Sender address",
"test": "Test",
"testHint": "Sends a short email with the saved settings.",
"testTo": "Send the test to",
"sendTest": "Send test email",
"sent": "Sent to {email}. Check the inbox (and the spam folder)."
},
"maintenance": {
"title": "Maintenance",
"backups": "Backups",
"backupsHint": "A backup holds the whole database and its files. To restore one, stop Docwell and replace docwell-db's data with the archive's contents.",
"creating": "Creating…",
"create": "Create backup",
"file": "File",
"size": "Size",
"created": "Created",
"noBackups": "No backups yet.",
"confirmDelete": "Delete the backup {key}?",
"jobs": "Background jobs",
"jobsHint": "Counted since the server started.",
"job": "Job",
"runs": "Runs",
"lastRun": "Last run",
"every": "every {every}",
"failedCount": "({n} failed)",
"running": "Running",
"failed": "Failed",
"ok": "OK",
"runNow": "Run now"
}
}
+272
View File
@@ -0,0 +1,272 @@
{
"common": {
"save": "Guardar",
"saved": "Guardado.",
"cancel": "Cancelar",
"create": "Crear",
"delete": "Eliminar",
"edit": "Editar",
"rename": "Renombrar",
"revoke": "Revocar",
"download": "Descargar",
"remove": "Quitar",
"actions": "Acciones",
"name": "Nombre",
"email": "Correo",
"password": "Contraseña",
"role": "Rol",
"status": "Estado",
"organization": "Organización",
"noOrganization": "Sin organización",
"previous": "Anterior",
"next": "Siguiente",
"pageOf": "Página {page} de {total}",
"unchanged": "Sin cambios",
"language": "Idioma",
"browserLanguage": "Idioma del navegador",
"cantReach": "No se puede conectar con el servidor.",
"checkForm": "Revisa el formulario.",
"requestFailed": "La solicitud falló ({code})."
},
"roles": {
"user": "Usuario",
"admin": "Administrador",
"superadmin": "Superadministrador"
},
"userStatus": {
"active": "Activo",
"invited": "Invitado",
"disabled": "Desactivado"
},
"nav": {
"overview": "Resumen",
"users": "Usuarios",
"organizations": "Organizaciones",
"organization": "Organización",
"security": "Seguridad",
"authentication": "Inicio de sesión",
"branding": "Apariencia",
"storage": "Almacenamiento",
"email": "Correo",
"maintenance": "Mantenimiento"
},
"shell": {
"badge": "Admin",
"superadmin": "Superadministrador",
"adminOf": "Administrador · {org}",
"noOrganization": "sin organización",
"signOut": "Cerrar sesión"
},
"login": {
"title": "Entrar en el panel de administración",
"hint": "Usa una cuenta de administrador de organización o de superadministrador.",
"totpHint": "Escribe el código de 6 cifras de tu aplicación de autenticación o un código de recuperación.",
"code": "Código de autenticación",
"submit": "Entrar",
"failed": "No se pudo iniciar sesión.",
"errors": {
"invalid_credentials": "Correo o contraseña incorrectos.",
"forbidden": "Solo los administradores de organización y los superadministradores pueden usar el panel de administración.",
"account_disabled": "Esta cuenta está desactivada.",
"mfa_required": "Esta cuenta usa inicio de sesión en dos pasos. Entra primero en la aplicación web; el panel de administración aún no lo admite.",
"invalid_code": "Ese código no es correcto o ya se usó.",
"invalid_token": "Ha tardado demasiado. Vuelve a iniciar sesión."
}
},
"overview": {
"title": "Resumen",
"instance": "Todo el servidor.",
"org": "Tu organización.",
"users": "Usuarios",
"organizations": "Organizaciones",
"workspaces": "Espacios de trabajo",
"spaces": "Espacios",
"pages": "Páginas",
"files": "Archivos",
"openNow": "Abiertas ahora",
"openNowValue": "{rooms} página(s) · {editors} editor(es)",
"searchIndex": "Índice de búsqueda",
"indexed": "{n} página(s)",
"system": "Sistema",
"version": "Versión",
"upFor": "En marcha desde hace",
"database": "Base de datos",
"connected": "Conectada · {ms} ms",
"unavailable": "No disponible",
"memory": "Memoria",
"memoryValue": "{mb} MB · {goroutines} gorrutinas",
"days": "{d} d {h} h",
"hours": "{h} h {m} min",
"minutes": "{m} min"
},
"users": {
"title": "Usuarios",
"everyone": "Todas las personas de este servidor.",
"membersOf": "Miembros de {org}.",
"new": "Nuevo usuario",
"search": "Buscar nombre o correo",
"searchLabel": "Buscar usuarios",
"filterOrg": "Filtrar por organización",
"allOrgs": "Todas las organizaciones",
"editTitle": "Editar {email}",
"newPassword": "Nueva contraseña (opcional)",
"ownRole": "No puedes cambiar tu propio rol.",
"createUser": "Crear usuario",
"resetPassword": "Restablecer contraseña",
"turnOffTotp": "Desactivar dos pasos",
"none": "No se encontraron usuarios.",
"resetSent": "Se ha enviado un enlace para restablecer la contraseña a {email}.",
"confirmTotp": "¿Desactivar el inicio de sesión en dos pasos para {email}? Entrará solo con su contraseña hasta que lo vuelva a configurar.",
"totpOff": "El inicio de sesión en dos pasos está desactivado para {email}.",
"confirmDelete": "¿Eliminar {email}? No se puede deshacer."
},
"invites": {
"title": "Invitar personas",
"emailLabel": "Correo a invitar",
"send": "Enviar invitación",
"mailed": "Se ha enviado una invitación a {email}.",
"notMailed": "{email} está invitado, pero no se pudo enviar el correo. Envíale el enlace tú.",
"copied": "Copiado",
"copyLink": "Copiar enlace",
"invitedBy": "invitado por {name}",
"someone": "alguien",
"expired": "Caducada",
"resend": "Reenviar"
},
"orgs": {
"titleAll": "Organizaciones",
"titleOne": "Organización",
"hintAll": "Todas las organizaciones de este servidor. Los administradores de una organización solo gestionan la suya.",
"hintOne": "Tu organización. Gestionas sus miembros y todos sus espacios de trabajo.",
"new": "Nueva organización",
"none": "Aún no hay organizaciones.",
"members": "{n} miembro | {n} miembros",
"workspaces": "{n} espacio de trabajo | {n} espacios de trabajo",
"confirmDeleteMine": "¿Eliminar {name}? Pasarás a ser un usuario normal y perderás el acceso al panel de administración.",
"confirmDelete": "¿Eliminar {name}? No se puede deshacer."
},
"security": {
"title": "Seguridad",
"hintAll": "Quién cambió qué, inicios de sesión y tokens de API.",
"hintOrg": "Quién cambió qué, inicios de sesión y tokens de API en tu organización.",
"auditLog": "Registro de auditoría",
"searchPlaceholder": "Acción, correo, id o IP",
"searchLabel": "Buscar en el registro de auditoría",
"since": "Desde",
"search": "Buscar",
"time": "Hora",
"action": "Acción",
"who": "Quién",
"target": "Objetivo",
"ip": "IP",
"nothing": "Sin resultados.",
"newer": "Más recientes",
"older": "Más antiguos",
"tokens": "Tokens de API",
"tokensHint": "Cada persona los crea en su cuenta. Revoca los que ya no deban funcionar.",
"lastUsed": "usado por última vez {when}",
"neverUsed": "nunca usado",
"expires": "caduca {when}",
"noTokens": "No hay tokens.",
"thisUser": "este usuario",
"confirmRevoke": "¿Revocar «{name}» de {email}? Los scripts que lo usan dejarán de funcionar."
},
"auth": {
"title": "Inicio de sesión",
"hint": "Quién puede crear una cuenta y cómo se entra.",
"signup": "Registro",
"anyone": "Cualquiera puede crear una cuenta",
"anyoneHint": "Desactivado: solo pueden unirse las personas invitadas. La primera cuenta siempre puede registrarse.",
"domains": "Dominios de correo permitidos",
"domainsHint": "Uno por línea. Vacío permite cualquier dominio. Las invitaciones ignoran esta lista. Las cuentas creadas por un proveedor de inicio de sesión también siguen estas reglas.",
"methods": "Formas de entrar",
"methodsHint": "Correo y contraseña siempre están activos. Cada persona puede añadir el inicio de sesión en dos pasos en su cuenta.",
"magicLink": "Enlaces de acceso por correo",
"magicLinkHint": "Se puede pedir un enlace y un código de un solo uso en vez de escribir la contraseña. Necesita correo operativo.",
"providers": "Proveedores de inicio de sesión",
"providersHint": "Registra Docwell en el proveedor con esta dirección de retorno y luego escribe el ID y el secreto del cliente:",
"clientId": "ID de cliente",
"clientSecret": "Secreto de cliente",
"secretSaved": "Guardado; escribe para sustituirlo",
"buttonLabel": "Texto del botón",
"singleSignOn": "Inicio de sesión único",
"authUrl": "URL de autorización",
"tokenUrl": "URL de tokens",
"userInfoUrl": "URL de información del usuario",
"consoles": {
"google": "Consola de Google Cloud → API y servicios → Credenciales",
"github": "GitHub → Settings → Developer settings → OAuth Apps",
"microsoft": "Centro de administración de Microsoft Entra → Registros de aplicaciones",
"oidc": "Tu proveedor de identidad (Keycloak, Authentik, Okta, …)"
}
},
"branding": {
"title": "Apariencia",
"hint": "Cómo se presenta este servidor en las páginas de acceso y en los correos.",
"accent": "Color de acento",
"pickAccent": "Elegir el color de acento",
"useDefault": "Usar el predeterminado",
"logo": "Logotipo",
"currentLogo": "Logotipo actual",
"defaultLogo": "El logotipo de Docwell.",
"upload": "Subir…",
"badType": "Usa una imagen PNG, JPEG, WebP o SVG.",
"tooBig": "El logotipo debe pesar menos de 190 KB."
},
"storage": {
"title": "Almacenamiento",
"hint": "Dónde se guardan las imágenes y los adjuntos.",
"warning": "Cambiar de almacenamiento no mueve los archivos existentes. Los subidos antes se quedan donde estaban y no se pueden abrir hasta copiarlos.",
"keep": "Guardar archivos",
"disk": "En el disco de docwell-db",
"s3": "En un bucket compatible con S3",
"endpoint": "Punto de acceso",
"bucket": "Bucket",
"region": "Región",
"accessKey": "Clave de acceso",
"secret": "Secreto",
"pathStyle": "Direccionamiento por ruta (lo necesitan MinIO y otros servidores)",
"test": "Probar el bucket guardado",
"reachable": "El bucket es accesible."
},
"email": {
"title": "Correo",
"hint": "Docwell envía por este servidor los correos de verificación, restablecimiento, invitación y acceso.",
"envNote": "Si DOCWELL_SMTP_HOST está definido para docwell-server, esos valores del entorno se vuelven a aplicar cada vez que arranca.",
"enabled": "Enviar correo mediante un servidor SMTP",
"host": "Servidor",
"port": "Puerto",
"username": "Usuario",
"tls": "Usar TLS desde el principio (normalmente puerto 465; el 587 lo activa solo)",
"senderName": "Nombre del remitente",
"senderAddress": "Dirección del remitente",
"test": "Prueba",
"testHint": "Envía un correo corto con la configuración guardada.",
"testTo": "Enviar la prueba a",
"sendTest": "Enviar correo de prueba",
"sent": "Enviado a {email}. Revisa la bandeja de entrada (y la de spam)."
},
"maintenance": {
"title": "Mantenimiento",
"backups": "Copias de seguridad",
"backupsHint": "Una copia contiene toda la base de datos y sus archivos. Para restaurarla, detén Docwell y sustituye los datos de docwell-db por el contenido del archivo.",
"creating": "Creando…",
"create": "Crear copia de seguridad",
"file": "Archivo",
"size": "Tamaño",
"created": "Creada",
"noBackups": "Aún no hay copias de seguridad.",
"confirmDelete": "¿Eliminar la copia {key}?",
"jobs": "Tareas en segundo plano",
"jobsHint": "Contadas desde que arrancó el servidor.",
"job": "Tarea",
"runs": "Ejecuciones",
"lastRun": "Última ejecución",
"every": "cada {every}",
"failedCount": "({n} fallidas)",
"running": "En marcha",
"failed": "Fallida",
"ok": "OK",
"runNow": "Ejecutar ahora"
}
}
+272
View File
@@ -0,0 +1,272 @@
{
"common": {
"save": "Enregistrer",
"saved": "Enregistré.",
"cancel": "Annuler",
"create": "Créer",
"delete": "Supprimer",
"edit": "Modifier",
"rename": "Renommer",
"revoke": "Révoquer",
"download": "Télécharger",
"remove": "Retirer",
"actions": "Actions",
"name": "Nom",
"email": "E-mail",
"password": "Mot de passe",
"role": "Rôle",
"status": "État",
"organization": "Organisation",
"noOrganization": "Aucune organisation",
"previous": "Précédente",
"next": "Suivante",
"pageOf": "Page {page} sur {total}",
"unchanged": "Inchangé",
"language": "Langue",
"browserLanguage": "Langue du navigateur",
"cantReach": "Impossible de joindre le serveur.",
"checkForm": "Vérifiez le formulaire.",
"requestFailed": "La requête a échoué ({code})."
},
"roles": {
"user": "Utilisateur",
"admin": "Administrateur",
"superadmin": "Super-administrateur"
},
"userStatus": {
"active": "Actif",
"invited": "Invité",
"disabled": "Désactivé"
},
"nav": {
"overview": "Vue d’ensemble",
"users": "Utilisateurs",
"organizations": "Organisations",
"organization": "Organisation",
"security": "Sécurité",
"authentication": "Connexion",
"branding": "Apparence",
"storage": "Stockage",
"email": "E-mail",
"maintenance": "Maintenance"
},
"shell": {
"badge": "Admin",
"superadmin": "Super-administrateur",
"adminOf": "Administrateur · {org}",
"noOrganization": "aucune organisation",
"signOut": "Se déconnecter"
},
"login": {
"title": "Se connecter à l’administration",
"hint": "Utilisez un compte d’administrateur d’organisation ou de super-administrateur.",
"totpHint": "Saisissez le code à 6 chiffres de votre application d’authentification, ou un code de secours.",
"code": "Code d’authentification",
"submit": "Se connecter",
"failed": "La connexion a échoué.",
"errors": {
"invalid_credentials": "E-mail ou mot de passe incorrect.",
"forbidden": "Seuls les administrateurs d’organisation et les super-administrateurs peuvent utiliser l’administration.",
"account_disabled": "Ce compte est désactivé.",
"mfa_required": "Ce compte utilise la connexion en deux étapes. Connectez-vous d’abord à l’application web ; l’administration ne la prend pas encore en charge.",
"invalid_code": "Ce code est incorrect ou a déjà servi.",
"invalid_token": "Cela a pris trop de temps. Reconnectez-vous."
}
},
"overview": {
"title": "Vue d’ensemble",
"instance": "Tout le serveur.",
"org": "Votre organisation.",
"users": "Utilisateurs",
"organizations": "Organisations",
"workspaces": "Espaces de travail",
"spaces": "Espaces",
"pages": "Pages",
"files": "Fichiers",
"openNow": "Ouvertes en ce moment",
"openNowValue": "{rooms} page(s) · {editors} éditeur(s)",
"searchIndex": "Index de recherche",
"indexed": "{n} page(s)",
"system": "Système",
"version": "Version",
"upFor": "En service depuis",
"database": "Base de données",
"connected": "Connectée · {ms} ms",
"unavailable": "Indisponible",
"memory": "Mémoire",
"memoryValue": "{mb} Mo · {goroutines} goroutines",
"days": "{d} j {h} h",
"hours": "{h} h {m} min",
"minutes": "{m} min"
},
"users": {
"title": "Utilisateurs",
"everyone": "Tout le monde sur ce serveur.",
"membersOf": "Membres de {org}.",
"new": "Nouvel utilisateur",
"search": "Chercher un nom ou un e-mail",
"searchLabel": "Chercher des utilisateurs",
"filterOrg": "Filtrer par organisation",
"allOrgs": "Toutes les organisations",
"editTitle": "Modifier {email}",
"newPassword": "Nouveau mot de passe (facultatif)",
"ownRole": "Vous ne pouvez pas changer votre propre rôle.",
"createUser": "Créer l’utilisateur",
"resetPassword": "Réinitialiser le mot de passe",
"turnOffTotp": "Désactiver les deux étapes",
"none": "Aucun utilisateur trouvé.",
"resetSent": "Un lien de réinitialisation est en route vers {email}.",
"confirmTotp": "Désactiver la connexion en deux étapes pour {email} ? Le mot de passe seul suffira jusqu’à ce qu’elle soit réactivée.",
"totpOff": "La connexion en deux étapes est désactivée pour {email}.",
"confirmDelete": "Supprimer {email} ? C’est définitif."
},
"invites": {
"title": "Inviter des personnes",
"emailLabel": "E-mail à inviter",
"send": "Envoyer l’invitation",
"mailed": "Une invitation est en route vers {email}.",
"notMailed": "{email} est invité, mais l’e-mail n’a pas pu partir. Envoyez-lui le lien vous-même.",
"copied": "Copié",
"copyLink": "Copier le lien",
"invitedBy": "invité par {name}",
"someone": "quelqu’un",
"expired": "Expirée",
"resend": "Renvoyer"
},
"orgs": {
"titleAll": "Organisations",
"titleOne": "Organisation",
"hintAll": "Toutes les organisations de ce serveur. Les administrateurs d’une organisation ne gèrent que la leur.",
"hintOne": "Votre organisation. Vous gérez ses membres et tous ses espaces de travail.",
"new": "Nouvelle organisation",
"none": "Aucune organisation pour l’instant.",
"members": "{n} membre | {n} membres",
"workspaces": "{n} espace de travail | {n} espaces de travail",
"confirmDeleteMine": "Supprimer {name} ? Vous deviendrez un utilisateur ordinaire et perdrez l’accès à l’administration.",
"confirmDelete": "Supprimer {name} ? C’est définitif."
},
"security": {
"title": "Sécurité",
"hintAll": "Qui a changé quoi, connexions et jetons d’API.",
"hintOrg": "Qui a changé quoi, connexions et jetons d’API dans votre organisation.",
"auditLog": "Journal d’audit",
"searchPlaceholder": "Action, e-mail, id ou IP",
"searchLabel": "Chercher dans le journal d’audit",
"since": "Depuis",
"search": "Chercher",
"time": "Heure",
"action": "Action",
"who": "Qui",
"target": "Cible",
"ip": "IP",
"nothing": "Aucun résultat.",
"newer": "Plus récents",
"older": "Plus anciens",
"tokens": "Jetons d’API",
"tokensHint": "Chacun les crée dans son compte. Révoquez ceux qui ne doivent plus fonctionner.",
"lastUsed": "utilisé le {when}",
"neverUsed": "jamais utilisé",
"expires": "expire le {when}",
"noTokens": "Aucun jeton.",
"thisUser": "cet utilisateur",
"confirmRevoke": "Révoquer « {name} » de {email} ? Les scripts qui l’utilisent ne fonctionneront plus."
},
"auth": {
"title": "Connexion",
"hint": "Qui peut créer un compte et comment se connecter.",
"signup": "Inscription",
"anyone": "Tout le monde peut créer un compte",
"anyoneHint": "Désactivé : seules les personnes invitées peuvent rejoindre. Le tout premier compte peut toujours s’inscrire.",
"domains": "Domaines e-mail autorisés",
"domainsHint": "Un par ligne. Vide : tous les domaines. Les invitations ignorent cette liste. Les comptes créés par un fournisseur de connexion suivent aussi ces règles.",
"methods": "Moyens de connexion",
"methodsHint": "E-mail et mot de passe sont toujours actifs. Chacun peut ajouter la connexion en deux étapes dans son compte.",
"magicLink": "Liens de connexion par e-mail",
"magicLinkHint": "On peut demander un lien et un code à usage unique au lieu de taper son mot de passe. Nécessite un e-mail fonctionnel.",
"providers": "Fournisseurs de connexion",
"providersHint": "Enregistrez Docwell auprès du fournisseur avec cette adresse de retour, puis saisissez l’ID et le secret client :",
"clientId": "ID client",
"clientSecret": "Secret client",
"secretSaved": "Enregistré ; tapez pour remplacer",
"buttonLabel": "Texte du bouton",
"singleSignOn": "Authentification unique",
"authUrl": "URL d’autorisation",
"tokenUrl": "URL des jetons",
"userInfoUrl": "URL des infos utilisateur",
"consoles": {
"google": "Console Google Cloud → API et services → Identifiants",
"github": "GitHub → Settings → Developer settings → OAuth Apps",
"microsoft": "Centre d’administration Microsoft Entra → Inscriptions d’applications",
"oidc": "Votre fournisseur d’identité (Keycloak, Authentik, Okta, …)"
}
},
"branding": {
"title": "Apparence",
"hint": "Comment ce serveur se présente sur les pages de connexion et dans les e-mails.",
"accent": "Couleur d’accent",
"pickAccent": "Choisir la couleur d’accent",
"useDefault": "Par défaut",
"logo": "Logo",
"currentLogo": "Logo actuel",
"defaultLogo": "Le logo Docwell.",
"upload": "Téléverser…",
"badType": "Utilisez une image PNG, JPEG, WebP ou SVG.",
"tooBig": "Le logo doit faire moins de 190 Ko."
},
"storage": {
"title": "Stockage",
"hint": "Où sont conservés les images et les pièces jointes.",
"warning": "Changer de stockage ne déplace pas les fichiers existants. Ceux envoyés avant restent où ils étaient et ne s’ouvrent pas tant qu’ils ne sont pas copiés.",
"keep": "Conserver les fichiers",
"disk": "Sur le disque de docwell-db",
"s3": "Dans un bucket compatible S3",
"endpoint": "Point d’accès",
"bucket": "Bucket",
"region": "Région",
"accessKey": "Clé d’accès",
"secret": "Secret",
"pathStyle": "Adressage par chemin (nécessaire pour MinIO et quelques autres serveurs)",
"test": "Tester le bucket enregistré",
"reachable": "Le bucket est joignable."
},
"email": {
"title": "E-mail",
"hint": "Docwell envoie par ce serveur les e-mails de vérification, de réinitialisation, d’invitation et de connexion.",
"envNote": "Si DOCWELL_SMTP_HOST est défini pour docwell-server, ces valeurs d’environnement sont réappliquées à chaque démarrage.",
"enabled": "Envoyer les e-mails par un serveur SMTP",
"host": "Hôte",
"port": "Port",
"username": "Nom d’utilisateur",
"tls": "TLS dès le départ (en général port 465 ; le port 587 bascule tout seul)",
"senderName": "Nom de l’expéditeur",
"senderAddress": "Adresse de l’expéditeur",
"test": "Test",
"testHint": "Envoie un court e-mail avec les réglages enregistrés.",
"testTo": "Envoyer le test à",
"sendTest": "Envoyer un e-mail de test",
"sent": "Envoyé à {email}. Vérifiez la boîte de réception (et les indésirables)."
},
"maintenance": {
"title": "Maintenance",
"backups": "Sauvegardes",
"backupsHint": "Une sauvegarde contient toute la base et ses fichiers. Pour la restaurer, arrêtez Docwell et remplacez les données de docwell-db par le contenu de l’archive.",
"creating": "Création…",
"create": "Créer une sauvegarde",
"file": "Fichier",
"size": "Taille",
"created": "Créée",
"noBackups": "Aucune sauvegarde pour l’instant.",
"confirmDelete": "Supprimer la sauvegarde {key} ?",
"jobs": "Tâches de fond",
"jobsHint": "Comptées depuis le démarrage du serveur.",
"job": "Tâche",
"runs": "Exécutions",
"lastRun": "Dernière exécution",
"every": "toutes les {every}",
"failedCount": "({n} en échec)",
"running": "En cours",
"failed": "En échec",
"ok": "OK",
"runNow": "Lancer maintenant"
}
}
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { describe, expect, it } from "vitest";
import { browserLocale, supportedLocales } from "../i18n";
type Messages = { [key: string]: string | Messages };
const files = import.meta.glob<Messages>("./*.json", { eager: true, import: "default" });
const messages = Object.fromEntries(Object.entries(files).map(([path, m]) => [path.replace(/^\.\/|\.json$/g, ""), m]));
/** Every message as "path.to.key" → text. */
function flatten(m: Messages, prefix = ""): Map<string, string> {
const out = new Map<string, string>();
for (const [k, v] of Object.entries(m)) {
if (typeof v === "string") out.set(prefix + k, v);
else for (const [kk, vv] of flatten(v, `${prefix}${k}.`)) out.set(kk, vv);
}
return out;
}
const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
const english = flatten(messages.en!);
describe("interface languages", () => {
it("has a file for every supported language and no others", () => {
expect(Object.keys(messages).sort()).toEqual([...supportedLocales].sort());
});
for (const locale of supportedLocales.filter((l) => l !== "en")) {
it(`${locale} has every English message, with the same placeholders`, () => {
const other = flatten(messages[locale]!);
expect([...other.keys()].sort()).toEqual([...english.keys()].sort());
for (const [key, text] of english) {
const translated = other.get(key)!;
// Plural forms differ in number (Polish has three), but each names the same values.
for (const form of translated.split(" | ")) {
expect(placeholders(form), `${locale}: ${key}`).toEqual(placeholders(text.split(" | ").at(-1)!));
}
// "@" and "|" outside plurals are vue-i18n syntax and would break the message.
expect(translated.replace(/ \| /g, ""), `${locale}: ${key}`).not.toMatch(/[@|]/);
}
});
}
it("picks the first browser language the app has", () => {
expect(browserLocale(["pt-BR", "fr-CA", "de"])).toBe("fr");
expect(browserLocale(["DE-at"])).toBe("de");
expect(browserLocale(["ja"])).toBe("en");
expect(browserLocale([])).toBe("en");
});
});
+272
View File
@@ -0,0 +1,272 @@
{
"common": {
"save": "Zapisz",
"saved": "Zapisano.",
"cancel": "Anuluj",
"create": "Utwórz",
"delete": "Usuń",
"edit": "Edytuj",
"rename": "Zmień nazwę",
"revoke": "Unieważnij",
"download": "Pobierz",
"remove": "Usuń",
"actions": "Działania",
"name": "Nazwa",
"email": "E-mail",
"password": "Hasło",
"role": "Rola",
"status": "Stan",
"organization": "Organizacja",
"noOrganization": "Bez organizacji",
"previous": "Poprzednia",
"next": "Następna",
"pageOf": "Strona {page} z {total}",
"unchanged": "Bez zmian",
"language": "Język",
"browserLanguage": "Język przeglądarki",
"cantReach": "Brak połączenia z serwerem.",
"checkForm": "Sprawdź formularz.",
"requestFailed": "Żądanie nie powiodło się ({code})."
},
"roles": {
"user": "Użytkownik",
"admin": "Administrator",
"superadmin": "Superadministrator"
},
"userStatus": {
"active": "Aktywny",
"invited": "Zaproszony",
"disabled": "Wyłączony"
},
"nav": {
"overview": "Przegląd",
"users": "Użytkownicy",
"organizations": "Organizacje",
"organization": "Organizacja",
"security": "Bezpieczeństwo",
"authentication": "Logowanie",
"branding": "Wygląd",
"storage": "Pliki",
"email": "E-mail",
"maintenance": "Konserwacja"
},
"shell": {
"badge": "Admin",
"superadmin": "Superadministrator",
"adminOf": "Administrator · {org}",
"noOrganization": "bez organizacji",
"signOut": "Wyloguj"
},
"login": {
"title": "Zaloguj się do panelu administracyjnego",
"hint": "Użyj konta administratora organizacji lub superadministratora.",
"totpHint": "Wpisz 6-cyfrowy kod z aplikacji uwierzytelniającej albo kod odzyskiwania.",
"code": "Kod uwierzytelniający",
"submit": "Zaloguj",
"failed": "Logowanie nie powiodło się.",
"errors": {
"invalid_credentials": "Nieprawidłowy e-mail lub hasło.",
"forbidden": "Z panelu administracyjnego mogą korzystać tylko administratorzy organizacji i superadministratorzy.",
"account_disabled": "To konto jest wyłączone.",
"mfa_required": "To konto używa logowania dwuetapowego. Najpierw zaloguj się w aplikacji internetowej; panel administracyjny jeszcze tego nie obsługuje.",
"invalid_code": "Ten kod jest nieprawidłowy albo został już użyty.",
"invalid_token": "Upłynęło zbyt wiele czasu. Zaloguj się ponownie."
}
},
"overview": {
"title": "Przegląd",
"instance": "Cały serwer.",
"org": "Twoja organizacja.",
"users": "Użytkownicy",
"organizations": "Organizacje",
"workspaces": "Obszary robocze",
"spaces": "Przestrzenie",
"pages": "Strony",
"files": "Pliki",
"openNow": "Otwarte teraz",
"openNowValue": "stron: {rooms} · edytujących: {editors}",
"searchIndex": "Indeks wyszukiwania",
"indexed": "stron: {n}",
"system": "System",
"version": "Wersja",
"upFor": "Działa od",
"database": "Baza danych",
"connected": "Połączono · {ms} ms",
"unavailable": "Niedostępna",
"memory": "Pamięć",
"memoryValue": "{mb} MB · gorutyny: {goroutines}",
"days": "{d} d {h} godz.",
"hours": "{h} godz. {m} min",
"minutes": "{m} min"
},
"users": {
"title": "Użytkownicy",
"everyone": "Wszyscy na tym serwerze.",
"membersOf": "Członkowie organizacji {org}.",
"new": "Nowy użytkownik",
"search": "Szukaj po nazwie lub e-mailu",
"searchLabel": "Szukaj użytkowników",
"filterOrg": "Filtruj według organizacji",
"allOrgs": "Wszystkie organizacje",
"editTitle": "Edytuj {email}",
"newPassword": "Nowe hasło (opcjonalnie)",
"ownRole": "Nie możesz zmienić własnej roli.",
"createUser": "Utwórz użytkownika",
"resetPassword": "Zresetuj hasło",
"turnOffTotp": "Wyłącz logowanie dwuetapowe",
"none": "Nie znaleziono użytkowników.",
"resetSent": "Link do zresetowania hasła został wysłany na {email}.",
"confirmTotp": "Wyłączyć logowanie dwuetapowe dla {email}? Do czasu ponownego włączenia będzie logować się samym hasłem.",
"totpOff": "Logowanie dwuetapowe dla {email} jest wyłączone.",
"confirmDelete": "Usunąć {email}? Tego nie można cofnąć."
},
"invites": {
"title": "Zaproś osoby",
"emailLabel": "E-mail do zaproszenia",
"send": "Wyślij zaproszenie",
"mailed": "Zaproszenie zostało wysłane na {email}.",
"notMailed": "{email} ma zaproszenie, ale nie udało się wysłać e-maila. Przekaż link samodzielnie.",
"copied": "Skopiowano",
"copyLink": "Kopiuj link",
"invitedBy": "zaprasza: {name}",
"someone": "ktoś",
"expired": "Wygasło",
"resend": "Wyślij ponownie"
},
"orgs": {
"titleAll": "Organizacje",
"titleOne": "Organizacja",
"hintAll": "Wszystkie organizacje na tym serwerze. Administratorzy organizacji zarządzają tylko własną.",
"hintOne": "Twoja organizacja. Zarządzasz jej członkami i wszystkimi jej obszarami roboczymi.",
"new": "Nowa organizacja",
"none": "Nie ma jeszcze organizacji.",
"members": "{n} członek | {n} członków | {n} członków",
"workspaces": "{n} obszar roboczy | {n} obszary robocze | {n} obszarów roboczych",
"confirmDeleteMine": "Usunąć {name}? Staniesz się zwykłym użytkownikiem i stracisz dostęp do panelu administracyjnego.",
"confirmDelete": "Usunąć {name}? Tego nie można cofnąć."
},
"security": {
"title": "Bezpieczeństwo",
"hintAll": "Kto co zmienił, logowania i tokeny API.",
"hintOrg": "Kto co zmienił, logowania i tokeny API w Twojej organizacji.",
"auditLog": "Dziennik zdarzeń",
"searchPlaceholder": "Działanie, e-mail, id lub IP",
"searchLabel": "Szukaj w dzienniku zdarzeń",
"since": "Od",
"search": "Szukaj",
"time": "Czas",
"action": "Działanie",
"who": "Kto",
"target": "Cel",
"ip": "IP",
"nothing": "Brak wyników.",
"newer": "Nowsze",
"older": "Starsze",
"tokens": "Tokeny API",
"tokensHint": "Użytkownicy tworzą je na swoim koncie. Unieważnij te, które nie powinny już działać.",
"lastUsed": "ostatnio użyty {when}",
"neverUsed": "nigdy nieużyty",
"expires": "wygasa {when}",
"noTokens": "Brak tokenów.",
"thisUser": "tego użytkownika",
"confirmRevoke": "Unieważnić „{name}” użytkownika {email}? Skrypty, które go używają, przestaną działać."
},
"auth": {
"title": "Logowanie",
"hint": "Kto może założyć konto i jak się logować.",
"signup": "Rejestracja",
"anyone": "Każdy może założyć konto",
"anyoneHint": "Wyłączone: dołączyć mogą tylko zaproszone osoby. Pierwsze konto zawsze może się zarejestrować.",
"domains": "Dozwolone domeny e-mail",
"domainsHint": "Jedna w wierszu. Pusta lista dopuszcza każdą domenę. Zaproszenia pomijają tę listę. Konta zakładane przez dostawcę logowania też podlegają tym zasadom.",
"methods": "Sposoby logowania",
"methodsHint": "E-mail i hasło są zawsze włączone. Logowanie dwuetapowe każdy może dodać na swoim koncie.",
"magicLink": "Linki do logowania e-mailem",
"magicLinkHint": "Zamiast wpisywać hasło, można poprosić o link i jednorazowy kod. Wymaga działającej poczty.",
"providers": "Dostawcy logowania",
"providersHint": "Zarejestruj Docwell u dostawcy z tym adresem zwrotnym, a potem wpisz identyfikator i sekret klienta:",
"clientId": "Identyfikator klienta",
"clientSecret": "Sekret klienta",
"secretSaved": "Zapisany; wpisz, aby zastąpić",
"buttonLabel": "Napis na przycisku",
"singleSignOn": "Logowanie jednokrotne",
"authUrl": "Adres autoryzacji",
"tokenUrl": "Adres tokenów",
"userInfoUrl": "Adres danych użytkownika",
"consoles": {
"google": "Konsola Google Cloud → Interfejsy API i usługi → Dane logowania",
"github": "GitHub → Settings → Developer settings → OAuth Apps",
"microsoft": "Centrum administracyjne Microsoft Entra → Rejestracje aplikacji",
"oidc": "Twój dostawca tożsamości (Keycloak, Authentik, Okta, …)"
}
},
"branding": {
"title": "Wygląd",
"hint": "Jak ten serwer przedstawia się na stronach logowania i w e-mailach.",
"accent": "Kolor wiodący",
"pickAccent": "Wybierz kolor wiodący",
"useDefault": "Użyj domyślnego",
"logo": "Logo",
"currentLogo": "Obecne logo",
"defaultLogo": "Logo Docwell.",
"upload": "Prześlij…",
"badType": "Użyj obrazu PNG, JPEG, WebP lub SVG.",
"tooBig": "Logo musi mieć mniej niż 190 KB."
},
"storage": {
"title": "Pliki",
"hint": "Gdzie przechowywane są obrazy i załączniki.",
"warning": "Zmiana miejsca nie przenosi istniejących plików. Pliki przesłane wcześniej zostają tam, gdzie były, i nie da się ich otworzyć, dopóki nie zostaną skopiowane.",
"keep": "Przechowuj pliki",
"disk": "Na dysku docwell-db",
"s3": "W zasobniku zgodnym z S3",
"endpoint": "Adres",
"bucket": "Zasobnik",
"region": "Region",
"accessKey": "Klucz dostępu",
"secret": "Sekret",
"pathStyle": "Adresowanie ścieżką (potrzebne w MinIO i niektórych innych serwerach)",
"test": "Sprawdź zapisany zasobnik",
"reachable": "Zasobnik jest osiągalny."
},
"email": {
"title": "E-mail",
"hint": "Docwell wysyła przez ten serwer e-maile weryfikacyjne, resetowania hasła, zaproszenia i linki do logowania.",
"envNote": "Jeśli dla docwell-server ustawiono DOCWELL_SMTP_HOST, te wartości ze zmiennych środowiskowych są stosowane ponownie przy każdym starcie.",
"enabled": "Wysyłaj e-maile przez serwer SMTP",
"host": "Host",
"port": "Port",
"username": "Nazwa użytkownika",
"tls": "Używaj TLS od początku (zwykle port 465; port 587 przełącza się sam)",
"senderName": "Nazwa nadawcy",
"senderAddress": "Adres nadawcy",
"test": "Test",
"testHint": "Wysyła krótki e-mail z zapisanymi ustawieniami.",
"testTo": "Wyślij test na adres",
"sendTest": "Wyślij e-mail testowy",
"sent": "Wysłano na {email}. Sprawdź skrzynkę (i folder spamu)."
},
"maintenance": {
"title": "Konserwacja",
"backups": "Kopie zapasowe",
"backupsHint": "Kopia zapasowa zawiera całą bazę danych i jej pliki. Aby ją przywrócić, zatrzymaj Docwell i zastąp dane docwell-db zawartością archiwum.",
"creating": "Tworzenie…",
"create": "Utwórz kopię zapasową",
"file": "Plik",
"size": "Rozmiar",
"created": "Utworzono",
"noBackups": "Nie ma jeszcze kopii zapasowych.",
"confirmDelete": "Usunąć kopię zapasową {key}?",
"jobs": "Zadania w tle",
"jobsHint": "Liczone od uruchomienia serwera.",
"job": "Zadanie",
"runs": "Uruchomienia",
"lastRun": "Ostatnie uruchomienie",
"every": "co {every}",
"failedCount": "(nieudane: {n})",
"running": "Działa",
"failed": "Błąd",
"ok": "OK",
"runNow": "Uruchom teraz"
}
}
+2 -1
View File
@@ -3,6 +3,7 @@
import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import { i18n } from "./i18n";
import { currentUser, isSuperadmin, restoreSession } from "./session";
import "./style.css";
@@ -50,4 +51,4 @@ router.beforeEach(async (to) => {
if (to.meta.superadmin && !isSuperadmin.value) return { name: "overview" };
});
createApp(App).use(router).mount("#app");
createApp(App).use(router).use(i18n).mount("#app");
+4 -3
View File
@@ -2,6 +2,7 @@
import { ApiError, createClient, createTokenStore, isManager, type User } from "@docwell/api-client";
import { computed, ref } from "vue";
import { t } from "./i18n";
// The admin panel is served by docwell-server itself, so the API is same-origin.
const tokens = createTokenStore("docwell.admin.token");
@@ -63,8 +64,8 @@ export async function restoreSession() {
/** A readable message for an API failure. */
export function errorMessage(e: unknown): string {
if (e instanceof ApiError) {
if (e.code === "validation") return Object.values(e.fields).join(" ") || "Please check the form.";
return e.serverMessage || `Request failed (${e.code}).`;
if (e.code === "validation") return Object.values(e.fields).join(" ") || t("common.checkForm");
return e.serverMessage || t("common.requestFailed", { code: e.code });
}
return "Can't reach the server.";
return t("common.cantReach");
}
+28 -38
View File
@@ -24,11 +24,12 @@ interface Row {
tokenUrl: string;
userInfoUrl: string;
}
const known: { name: Name; label: string; console: string }[] = [
{ name: "google", label: "Google", console: "Google Cloud console → APIs & Services → Credentials" },
{ name: "github", label: "GitHub", console: "GitHub → Settings → Developer settings → OAuth Apps" },
{ name: "microsoft", label: "Microsoft", console: "Microsoft Entra admin center → App registrations" },
{ name: "oidc", label: "OpenID Connect", console: "Your identity provider (Keycloak, Authentik, Okta, …)" },
// Provider names are brands; where to register the app is translated (auth.consoles).
const known: { name: Name; label: string }[] = [
{ name: "google", label: "Google" },
{ name: "github", label: "GitHub" },
{ name: "microsoft", label: "Microsoft" },
{ name: "oidc", label: "OpenID Connect" },
];
const rows = ref<Row[]>([]);
@@ -86,25 +87,23 @@ const fieldError = (i: number, f: string) => {
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Authentication</h1>
<p class="mt-1 text-ink-muted">Who can create an account, and how people sign in.</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("auth.title") }}</h1>
<p class="mt-1 text-ink-muted">{{ $t("auth.hint") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">{{ $t("common.saved") }}</DwCallout>
<form v-if="settings" class="mt-6 max-w-xl space-y-6" @submit.prevent="submit">
<section class="dw-card space-y-4">
<h2 class="text-ui-lg">Sign-up</h2>
<h2 class="text-ui-lg">{{ $t("auth.signup") }}</h2>
<label class="flex items-start gap-3">
<input v-model="signupEnabled" type="checkbox" class="mt-1 accent-primary" data-testid="signup-enabled" />
<span>
<span class="font-medium">Anyone can create an account</span>
<span class="block text-ui-sm text-ink-muted">
Off: only invited people can join. The very first account can always sign up.
</span>
<span class="font-medium">{{ $t("auth.anyone") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("auth.anyoneHint") }}</span>
</span>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Allowed email domains</span>
<span class="text-ui-sm font-semibold">{{ $t("auth.domains") }}</span>
<textarea
v-model="domains"
rows="3"
@@ -112,33 +111,26 @@ const fieldError = (i: number, f: string) => {
placeholder="example.com"
data-testid="signup-domains"
/>
<span class="text-ui-sm text-ink-muted"
>One per line. Empty allows every domain. Invites ignore this list. Accounts created by a sign-in provider
follow these rules too.</span
>
<span class="text-ui-sm text-ink-muted">{{ $t("auth.domainsHint") }}</span>
</label>
</section>
<section class="dw-card space-y-4">
<h2 class="text-ui-lg">Sign-in methods</h2>
<p class="text-ui-md">Email and password is always on. People can add two-step sign-in in their account.</p>
<h2 class="text-ui-lg">{{ $t("auth.methods") }}</h2>
<p class="text-ui-md">{{ $t("auth.methodsHint") }}</p>
<label class="flex items-start gap-3">
<input v-model="magicLink" type="checkbox" class="mt-1 accent-primary" data-testid="magic-link" />
<span>
<span class="font-medium">Sign-in links by email</span>
<span class="block text-ui-sm text-ink-muted">
People can ask for a link and a one-time code instead of typing their password. Needs working email.
</span>
<span class="font-medium">{{ $t("auth.magicLink") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("auth.magicLinkHint") }}</span>
</span>
</label>
</section>
<section class="dw-card space-y-4" data-testid="oauth-providers">
<div>
<h2 class="text-ui-lg">Sign-in providers</h2>
<p class="mt-1 text-ui-sm text-ink-muted">
Register Docwell with the provider, using this callback address, then enter the client ID and secret:
</p>
<h2 class="text-ui-lg">{{ $t("auth.providers") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("auth.providersHint") }}</p>
<code class="mt-1 block break-all rounded-sm bg-surface-sunken px-2 py-1 font-mono text-ui-sm">{{
callback
}}</code>
@@ -149,39 +141,37 @@ const fieldError = (i: number, f: string) => {
<input v-model="r.on" type="checkbox" class="mt-1 accent-primary" :data-testid="`oauth-${r.name}`" />
<span>
<span class="font-medium">{{ known[i]!.label }}</span>
<span class="block text-ui-sm text-ink-muted">{{ known[i]!.console }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t(`auth.consoles.${r.name}`) }}</span>
</span>
</label>
<div v-if="r.on" class="grid gap-3 pl-7 sm:grid-cols-2">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Client ID</span>
<span class="text-ui-sm font-semibold">{{ $t("auth.clientId") }}</span>
<input v-model="r.clientId" class="dw-input" required />
<span v-if="fieldError(i, 'clientId')" class="text-ui-sm text-danger">{{ fieldError(i, "clientId") }}</span>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Client secret</span>
<span class="text-ui-sm font-semibold">{{ $t("auth.clientSecret") }}</span>
<input
v-model="r.clientSecret"
type="password"
autocomplete="new-password"
class="dw-input"
:placeholder="r.hasSecret ? 'Saved; type to replace' : ''"
:placeholder="r.hasSecret ? $t('auth.secretSaved') : ''"
:required="!r.hasSecret"
/>
</label>
<template v-if="r.name === 'oidc'">
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">Button label</span>
<input v-model="r.displayName" class="dw-input" placeholder="Single sign-on" />
<span class="text-ui-sm font-semibold">{{ $t("auth.buttonLabel") }}</span>
<input v-model="r.displayName" class="dw-input" :placeholder="$t('auth.singleSignOn')" />
</label>
<label
v-for="f in ['authUrl', 'tokenUrl', 'userInfoUrl'] as const"
:key="f"
class="flex flex-col gap-1.5 sm:col-span-2"
>
<span class="text-ui-sm font-semibold">{{
{ authUrl: "Authorization URL", tokenUrl: "Token URL", userInfoUrl: "User info URL" }[f]
}}</span>
<span class="text-ui-sm font-semibold">{{ $t(`auth.${f}`) }}</span>
<input v-model="r[f]" type="url" class="dw-input font-mono" required placeholder="https://" />
<span v-if="fieldError(i, f)" class="text-ui-sm text-danger">{{ fieldError(i, f) }}</span>
</label>
@@ -190,6 +180,6 @@ const fieldError = (i: number, f: string) => {
</fieldset>
</section>
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy">{{ $t("common.save") }}</DwButton>
</form>
</template>
+20 -16
View File
@@ -2,10 +2,12 @@
<script setup lang="ts">
import { DwButton, DwCallout } from "@docwell/ui";
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useInstanceSettings } from "../settings";
// The server's name, accent colour and logo, shown on the sign-in pages and in emails.
const { settings, error, saved, busy, save } = useInstanceSettings();
const { t } = useI18n();
const appName = ref("");
const accent = ref("");
const logo = ref("");
@@ -27,11 +29,11 @@ function pickLogo(e: Event) {
fileError.value = "";
if (!file) return;
if (!/^image\/(png|jpeg|webp|svg\+xml)$/.test(file.type)) {
fileError.value = "Use a PNG, JPEG, WebP or SVG image.";
fileError.value = t("branding.badType");
return;
}
if (file.size > maxLogo) {
fileError.value = "The logo must be smaller than 190 KB.";
fileError.value = t("branding.tooBig");
return;
}
const reader = new FileReader();
@@ -45,23 +47,23 @@ function submit() {
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Branding</h1>
<p class="mt-1 text-ink-muted">How this server presents itself on the sign-in pages and in emails.</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("branding.title") }}</h1>
<p class="mt-1 text-ink-muted">{{ $t("branding.hint") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">{{ $t("common.saved") }}</DwCallout>
<form v-if="settings" class="mt-6 max-w-xl space-y-4 dw-card" @submit.prevent="submit">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Name</span>
<span class="text-ui-sm font-semibold">{{ $t("common.name") }}</span>
<input v-model="appName" required maxlength="60" class="dw-input" data-testid="app-name" />
</label>
<div class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Accent colour</span>
<span class="text-ui-sm font-semibold">{{ $t("branding.accent") }}</span>
<div class="flex items-center gap-2">
<input
type="color"
:value="accent || '#2f7d6d'"
aria-label="Pick the accent colour"
:aria-label="$t('branding.pickAccent')"
class="h-control-md w-12 cursor-pointer rounded-sm border border-line bg-surface"
@input="accent = ($event.target as HTMLInputElement).value"
/>
@@ -70,29 +72,31 @@ function submit() {
placeholder="#2f7d6d"
maxlength="7"
class="dw-input w-32 font-mono"
aria-label="Accent colour"
:aria-label="$t('branding.accent')"
/>
<DwButton v-if="accent" variant="ghost" size="sm" @click="accent = ''">Use default</DwButton>
<DwButton v-if="accent" variant="ghost" size="sm" @click="accent = ''">{{
$t("branding.useDefault")
}}</DwButton>
</div>
</div>
<div class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Logo</span>
<span class="text-ui-sm font-semibold">{{ $t("branding.logo") }}</span>
<div class="flex flex-wrap items-center gap-3">
<img
v-if="logo"
:src="logo"
alt="Current logo"
:alt="$t('branding.currentLogo')"
class="h-10 max-w-48 rounded-sm border border-line bg-surface p-1"
/>
<span v-else class="text-ui-sm text-ink-muted">The Docwell logo.</span>
<span v-else class="text-ui-sm text-ink-muted">{{ $t("branding.defaultLogo") }}</span>
<label class="cursor-pointer text-ui-md font-semibold text-accent hover:underline">
Upload…
{{ $t("branding.upload") }}
<input type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" class="hidden" @change="pickLogo" />
</label>
<DwButton v-if="logo" variant="ghost" size="sm" @click="logo = ''">Remove</DwButton>
<DwButton v-if="logo" variant="ghost" size="sm" @click="logo = ''">{{ $t("common.remove") }}</DwButton>
</div>
<span v-if="fileError" class="text-ui-sm text-danger">{{ fileError }}</span>
</div>
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy">{{ $t("common.save") }}</DwButton>
</form>
</template>
+21 -23
View File
@@ -2,11 +2,13 @@
<script setup lang="ts">
import { DwButton, DwCallout } from "@docwell/ui";
import { reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useInstanceSettings } from "../settings";
import { api, currentUser, errorMessage } from "../session";
// Outgoing mail: verification, password reset, invites and sign-in links.
const { settings, error, saved, busy, save } = useInstanceSettings();
const { t } = useI18n();
const form = reactive({
enabled: false,
host: "",
@@ -36,7 +38,7 @@ async function sendTest() {
testState.value = null;
try {
await api.settings.testEmail(testTo.value);
testState.value = { ok: true, text: `Sent to ${testTo.value}. Check the inbox (and the spam folder).` };
testState.value = { ok: true, text: t("email.sent", { email: testTo.value }) };
} catch (e) {
testState.value = { ok: false, text: errorMessage(e) };
}
@@ -44,66 +46,62 @@ async function sendTest() {
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Email</h1>
<p class="mt-1 text-ink-muted">
Docwell sends verification, password reset, invite and sign-in emails through this server.
</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("email.title") }}</h1>
<p class="mt-1 text-ink-muted">{{ $t("email.hint") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
<DwCallout size="ui" class="mt-4 max-w-xl">
If DOCWELL_SMTP_HOST is set for docwell-server, those environment values are applied again whenever it starts.
</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">{{ $t("common.saved") }}</DwCallout>
<DwCallout size="ui" class="mt-4 max-w-xl">{{ $t("email.envNote") }}</DwCallout>
<form v-if="settings" class="mt-6 grid max-w-xl gap-4 dw-card sm:grid-cols-2" @submit.prevent="submit">
<label class="flex items-center gap-3 sm:col-span-2">
<input v-model="form.enabled" type="checkbox" class="accent-primary" />
<span class="font-medium">Send email through an SMTP server</span>
<span class="font-medium">{{ $t("email.enabled") }}</span>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Host</span>
<span class="text-ui-sm font-semibold">{{ $t("email.host") }}</span>
<input v-model="form.host" :required="form.enabled" class="dw-input" placeholder="smtp.example.com" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Port</span>
<span class="text-ui-sm font-semibold">{{ $t("email.port") }}</span>
<input v-model.number="form.port" type="number" min="1" max="65535" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Username</span>
<span class="text-ui-sm font-semibold">{{ $t("email.username") }}</span>
<input v-model="form.username" autocomplete="off" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Password</span>
<span class="text-ui-sm font-semibold">{{ $t("common.password") }}</span>
<input
v-model="form.password"
type="password"
autocomplete="new-password"
class="dw-input"
:placeholder="settings.smtp.passwordSet ? 'Unchanged' : ''"
:placeholder="settings.smtp.passwordSet ? $t('common.unchanged') : ''"
/>
</label>
<label class="flex items-center gap-3 sm:col-span-2">
<input v-model="form.tls" type="checkbox" class="accent-primary" />
<span>Use TLS from the start (usually port 465; port 587 upgrades on its own)</span>
<span>{{ $t("email.tls") }}</span>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Sender name</span>
<span class="text-ui-sm font-semibold">{{ $t("email.senderName") }}</span>
<input v-model="form.senderName" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Sender address</span>
<span class="text-ui-sm font-semibold">{{ $t("email.senderAddress") }}</span>
<input v-model="form.senderAddress" type="email" required class="dw-input" />
</label>
<div class="sm:col-span-2">
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy">{{ $t("common.save") }}</DwButton>
</div>
</form>
<section v-if="settings" class="mt-6 max-w-xl dw-card">
<h2 class="text-ui-lg">Test</h2>
<p class="mt-1 text-ui-sm text-ink-muted">Sends a short email with the saved settings.</p>
<h2 class="text-ui-lg">{{ $t("email.test") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("email.testHint") }}</p>
<form class="mt-3 flex flex-wrap gap-2" @submit.prevent="sendTest">
<input v-model="testTo" type="email" required class="dw-input min-w-48 flex-1" aria-label="Send the test to" />
<DwButton type="submit">Send test email</DwButton>
<input v-model="testTo" type="email" required class="dw-input min-w-48 flex-1" :aria-label="$t('email.testTo')" />
<DwButton type="submit">{{ $t("email.sendTest") }}</DwButton>
</form>
<DwCallout v-if="testState" :tone="testState.ok ? 'success' : 'danger'" size="ui" class="mt-3">
{{ testState.text }}
+22 -18
View File
@@ -3,6 +3,7 @@
import { ApiError } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout, DwLogo, DwTextField } from "@docwell/ui";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { signIn } from "../session";
@@ -16,15 +17,7 @@ const code = ref("");
const error = ref("");
const busy = ref(false);
const messages: Record<string, string> = {
invalid_credentials: "Wrong email or password.",
forbidden: "Only organization admins and superadmins can use the admin panel.",
account_disabled: "This account is disabled.",
mfa_required:
"This account uses two-step sign-in. Sign in to the web app first; MFA for the admin panel is not supported yet.",
invalid_code: "That code is not right, or was already used.",
invalid_token: "That took too long. Sign in again.",
};
const { t, te } = useI18n();
async function submit() {
busy.value = true;
@@ -45,7 +38,12 @@ async function submit() {
return;
}
if (e instanceof ApiError && e.code === "invalid_token") challenge.value = "";
error.value = e instanceof ApiError ? (messages[e.code] ?? "Sign-in failed.") : "Can't reach the server.";
error.value =
e instanceof ApiError
? te(`login.errors.${e.code}`)
? t(`login.errors.${e.code}`)
: t("login.failed")
: t("common.cantReach");
} finally {
busy.value = false;
}
@@ -57,21 +55,27 @@ async function submit() {
<div class="w-full max-w-sm">
<div class="mb-8 flex items-center justify-center gap-2">
<DwLogo class="h-8" />
<DwBadge tone="accent">Admin</DwBadge>
<DwBadge tone="accent">{{ $t("shell.badge") }}</DwBadge>
</div>
<form class="space-y-4 dw-card" @submit.prevent="submit">
<h1 class="text-ui-lg">Sign in to the admin panel</h1>
<p class="text-ink-muted">Use an organization admin or superadmin account.</p>
<h1 class="text-ui-lg">{{ $t("login.title") }}</h1>
<p class="text-ink-muted">{{ $t("login.hint") }}</p>
<template v-if="!challenge">
<DwTextField v-model="email" label="Email" type="email" autocomplete="email" required />
<DwTextField v-model="password" label="Password" type="password" autocomplete="current-password" required />
<DwTextField v-model="email" :label="$t('common.email')" type="email" autocomplete="email" required />
<DwTextField
v-model="password"
:label="$t('common.password')"
type="password"
autocomplete="current-password"
required
/>
</template>
<template v-else>
<p data-testid="admin-totp">Enter the 6-digit code from your authenticator app, or a recovery code.</p>
<DwTextField v-model="code" label="Authenticator code" autocomplete="one-time-code" required />
<p data-testid="admin-totp">{{ $t("login.totpHint") }}</p>
<DwTextField v-model="code" :label="$t('login.code')" autocomplete="one-time-code" required />
</template>
<DwCallout v-if="error" tone="danger" size="ui">{{ error }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full" :disabled="busy">Sign in</DwButton>
<DwButton type="submit" variant="primary" class="w-full" :disabled="busy">{{ $t("login.submit") }}</DwButton>
</form>
</div>
</div>
+43 -34
View File
@@ -3,10 +3,12 @@
import type { Backup, Job } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
import { onBeforeUnmount, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { formatBytes, saveBlob } from "../settings";
import { api, errorMessage } from "../session";
// Backups of docwell-db and the server's background jobs.
const { t } = useI18n();
const backups = ref<Backup[]>([]);
const jobs = ref<Job[]>([]);
const error = ref("");
@@ -50,7 +52,7 @@ const download = (b: Backup) =>
saveBlob(blob, filename);
});
const remove = (b: Backup) => {
if (!confirm(`Delete the backup ${b.key}?`)) return;
if (!confirm(t("maintenance.confirmDelete", { key: b.key }))) return;
run(b.key, async () => {
await api.admin.deleteBackup(b.key);
await loadBackups();
@@ -66,30 +68,29 @@ const when = (s: string) => (s ? new Date(s.replace(" ", "T")).toLocaleString()
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Maintenance</h1>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("maintenance.title") }}</h1>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<section class="mt-6" data-testid="backups">
<div class="flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-ui-lg">Backups</h2>
<p class="text-ui-sm text-ink-muted">
A backup holds the whole database and its files. To restore one, stop Docwell and replace docwell-db's data
with the archive's contents.
</p>
<h2 class="text-ui-lg">{{ $t("maintenance.backups") }}</h2>
<p class="text-ui-sm text-ink-muted">{{ $t("maintenance.backupsHint") }}</p>
</div>
<DwButton variant="primary" :disabled="!!busy" @click="createBackup">
{{ busy === "create" ? "Creating…" : "Create backup" }}
{{ busy === "create" ? $t("maintenance.creating") : $t("maintenance.create") }}
</DwButton>
</div>
<div class="mt-3 overflow-x-auto rounded-md border border-line bg-surface-raised">
<table class="w-full text-left text-ui-md">
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
<tr>
<th class="px-4 py-2 font-medium">File</th>
<th class="px-4 py-2 font-medium">Size</th>
<th class="px-4 py-2 font-medium">Created</th>
<th class="px-4 py-2"><span class="sr-only">Actions</span></th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.file") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.size") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.created") }}</th>
<th class="px-4 py-2">
<span class="sr-only">{{ $t("common.actions") }}</span>
</th>
</tr>
</thead>
<tbody>
@@ -98,16 +99,16 @@ const when = (s: string) => (s ? new Date(s.replace(" ", "T")).toLocaleString()
<td class="px-4 py-2 tabular-nums">{{ formatBytes(b.size) }}</td>
<td class="px-4 py-2">{{ when(b.modified) }}</td>
<td class="px-4 py-2 text-right whitespace-nowrap">
<DwButton variant="ghost" size="sm" icon="download" :disabled="!!busy" @click="download(b)"
>Download</DwButton
>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="!!busy" @click="remove(b)"
>Delete</DwButton
>
<DwButton variant="ghost" size="sm" icon="download" :disabled="!!busy" @click="download(b)">{{
$t("common.download")
}}</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="!!busy" @click="remove(b)">{{
$t("common.delete")
}}</DwButton>
</td>
</tr>
<tr v-if="!backups.length">
<td colspan="4" class="px-4 py-6 text-center text-ink-muted">No backups yet.</td>
<td colspan="4" class="px-4 py-6 text-center text-ink-muted">{{ $t("maintenance.noBackups") }}</td>
</tr>
</tbody>
</table>
@@ -115,17 +116,19 @@ const when = (s: string) => (s ? new Date(s.replace(" ", "T")).toLocaleString()
</section>
<section class="mt-10" data-testid="jobs">
<h2 class="text-ui-lg">Background jobs</h2>
<p class="text-ui-sm text-ink-muted">Counted since the server started.</p>
<h2 class="text-ui-lg">{{ $t("maintenance.jobs") }}</h2>
<p class="text-ui-sm text-ink-muted">{{ $t("maintenance.jobsHint") }}</p>
<div class="mt-3 overflow-x-auto rounded-md border border-line bg-surface-raised">
<table class="w-full text-left text-ui-md">
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
<tr>
<th class="px-4 py-2 font-medium">Job</th>
<th class="px-4 py-2 font-medium">Runs</th>
<th class="px-4 py-2 font-medium">Last run</th>
<th class="px-4 py-2 font-medium">Status</th>
<th class="px-4 py-2"><span class="sr-only">Actions</span></th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.job") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.runs") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("maintenance.lastRun") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("common.status") }}</th>
<th class="px-4 py-2">
<span class="sr-only">{{ $t("common.actions") }}</span>
</th>
</tr>
</thead>
<tbody>
@@ -133,27 +136,33 @@ const when = (s: string) => (s ? new Date(s.replace(" ", "T")).toLocaleString()
<td class="px-4 py-2">
<div class="font-mono text-ui-sm">{{ j.name }}</div>
<div class="text-ui-sm text-ink-muted">
{{ j.description }}<template v-if="j.every"> · every {{ j.every }}</template>
{{ j.description
}}<template v-if="j.every"> · {{ $t("maintenance.every", { every: j.every }) }}</template>
</div>
</td>
<td class="px-4 py-2 tabular-nums">
{{ j.runs }}<span v-if="j.failures" class="text-danger"> ({{ j.failures }} failed)</span>
{{ j.runs
}}<span v-if="j.failures" class="text-danger">
{{ $t("maintenance.failedCount", { n: j.failures }) }}</span
>
</td>
<td class="px-4 py-2">
{{ when(j.lastStarted) }}
<div v-if="j.lastStarted" class="text-ui-sm text-ink-muted">{{ j.lastDurationMs }} ms</div>
</td>
<td class="px-4 py-2">
<DwBadge v-if="j.running" tone="accent">Running</DwBadge>
<DwBadge v-else-if="j.lastError" tone="danger" :title="j.lastError">Failed</DwBadge>
<DwBadge v-else-if="j.runs" tone="success">OK</DwBadge>
<DwBadge v-if="j.running" tone="accent">{{ $t("maintenance.running") }}</DwBadge>
<DwBadge v-else-if="j.lastError" tone="danger" :title="j.lastError">{{
$t("maintenance.failed")
}}</DwBadge>
<DwBadge v-else-if="j.runs" tone="success">{{ $t("maintenance.ok") }}</DwBadge>
<span v-else class="text-ink-muted">—</span>
<div v-if="j.lastError" class="mt-1 max-w-64 text-ui-sm break-words text-danger">{{ j.lastError }}</div>
</td>
<td class="px-4 py-2 text-right">
<DwButton v-if="j.runnable" size="sm" :disabled="!!busy || j.running" @click="runJob(j)"
>Run now</DwButton
>
<DwButton v-if="j.runnable" size="sm" :disabled="!!busy || j.running" @click="runJob(j)">{{
$t("maintenance.runNow")
}}</DwButton>
</td>
</tr>
</tbody>
+18 -20
View File
@@ -3,6 +3,7 @@
import type { Organization } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { api, currentUser, errorMessage, isSuperadmin, reloadUser } from "../session";
@@ -10,6 +11,7 @@ import { api, currentUser, errorMessage, isSuperadmin, reloadUser } from "../ses
// rename it, and delete it once they are its last member (they then drop back
// to a plain user and lose access to this panel). The server enforces all of it.
const router = useRouter();
const { t } = useI18n();
const orgs = ref<Organization[]>([]);
const error = ref("");
const busy = ref(false);
@@ -55,9 +57,7 @@ async function save() {
async function remove(o: Organization) {
const mine = !isSuperadmin.value && o.id === currentUser.value?.organization;
const msg = mine
? `Delete ${o.name}? You will become a regular user and lose access to the admin panel.`
: `Delete ${o.name}? This cannot be undone.`;
const msg = mine ? t("orgs.confirmDeleteMine", { name: o.name }) : t("orgs.confirmDelete", { name: o.name });
if (!confirm(msg)) return;
busy.value = true;
error.value = "";
@@ -80,44 +80,42 @@ async function remove(o: Organization) {
<template>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-2xl font-semibold tracking-tight">{{ isSuperadmin ? "Organizations" : "Organization" }}</h1>
<p class="mt-1 text-ink-muted">
{{
isSuperadmin
? "Every organization on this server. Admins of an organization manage only their own."
: "Your organization. You manage its members and all of its workspaces."
}}
</p>
<h1 class="text-2xl font-semibold tracking-tight">
{{ isSuperadmin ? $t("orgs.titleAll") : $t("orgs.titleOne") }}
</h1>
<p class="mt-1 text-ink-muted">{{ isSuperadmin ? $t("orgs.hintAll") : $t("orgs.hintOne") }}</p>
</div>
<DwButton v-if="isSuperadmin" variant="primary" @click="startNew">New organization</DwButton>
<DwButton v-if="isSuperadmin" variant="primary" @click="startNew">{{ $t("orgs.new") }}</DwButton>
</div>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<form v-if="editing" class="mt-4 flex flex-wrap items-end gap-2 dw-card !p-4" @submit.prevent="save">
<label class="flex flex-1 flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Name</span>
<span class="text-ui-sm font-semibold">{{ $t("common.name") }}</span>
<input v-model="draft" required maxlength="120" class="dw-input w-full" />
</label>
<DwButton type="submit" variant="primary" :disabled="busy || !draft.trim()">{{
editing === "new" ? "Create" : "Save"
editing === "new" ? $t("common.create") : $t("common.save")
}}</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">{{ $t("common.cancel") }}</DwButton>
</form>
<p v-if="!orgs.length && !error" class="mt-6 text-ui-md text-ink-muted">No organizations yet.</p>
<p v-if="!orgs.length && !error" class="mt-6 text-ui-md text-ink-muted">{{ $t("orgs.none") }}</p>
<ul v-else class="mt-6 divide-y divide-line rounded-md border border-line bg-surface-raised">
<li v-for="o in orgs" :key="o.id" class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
<div class="min-w-0">
<p class="truncate font-medium text-ink">{{ o.name }}</p>
<p class="text-ui-sm text-ink-muted">
{{ o.members }} {{ o.members === 1 ? "member" : "members" }} · {{ o.workspaces }}
{{ o.workspaces === 1 ? "workspace" : "workspaces" }}
{{ $t("orgs.members", { n: o.members }, o.members) }} ·
{{ $t("orgs.workspaces", { n: o.workspaces }, o.workspaces) }}
</p>
</div>
<div class="flex shrink-0 gap-1">
<DwButton variant="ghost" size="sm" @click="startEdit(o)">Rename</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="remove(o)">Delete</DwButton>
<DwButton variant="ghost" size="sm" @click="startEdit(o)">{{ $t("common.rename") }}</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="remove(o)">{{
$t("common.delete")
}}</DwButton>
</div>
</li>
</ul>
+22 -18
View File
@@ -3,9 +3,11 @@
import type { AdminHealth, AdminStats } from "@docwell/api-client";
import { DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { formatBytes } from "../settings";
import { api, errorMessage, isSuperadmin } from "../session";
const { t } = useI18n();
const stats = ref<AdminStats | null>(null);
const health = ref<AdminHealth | null>(null);
const error = ref("");
@@ -23,19 +25,19 @@ const cards = computed(() => {
const s = stats.value;
if (!s) return [];
const list = [
{ label: "Users", value: String(s.users), to: "/users" },
{ label: t("overview.users"), value: String(s.users), to: "/users" },
...(s.scope === "instance"
? [{ label: "Organizations", value: String(s.organizations), to: "/organizations" }]
? [{ label: t("overview.organizations"), value: String(s.organizations), to: "/organizations" }]
: []),
{ label: "Workspaces", value: String(s.workspaces) },
{ label: "Spaces", value: String(s.spaces) },
{ label: "Pages", value: String(s.pages) },
{ label: "Files", value: `${s.attachments} · ${formatBytes(s.storageBytes)}` },
{ label: t("overview.workspaces"), value: String(s.workspaces) },
{ label: t("overview.spaces"), value: String(s.spaces) },
{ label: t("overview.pages"), value: String(s.pages) },
{ label: t("overview.files"), value: `${s.attachments} · ${formatBytes(s.storageBytes)}` },
];
if (s.scope === "instance") {
list.push(
{ label: "Open now", value: `${s.rooms} page(s) · ${s.editors} editor(s)` },
{ label: "Search index", value: `${s.indexed} page(s)`, to: "/maintenance" },
{ label: t("overview.openNow"), value: t("overview.openNowValue", { rooms: s.rooms, editors: s.editors }) },
{ label: t("overview.searchIndex"), value: t("overview.indexed", { n: s.indexed }), to: "/maintenance" },
);
}
return list;
@@ -45,14 +47,14 @@ function uptime(sec: number) {
const d = Math.floor(sec / 86400);
const h = Math.floor((sec % 86400) / 3600);
const m = Math.floor((sec % 3600) / 60);
return d ? `${d} d ${h} h` : h ? `${h} h ${m} min` : `${m} min`;
return d ? t("overview.days", { d, h }) : h ? t("overview.hours", { h, m }) : t("overview.minutes", { m });
}
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Overview</h1>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("overview.title") }}</h1>
<p v-if="stats" class="mt-1 text-ink-muted">
{{ stats.scope === "instance" ? "The whole server." : "Your organization." }}
{{ stats.scope === "instance" ? $t("overview.instance") : $t("overview.org") }}
</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
@@ -71,22 +73,24 @@ function uptime(sec: number) {
</div>
<section v-if="health" class="mt-8" data-testid="health">
<h2 class="text-ui-lg">System</h2>
<h2 class="text-ui-lg">{{ $t("overview.system") }}</h2>
<dl class="mt-3 grid gap-x-8 gap-y-2 text-ui-md sm:grid-cols-[max-content_1fr]">
<dt class="text-ink-muted">Version</dt>
<dt class="text-ink-muted">{{ $t("overview.version") }}</dt>
<dd>
{{ health.version }} <span class="text-ink-muted">({{ health.goVersion }})</span>
</dd>
<dt class="text-ink-muted">Up for</dt>
<dt class="text-ink-muted">{{ $t("overview.upFor") }}</dt>
<dd>{{ uptime(health.uptimeSeconds) }}</dd>
<dt class="text-ink-muted">Database</dt>
<dt class="text-ink-muted">{{ $t("overview.database") }}</dt>
<dd :class="health.database.ok ? 'text-success' : 'text-danger'">
{{
health.database.ok ? `Connected · ${health.database.latencyMs} ms` : health.database.error || "Unavailable"
health.database.ok
? $t("overview.connected", { ms: health.database.latencyMs })
: health.database.error || $t("overview.unavailable")
}}
</dd>
<dt class="text-ink-muted">Memory</dt>
<dd>{{ health.memoryMb }} MB · {{ health.goroutines }} goroutines</dd>
<dt class="text-ink-muted">{{ $t("overview.memory") }}</dt>
<dd>{{ $t("overview.memoryValue", { mb: health.memoryMb, goroutines: health.goroutines }) }}</dd>
</dl>
</section>
</template>
+34 -33
View File
@@ -3,11 +3,13 @@
import type { ApiToken, AuditPage } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { saveBlob } from "../settings";
import { api, errorMessage, isSuperadmin } from "../session";
// The audit log and API tokens: everything for superadmins, their own
// organization for org admins (the server scopes both).
const { t } = useI18n();
const log = ref<AuditPage | null>(null);
const tokens = ref<ApiToken[]>([]);
const q = ref("");
@@ -57,10 +59,11 @@ const exportCsv = () =>
const { blob, filename } = await api.admin.exportAudit(filters());
saveBlob(blob, filename);
});
const revoke = (t: ApiToken) =>
const revoke = (tok: ApiToken) =>
run(async () => {
if (!confirm(`Revoke “${t.name}” of ${t.user?.email ?? "this user"}? Scripts using it stop working.`)) return;
await api.admin.revokeToken(t.id);
if (!confirm(t("security.confirmRevoke", { name: tok.name, email: tok.user?.email ?? t("security.thisUser") })))
return;
await api.admin.revokeToken(tok.id);
tokens.value = await api.admin.tokens();
});
@@ -69,25 +72,23 @@ const tone = (a: string) => (a.endsWith(".failed") ? "danger" : a.startsWith("au
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Security</h1>
<p class="mt-1 text-ink-muted">
Who changed what, sign-ins, and API tokens{{ isSuperadmin ? "" : " in your organization" }}.
</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("security.title") }}</h1>
<p class="mt-1 text-ink-muted">{{ isSuperadmin ? $t("security.hintAll") : $t("security.hintOrg") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<section class="dw-card mt-6" data-testid="audit-log">
<div class="flex flex-wrap items-end justify-between gap-3">
<h2 class="text-ui-lg">Audit log</h2>
<h2 class="text-ui-lg">{{ $t("security.auditLog") }}</h2>
<form class="flex flex-wrap items-end gap-2" @submit.prevent="search">
<input
v-model="q"
class="dw-input w-64"
placeholder="Action, email, id or IP"
aria-label="Search the audit log"
:placeholder="$t('security.searchPlaceholder')"
:aria-label="$t('security.searchLabel')"
data-testid="audit-search"
/>
<input v-model="since" type="date" class="dw-input" aria-label="Since" />
<DwButton type="submit" :disabled="busy">Search</DwButton>
<input v-model="since" type="date" class="dw-input" :aria-label="$t('security.since')" />
<DwButton type="submit" :disabled="busy">{{ $t("security.search") }}</DwButton>
<DwButton variant="ghost" icon="download" :disabled="busy" @click="exportCsv">CSV</DwButton>
</form>
</div>
@@ -96,11 +97,11 @@ const tone = (a: string) => (a.endsWith(".failed") ? "danger" : a.startsWith("au
<table class="w-full text-left text-ui-sm">
<thead class="text-ink-muted">
<tr>
<th class="py-1 pr-3 font-medium">Time</th>
<th class="py-1 pr-3 font-medium">Action</th>
<th class="py-1 pr-3 font-medium">Who</th>
<th class="py-1 pr-3 font-medium">Target</th>
<th class="py-1 font-medium">IP</th>
<th class="py-1 pr-3 font-medium">{{ $t("security.time") }}</th>
<th class="py-1 pr-3 font-medium">{{ $t("security.action") }}</th>
<th class="py-1 pr-3 font-medium">{{ $t("security.who") }}</th>
<th class="py-1 pr-3 font-medium">{{ $t("security.target") }}</th>
<th class="py-1 font-medium">{{ $t("security.ip") }}</th>
</tr>
</thead>
<tbody class="divide-y divide-line">
@@ -123,34 +124,34 @@ const tone = (a: string) => (a.endsWith(".failed") ? "danger" : a.startsWith("au
</template>
</tbody>
</table>
<p v-if="!log.items.length" class="mt-3 text-ui-sm text-ink-muted">Nothing matches.</p>
<p v-if="!log.items.length" class="mt-3 text-ui-sm text-ink-muted">{{ $t("security.nothing") }}</p>
<div v-if="log.total > perPage" class="mt-3 flex items-center gap-2 text-ui-sm">
<DwButton size="sm" :disabled="busy || page <= 1" @click="go(page - 1)">Newer</DwButton>
<span class="text-ink-muted">Page {{ page }} of {{ Math.ceil(log.total / perPage) }}</span>
<DwButton size="sm" :disabled="busy || page * perPage >= log.total" @click="go(page + 1)">Older</DwButton>
<DwButton size="sm" :disabled="busy || page <= 1" @click="go(page - 1)">{{ $t("security.newer") }}</DwButton>
<span class="text-ink-muted">{{ $t("common.pageOf", { page, total: Math.ceil(log.total / perPage) }) }}</span>
<DwButton size="sm" :disabled="busy || page * perPage >= log.total" @click="go(page + 1)">{{
$t("security.older")
}}</DwButton>
</div>
</div>
</section>
<section class="dw-card mt-6" data-testid="admin-tokens">
<h2 class="text-ui-lg">API tokens</h2>
<p class="mt-1 text-ui-sm text-ink-muted">
People create these in their account. Revoke any that should not work any more.
</p>
<h2 class="text-ui-lg">{{ $t("security.tokens") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("security.tokensHint") }}</p>
<ul v-if="tokens.length" class="mt-3 divide-y divide-line">
<li v-for="t in tokens" :key="t.id" class="flex flex-wrap items-center gap-3 py-2 text-ui-md">
<li v-for="tok in tokens" :key="tok.id" class="flex flex-wrap items-center gap-3 py-2 text-ui-md">
<span class="min-w-0 flex-1">
<span class="font-medium">{{ t.name }}</span>
<span class="text-ink-muted"> · {{ t.user?.email }}</span>
<span class="font-medium">{{ tok.name }}</span>
<span class="text-ink-muted"> · {{ tok.user?.email }}</span>
<span class="block text-ui-sm text-ink-muted">
<code class="font-mono">{{ t.prefix }}…</code> · {{ t.scope }} ·
{{ t.lastUsed ? `last used ${when(t.lastUsed)}` : "never used" }}
<template v-if="t.expires"> · expires {{ when(t.expires) }}</template>
<code class="font-mono">{{ tok.prefix }}…</code> · {{ tok.scope }} ·
{{ tok.lastUsed ? $t("security.lastUsed", { when: when(tok.lastUsed) }) : $t("security.neverUsed") }}
<template v-if="tok.expires"> · {{ $t("security.expires", { when: when(tok.expires) }) }}</template>
</span>
</span>
<DwButton size="sm" variant="danger" :disabled="busy" @click="revoke(t)">Revoke</DwButton>
<DwButton size="sm" variant="danger" :disabled="busy" @click="revoke(tok)">{{ $t("common.revoke") }}</DwButton>
</li>
</ul>
<p v-else class="mt-3 text-ui-sm text-ink-muted">No tokens.</p>
<p v-else class="mt-3 text-ui-sm text-ink-muted">{{ $t("security.noTokens") }}</p>
</section>
</template>
+19 -20
View File
@@ -2,11 +2,13 @@
<script setup lang="ts">
import { DwButton, DwCallout } from "@docwell/ui";
import { reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useInstanceSettings } from "../settings";
import { api, errorMessage } from "../session";
// Where uploaded files live: docwell-db's disk, or an S3-compatible bucket.
const { settings, error, saved, busy, save } = useInstanceSettings();
const { t } = useI18n();
const form = reactive({
s3: false,
bucket: "",
@@ -31,7 +33,7 @@ async function test() {
testState.value = null;
try {
await api.settings.testStorage();
testState.value = { ok: true, text: "The bucket is reachable." };
testState.value = { ok: true, text: t("storage.reachable") };
} catch (e) {
testState.value = { ok: false, text: errorMessage(e) };
}
@@ -39,60 +41,57 @@ async function test() {
</script>
<template>
<h1 class="text-2xl font-semibold tracking-tight">Storage</h1>
<p class="mt-1 text-ink-muted">Where images and attachments are kept.</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("storage.title") }}</h1>
<p class="mt-1 text-ink-muted">{{ $t("storage.hint") }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">Saved.</DwCallout>
<DwCallout tone="warning" size="ui" class="mt-4 max-w-xl">
Switching storage does not move existing files. Files uploaded before the switch stay where they were and cannot be
opened until they are copied over.
</DwCallout>
<DwCallout v-if="saved" tone="success" size="ui" class="mt-4">{{ $t("common.saved") }}</DwCallout>
<DwCallout tone="warning" size="ui" class="mt-4 max-w-xl">{{ $t("storage.warning") }}</DwCallout>
<form v-if="settings" class="mt-6 grid max-w-xl gap-4 dw-card sm:grid-cols-2" @submit.prevent="submit">
<fieldset class="space-y-2 sm:col-span-2">
<legend class="text-ui-sm font-semibold">Keep files</legend>
<legend class="text-ui-sm font-semibold">{{ $t("storage.keep") }}</legend>
<label class="flex items-center gap-2"
><input v-model="form.s3" type="radio" :value="false" class="accent-primary" /> On docwell-db's disk</label
><input v-model="form.s3" type="radio" :value="false" class="accent-primary" /> {{ $t("storage.disk") }}</label
>
<label class="flex items-center gap-2"
><input v-model="form.s3" type="radio" :value="true" class="accent-primary" /> In an S3-compatible bucket</label
><input v-model="form.s3" type="radio" :value="true" class="accent-primary" /> {{ $t("storage.s3") }}</label
>
</fieldset>
<template v-if="form.s3">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Endpoint</span>
<span class="text-ui-sm font-semibold">{{ $t("storage.endpoint") }}</span>
<input v-model="form.endpoint" required class="dw-input" placeholder="https://s3.eu-central-1.amazonaws.com" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Bucket</span>
<span class="text-ui-sm font-semibold">{{ $t("storage.bucket") }}</span>
<input v-model="form.bucket" required class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Region</span>
<span class="text-ui-sm font-semibold">{{ $t("storage.region") }}</span>
<input v-model="form.region" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Access key</span>
<span class="text-ui-sm font-semibold">{{ $t("storage.accessKey") }}</span>
<input v-model="form.accessKey" autocomplete="off" class="dw-input" />
</label>
<label class="flex flex-col gap-1.5 sm:col-span-2">
<span class="text-ui-sm font-semibold">Secret</span>
<span class="text-ui-sm font-semibold">{{ $t("storage.secret") }}</span>
<input
v-model="form.secret"
type="password"
autocomplete="new-password"
class="dw-input"
:placeholder="settings.storage.secretSet ? 'Unchanged' : ''"
:placeholder="settings.storage.secretSet ? $t('common.unchanged') : ''"
/>
</label>
<label class="flex items-center gap-3 sm:col-span-2">
<input v-model="form.forcePathStyle" type="checkbox" class="accent-primary" />
Path-style addressing (MinIO and some other servers need it)
{{ $t("storage.pathStyle") }}
</label>
</template>
<div class="flex gap-2 sm:col-span-2">
<DwButton type="submit" variant="primary" :disabled="busy">Save</DwButton>
<DwButton v-if="settings.storage.s3" @click="test">Test the saved bucket</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy">{{ $t("common.save") }}</DwButton>
<DwButton v-if="settings.storage.s3" @click="test">{{ $t("storage.test") }}</DwButton>
</div>
<DwCallout v-if="testState" :tone="testState.ok ? 'success' : 'danger'" size="ui" class="sm:col-span-2">
{{ testState.text }}
+59 -54
View File
@@ -3,6 +3,7 @@
import type { Organization, Role, User, UserList } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import InvitesPanel from "../components/InvitesPanel.vue";
import { api, currentUser, errorMessage, isSuperadmin } from "../session";
@@ -19,7 +20,8 @@ const error = ref("");
const busy = ref(false);
const roles = computed<Role[]>(() => (isSuperadmin.value ? ["user", "admin", "superadmin"] : ["user", "admin"]));
const roleLabel: Record<string, string> = { user: "User", admin: "Admin", superadmin: "Superadmin" };
const { t } = useI18n();
const roleLabel = (r: string) => t(`roles.${r}`);
async function load() {
error.value = "";
@@ -115,7 +117,7 @@ async function sendReset(u: User) {
notice.value = "";
try {
await api.users.sendPasswordReset(u.id);
notice.value = `A password reset link is on its way to ${u.email}.`;
notice.value = t("users.resetSent", { email: u.email });
} catch (e) {
error.value = errorMessage(e);
} finally {
@@ -124,18 +126,13 @@ async function sendReset(u: User) {
}
async function resetTotp(u: User) {
if (
!confirm(
`Turn off two-step sign-in for ${u.email}? They will sign in with their password alone until they set it up again.`,
)
)
return;
if (!confirm(t("users.confirmTotp", { email: u.email }))) return;
busy.value = true;
error.value = "";
notice.value = "";
try {
await api.users.resetTotp(u.id);
notice.value = `Two-step sign-in is off for ${u.email}.`;
notice.value = t("users.totpOff", { email: u.email });
await load();
} catch (e) {
error.value = errorMessage(e);
@@ -145,7 +142,7 @@ async function resetTotp(u: User) {
}
async function remove(u: User) {
if (!confirm(`Delete ${u.email}? This cannot be undone.`)) return;
if (!confirm(t("users.confirmDelete", { email: u.email }))) return;
busy.value = true;
error.value = "";
try {
@@ -162,25 +159,25 @@ async function remove(u: User) {
<template>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-2xl font-semibold tracking-tight">Users</h1>
<h1 class="text-2xl font-semibold tracking-tight">{{ $t("users.title") }}</h1>
<p class="mt-1 text-ink-muted">
{{ isSuperadmin ? "Everyone on this server." : `Members of ${currentUser?.organizationName}.` }}
{{ isSuperadmin ? $t("users.everyone") : $t("users.membersOf", { org: currentUser?.organizationName }) }}
</p>
</div>
<DwButton variant="primary" @click="startNew">New user</DwButton>
<DwButton variant="primary" @click="startNew">{{ $t("users.new") }}</DwButton>
</div>
<div class="mt-4 flex flex-wrap gap-2">
<input
v-model="search"
type="search"
placeholder="Search name or email"
aria-label="Search users"
:placeholder="$t('users.search')"
:aria-label="$t('users.searchLabel')"
class="dw-input sm:w-64"
/>
<select v-if="isSuperadmin" v-model="orgFilter" aria-label="Filter by organization" class="dw-input sm:w-56">
<option value="">All organizations</option>
<option value="none">No organization</option>
<select v-if="isSuperadmin" v-model="orgFilter" :aria-label="$t('users.filterOrg')" class="dw-input sm:w-56">
<option value="">{{ $t("users.allOrgs") }}</option>
<option value="none">{{ $t("common.noOrganization") }}</option>
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
</div>
@@ -191,17 +188,21 @@ async function remove(u: User) {
<DwCallout v-if="notice" tone="success" size="ui" class="mt-4">{{ notice }}</DwCallout>
<form v-if="editing" class="mt-4 grid gap-3 dw-card !p-4 sm:grid-cols-2" @submit.prevent="save">
<h2 class="text-ui-lg sm:col-span-2">{{ editing === "new" ? "New user" : `Edit ${editing.email}` }}</h2>
<h2 class="text-ui-lg sm:col-span-2">
{{ editing === "new" ? $t("users.new") : $t("users.editTitle", { email: editing.email }) }}
</h2>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Name</span>
<span class="text-ui-sm font-semibold">{{ $t("common.name") }}</span>
<input v-model="form.name" required class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Email</span>
<span class="text-ui-sm font-semibold">{{ $t("common.email") }}</span>
<input v-model="form.email" type="email" required class="dw-input" />
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ editing === "new" ? "Password" : "New password (optional)" }}</span>
<span class="text-ui-sm font-semibold">{{
editing === "new" ? $t("common.password") : $t("users.newPassword")
}}</span>
<input
v-model="form.password"
type="password"
@@ -212,31 +213,31 @@ async function remove(u: User) {
/>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Role</span>
<span class="text-ui-sm font-semibold">{{ $t("common.role") }}</span>
<select v-model="form.role" :disabled="isSelf" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel[r] }}</option>
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel(r) }}</option>
</select>
<span v-if="isSelf" class="text-ui-sm text-ink-muted">You cannot change your own role.</span>
<span v-if="isSelf" class="text-ui-sm text-ink-muted">{{ $t("users.ownRole") }}</span>
</label>
<label v-if="isSuperadmin" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Organization</span>
<span class="text-ui-sm font-semibold">{{ $t("common.organization") }}</span>
<select v-model="form.organization" class="dw-input">
<option value="">No organization</option>
<option value="">{{ $t("common.noOrganization") }}</option>
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
</label>
<label v-if="editing !== 'new'" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Status</span>
<span class="text-ui-sm font-semibold">{{ $t("common.status") }}</span>
<select v-model="form.status" :disabled="isSelf" class="dw-input">
<option value="active">Active</option>
<option value="disabled">Disabled</option>
<option value="active">{{ $t("userStatus.active") }}</option>
<option value="disabled">{{ $t("userStatus.disabled") }}</option>
</select>
</label>
<div class="flex gap-2 sm:col-span-2">
<DwButton type="submit" variant="primary" :disabled="busy">{{
editing === "new" ? "Create user" : "Save"
editing === "new" ? $t("users.createUser") : $t("common.save")
}}</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">{{ $t("common.cancel") }}</DwButton>
</div>
</form>
@@ -244,34 +245,36 @@ async function remove(u: User) {
<table class="w-full text-left text-ui-md">
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
<tr>
<th class="px-4 py-2 font-medium">Name</th>
<th class="px-4 py-2 font-medium">Email</th>
<th class="px-4 py-2 font-medium">Role</th>
<th v-if="isSuperadmin" class="px-4 py-2 font-medium">Organization</th>
<th class="px-4 py-2 font-medium">Status</th>
<th class="px-4 py-2"><span class="sr-only">Actions</span></th>
<th class="px-4 py-2 font-medium">{{ $t("common.name") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("common.email") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("common.role") }}</th>
<th v-if="isSuperadmin" class="px-4 py-2 font-medium">{{ $t("common.organization") }}</th>
<th class="px-4 py-2 font-medium">{{ $t("common.status") }}</th>
<th class="px-4 py-2">
<span class="sr-only">{{ $t("common.actions") }}</span>
</th>
</tr>
</thead>
<tbody>
<tr v-for="u in list?.items" :key="u.id" class="border-t border-line">
<td class="px-4 py-2 font-medium">{{ u.name }}</td>
<td class="px-4 py-2">{{ u.email }}</td>
<td class="px-4 py-2">{{ roleLabel[u.role] }}</td>
<td class="px-4 py-2">{{ roleLabel(u.role) }}</td>
<td v-if="isSuperadmin" class="px-4 py-2">{{ u.organizationName || "—" }}</td>
<td class="px-4 py-2">
<DwBadge
:tone="u.status === 'active' ? 'success' : u.status === 'disabled' ? 'danger' : 'neutral'"
class="capitalize"
>{{ u.status }}</DwBadge
>
<DwBadge :tone="u.status === 'active' ? 'success' : u.status === 'disabled' ? 'danger' : 'neutral'">{{
$t(`userStatus.${u.status}`)
}}</DwBadge>
</td>
<td class="px-4 py-2 text-right whitespace-nowrap">
<template v-if="canEdit(u)">
<DwButton variant="ghost" size="sm" @click="startEdit(u)">Edit</DwButton>
<DwButton variant="ghost" size="sm" :disabled="busy" @click="sendReset(u)">Reset password</DwButton>
<DwButton v-if="u.totp" variant="ghost" size="sm" :disabled="busy" @click="resetTotp(u)"
>Turn off two-step</DwButton
>
<DwButton variant="ghost" size="sm" @click="startEdit(u)">{{ $t("common.edit") }}</DwButton>
<DwButton variant="ghost" size="sm" :disabled="busy" @click="sendReset(u)">{{
$t("users.resetPassword")
}}</DwButton>
<DwButton v-if="u.totp" variant="ghost" size="sm" :disabled="busy" @click="resetTotp(u)">{{
$t("users.turnOffTotp")
}}</DwButton>
<DwButton
v-if="u.id !== currentUser?.id"
variant="ghost"
@@ -280,21 +283,23 @@ async function remove(u: User) {
:disabled="busy"
@click="remove(u)"
>
Delete
{{ $t("common.delete") }}
</DwButton>
</template>
</td>
</tr>
<tr v-if="list && list.items.length === 0">
<td :colspan="isSuperadmin ? 6 : 5" class="px-4 py-6 text-center text-ink-muted">No users found.</td>
<td :colspan="isSuperadmin ? 6 : 5" class="px-4 py-6 text-center text-ink-muted">
{{ $t("users.none") }}
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="list && list.totalItems > perPage" class="mt-4 flex items-center gap-3 text-ui-md">
<DwButton size="sm" :disabled="page <= 1" @click="page--">Previous</DwButton>
<span class="text-ink-muted">Page {{ page }} of {{ Math.ceil(list.totalItems / perPage) }}</span>
<DwButton size="sm" :disabled="page * perPage >= list.totalItems" @click="page++">Next</DwButton>
<DwButton size="sm" :disabled="page <= 1" @click="page--">{{ $t("common.previous") }}</DwButton>
<span class="text-ink-muted">{{ $t("common.pageOf", { page, total: Math.ceil(list.totalItems / perPage) }) }}</span>
<DwButton size="sm" :disabled="page * perPage >= list.totalItems" @click="page++">{{ $t("common.next") }}</DwButton>
</div>
</template>
+4 -1
View File
@@ -2,7 +2,7 @@
import tailwindcss from "@tailwindcss/vite";
import vue from "@vitejs/plugin-vue";
import { defineConfig } from "vite";
import { defineConfig } from "vitest/config";
// DOCWELL_DEV_API points the dev proxy at another docwell-server.
// The config runs in Node, but this tsconfig has no Node types.
@@ -24,4 +24,7 @@ export default defineConfig({
"/readyz": api,
},
},
test: {
environment: "jsdom",
},
});
+13 -3
View File
@@ -1911,7 +1911,10 @@ type WebhookInput struct {
// Workspace defines model for Workspace.
type Workspace struct {
Created string `json:"created"`
Created string `json:"created"`
// DefaultPageMode The view new pages of the workspace open in
DefaultPageMode PageMode `json:"defaultPageMode"`
Id string `json:"id"`
Name string `json:"name"`
Organization string `json:"organization"`
@@ -2257,6 +2260,13 @@ type CreateWorkspaceJSONBody struct {
Organization *string `json:"organization,omitempty"`
}
// UpdateWorkspaceJSONBody defines parameters for UpdateWorkspace.
type UpdateWorkspaceJSONBody struct {
// DefaultPageMode The view a page opens in for everyone, its text or the edgeless canvas; "?mode=" in an address overrides it
DefaultPageMode *PageMode `json:"defaultPageMode,omitempty"`
Name *string `json:"name,omitempty"`
}
// ListDocsParams defines parameters for ListDocs.
type ListDocsParams struct {
// Space Only pages in this space
@@ -2493,8 +2503,8 @@ type UpdateWebhookJSONRequestBody = WebhookInput
// CreateWorkspaceJSONRequestBody defines body for CreateWorkspace for application/json ContentType.
type CreateWorkspaceJSONRequestBody CreateWorkspaceJSONBody
// RenameWorkspaceJSONRequestBody defines body for RenameWorkspace for application/json ContentType.
type RenameWorkspaceJSONRequestBody = NameRequest
// UpdateWorkspaceJSONRequestBody defines body for UpdateWorkspace for application/json ContentType.
type UpdateWorkspaceJSONRequestBody UpdateWorkspaceJSONBody
// CreateCollectionJSONRequestBody defines body for CreateCollection for application/json ContentType.
type CreateCollectionJSONRequestBody = CollectionInput
+236 -8
View File
@@ -4,6 +4,8 @@ package convert
import (
"encoding/json"
"math"
"sort"
"strings"
"time"
)
@@ -14,16 +16,35 @@ import (
// columns, in the rows' own order.
// expandDatabases replaces database nodes, at any depth, with a title and a table.
// Relations and rollups read the page's other databases; one on another page
// shows how many records it links to.
func expandDatabases(n Node) Node {
all := map[string]map[string]any{}
var collect func(Node)
collect = func(x Node) {
if x.Type == "database" {
if data, _ := x.Attrs["data"].(map[string]any); data != nil {
all[str(x.Attrs["id"])] = data
}
}
for _, c := range x.Content {
collect(c)
}
}
collect(n)
return expandWith(n, all)
}
func expandWith(n Node, all map[string]map[string]any) Node {
if len(n.Content) == 0 {
return n
}
out := make([]Node, 0, len(n.Content))
for _, c := range n.Content {
if c.Type == "database" {
out = append(out, databaseNodes(c)...)
out = append(out, databaseNodes(c, all)...)
} else {
out = append(out, expandDatabases(c))
out = append(out, expandWith(c, all))
}
}
n.Content = out
@@ -33,13 +54,13 @@ func expandDatabases(n Node) Node {
type dbColumn struct {
id, name, typ string
options map[string]string
// relation: the related database (same page only; empty when on another page).
relPage, relDB string
// rollup: the relation column, the related property ("" = the records) and the function.
rollRel, rollProp, rollFn string
}
func databaseNodes(n Node) []Node {
data, _ := n.Attrs["data"].(map[string]any)
if data == nil {
return nil
}
func readColumns(data map[string]any) []dbColumn {
var cols []dbColumn
for _, raw := range list(data["columns"]) {
c, _ := raw.(map[string]any)
@@ -53,8 +74,23 @@ func databaseNodes(n Node) []Node {
col.options[str(om["id"])] = str(om["name"])
}
}
if r, ok := c["relation"].(map[string]any); ok {
col.relPage, col.relDB = str(r["page"]), str(r["database"])
}
if r, ok := c["rollup"].(map[string]any); ok {
col.rollRel, col.rollProp, col.rollFn = str(r["relation"]), str(r["property"]), str(r["fn"])
}
cols = append(cols, col)
}
return cols
}
func databaseNodes(n Node, all map[string]map[string]any) []Node {
data, _ := n.Attrs["data"].(map[string]any)
if data == nil {
return nil
}
cols := readColumns(data)
// The first view decides which columns show.
hidden := map[string]bool{}
if views := list(data["views"]); len(views) > 0 {
@@ -93,7 +129,14 @@ func databaseNodes(n Node) []Node {
}
row := Node{Type: "tableRow"}
for _, c := range shown {
row.Content = append(row.Content, cell("tableCell", cellText(c, r)))
text := cellText(c, r)
switch c.typ {
case "relation":
text = relationText(c, r, all)
case "rollup":
text = rollupText(c, cols, r, all)
}
row.Content = append(row.Content, cell("tableCell", text))
}
table.Content = append(table.Content, row)
}
@@ -256,3 +299,188 @@ func jsonText(v any, parts []string) []string {
}
return parts
}
// related returns the rows a relation cell links to and the related
// database's columns; ok is false when the database is on another page.
func related(c dbColumn, row map[string]any, all map[string]map[string]any) (rows []map[string]any, cols []dbColumn, ids []string, ok bool) {
cells, _ := row["cells"].(map[string]any)
for _, id := range list(cells[c.id]) {
if s := str(id); s != "" {
ids = append(ids, s)
}
}
target := all[c.relDB]
if c.relPage != "" || target == nil {
return nil, nil, ids, false
}
byID := map[string]map[string]any{}
for _, raw := range list(target["rows"]) {
if r, _ := raw.(map[string]any); r != nil {
byID[str(r["id"])] = r
}
}
for _, id := range ids {
if r := byID[id]; r != nil {
rows = append(rows, r)
}
}
return rows, readColumns(target), ids, true
}
func titleOf(cols []dbColumn) *dbColumn {
for i := range cols {
if cols[i].typ == "title" {
return &cols[i]
}
}
return nil
}
// relationText is the related records' titles, like computeLinked in linked.ts.
func relationText(c dbColumn, row map[string]any, all map[string]map[string]any) string {
rows, cols, ids, ok := related(c, row, all)
if !ok {
if len(ids) == 0 {
return ""
}
return formatNumber(float64(len(ids))) + " linked"
}
title := titleOf(cols)
var names []string
for _, r := range rows {
if title != nil {
names = append(names, cellText(*title, r))
}
}
return strings.Join(names, ", ")
}
// rollupText works out a rollup cell, like rollup in linked.ts.
func rollupText(c dbColumn, cols []dbColumn, row map[string]any, all map[string]map[string]any) string {
var rel *dbColumn
for i := range cols {
if cols[i].id == c.rollRel && cols[i].typ == "relation" {
rel = &cols[i]
}
}
if rel == nil {
return ""
}
rows, tcols, _, ok := related(*rel, row, all)
if !ok {
return ""
}
prop := titleOf(tcols)
if c.rollProp != "" {
prop = nil
for i := range tcols {
if tcols[i].id == c.rollProp {
prop = &tcols[i]
}
}
}
var texts []string
var nums []float64
var dates []string
checked := 0
for _, r := range rows {
if prop == nil {
texts = append(texts, "")
continue
}
t := cellText(*prop, r)
cells, _ := r["cells"].(map[string]any)
if prop.typ == "checkbox" {
if cells[prop.id] == true {
checked++
t = "✓"
} else {
t = ""
}
}
texts = append(texts, t)
if f, ok := cells[prop.id].(float64); ok {
nums = append(nums, f)
}
if len(t) >= 10 && (prop.typ == "date" || prop.typ == "createdTime") {
dates = append(dates, t[:10])
}
}
filled := 0
unique := map[string]bool{}
for _, t := range texts {
if t != "" {
filled++
unique[t] = true
}
}
sort.Float64s(nums)
sort.Strings(dates)
num := func(f float64) string { return formatNumber(math.Round(f*100) / 100) }
pct := func(n int) string {
if len(rows) == 0 {
return ""
}
return num(float64(n)*100/float64(len(rows))) + "%"
}
sum := 0.0
for _, f := range nums {
sum += f
}
switch c.rollFn {
case "count", "":
return num(float64(len(rows)))
case "countValues", "countNotEmpty":
return num(float64(filled))
case "countUnique":
return num(float64(len(unique)))
case "countEmpty":
return num(float64(len(rows) - filled))
case "percentNotEmpty":
return pct(filled)
case "checked":
return num(float64(checked))
case "percentChecked":
return pct(checked)
case "earliest":
if len(dates) > 0 {
return dates[0]
}
return ""
case "latest":
if len(dates) > 0 {
return dates[len(dates)-1]
}
return ""
case "showOriginal":
var shown []string
for _, t := range texts {
if t != "" {
shown = append(shown, t)
}
}
return strings.Join(shown, ", ")
}
if len(nums) == 0 {
return ""
}
switch c.rollFn {
case "sum":
return num(sum)
case "average":
return num(sum / float64(len(nums)))
case "median":
m := len(nums) / 2
if len(nums)%2 == 1 {
return num(nums[m])
}
return num((nums[m-1] + nums[m]) / 2)
case "min":
return num(nums[0])
case "max":
return num(nums[len(nums)-1])
case "range":
return num(nums[len(nums)-1] - nums[0])
}
return ""
}
+23
View File
@@ -73,3 +73,26 @@ func TestRecordsForSearch(t *testing.T) {
}
}
}
func TestRelationsAndRollupsExport(t *testing.T) {
doc, err := Parse([]byte(`{"type":"doc","content":[
{"type":"database","attrs":{"id":"p","data":{"title":"Projects",
"columns":[{"id":"t","name":"Name","type":"title"},
{"id":"rel","name":"Tasks","type":"relation","relation":{"page":"","database":"k"}},
{"id":"n","name":"Hours","type":"rollup","rollup":{"relation":"rel","property":"h","fn":"sum"}},
{"id":"d","name":"Done","type":"rollup","rollup":{"relation":"rel","property":"c","fn":"percentChecked"}},
{"id":"far","name":"Elsewhere","type":"relation","relation":{"page":"other","database":"x"}}],
"rows":[{"id":"p1","cells":{"t":"Launch","rel":["k1","k2","gone"],"far":["a","b"]}}],
"views":[{"id":"v","type":"table"}]}}},
{"type":"database","attrs":{"id":"k","data":{"title":"Tasks",
"columns":[{"id":"t","name":"Name","type":"title"},{"id":"h","name":"Hours","type":"number"},{"id":"c","name":"Done","type":"checkbox"}],
"rows":[{"id":"k1","cells":{"t":"Write","h":2.5,"c":true}},{"id":"k2","cells":{"t":"Ship","h":4}}],
"views":[{"id":"v","type":"table"}]}}}]}`))
if err != nil {
t.Fatal(err)
}
md := Markdown(doc, Options{})
if want := "| Launch | Write, Ship | 6.5 | 50% | 2 linked |"; !strings.Contains(md, want) {
t.Errorf("markdown lacks %q:\n%s", want, md)
}
}
+45 -9
View File
@@ -552,6 +552,8 @@ type Workspace struct {
// Role is the caller's effective role after the cascade.
Role string `json:"role"`
Created string `json:"created"`
// DefaultPageMode is the view new pages open in: "page" or "edgeless".
DefaultPageMode string `json:"defaultPageMode"`
}
type workspaceRecord struct {
@@ -560,7 +562,9 @@ type workspaceRecord struct {
Slug string `json:"slug"`
Organization string `json:"organization"`
Created string `json:"created"`
Expand struct {
// DefaultPageMode is "edgeless" when new pages open as a canvas.
DefaultPageMode string `json:"default_page_mode"`
Expand struct {
Organization *struct {
Name string `json:"name"`
} `json:"organization"`
@@ -568,7 +572,10 @@ type workspaceRecord struct {
}
func (r workspaceRecord) view(role string) Workspace {
w := Workspace{ID: r.ID, Name: r.Name, Slug: r.Slug, Organization: r.Organization, Role: role, Created: r.Created}
w := Workspace{
ID: r.ID, Name: r.Name, Slug: r.Slug, Organization: r.Organization, Role: role, Created: r.Created,
DefaultPageMode: pageMode(r.DefaultPageMode),
}
if r.Expand.Organization != nil {
w.OrganizationName = r.Expand.Organization.Name
}
@@ -732,11 +739,32 @@ func slugify(name, fallback string) string {
return s
}
// RenameWorkspace renames a workspace (workspace admin or above).
func (s *Service) RenameWorkspace(ctx context.Context, c access.Caller, id, name string) (Workspace, error) {
name, err := cleanName(name, "Workspace")
if err != nil {
return Workspace{}, err
type UpdateWorkspaceInput struct {
Name *string `json:"name"`
// DefaultPageMode is "page" or "edgeless": how new pages open.
DefaultPageMode *string `json:"defaultPageMode"`
}
// UpdateWorkspace renames a workspace or changes how its new pages open
// (workspace admin or above).
func (s *Service) UpdateWorkspace(ctx context.Context, c access.Caller, id string, in UpdateWorkspaceInput) (Workspace, error) {
patch := map[string]any{}
if in.Name != nil {
name, err := cleanName(*in.Name, "Workspace")
if err != nil {
return Workspace{}, err
}
patch["name"] = name
}
if in.DefaultPageMode != nil {
switch *in.DefaultPageMode {
case "page":
patch["default_page_mode"] = ""
case "edgeless":
patch["default_page_mode"] = "edgeless"
default:
return Workspace{}, apperr.InvalidFields(map[string]string{"defaultPageMode": "Mode must be page or edgeless."})
}
}
ws, role, err := s.workspaceFor(ctx, c, id)
if err != nil {
@@ -745,10 +773,18 @@ func (s *Service) RenameWorkspace(ctx context.Context, c access.Caller, id, name
if err := access.RenameWorkspace(role); err != nil {
return Workspace{}, err
}
if _, err := pocketbase.Update[workspaceRecord](ctx, s.pb, "workspaces", ws.ID, map[string]any{"name": name}); err != nil {
if len(patch) == 0 {
return ws.view(role), nil
}
if _, err := pocketbase.Update[workspaceRecord](ctx, s.pb, "workspaces", ws.ID, patch); err != nil {
return Workspace{}, mapPB(err, "workspace not found")
}
ws.Name = name
if v, ok := patch["name"].(string); ok {
ws.Name = v
}
if v, ok := patch["default_page_mode"].(string); ok {
ws.DefaultPageMode = v
}
return ws.view(role), nil
}
+4
View File
@@ -431,6 +431,10 @@ func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID strin
if in.Parent != "" {
body["parent"] = in.Parent
}
// New pages open the way their workspace says (ADR-14).
if ws, err := s.getWorkspace(ctx, a.space.Workspace); err == nil && ws.DefaultPageMode == "edgeless" {
body["default_mode"] = "edgeless"
}
rec, err := pocketbase.Create[pageRecord](ctx, s.pb, "pages", body)
if err != nil {
return Page{}, mapPB(err, "page not found")
+1 -1
View File
@@ -77,7 +77,7 @@ func (f fakeDir) DeleteOrg(context.Context, access.Caller, string) error {
return apperr.Forbidden("you can only delete your own organization")
}
func (f fakeDir) RenameWorkspace(context.Context, access.Caller, string, string) (directory.Workspace, error) {
func (f fakeDir) UpdateWorkspace(context.Context, access.Caller, string, directory.UpdateWorkspaceInput) (directory.Workspace, error) {
return directory.Workspace{}, apperr.NotFound("workspace not found")
}
+3 -3
View File
@@ -26,7 +26,7 @@ type DirectoryService interface {
ListWorkspaces(ctx context.Context, c access.Caller) ([]directory.Workspace, error)
CreateWorkspace(ctx context.Context, c access.Caller, in directory.CreateWorkspaceInput) (directory.Workspace, error)
RenameWorkspace(ctx context.Context, c access.Caller, id, name string) (directory.Workspace, error)
UpdateWorkspace(ctx context.Context, c access.Caller, id string, in directory.UpdateWorkspaceInput) (directory.Workspace, error)
DeleteWorkspace(ctx context.Context, c access.Caller, id string) error
ListMembers(ctx context.Context, c access.Caller, wsID string) ([]directory.Member, error)
SetMember(ctx context.Context, c access.Caller, wsID, email, role string) (directory.Member, error)
@@ -124,11 +124,11 @@ func (a *api) directoryRoutes(mux *routeMux) {
a.respondStatus(w, http.StatusCreated, ws, err)
}))
mux.HandleFunc("PATCH /api/v1/workspaces/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Name string }
var in directory.UpdateWorkspaceInput
if !a.decode(w, r, &in) {
return
}
ws, err := a.dir.RenameWorkspace(r.Context(), caller(r), r.PathValue("id"), in.Name)
ws, err := a.dir.UpdateWorkspace(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, ws, err)
}))
mux.HandleFunc("DELETE /api/v1/workspaces/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+14
View File
@@ -477,6 +477,20 @@
"required": true,
"system": false,
"type": "relation"
},
{
"help": "",
"hidden": false,
"id": "select2171368406",
"maxSelect": 1,
"name": "default_page_mode",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"edgeless"
]
}
],
"id": "pbc_2170078043",
@@ -1,11 +1,12 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Page, PageVersion } from "@docwell/api-client";
import { DocwellEditor, type JSONContent } from "@docwell/editor";
import { DocwellEdgeless, DocwellEditor, hasSurface, surfaceOfJSON, type JSONContent } from "@docwell/editor";
import { DwButton, DwIcon } from "@docwell/ui";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { useEditorLabels } from "../composables/useEditorHosts";
import { diffDocs, diffStats, type DiffRow } from "../lib/diff";
// The page's saved versions, with a read-only preview, the changes against
@@ -20,7 +21,27 @@ const versions = ref<PageVersion[] | null>(null);
const selected = ref<PageVersion | null>(null);
const preview = ref<JSONContent | null>(null);
const busy = ref(false);
const view = ref<"preview" | "changes">("preview");
const view = ref<"preview" | "canvas" | "changes">("preview");
const labels = useEditorLabels();
// Versions with an edgeless canvas (ADR-14) can be looked at as one too.
const hasCanvas = computed(() => hasSurface(preview.value));
watch(hasCanvas, (on) => !on && view.value === "canvas" && (view.value = "preview"));
/** Canvas elements added, removed and changed between two versions, by element id. */
function canvasChanges(before: JSONContent | null, after: JSONContent | null) {
const map = (doc: JSONContent | null) => new Map(surfaceOfJSON(doc).map((e) => [e.id, JSON.stringify(e)]));
const a = map(before);
const b = map(after);
let added = 0;
let removed = 0;
let changed = 0;
for (const [id, json] of b) {
if (!a.has(id)) added++;
else if (a.get(id) !== json) changed++;
}
for (const id of a.keys()) if (!b.has(id)) removed++;
return { added, removed, changed };
}
const against = ref<"previous" | "current">("previous");
const base = ref<JSONContent | null | undefined>(undefined);
@@ -89,6 +110,12 @@ const rows = computed<DiffRow[] | null>(() => {
});
const stats = computed(() => (rows.value ? diffStats(rows.value) : null));
const changedRows = computed(() => rows.value?.filter((r) => r.change !== "same") ?? []);
const canvasStats = computed(() => {
if (!preview.value || base.value === undefined) return null;
const c =
against.value === "current" ? canvasChanges(preview.value, base.value) : canvasChanges(base.value, preview.value);
return c.added || c.removed || c.changed ? c : null;
});
async function restore() {
const v = selected.value;
@@ -165,6 +192,17 @@ const tab =
>
{{ $t("page.history.preview") }}
</button>
<button
v-if="hasCanvas"
type="button"
role="tab"
:class="tab"
:aria-selected="view === 'canvas'"
data-testid="history-canvas"
@click="view = 'canvas'"
>
{{ $t("edgeless.canvas") }}
</button>
<button
type="button"
role="tab"
@@ -184,7 +222,18 @@ const tab =
</label>
</div>
<div class="max-h-96 overflow-y-auto rounded-sm border border-line px-4 py-3">
<div v-if="view === 'canvas'" class="h-96 overflow-hidden rounded-sm border border-line">
<DocwellEdgeless
v-if="preview"
:key="selected.id"
:content="preview"
:editable="false"
:labels="labels"
:page-title="page.title || $t('home.untitled')"
data-testid="version-canvas"
/>
</div>
<div v-else class="max-h-96 overflow-y-auto rounded-sm border border-line px-4 py-3">
<template v-if="view === 'preview'">
<DocwellEditor
v-if="preview"
@@ -199,8 +248,11 @@ const tab =
<template v-if="against === 'previous' && base === null">{{
$t("page.history.firstVersion")
}}</template>
<template v-else-if="!changedRows.length">{{ $t("page.history.noChanges") }}</template>
<template v-else>{{ $t("page.history.stats", stats) }}</template>
<template v-else-if="changedRows.length">{{ $t("page.history.stats", stats) }}</template>
<template v-else-if="!canvasStats">{{ $t("page.history.noChanges") }}</template>
</p>
<p v-if="canvasStats" class="mb-2 text-ui-sm text-ink-muted" data-testid="canvas-diff">
{{ $t("page.history.canvasStats", canvasStats) }}
</p>
<ol class="flex flex-col gap-1 text-ui-md" data-testid="version-diff">
<li
+49 -3
View File
@@ -185,7 +185,9 @@
"invitedBy": "eingeladen von {name}",
"inviteExpired": "abgelaufen",
"resend": "Erneut senden",
"revoke": "Zurückziehen"
"revoke": "Zurückziehen",
"pageMode": "Neue Seiten öffnen als",
"pageModeHint": "Jede Seite lässt sich weiter umschalten, und jede Person kann für Seiten, die sie auf ihrem Gerät anlegt, anders wählen."
},
"space": {
"new": "Neuer Bereich",
@@ -275,7 +277,8 @@
"added": "Hinzugefügt",
"removed": "Entfernt",
"changed": "Bearbeitet"
}
},
"canvasStats": "Tafel: {added} hinzugefügt, {removed} entfernt, {changed} geändert"
},
"notFound": "Diese Seite existiert nicht oder du hast keinen Zugriff darauf.",
"favorite": "Zu Favoriten hinzufügen",
@@ -714,6 +717,47 @@
"typeMember": "Person",
"typeCreatedTime": "Erstellt am",
"typeCreatedBy": "Erstellt von",
"typeRelation": "Relation",
"typeRollup": "Rollup",
"linkedCount": "{n} verknüpft",
"rollupDays": "{n} Tage",
"relationTo": "Verknüpfte Datenbank",
"relationPick": "Datenbank wählen",
"relationThisPage": "Auf dieser Seite",
"relationOtherPage": "Auf einer anderen Seite…",
"relationSearchPage": "Seite suchen",
"relationNoDatabases": "Keine Datenbanken auf dieser Seite",
"relationMissing": "Die verknüpfte Datenbank ist nicht verfügbar.",
"linkRecord": "Eintrag verknüpfen",
"searchRecords": "Einträge suchen",
"noRecords": "Keine Einträge",
"openRelated": "Eintrag öffnen",
"rollupSettings": "Rollup",
"rollupRelation": "Relation",
"rollupProperty": "Eigenschaft",
"rollupFn": "Berechnen",
"rollupRecords": "Einträge",
"rollupNeedsRelation": "Füge zuerst eine Relation hinzu.",
"fnShowOriginal": "Werte anzeigen",
"fnCount": "Einträge zählen",
"fnCountValues": "Werte zählen",
"fnCountUnique": "Eindeutige Werte zählen",
"fnCountEmpty": "Leere zählen",
"fnCountNotEmpty": "Nicht leere zählen",
"fnPercentNotEmpty": "Prozent nicht leer",
"fnSum": "Summe",
"fnAverage": "Durchschnitt",
"fnMedian": "Median",
"fnMin": "Minimum",
"fnMax": "Maximum",
"fnRange": "Spanne",
"fnEarliest": "Frühestes Datum",
"fnLatest": "Spätestes Datum",
"fnChecked": "Angehakt",
"fnPercentChecked": "Prozent angehakt",
"openFullPage": "Als ganze Seite öffnen",
"backToPage": "Zurück zur Seite",
"recordNotFound": "Dieser Eintrag ist nicht mehr in der Datenbank.",
"opContains": "enthält",
"opNotContains": "enthält nicht",
"opIs": "ist",
@@ -850,6 +894,7 @@
"copy": "Kopieren",
"editText": "Text bearbeiten",
"openLink": "Link öffnen",
"comment": "Kommentieren",
"frameTitle": "Rahmen",
"groupTitle": "Gruppe",
"linkPrompt": "Linkadresse",
@@ -1004,7 +1049,8 @@
"newPageMode": "Neue Seiten öffnen als",
"modes": {
"page": "Seite",
"edgeless": "Tafel"
"edgeless": "Tafel",
"workspace": "Wie im Arbeitsbereich"
},
"edgelessStyles": "Stile der Tafel",
"edgelessStylesHint": "Neue Formen, Linien und Notizen sehen aus wie die zuletzt gestalteten.",
+49 -3
View File
@@ -185,7 +185,9 @@
"invitedBy": "invited by {name}",
"inviteExpired": "expired",
"resend": "Resend",
"revoke": "Revoke"
"revoke": "Revoke",
"pageMode": "New pages open as",
"pageModeHint": "Each page can still be switched, and each person can choose otherwise for the pages they make on their device."
},
"space": {
"new": "New space",
@@ -275,7 +277,8 @@
"added": "Added",
"removed": "Removed",
"changed": "Edited"
}
},
"canvasStats": "Canvas: {added} added, {removed} removed, {changed} changed"
},
"notFound": "This page does not exist or you don't have access to it.",
"favorite": "Add to favorites",
@@ -714,6 +717,47 @@
"typeMember": "Member",
"typeCreatedTime": "Created time",
"typeCreatedBy": "Created by",
"typeRelation": "Relation",
"typeRollup": "Rollup",
"linkedCount": "{n} linked",
"rollupDays": "{n} days",
"relationTo": "Related database",
"relationPick": "Choose a database",
"relationThisPage": "On this page",
"relationOtherPage": "On another page…",
"relationSearchPage": "Find a page",
"relationNoDatabases": "No databases on that page",
"relationMissing": "The related database is not available.",
"linkRecord": "Link a record",
"searchRecords": "Search records",
"noRecords": "No records",
"openRelated": "Open record",
"rollupSettings": "Rollup",
"rollupRelation": "Relation",
"rollupProperty": "Property",
"rollupFn": "Calculate",
"rollupRecords": "Records",
"rollupNeedsRelation": "Add a relation property first.",
"fnShowOriginal": "Show values",
"fnCount": "Count records",
"fnCountValues": "Count values",
"fnCountUnique": "Count unique values",
"fnCountEmpty": "Count empty",
"fnCountNotEmpty": "Count not empty",
"fnPercentNotEmpty": "Percent not empty",
"fnSum": "Sum",
"fnAverage": "Average",
"fnMedian": "Median",
"fnMin": "Min",
"fnMax": "Max",
"fnRange": "Range",
"fnEarliest": "Earliest date",
"fnLatest": "Latest date",
"fnChecked": "Checked",
"fnPercentChecked": "Percent checked",
"openFullPage": "Open as full page",
"backToPage": "Back to the page",
"recordNotFound": "This record is not in the database any more.",
"opContains": "contains",
"opNotContains": "does not contain",
"opIs": "is",
@@ -850,6 +894,7 @@
"copy": "Copy",
"editText": "Edit text",
"openLink": "Open link",
"comment": "Comment",
"frameTitle": "Frame",
"groupTitle": "Group",
"linkPrompt": "Link address",
@@ -1004,7 +1049,8 @@
"newPageMode": "New pages open as",
"modes": {
"page": "Page",
"edgeless": "Canvas"
"edgeless": "Canvas",
"workspace": "Workspace default"
},
"edgelessStyles": "Canvas styles",
"edgelessStylesHint": "New shapes, lines and notes look like the ones you styled last.",
+49 -3
View File
@@ -185,7 +185,9 @@
"invitedBy": "invitado por {name}",
"inviteExpired": "caducada",
"resend": "Reenviar",
"revoke": "Revocar"
"revoke": "Revocar",
"pageMode": "Las páginas nuevas se abren como",
"pageModeHint": "Cada página se puede cambiar igualmente, y cada persona puede elegir otra cosa para las páginas que cree en su dispositivo."
},
"space": {
"new": "Nuevo espacio",
@@ -275,7 +277,8 @@
"added": "Añadido",
"removed": "Eliminado",
"changed": "Editado"
}
},
"canvasStats": "Lienzo: {added} añadidos, {removed} eliminados, {changed} cambiados"
},
"notFound": "Esta página no existe o no tienes acceso.",
"favorite": "Añadir a favoritos",
@@ -714,6 +717,47 @@
"typeMember": "Miembro",
"typeCreatedTime": "Fecha de creación",
"typeCreatedBy": "Creado por",
"typeRelation": "Relación",
"typeRollup": "Resumen",
"linkedCount": "{n} vinculados",
"rollupDays": "{n} días",
"relationTo": "Base de datos relacionada",
"relationPick": "Elige una base de datos",
"relationThisPage": "En esta página",
"relationOtherPage": "En otra página…",
"relationSearchPage": "Buscar una página",
"relationNoDatabases": "No hay bases de datos en esa página",
"relationMissing": "La base de datos relacionada no está disponible.",
"linkRecord": "Vincular un registro",
"searchRecords": "Buscar registros",
"noRecords": "No hay registros",
"openRelated": "Abrir registro",
"rollupSettings": "Resumen",
"rollupRelation": "Relación",
"rollupProperty": "Propiedad",
"rollupFn": "Calcular",
"rollupRecords": "Registros",
"rollupNeedsRelation": "Añade primero una propiedad de relación.",
"fnShowOriginal": "Mostrar valores",
"fnCount": "Contar registros",
"fnCountValues": "Contar valores",
"fnCountUnique": "Contar valores únicos",
"fnCountEmpty": "Contar vacíos",
"fnCountNotEmpty": "Contar no vacíos",
"fnPercentNotEmpty": "Porcentaje no vacío",
"fnSum": "Suma",
"fnAverage": "Media",
"fnMedian": "Mediana",
"fnMin": "Mínimo",
"fnMax": "Máximo",
"fnRange": "Rango",
"fnEarliest": "Fecha más temprana",
"fnLatest": "Fecha más tardía",
"fnChecked": "Marcados",
"fnPercentChecked": "Porcentaje marcado",
"openFullPage": "Abrir como página completa",
"backToPage": "Volver a la página",
"recordNotFound": "Este registro ya no está en la base de datos.",
"opContains": "contiene",
"opNotContains": "no contiene",
"opIs": "es",
@@ -850,6 +894,7 @@
"copy": "Copiar",
"editText": "Editar texto",
"openLink": "Abrir enlace",
"comment": "Comentar",
"frameTitle": "Marco",
"groupTitle": "Grupo",
"linkPrompt": "Dirección del enlace",
@@ -1004,7 +1049,8 @@
"newPageMode": "Las páginas nuevas se abren como",
"modes": {
"page": "Página",
"edgeless": "Lienzo"
"edgeless": "Lienzo",
"workspace": "Como el espacio de trabajo"
},
"edgelessStyles": "Estilos del lienzo",
"edgelessStylesHint": "Las formas, líneas y notas nuevas se ven como las últimas que estilizaste.",
+49 -3
View File
@@ -185,7 +185,9 @@
"invitedBy": "invité par {name}",
"inviteExpired": "expirée",
"resend": "Renvoyer",
"revoke": "Révoquer"
"revoke": "Révoquer",
"pageMode": "Les nouvelles pages s’ouvrent en",
"pageModeHint": "Chaque page peut toujours être basculée, et chacun peut choisir autrement pour les pages créées sur son appareil."
},
"space": {
"new": "Nouvel espace",
@@ -275,7 +277,8 @@
"added": "Ajouté",
"removed": "Supprimé",
"changed": "Modifié"
}
},
"canvasStats": "Tableau : {added} ajoutés, {removed} supprimés, {changed} modifiés"
},
"notFound": "Cette page n’existe pas ou vous n’y avez pas accès.",
"favorite": "Ajouter aux favoris",
@@ -714,6 +717,47 @@
"typeMember": "Membre",
"typeCreatedTime": "Date de création",
"typeCreatedBy": "Créé par",
"typeRelation": "Relation",
"typeRollup": "Agrégation",
"linkedCount": "{n} liés",
"rollupDays": "{n} jours",
"relationTo": "Base liée",
"relationPick": "Choisir une base de données",
"relationThisPage": "Sur cette page",
"relationOtherPage": "Sur une autre page…",
"relationSearchPage": "Chercher une page",
"relationNoDatabases": "Aucune base de données sur cette page",
"relationMissing": "La base liée n’est pas disponible.",
"linkRecord": "Lier un enregistrement",
"searchRecords": "Chercher des enregistrements",
"noRecords": "Aucun enregistrement",
"openRelated": "Ouvrir l’enregistrement",
"rollupSettings": "Agrégation",
"rollupRelation": "Relation",
"rollupProperty": "Propriété",
"rollupFn": "Calculer",
"rollupRecords": "Enregistrements",
"rollupNeedsRelation": "Ajoutez d’abord une propriété de relation.",
"fnShowOriginal": "Afficher les valeurs",
"fnCount": "Compter les enregistrements",
"fnCountValues": "Compter les valeurs",
"fnCountUnique": "Compter les valeurs uniques",
"fnCountEmpty": "Compter les vides",
"fnCountNotEmpty": "Compter les non vides",
"fnPercentNotEmpty": "Pourcentage non vide",
"fnSum": "Somme",
"fnAverage": "Moyenne",
"fnMedian": "Médiane",
"fnMin": "Minimum",
"fnMax": "Maximum",
"fnRange": "Étendue",
"fnEarliest": "Date la plus ancienne",
"fnLatest": "Date la plus récente",
"fnChecked": "Cochés",
"fnPercentChecked": "Pourcentage cochés",
"openFullPage": "Ouvrir en pleine page",
"backToPage": "Retour à la page",
"recordNotFound": "Cet enregistrement n’est plus dans la base.",
"opContains": "contient",
"opNotContains": "ne contient pas",
"opIs": "est",
@@ -850,6 +894,7 @@
"copy": "Copier",
"editText": "Modifier le texte",
"openLink": "Ouvrir le lien",
"comment": "Commenter",
"frameTitle": "Cadre",
"groupTitle": "Groupe",
"linkPrompt": "Adresse du lien",
@@ -1004,7 +1049,8 @@
"newPageMode": "Les nouvelles pages s’ouvrent en",
"modes": {
"page": "Page",
"edgeless": "Tableau"
"edgeless": "Tableau",
"workspace": "Comme l’espace de travail"
},
"edgelessStyles": "Styles du tableau",
"edgelessStylesHint": "Les nouvelles formes, lignes et notes ressemblent aux dernières mises en forme.",
+49 -3
View File
@@ -185,7 +185,9 @@
"invitedBy": "zaprasza {name}",
"inviteExpired": "wygasło",
"resend": "Wyślij ponownie",
"revoke": "Cofnij"
"revoke": "Cofnij",
"pageMode": "Nowe strony otwieraj jako",
"pageModeHint": "Każdą stronę nadal można przełączyć, a każdy może wybrać inaczej dla stron tworzonych na swoim urządzeniu."
},
"space": {
"new": "Nowa przestrzeń",
@@ -275,7 +277,8 @@
"added": "Dodane",
"removed": "Usunięte",
"changed": "Zmienione"
}
},
"canvasStats": "Tablica: dodano {added}, usunięto {removed}, zmieniono {changed}"
},
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu.",
"favorite": "Dodaj do ulubionych",
@@ -714,6 +717,47 @@
"typeMember": "Osoba",
"typeCreatedTime": "Data utworzenia",
"typeCreatedBy": "Utworzył(a)",
"typeRelation": "Relacja",
"typeRollup": "Podsumowanie",
"linkedCount": "Powiązane: {n}",
"rollupDays": "Dni: {n}",
"relationTo": "Powiązana baza danych",
"relationPick": "Wybierz bazę danych",
"relationThisPage": "Na tej stronie",
"relationOtherPage": "Na innej stronie…",
"relationSearchPage": "Znajdź stronę",
"relationNoDatabases": "Na tej stronie nie ma baz danych",
"relationMissing": "Powiązana baza danych jest niedostępna.",
"linkRecord": "Powiąż rekord",
"searchRecords": "Szukaj rekordów",
"noRecords": "Brak rekordów",
"openRelated": "Otwórz rekord",
"rollupSettings": "Podsumowanie",
"rollupRelation": "Relacja",
"rollupProperty": "Właściwość",
"rollupFn": "Oblicz",
"rollupRecords": "Rekordy",
"rollupNeedsRelation": "Najpierw dodaj właściwość relacji.",
"fnShowOriginal": "Pokaż wartości",
"fnCount": "Liczba rekordów",
"fnCountValues": "Liczba wartości",
"fnCountUnique": "Liczba unikalnych wartości",
"fnCountEmpty": "Liczba pustych",
"fnCountNotEmpty": "Liczba niepustych",
"fnPercentNotEmpty": "Procent niepustych",
"fnSum": "Suma",
"fnAverage": "Średnia",
"fnMedian": "Mediana",
"fnMin": "Minimum",
"fnMax": "Maksimum",
"fnRange": "Zakres",
"fnEarliest": "Najwcześniejsza data",
"fnLatest": "Najpóźniejsza data",
"fnChecked": "Zaznaczone",
"fnPercentChecked": "Procent zaznaczonych",
"openFullPage": "Otwórz jako pełną stronę",
"backToPage": "Wróć do strony",
"recordNotFound": "Tego rekordu nie ma już w bazie danych.",
"opContains": "zawiera",
"opNotContains": "nie zawiera",
"opIs": "jest",
@@ -850,6 +894,7 @@
"copy": "Kopiuj",
"editText": "Edytuj tekst",
"openLink": "Otwórz link",
"comment": "Skomentuj",
"frameTitle": "Ramka",
"groupTitle": "Grupa",
"linkPrompt": "Adres linku",
@@ -1004,7 +1049,8 @@
"newPageMode": "Nowe strony otwieraj jako",
"modes": {
"page": "Strona",
"edgeless": "Tablica"
"edgeless": "Tablica",
"workspace": "Jak w obszarze roboczym"
},
"edgelessStyles": "Style tablicy",
"edgelessStylesHint": "Nowe kształty, linie i notatki wyglądają jak ostatnio ostylowane.",
+7
View File
@@ -26,6 +26,13 @@ export function createDocwellRouter(platform: Platform) {
children: [
{ path: "", name: "home", component: () => import("./views/HomeView.vue") },
{ path: "p/:id", name: "page", component: () => import("./views/page/PageView.vue"), props: true },
// A database record as a full page: the page's editor stays loaded behind it.
{
path: "p/:id/r/:database/:row",
name: "record",
component: () => import("./views/page/PageView.vue"),
props: (r) => ({ id: r.params.id, record: { database: r.params.database, row: r.params.row } }),
},
{ path: "s/:id", name: "space", component: () => import("./views/space/SpaceView.vue"), props: true },
{ path: "s/:id/trash", name: "trash", component: () => import("./views/space/TrashView.vue"), props: true },
{
+3 -3
View File
@@ -16,8 +16,8 @@ export interface EditorPrefs {
showBacklinks: boolean;
/** Code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers: boolean;
/** New pages open as text or as the edgeless canvas. */
newPageMode: "page" | "edgeless";
/** New pages open as text or as the edgeless canvas; "" follows the workspace. */
newPageMode: "" | "page" | "edgeless";
/** What new canvas elements look like: the style picked last for each kind (null = built in). */
edgelessStyles: Record<string, unknown> | null;
}
@@ -30,7 +30,7 @@ export const defaultEditorPrefs: EditorPrefs = {
showProperties: true,
showBacklinks: true,
codeLineNumbers: false,
newPageMode: "page",
newPageMode: "",
edgelessStyles: null,
};
+4 -2
View File
@@ -109,10 +109,12 @@ export const useSpacesStore = defineStore("spaces", () => {
title = new Intl.DateTimeFormat(lang, { dateStyle: "long" }).format(new Date());
}
let page = await api.spaces.createPage(spaceId, title ? { parent, title } : { parent });
if (prefs.newPageFullWidth || prefs.newPageMode === "edgeless")
// The page starts in its workspace's mode; this device can choose otherwise.
const mode = prefs.newPageMode && prefs.newPageMode !== page.defaultMode ? prefs.newPageMode : null;
if (prefs.newPageFullWidth || mode)
page = await api.pages.update(page.id, {
...(prefs.newPageFullWidth ? { fullWidth: true } : {}),
...(prefs.newPageMode === "edgeless" ? { defaultMode: "edgeless" as const } : {}),
...(mode ? { defaultMode: mode } : {}),
});
if (parent) setExpanded(parent, true);
await loadTree(spaceId);
+100 -1
View File
@@ -9,6 +9,7 @@ import {
insertFiles,
followLink,
isTargetHash,
openRecord,
pagePath,
setCommentMarks,
userColor,
@@ -40,7 +41,15 @@ import { atLeast, useWorkspacesStore } from "../../stores/workspaces";
// pane "split" is the page shown beside the main view: it has its own
// header and leaves the sidebar, the address and the hash to the main view.
const props = withDefaults(defineProps<{ id: string; pane?: "main" | "split" }>(), { pane: "main" });
const props = withDefaults(
defineProps<{
id: string;
pane?: "main" | "split";
/** A database record of the page, shown as a full page (the "record" route). */
record?: { database: string; row: string };
}>(),
{ pane: "main", record: undefined },
);
const main = computed(() => props.pane === "main");
const headerTarget = computed(() => (main.value ? "#app-header" : "#split-header"));
// Header buttons show their words on wide main views; the side pane is narrow.
@@ -141,6 +150,18 @@ const canComment = computed(() => !!page.value && !page.value.inTrash && spaceAt
// Open threads only: resolved ones and replies light no text.
const openThreads = computed(() => comments.value.filter((c) => !c.parent && !c.resolvedAt));
// Threads on canvas elements (anchor {element}) show as badges in edgeless mode.
const elementThreads = computed(() =>
openThreads.value.flatMap((c) => {
const el = (c.anchor as { element?: unknown } | null)?.element;
return typeof el === "string" && el ? [{ comment: c.id, element: el }] : [];
}),
);
function commentOnElement(target: { element: string; text: string }) {
draft.value = { quote: target.text, anchor: { element: target.element } };
commentsOpen.value = true;
historyOpen.value = false;
}
async function loadComments() {
if (!page.value) return;
@@ -266,6 +287,8 @@ async function attachPicked() {
const edgelessRef = ref<InstanceType<typeof DocwellEdgeless> | null>(null);
const paneMode = ref<PageMode | null>(null);
const mode = computed<PageMode>(() => {
// A record is drawn by the text's database block.
if (props.record) return "page";
const wanted = main.value ? route.query.mode : paneMode.value;
if (wanted === "page" || wanted === "edgeless") return wanted;
return page.value?.defaultMode === "edgeless" ? "edgeless" : "page";
@@ -294,6 +317,55 @@ const exportImage = (kind: "png" | "svg") =>
saveBlob(blob, `${title.value.trim() || t("home.untitled")}.${kind}`);
});
// A record as a full page: the database block draws it in recordHost once
// the text has loaded; leaving it goes back to the page.
const recordHost = ref<HTMLElement | null>(null);
const recordMissing = ref(false);
const recordPage = (database: string, row: string) =>
router.push({ name: "record", params: { id: page.value?.id ?? props.id, database, row } });
let recordTimer: ReturnType<typeof setTimeout> | undefined;
function showRecord() {
clearTimeout(recordTimer);
recordMissing.value = false;
const r = props.record;
const editor = editorRef.value?.editor;
if (!r || !editor || !recordHost.value) return;
const started = Date.now();
const tryOpen = () => {
// The route makes a new object on each render; the same record is the same ids.
if (props.record?.database !== r.database || props.record.row !== r.row) return;
let open = false;
try {
open = openRecord(editor, r.database, r.row, {
container: recordHost.value!,
onClose: () => router.push({ name: "page", params: { id: page.value?.id ?? props.id } }),
});
} catch {
// The editor's view is not mounted yet.
}
// The database may still be on its way from the server.
if (!open) {
if (Date.now() - started > 4000) recordMissing.value = true;
else recordTimer = setTimeout(tryOpen, 150);
}
};
tryOpen();
}
watch([() => props.record?.database, () => props.record?.row, () => editorRef.value?.editor, recordHost], showRecord);
// The text can redraw its blocks (the first sync with the server does),
// which takes the record away with its block: open it again.
const recordGone = new MutationObserver(() => {
if (props.record && recordHost.value && !recordHost.value.childElementCount) showRecord();
});
watch(recordHost, (el, old) => {
if (old) recordGone.disconnect();
if (el) recordGone.observe(el, { childList: true });
});
onBeforeUnmount(() => {
clearTimeout(recordTimer);
recordGone.disconnect();
});
// Redraw comment highlights when the list, the active one or the editor changes.
watch([comments, activeComment, () => editorRef.value?.editor], drawComments);
watch(() => editorRef.value?.editor, trackEmpty);
@@ -733,11 +805,25 @@ const purge = () =>
:page-title="title.trim() || $t('home.untitled')"
:styles="(prefs.edgelessStyles as never) ?? undefined"
:view-key="`docwell.edgeless.${page.id}`"
:can-comment="canComment"
:comments="elementThreads"
:active-comment="activeComment"
@comment="commentOnElement"
@comment-select="selectComment"
@styles="prefs.edgelessStyles = $event as never"
@navigate="router.push($event)"
@block-link-copied="blockLinkCopied"
@error="emit('error', $event)"
/>
<!-- History floats over the canvas, which has no column to put it in. -->
<PageHistory
v-if="historyOpen"
:page="page"
:can-restore="editable"
class="absolute inset-x-3 top-3 z-20 max-h-[calc(100%-1.5rem)] overflow-y-auto bg-surface shadow-dialog sm:left-auto sm:w-[44rem]"
@close="historyOpen = false"
@error="emit('error', $event)"
/>
<p
v-if="page.inTrash || page.archived"
role="status"
@@ -750,6 +836,7 @@ const purge = () =>
v-else
class="mx-auto min-w-0 flex-1 px-4 pt-6 pb-16 sm:px-16 sm:pt-10"
:class="[
record ? '[&>*:not(.dw-record-host)]:hidden' : '',
page?.fullWidth ? 'max-w-doc-wide' : 'max-w-doc',
page?.font ? `dw-font-${page.font}` : '',
prefs.textSize !== 'md' ? `dw-size-${prefs.textSize}` : '',
@@ -757,6 +844,17 @@ const purge = () =>
data-testid="page-article"
>
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("page.notFound") }}</DwCallout>
<div v-if="record" class="dw-record-host" data-testid="record-page">
<div ref="recordHost" />
<DwCallout v-if="recordMissing" tone="info" size="ui">
{{ labels.database.recordNotFound }}
<template #actions>
<DwButton size="sm" icon="chevron-left" @click="router.push({ name: 'page', params: { id } })">
{{ labels.database.backToPage }}
</DwButton>
</template>
</DwCallout>
</div>
<template v-if="page">
<DwCallout v-if="page.inTrash" tone="warning" size="ui" class="mb-4 items-center" role="status">
{{ page.deletedAt ? $t("page.inTrash") : $t("page.parentInTrash") }}
@@ -858,6 +956,7 @@ const purge = () =>
:can-comment="canComment"
:journals="canOrganize"
:synced-pages="syncedPages"
:record-page="main ? recordPage : undefined"
:code-line-numbers="prefs.codeLineNumbers"
:user="me"
:editable="editable"
@@ -156,6 +156,7 @@ const when = (s: string) =>
<label class="flex flex-wrap items-center gap-3 text-ui-md">
<span class="min-w-0 flex-1">{{ $t("account.editor.newPageMode") }}</span>
<select v-model="prefs.newPageMode" class="dw-input" data-testid="new-page-mode">
<option value="">{{ $t("account.editor.modes.workspace") }}</option>
<option value="page">{{ $t("account.editor.modes.page") }}</option>
<option value="edgeless">{{ $t("account.editor.modes.edgeless") }}</option>
</select>
@@ -1,6 +1,6 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Invite, Workspace, WorkspaceMember, WorkspaceRole } from "@docwell/api-client";
import type { Invite, PageMode, Workspace, WorkspaceMember, WorkspaceRole } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
@@ -72,6 +72,8 @@ async function run(action: () => Promise<unknown>) {
}
const rename = () => run(() => api.workspaces.rename(props.id, name.value));
const setPageMode = (e: Event) =>
run(() => api.workspaces.setDefaultPageMode(props.id, (e.target as HTMLSelectElement).value as PageMode));
const setRole = (m: WorkspaceMember, role: WorkspaceRole) =>
run(() => api.workspaces.setMember(props.id, m.user.email, role));
const removeMember = (m: WorkspaceMember) => run(() => api.workspaces.removeMember(props.id, m.user.id));
@@ -132,6 +134,23 @@ async function removeWorkspace() {
}}</DwButton>
</form>
<label v-if="canManage" class="flex flex-wrap items-center gap-3 text-ui-md dw-card">
<span class="min-w-0 flex-1">
<span class="font-semibold">{{ $t("workspace.pageMode") }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t("workspace.pageModeHint") }}</span>
</span>
<select
:value="ws.defaultPageMode"
class="dw-input"
:disabled="busy"
data-testid="workspace-page-mode"
@change="setPageMode"
>
<option value="page">{{ $t("account.editor.modes.page") }}</option>
<option value="edgeless">{{ $t("account.editor.modes.edgeless") }}</option>
</select>
</label>
<section class="dw-card">
<h2 class="text-ui-lg">{{ $t("workspace.members") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("workspace.cascadeHint") }}</p>
+9 -4
View File
@@ -630,15 +630,19 @@ paths:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
patch:
operationId: renameWorkspace
operationId: updateWorkspace
tags: [workspaces]
summary: Rename a workspace (workspace admin or above)
summary: Rename a workspace or change how its new pages open (workspace admin or above)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/NameRequest" }
schema:
type: object
properties:
name: { type: string, maxLength: 120 }
defaultPageMode: { $ref: "#/components/schemas/PageMode" }
responses:
"200":
description: OK
@@ -3116,7 +3120,7 @@ components:
workspaces: { type: integer }
Workspace:
type: object
required: [id, name, slug, organization, organizationName, role, created]
required: [id, name, slug, organization, organizationName, role, created, defaultPageMode]
properties:
id: { type: string }
name: { type: string }
@@ -3125,6 +3129,7 @@ components:
organizationName: { type: string }
role: { $ref: "#/components/schemas/WorkspaceRole" }
created: { type: string }
defaultPageMode: { $ref: "#/components/schemas/PageMode", description: The view new pages of the workspace open in }
WorkspaceMember:
type: object
required: [user, role]
+3
View File
@@ -11643,14 +11643,17 @@
"@docwell/api-client": "*",
"@docwell/ui": "*",
"vue": "^3.5.44",
"vue-i18n": "^11.4.16",
"vue-router": "^5.4.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@vitejs/plugin-vue": "^6.0.10",
"jsdom": "^30.1.3",
"tailwindcss": "^4.3.3",
"typescript": "~5.9.3",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"vue-tsc": "^3.3.14"
}
},