Files
Docwell/Packages/editor/src/database/database.test.ts
T
tajniak81andClaude Opus 5.5 3102a476a6
CI / go (Server) (push) Failing after 4m1s
CI / go (Web-App) (push) Successful in 10m50s
CI / frontend (push) Failing after 6m46s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m39s
CI / mobile (push) Failing after 3m2s
CI / docker (push) Successful in 35m59s
Docs / build (push) Successful in 13m26s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add databases: table, kanban and calendar views with rows as pages
Phase C of docs/AFFINE.md (ADR-13).

A database is a block whose records live in the page's Y.Doc, in
ydoc.getMap("blocks") under the block's id: columns, rows (each cell its
own map entry, so concurrent edits to one row merge) and views. Order is
a fractional position per item, so moving a row keeps edits made to it at
the same time. Database edits share the page's undo history.

- Thirteen property types: title, text, number, checkbox, select,
  multi-select, date, progress, link, attachment, member, created time
  and created by. The column menu renames, changes type (converting the
  values), sorts, filters, hides, inserts, moves, duplicates and deletes;
  columns resize and drag.
- Table view: keyboard navigation, range selection, typing to edit,
  copy and paste with spreadsheets (pasting adds rows as needed), row
  dragging, bulk delete, grouping.
- Views in tabs, each with its own filters (all/any), sorts, grouping
  and visible properties; kanban grouped by select, multi-select,
  checkbox or member with cards dragged between columns; calendar by a
  date property with records dragged between days.
- A record opens beside the page with its properties and a body of its
  own (a Y.XmlFragment in the row, edited by a second editor).
- /database, Ctrl+G or "Group as database" turns a list into a database;
  CSV export and import; a copied, pasted or duplicated database gets
  its own copy of the records.

Server: yrs writes each database's records into its node as attrs.data
when it turns a document into JSON, adds them to the search text, and
writes them back on imports, restores and templates. Markdown, HTML,
PDF and Word exports show a database as a table of its first view's
columns. Notion database CSVs import as database blocks with guessed
types. Share links and history previews show databases read-only.

Strings are translated into all five languages, the user guide covers
databases, and the mobile editor bundle is rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:06:18 +01:00

132 lines
5.8 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { describe, expect, it } from "vitest";
import * as Y from "yjs";
import { formatDelimited, fromCSV, parseDelimited, toCSV } from "./csv";
import { convertValue, defaultView, groupRows, monthGrid, moveToGroup, normalize, viewRows, type Column, type DbData, type Row } from "./model";
import { blocksOf, DbStore, readDb, seedDb } from "./store";
const title: Column = { id: "t", name: "Name", type: "title" };
const status: Column = {
id: "s",
name: "Status",
type: "select",
options: [
{ id: "todo", name: "To do", color: "gray" },
{ id: "done", name: "Done", color: "green" },
],
};
const points: Column = { id: "p", name: "Points", type: "number" };
const row = (id: string, cells: Record<string, unknown>): Row => ({ id, cells, createdAt: 1, createdBy: null });
function sample(): DbData {
return {
title: "Tasks",
columns: [title, status, points],
rows: [row("a", { t: "Write", s: "todo", p: 3 }), row("b", { t: "Read", s: "done", p: 1 }), row("c", { t: "Ship", p: 5 })],
views: [defaultView("table", "Table", [title, status, points])],
};
}
describe("database model", () => {
it("filters, searches and sorts rows, keeping empty cells last", () => {
const db = sample();
const v = db.views[0]!;
expect(viewRows(db, { ...v, filters: [{ column: "s", op: "is", value: "todo" }] }).map((r) => r.id)).toEqual(["a"]);
expect(viewRows(db, { ...v, filters: [{ column: "s", op: "isEmpty" }] }).map((r) => r.id)).toEqual(["c"]);
expect(viewRows(db, { ...v, filters: [{ column: "p", op: "gt", value: 2 }] }).map((r) => r.id)).toEqual(["a", "c"]);
expect(viewRows(db, v, "rea").map((r) => r.id)).toEqual(["b"]);
expect(viewRows(db, { ...v, sorts: [{ column: "p", desc: true }] }).map((r) => r.id)).toEqual(["c", "a", "b"]);
// Choices sort in their own order; the row without one goes last either way.
expect(viewRows(db, { ...v, sorts: [{ column: "s", desc: true }] }).map((r) => r.id)).toEqual(["b", "a", "c"]);
});
it("groups rows by a choice, with a group for rows without one", () => {
const db = sample();
const groups = groupRows(db.rows, status, "No value", "Yes", "No");
expect(groups.map((g) => [g.key, g.rows.map((r) => r.id)])).toEqual([
["", ["c"]],
["todo", ["a"]],
["done", ["b"]],
]);
expect(moveToGroup(db.rows[0]!, status, "todo", "done")).toBe("done");
});
it("converts values when a column changes type", () => {
const text: Column = { id: "x", name: "X", type: "text" };
const out = convertValue("Red, Blue", text, "multiSelect", []);
expect(out.options.map((o) => o.name)).toEqual(["Red", "Blue"]);
expect(out.value).toEqual(out.options.map((o) => o.id));
expect(convertValue("done", status, "text", []).value).toBe("Done");
expect(convertValue("12,5", text, "number", []).value).toBe(12.5);
});
it("normalizes untrusted data and always has a title column", () => {
const db = normalize({ columns: [{ id: "a", type: "bogus" }], rows: [{ id: 3 }, { id: "r", cells: { a: "x" } }] });
expect(db.columns.map((c) => c.type)).toEqual(["title", "text"]);
expect(db.rows.map((r) => r.id)).toEqual(["r"]);
});
it("lays out a month from Monday", () => {
const days = monthGrid(2026, 10); // November 2026 starts on a Sunday
expect(days[0]).toBe("2026-10-26");
expect(days.length % 7).toBe(0);
expect(days).toContain("2026-11-30");
});
});
describe("CSV", () => {
it("reads quoted fields with separators and line breaks", () => {
expect(parseDelimited('a,"b,c","d ""e""\nf"\r\n1,2,3')).toEqual([
["a", "b,c", 'd "e"\nf'],
["1", "2", "3"],
]);
expect(formatDelimited([["a", "b,c"], ['x"y', ""]])).toBe('a,"b,c"\r\n"x""y",');
});
it("guesses column types on import and writes them back", () => {
const { columns, rows } = fromCSV("Name,Points,Due,Done\nA,1,2026-11-01,yes\nB,2.5,2026-11-02,no\n");
expect(columns.map((c) => c.type)).toEqual(["title", "number", "date", "checkbox"]);
expect(rows[1]).toEqual({ [columns[0]!.id]: "B", [columns[1]!.id]: 2.5, [columns[2]!.id]: "2026-11-02", [columns[3]!.id]: false });
const db = sample();
expect(toCSV(db, db.columns, db.rows).split("\r\n")[1]).toBe("Write,To do,3");
});
});
describe("database store", () => {
it("edits a database in the Y.Doc and moves rows without recreating them", () => {
const doc = new Y.Doc();
seedDb(doc, "db1", sample(), () => {});
const store = new DbStore(doc, blocksOf(doc).get("db1")!, () => ({ id: "u1", name: "Ann" }));
store.setCell("a", "p", 8);
const id = store.addRow({ t: "New" }, 0);
expect(store.snapshot().rows.map((r) => r.id)).toEqual([id, "a", "b", "c"]);
expect(store.snapshot().rows[0]!.createdBy).toEqual({ id: "u1", name: "Ann" });
const body = store.rowBody("a")!;
store.moveRow("a", 3);
expect(store.snapshot().rows.map((r) => r.id)).toEqual([id, "b", "c", "a"]);
expect(store.rowBody("a")).toBe(body);
expect(store.snapshot().rows.find((r) => r.id === "a")!.cells.p).toBe(8);
store.changeType("s", "text");
expect(readDb(store.map).rows.find((r) => r.id === "b")!.cells.s).toBe("Done");
store.deleteColumn("s");
expect(store.snapshot().columns.map((c) => c.id)).toEqual(["t", "p"]);
});
it("merges concurrent edits to different cells of a row", () => {
const a = new Y.Doc();
seedDb(a, "db", sample(), () => {});
const b = new Y.Doc();
Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
new DbStore(a, blocksOf(a).get("db")!, () => null).setCell("a", "t", "Write more");
new DbStore(b, blocksOf(b).get("db")!, () => null).setCell("a", "p", 13);
Y.applyUpdate(a, Y.encodeStateAsUpdate(b));
Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
for (const d of [a, b]) {
expect(readDb(blocksOf(d).get("db")!).rows[0]!.cells).toEqual({ t: "Write more", s: "todo", p: 13 });
}
});
});