Files
Docwell/Packages/editor/src/database/store.ts
T
tajniak81andClaude Opus 5.5 0640004895
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
Add database relations and rollups, full-page records, and translate the admin panel and phone app
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>
2026-11-15 17:11:47 +01:00

506 lines
16 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
// A database's live data in the page's Y.Doc (ADR-13):
// ydoc.getMap("blocks").get(id) → Y.Map { title, columns, rows, views }.
// Every edit runs in one transaction with DB_ORIGIN, which the page's undo
// manager tracks, so Ctrl+Z undoes it like typing.
import * as Y from "yjs";
import type { RelationTarget, RollupConfig } from "./linked";
import {
convertValue,
defaultView,
isObject,
newId,
normalize,
type Column,
type ColumnType,
type DbData,
type Person,
type Row,
type SelectOption,
type View,
type ViewType,
} from "./model";
/** The transaction origin of database edits; the Collaboration undo manager tracks it. */
export const DB_ORIGIN = "docwell-database";
export const blocksOf = (doc: Y.Doc) => doc.getMap<Y.Map<unknown>>("blocks");
type Key = "columns" | "rows" | "views";
type YItem = Y.Map<unknown>;
/** Writes a database (from JSON) as a new Y.Map, to put into the blocks map. */
export function dbToY(data: DbData): YItem {
const m = new Y.Map<unknown>();
m.set("title", data.title);
const list = <T,>(items: T[], toY: (x: T) => YItem) => {
const a = new Y.Array<YItem>();
a.push(items.map((x, i) => withPos(toY(x), i)));
return a;
};
m.set("columns", list(data.columns, columnToY));
m.set("rows", list(data.rows, rowToY));
m.set("views", list(data.views, viewToY));
return m;
}
function withPos(m: YItem, pos: number): YItem {
m.set("pos", pos);
return m;
}
function columnToY(c: Column): YItem {
const m = new Y.Map<unknown>();
m.set("id", c.id);
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;
}
function rowToY(r: Row): YItem {
const m = new Y.Map<unknown>();
m.set("id", r.id);
m.set("createdAt", r.createdAt);
if (r.createdBy) m.set("createdBy", r.createdBy);
const cells = new Y.Map<unknown>();
for (const [k, v] of Object.entries(r.cells)) if (v !== undefined && v !== null) cells.set(k, v);
m.set("cells", cells);
return m;
}
function viewToY(v: View): YItem {
const m = new Y.Map<unknown>();
for (const [k, val] of Object.entries(v)) m.set(k, val);
return m;
}
/**
* Items of a list in display order. Order is a fractional "pos" on each
* item, not the array order, so moving one only changes its pos: concurrent
* edits to the moved item survive, and a row's open body stays bound.
*/
export function ordered(a: Y.Array<YItem>): YItem[] {
return a
.toArray()
.filter((m): m is YItem => m instanceof Y.Map)
.map((m, i) => ({ m, p: posOf(m, i), i }))
.sort((x, y) => x.p - y.p || x.i - y.i)
.map((x) => x.m);
}
function posOf(m: YItem | undefined, fallback: number): number {
const p = m?.get("pos");
return typeof p === "number" ? p : fallback;
}
/** A pos that sorts at index at of list (display order), between its neighbours. */
function posAt(list: YItem[], at: number, skip?: YItem): number {
const rest = skip ? list.filter((m) => m !== skip) : list;
const i = Math.max(0, Math.min(at, rest.length));
const before = i > 0 ? posOf(rest[i - 1], i - 1) : null;
const after = i < rest.length ? posOf(rest[i], i) : null;
if (before === null && after === null) return 0;
if (before === null) return after! - 1;
if (after === null) return before + 1;
return (before + after) / 2;
}
/** A plain snapshot of the Y.Map, for rendering. */
export function readDb(m: YItem): DbData {
const arr = (key: Key) => {
const a = m.get(key);
return a instanceof Y.Array ? ordered(a as Y.Array<YItem>) : [];
};
const plain = (x: YItem) => {
const o = x.toJSON() as Record<string, unknown>;
delete o.pos;
return o;
};
const bodies = new Set<string>();
const rows = arr("rows").map((r) => {
const cells = r.get("cells");
const body = r.get("body");
const id = r.get("id");
if (typeof id === "string" && body instanceof Y.XmlFragment && body.length > 0) bodies.add(id);
return {
id,
createdAt: r.get("createdAt"),
createdBy: r.get("createdBy"),
cells: cells instanceof Y.Map ? cells.toJSON() : {},
};
});
const db = normalize({
title: m.get("title"),
columns: arr("columns").map(plain),
rows,
views: arr("views").map(plain),
});
for (const r of db.rows) if (bodies.has(r.id)) r.hasBody = true;
return db;
}
export interface DbLabels {
tableView: string;
/** The default names of new columns, by type. */
columnName: (type: ColumnType) => string;
}
/** A new, empty database: a title column, a status column, three rows and one table view. */
export function emptyDb(labels: DbLabels, title = ""): DbData {
const name: Column = { id: newId(), name: labels.columnName("title"), type: "title" };
const status: Column = { id: newId(), name: labels.columnName("select"), type: "select", options: [] };
const columns = [name, status];
const now = Date.now();
return {
title,
columns,
rows: [0, 1, 2].map((i) => ({ id: newId(), cells: {}, createdAt: now + i, createdBy: null })),
views: [defaultView("table", labels.tableView, columns)],
};
}
const isEmpty = (v: unknown) => v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length);
/** Edits one database. Methods are no-ops for ids that no longer exist (a peer deleted them). */
export class DbStore {
constructor(
readonly doc: Y.Doc,
readonly map: YItem,
private readonly me: () => Person | null,
) {}
snapshot(): DbData {
return readDb(this.map);
}
/** Calls fn after every change, local or remote; returns the unsubscribe. */
observe(fn: () => void): () => void {
const h = () => fn();
this.map.observeDeep(h);
return () => this.map.unobserveDeep(h);
}
/** Runs fn as one undo step. */
tx(fn: () => void) {
this.doc.transact(fn, DB_ORIGIN);
}
private list(key: Key): Y.Array<YItem> {
let a = this.map.get(key);
if (!(a instanceof Y.Array)) {
a = new Y.Array<YItem>();
this.map.set(key, a);
}
return a as Y.Array<YItem>;
}
/** The item with id and its index in display order. */
private find(key: Key, id: string): { item: YItem; index: number } | null {
const list = ordered(this.list(key));
const index = list.findIndex((m) => m.get("id") === id);
return index < 0 ? null : { item: list[index]!, index };
}
/** Inserts items at index at of the display order (the end by default). */
private insertAt(key: Key, at: number | undefined, items: YItem[]) {
const a = this.list(key);
const list = ordered(a);
let i = Math.max(0, Math.min(at ?? list.length, list.length));
for (const item of items) {
item.set("pos", posAt(list, i));
list.splice(i++, 0, item);
}
a.push(items);
}
private moveTo(key: Key, id: string, to: number) {
const found = this.find(key, id);
if (!found || found.index === to) return;
found.item.set("pos", posAt(ordered(this.list(key)), to, found.item));
}
private remove(key: Key, item: YItem) {
const a = this.list(key);
const i = a.toArray().indexOf(item);
if (i >= 0) a.delete(i, 1);
}
setTitle(title: string) {
this.tx(() => this.map.set("title", title));
}
// ---- columns ----
addColumn(type: ColumnType, name: string, at?: number): string {
const col: Column = { id: newId(), name, type };
if (type === "select" || type === "multiSelect") col.options = [];
this.tx(() => this.insertAt("columns", at, [columnToY(col)]));
return col.id;
}
renameColumn(id: string, name: string) {
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));
}
/** Changes a column's type and converts every row's value. */
changeType(id: string, type: ColumnType) {
const db = this.snapshot();
const col = db.columns.find((c) => c.id === id);
if (!col || col.type === type || col.type === "title" || type === "title") return;
let options = type === "select" || type === "multiSelect" ? (col.options ?? []) : [];
const values = new Map<string, unknown>();
for (const r of db.rows) {
const out = convertValue(r.cells[id], col, type, options);
options = out.options;
values.set(r.id, out.value);
}
this.tx(() => {
const found = this.find("columns", id);
if (!found) return;
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;
const v = values.get(String(yr.get("id")));
if (isEmpty(v) || v === false) cells.delete(id);
else cells.set(id, v);
}
});
}
deleteColumn(id: string) {
this.tx(() => {
const found = this.find("columns", id);
if (!found || found.item.get("type") === "title") return;
this.remove("columns", found.item);
for (const yr of this.list("rows").toArray()) {
const cells = yr.get("cells");
if (cells instanceof Y.Map) cells.delete(id);
}
});
}
moveColumn(id: string, to: number) {
this.tx(() => this.moveTo("columns", id, to));
}
duplicateColumn(id: string, name: string): string | null {
const col = this.snapshot().columns.find((c) => c.id === id);
if (!col || col.type === "title") return null;
const copy: Column = { ...structuredClone(col), id: newId(), name };
this.tx(() => {
const found = this.find("columns", id);
if (!found) return;
this.insertAt("columns", found.index + 1, [columnToY(copy)]);
for (const yr of this.list("rows").toArray()) {
const cells = yr.get("cells");
if (cells instanceof Y.Map && cells.has(id)) cells.set(copy.id, cells.get(id));
}
});
return copy.id;
}
// ---- rows ----
/** Adds a row with these cells at index at (the end by default); returns its id. */
addRow(cells: Record<string, unknown> = {}, at?: number): string {
return this.addRows([cells], at)[0]!;
}
/** Adds many rows in one undo step (paste, CSV import). */
addRows(list: Record<string, unknown>[], at?: number): string[] {
const me = this.me();
const now = Date.now();
const rows: Row[] = list.map((cells, i) => ({ id: newId(), cells, createdAt: now + i, createdBy: me }));
this.tx(() => this.insertAt("rows", at, rows.map(rowToY)));
return rows.map((r) => r.id);
}
setCell(row: string, col: string, value: unknown) {
this.setCells([{ row, col, value }]);
}
/** Sets several cells in one undo step. Empty values are removed. */
setCells(changes: { row: string; col: string; value: unknown }[]) {
this.tx(() => {
for (const { row, col, value } of changes) {
const cells = this.find("rows", row)?.item.get("cells");
if (!(cells instanceof Y.Map)) continue;
if (isEmpty(value)) cells.delete(col);
else cells.set(col, value);
}
});
}
deleteRows(ids: string[]) {
this.tx(() => {
const a = this.list("rows");
for (let i = a.length - 1; i >= 0; i--) {
if (ids.includes(String(a.get(i)?.get("id")))) a.delete(i, 1);
}
});
}
/** Moves a row to index to of the full, unfiltered order. */
moveRow(id: string, to: number) {
this.tx(() => this.moveTo("rows", id, to));
}
duplicateRow(id: string): string | null {
const found = this.find("rows", id);
if (!found) return null;
const copy = cloneRow(found.item, this.me());
this.tx(() => this.insertAt("rows", found.index + 1, [copy]));
return String(copy.get("id"));
}
/** The row's body fragment, made on first use (opening a row as a page). */
rowBody(id: string): Y.XmlFragment | null {
const found = this.find("rows", id);
if (!found) return null;
const body = found.item.get("body");
if (body instanceof Y.XmlFragment) return body;
const fresh = new Y.XmlFragment();
this.tx(() => found.item.set("body", fresh));
return fresh;
}
/** The row's index in the full order, or -1. */
rowIndex(id: string): number {
return this.find("rows", id)?.index ?? -1;
}
// ---- views ----
addView(type: ViewType, name: string): string {
const view = defaultView(type, name, this.snapshot().columns);
this.tx(() => this.insertAt("views", undefined, [viewToY(view)]));
return view.id;
}
updateView(id: string, patch: Partial<Omit<View, "id">>) {
this.tx(() => {
const found = this.find("views", id);
if (!found) return;
for (const [k, v] of Object.entries(patch)) found.item.set(k, v);
});
}
duplicateView(id: string, name: string): string | null {
const view = this.snapshot().views.find((v) => v.id === id);
if (!view) return null;
const copy: View = { ...structuredClone(view), id: newId(), name };
this.tx(() => {
const found = this.find("views", id);
this.insertAt("views", (found?.index ?? -1) + 1, [viewToY(copy)]);
});
return copy.id;
}
deleteView(id: string) {
this.tx(() => {
const found = this.find("views", id);
if (found && this.list("views").length > 1) this.remove("views", found.item);
});
}
moveView(id: string, to: number) {
this.tx(() => this.moveTo("views", id, to));
}
}
/** Copies a row map with a new id, its cells and its body. */
function cloneRow(m: YItem, me: Person | null): YItem {
const out = new Y.Map<unknown>();
out.set("id", newId());
out.set("createdAt", Date.now());
const by = me ?? m.get("createdBy");
if (isObject(by)) out.set("createdBy", by);
const cells = new Y.Map<unknown>();
const old = m.get("cells");
if (old instanceof Y.Map) for (const [k, v] of old.entries()) cells.set(k, v);
out.set("cells", cells);
const body = m.get("body");
if (body instanceof Y.XmlFragment && body.length) {
const copy = new Y.XmlFragment();
copy.insert(
0,
body.toArray().map((n) => n.clone() as Y.XmlElement | Y.XmlText),
);
out.set("body", copy);
}
return out;
}
/** The database's JSON with row bodies, for copying (ADR-13: a pasted copy seeds its own map). */
export function exportDb(m: YItem, bodyJSON: (f: Y.XmlFragment) => unknown[]): DbData {
const db = readDb(m);
const rows = m.get("rows");
if (rows instanceof Y.Array) {
const bodies = new Map<string, Y.XmlFragment>();
for (const r of rows.toArray() as YItem[]) {
const b = r.get("body");
if (b instanceof Y.XmlFragment && b.length) bodies.set(String(r.get("id")), b);
}
for (const r of db.rows) {
const b = bodies.get(r.id);
if (b) r.body = bodyJSON(b) as Row["body"];
}
}
return db;
}
/**
* Writes a database with row bodies (from exportDb or the server's JSON)
* into the blocks map under id. Bodies are written once the map is part of
* the document, which y-prosemirror needs.
*/
export function seedDb(doc: Y.Doc, id: string, data: DbData, writeBody: (json: unknown[], f: Y.XmlFragment) => void) {
doc.transact(() => {
const m = dbToY(data);
blocksOf(doc).set(id, m);
const rows = m.get("rows") as Y.Array<YItem>;
const byId = new Map(data.rows.map((r) => [r.id, r]));
for (const yr of rows.toArray()) {
const body = byId.get(String(yr.get("id")))?.body;
if (!body?.length) continue;
const f = new Y.XmlFragment();
yr.set("body", f);
writeBody(body, f);
}
}, DB_ORIGIN);
}