A restore, import or template replaces the page through yrs, which writes a new map for each database under the same id. An open editor kept watching and editing the old, detached map: it showed the records from before the restore, its edits went nowhere, and its records could not open their bodies. The block now follows its entry in the blocks map and rebinds (and reopens an open record) when the entry is replaced. Found by testing databases in the web app against a running server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
510 lines
19 KiB
TypeScript
510 lines
19 KiB
TypeScript
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// The database block (ADR-13). The node keeps only an id; its records live
|
|
// in ydoc.getMap("blocks"). Editors without a live document (share links,
|
|
// history previews) draw it read-only from the node's data attribute, which
|
|
// the server fills in when it turns the document into JSON.
|
|
|
|
import { Editor, mergeAttributes, Node, type AnyExtension, type JSONContent } from "@tiptap/core";
|
|
import { Fragment, Slice, type Node as PMNode } from "@tiptap/pm/model";
|
|
import { NodeSelection, Plugin, PluginKey } from "@tiptap/pm/state";
|
|
import { prosemirrorJSONToYXmlFragment, ySyncPluginKey, yUndoPluginKey, yXmlFragmentToProsemirrorJSON } from "@tiptap/y-tiptap";
|
|
import * as Y from "yjs";
|
|
import type { FileHost } from "../files";
|
|
import { englishLabels, type EditorLabels } from "../labels";
|
|
import type { MentionHost } from "../mention";
|
|
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";
|
|
|
|
export interface DatabaseOptions {
|
|
labels: EditorLabels | null;
|
|
/** The page's live document; without it databases show read-only from their data attribute. */
|
|
doc?: Y.Doc;
|
|
/** The document is shown read-only (a synced page). */
|
|
readOnlyDoc?: boolean;
|
|
/** Adds database edits to the editor's undo history (not in row bodies, whose page has it). */
|
|
undoScope?: boolean;
|
|
files?: FileHost;
|
|
people?: MentionHost;
|
|
/** The signed-in person, recorded as the creator of new rows. */
|
|
me?: () => Person | null;
|
|
/**
|
|
* The extensions of a row body's editor: bound to fragment, or (null) for
|
|
* a read-only body from JSON.
|
|
*/
|
|
rowExtensions?: (fragment: Y.XmlFragment | null) => AnyExtension[];
|
|
/** Shows a short message, e.g. "Copied 6 cells". */
|
|
notify?: (text: string) => void;
|
|
}
|
|
|
|
declare module "@tiptap/core" {
|
|
interface Commands<ReturnType> {
|
|
database: {
|
|
/** Inserts a database; data defaults to an empty one. */
|
|
insertDatabase: (data?: DbData) => ReturnType;
|
|
/** Turns the list (or paragraphs) around the selection into a database, one row per item. */
|
|
groupAsDatabase: () => ReturnType;
|
|
};
|
|
}
|
|
}
|
|
|
|
const dbLabels = (l: EditorLabels | null) => (l ?? englishLabels).database;
|
|
|
|
function dbDefaults(l: EditorLabels | null) {
|
|
const d = dbLabels(l);
|
|
return { tableView: d.viewTable, columnName: (t: Column["type"]) => (t === "title" ? d.typeTitle : typeLabel(d, t)) };
|
|
}
|
|
|
|
/** The ProseMirror JSON of a row body fragment, as nodes. */
|
|
const bodyJSON = (f: Y.XmlFragment) => (yXmlFragmentToProsemirrorJSON(f).content as unknown[] | undefined) ?? [];
|
|
|
|
/** Copies database nodes in a fragment through fn (copy and paste). */
|
|
function mapDatabases(fragment: Fragment, fn: (node: PMNode) => PMNode): Fragment {
|
|
const out: PMNode[] = [];
|
|
fragment.forEach((child) => {
|
|
if (child.type.name === "database") out.push(fn(child));
|
|
else if (child.content.size) out.push(child.copy(mapDatabases(child.content, fn)));
|
|
else out.push(child);
|
|
});
|
|
return Fragment.from(out);
|
|
}
|
|
|
|
function hasDatabase(fragment: Fragment): boolean {
|
|
let found = false;
|
|
fragment.descendants((n) => {
|
|
if (n.type.name === "database") found = true;
|
|
return !found;
|
|
});
|
|
return found;
|
|
}
|
|
|
|
export const Database = Node.create<DatabaseOptions>({
|
|
name: "database",
|
|
group: "block",
|
|
atom: true,
|
|
draggable: true,
|
|
selectable: true,
|
|
|
|
addOptions() {
|
|
return {
|
|
labels: null,
|
|
doc: undefined,
|
|
readOnlyDoc: false,
|
|
undoScope: true,
|
|
files: undefined,
|
|
people: undefined,
|
|
me: undefined,
|
|
rowExtensions: undefined,
|
|
notify: undefined,
|
|
};
|
|
},
|
|
|
|
addAttributes() {
|
|
return {
|
|
id: {
|
|
default: "",
|
|
parseHTML: (el) => el.getAttribute("data-id") ?? "",
|
|
renderHTML: (a) => ({ "data-id": a.id }),
|
|
},
|
|
// The records as JSON, only where there is no live map: read-only
|
|
// readers, the clipboard, and documents written by the server.
|
|
data: {
|
|
default: null,
|
|
parseHTML: (el) => {
|
|
try {
|
|
const raw = el.getAttribute("data-db");
|
|
return raw ? JSON.parse(raw) : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
},
|
|
renderHTML: (a) => (a.data ? { "data-db": JSON.stringify(a.data) } : {}),
|
|
},
|
|
};
|
|
},
|
|
|
|
parseHTML() {
|
|
return [{ tag: "div[data-type='database']" }];
|
|
},
|
|
|
|
// As HTML (copying to other apps), a database is a table of its records.
|
|
renderHTML({ node, HTMLAttributes }) {
|
|
const attrs = mergeAttributes(HTMLAttributes, { "data-type": "database" });
|
|
if (!node.attrs.data) return ["div", attrs];
|
|
const db = normalize(node.attrs.data);
|
|
const view = db.views[0];
|
|
const cols = db.columns.filter((c) => c.type === "title" || !view?.hidden.includes(c.id));
|
|
return [
|
|
"div",
|
|
attrs,
|
|
["p", {}, ["strong", {}, db.title || dbLabels(this.options.labels).untitled]],
|
|
[
|
|
"table",
|
|
{},
|
|
["tr", {}, ...cols.map((c) => ["th", {}, c.name])],
|
|
...db.rows.map((r) => ["tr", {}, ...cols.map((c) => ["td", {}, cellText(r, c)])]),
|
|
],
|
|
];
|
|
},
|
|
|
|
renderText({ node }) {
|
|
const db = node.attrs.data ? normalize(node.attrs.data) : null;
|
|
if (!db) return "";
|
|
const title = titleColumn(db);
|
|
return [db.title, ...db.rows.map((r) => cellText(r, title))].filter(Boolean).join("\n");
|
|
},
|
|
|
|
onCreate() {
|
|
const { doc, readOnlyDoc, undoScope } = this.options;
|
|
if (!doc || readOnlyDoc || !undoScope) return;
|
|
// Database edits are undone with the page's own Ctrl+Z.
|
|
const um = yUndoPluginKey.getState(this.editor.state)?.undoManager as Y.UndoManager | undefined;
|
|
um?.addToScope(blocksOf(doc));
|
|
},
|
|
|
|
addCommands() {
|
|
/** A new node's attributes. With a live document the map goes in first, so peers never see a node without data. */
|
|
const attrsFor = (db: DbData) => {
|
|
const id = newId();
|
|
const { doc, readOnlyDoc } = this.options;
|
|
if (!doc || readOnlyDoc) return { id, data: db };
|
|
seedDb(doc, id, db, (json, f) => writeBody(this.editor, json, f));
|
|
return { id, data: null };
|
|
};
|
|
return {
|
|
insertDatabase:
|
|
(data) =>
|
|
({ commands }) =>
|
|
commands.insertContent([
|
|
{ type: this.name, attrs: attrsFor(data ?? emptyDb(dbDefaults(this.options.labels))) },
|
|
{ type: "paragraph" },
|
|
]),
|
|
groupAsDatabase:
|
|
() =>
|
|
({ state, dispatch, commands }) => {
|
|
const found = listAt(state.selection.$from, state.selection.$to);
|
|
if (!found) return false;
|
|
if (!dispatch) return true;
|
|
const l = dbLabels(this.options.labels);
|
|
const title: Column = { id: newId(), name: l.typeTitle, type: "title" };
|
|
const columns: Column[] = [title];
|
|
const done: Column | null = found.checks ? { id: newId(), name: l.done, type: "checkbox" } : null;
|
|
if (done) columns.push(done);
|
|
const now = Date.now();
|
|
const rows: Row[] = found.items.map((it, i) => ({
|
|
id: newId(),
|
|
cells: { [title.id]: it.text, ...(done && it.checked ? { [done.id]: true } : {}) },
|
|
createdAt: now + i,
|
|
createdBy: this.options.me?.() ?? null,
|
|
body: it.rest.length ? it.rest : undefined,
|
|
}));
|
|
const db: DbData = { title: "", columns, rows, views: [defaultView("table", l.viewTable, columns)] };
|
|
const node = this.type.create(attrsFor(db));
|
|
return commands.command(({ tr }) => {
|
|
// The list itself is replaced, whatever sits next to it.
|
|
tr.replaceWith(found.from, found.to, node);
|
|
tr.setSelection(NodeSelection.create(tr.doc, found.from));
|
|
return true;
|
|
});
|
|
},
|
|
};
|
|
},
|
|
|
|
addKeyboardShortcuts() {
|
|
return {
|
|
"Mod-g": () => this.editor.commands.groupAsDatabase(),
|
|
};
|
|
},
|
|
|
|
addProseMirrorPlugins() {
|
|
const { doc, readOnlyDoc } = this.options;
|
|
const live = doc && !readOnlyDoc ? doc : null;
|
|
const editor = this.editor;
|
|
return [
|
|
new Plugin({
|
|
key: new PluginKey("databaseClipboard"),
|
|
props: {
|
|
// A copied database carries its records, so it pastes as its own copy.
|
|
transformCopied: (slice) => {
|
|
if (!doc || !hasDatabase(slice.content)) return slice;
|
|
const content = mapDatabases(slice.content, (n) => {
|
|
const m = blocksOf(doc).get(String(n.attrs.id));
|
|
return m instanceof Y.Map ? n.type.create({ ...n.attrs, data: exportDb(m, bodyJSON) }) : n;
|
|
});
|
|
return new Slice(content, slice.openStart, slice.openEnd);
|
|
},
|
|
transformPasted: (slice) => {
|
|
if (!hasDatabase(slice.content)) return slice;
|
|
const content = mapDatabases(slice.content, (n) => {
|
|
const id = newId();
|
|
if (!live) return n.type.create({ ...n.attrs, id });
|
|
const source = n.attrs.data ? normalize(n.attrs.data) : null;
|
|
const m = blocksOf(live).get(String(n.attrs.id));
|
|
const data = source ?? (m instanceof Y.Map ? exportDb(m, bodyJSON) : emptyDb(dbDefaults(this.options.labels)));
|
|
seedDb(live, id, freshIds(data), (json, f) => writeBody(editor, json, f));
|
|
return n.type.create({ id, data: null });
|
|
});
|
|
return new Slice(content, slice.openStart, slice.openEnd);
|
|
},
|
|
},
|
|
// Two nodes never share one map: a duplicated block gets a copy of the records.
|
|
appendTransaction: (trs, _old, state) => {
|
|
if (!live || !trs.some((tr) => tr.docChanged && !tr.getMeta(ySyncPluginKey))) return null;
|
|
if (!trs.some((tr) => tr.steps.some((s) => hasDatabase((s as unknown as { slice?: Slice }).slice?.content ?? Fragment.empty)))) return null;
|
|
const seen = new Set<string>();
|
|
const fix: { pos: number; node: PMNode }[] = [];
|
|
state.doc.descendants((n, pos) => {
|
|
if (n.type.name !== "database") return;
|
|
const id = String(n.attrs.id);
|
|
if (id && seen.has(id)) fix.push({ pos, node: n });
|
|
seen.add(id);
|
|
return false;
|
|
});
|
|
if (!fix.length) return null;
|
|
const tr = state.tr;
|
|
for (const { pos, node } of fix) {
|
|
const m = blocksOf(live).get(String(node.attrs.id));
|
|
const id = newId();
|
|
if (m instanceof Y.Map) seedDb(live, id, freshIds(exportDb(m, bodyJSON)), (json, f) => writeBody(editor, json, f));
|
|
tr.setNodeMarkup(pos, undefined, { ...node.attrs, id, data: null });
|
|
}
|
|
return tr;
|
|
},
|
|
}),
|
|
];
|
|
},
|
|
|
|
addNodeView() {
|
|
const opts = this.options;
|
|
return ({ node: initial, editor, getPos }) => {
|
|
let node = initial;
|
|
const labels = opts.labels ?? englishLabels;
|
|
const doc = opts.doc;
|
|
const canEdit = () => editor.isEditable && !!doc && !opts.readOnlyDoc;
|
|
|
|
let store: DbStore | null = null;
|
|
let stop: (() => void) | null = null;
|
|
let peek: RowPeek | null = null;
|
|
let view: DatabaseView | null = null;
|
|
const wrap = h("div", { class: "dw-db-node" });
|
|
|
|
const id = () => String(node.attrs.id);
|
|
const mapOf = () => {
|
|
const m = doc ? blocksOf(doc).get(id()) : undefined;
|
|
return m instanceof Y.Map ? m : null;
|
|
};
|
|
const snapshot = (): DbData => {
|
|
const m = mapOf();
|
|
if (m) return readDb(m);
|
|
return node.attrs.data ? normalize(node.attrs.data) : emptyDb(dbDefaults(opts.labels));
|
|
};
|
|
|
|
const host = () => ({
|
|
labels: labels.database,
|
|
colorNames: labels.colors,
|
|
locale: labels.locale,
|
|
files: opts.files,
|
|
people: opts.people,
|
|
store,
|
|
});
|
|
|
|
const mountBody = (el: HTMLElement, row: Row) => {
|
|
const make = opts.rowExtensions;
|
|
if (!make) return null;
|
|
const m = mapOf();
|
|
let fragment: Y.XmlFragment | null = null;
|
|
if (m) {
|
|
fragment = store ? store.rowBody(row.id) : findBody(m, row.id);
|
|
if (!fragment) {
|
|
el.append(h("p", { class: "dw-db-peek__note" }, labels.database.bodyReadOnly));
|
|
return null;
|
|
}
|
|
}
|
|
const editable = !!store;
|
|
const ed = new Editor({
|
|
element: el,
|
|
editable,
|
|
extensions: make(fragment),
|
|
content: fragment ? undefined : { type: "doc", content: (row.body as JSONContent[] | undefined) ?? [{ type: "paragraph" }] },
|
|
editorProps: { attributes: { class: "dw-prose dw-db-peek__prose" } },
|
|
});
|
|
if (!fragment && !row.body?.length) el.replaceChildren(h("p", { class: "dw-db-peek__note" }, labels.database.bodyReadOnly));
|
|
return () => ed.destroy();
|
|
};
|
|
|
|
const openRow = (rowId: string, order: string[]) => {
|
|
peek?.close();
|
|
peek = new RowPeek({ ctx: { ...host(), }, mountBody }, snapshot(), rowId, order, () => (peek = null));
|
|
};
|
|
|
|
const refresh = () => {
|
|
const db = snapshot();
|
|
view?.update(db, { store });
|
|
peek?.update(db, { store });
|
|
};
|
|
|
|
/** Binds to the database's map, making it when an editor finds none. */
|
|
const bind = () => {
|
|
stop?.();
|
|
stop = null;
|
|
store = null;
|
|
if (!doc) return;
|
|
let m = mapOf();
|
|
if (!m && canEdit()) {
|
|
const data = node.attrs.data ? normalize(node.attrs.data) : emptyDb(dbDefaults(opts.labels));
|
|
const newIdNeeded = !id();
|
|
const key = newIdNeeded ? newId() : id();
|
|
seedDb(doc, key, data, (json, f) => writeBody(editor, json, f));
|
|
// Keep only the id in the document from now on.
|
|
queueMicrotask(() => {
|
|
const pos = typeof getPos === "function" ? getPos() : undefined;
|
|
if (pos !== undefined && editor.state.doc.nodeAt(pos)?.type.name === "database") {
|
|
editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, id: key, data: null }).setMeta("addToHistory", false));
|
|
}
|
|
});
|
|
m = blocksOf(doc).get(key) as Y.Map<unknown>;
|
|
}
|
|
// The entry can be replaced as a whole: the server writes a new map on a
|
|
// restore or import, and a peer's map may still be on its way. Either
|
|
// way, bind to whatever is there now.
|
|
const blocks = blocksOf(doc);
|
|
const onKey = (e: Y.YMapEvent<Y.Map<unknown>>) => {
|
|
if (!e.keysChanged.has(id())) return;
|
|
bind();
|
|
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]);
|
|
};
|
|
blocks.observe(onKey);
|
|
if (m) {
|
|
if (canEdit()) store = new DbStore(doc, m, () => opts.me?.() ?? null);
|
|
const watched = m;
|
|
const onChange = () => refresh();
|
|
watched.observeDeep(onChange);
|
|
stop = () => {
|
|
blocks.unobserve(onKey);
|
|
watched.unobserveDeep(onChange);
|
|
};
|
|
} else {
|
|
stop = () => blocks.unobserve(onKey);
|
|
}
|
|
};
|
|
bind();
|
|
|
|
view = new DatabaseView(
|
|
{
|
|
...host(),
|
|
openRow,
|
|
undo: () => editor.commands.undo?.(),
|
|
redo: () => editor.commands.redo?.(),
|
|
notify: opts.notify,
|
|
},
|
|
snapshot(),
|
|
);
|
|
wrap.append(view.dom);
|
|
|
|
let wasEditable = canEdit();
|
|
const onEditable = () => {
|
|
if (canEdit() === wasEditable) return;
|
|
wasEditable = canEdit();
|
|
bind();
|
|
refresh();
|
|
};
|
|
editor.on("update", onEditable);
|
|
editor.on("transaction", onEditable);
|
|
|
|
return {
|
|
dom: wrap,
|
|
update(next) {
|
|
if (next.type !== node.type) return false;
|
|
const changed = next.attrs.id !== node.attrs.id;
|
|
node = next;
|
|
if (changed) bind();
|
|
refresh();
|
|
return true;
|
|
},
|
|
ignoreMutation: () => true,
|
|
// The block handles its own clicks, keys, drags and clipboard, except the drag of the whole block.
|
|
stopEvent: (e) => !(e.type === "dragstart" && (e.target as HTMLElement) === wrap),
|
|
destroy() {
|
|
stop?.();
|
|
peek?.close();
|
|
view?.destroy();
|
|
editor.off("update", onEditable);
|
|
editor.off("transaction", onEditable);
|
|
},
|
|
};
|
|
};
|
|
},
|
|
});
|
|
|
|
/** Writes ProseMirror nodes into a row body fragment with the editor's schema. */
|
|
function writeBody(editor: Editor, json: unknown[], f: Y.XmlFragment) {
|
|
try {
|
|
prosemirrorJSONToYXmlFragment(editor.schema, { type: "doc", content: json }, f);
|
|
} catch {
|
|
/* a body with nodes this editor does not know stays empty */
|
|
}
|
|
}
|
|
|
|
function findBody(m: Y.Map<unknown>, rowId: string): Y.XmlFragment | null {
|
|
const rows = m.get("rows");
|
|
if (!(rows instanceof Y.Array)) return null;
|
|
for (const r of rows.toArray() as Y.Map<unknown>[]) {
|
|
if (r.get("id") === rowId) {
|
|
const b = r.get("body");
|
|
return b instanceof Y.XmlFragment && b.length ? b : null;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** A copy of a database with new row ids (column and view ids stay, they are local to it). */
|
|
function freshIds(db: DbData): DbData {
|
|
return { ...db, rows: db.rows.map((r) => ({ ...r, id: newId() })) };
|
|
}
|
|
|
|
interface ListFound {
|
|
from: number;
|
|
to: number;
|
|
checks: boolean;
|
|
items: { text: string; checked: boolean; rest: JSONContent[] }[];
|
|
}
|
|
|
|
/**
|
|
* The list around the selection (or the top-level blocks it spans) as items:
|
|
* each item's first line is its title, the rest its body.
|
|
*/
|
|
function listAt($from: import("@tiptap/pm/model").ResolvedPos, $to: import("@tiptap/pm/model").ResolvedPos): ListFound | null {
|
|
for (let d = $from.depth; d > 0; d--) {
|
|
const n = $from.node(d);
|
|
if (["bulletList", "orderedList", "taskList"].includes(n.type.name)) {
|
|
const items: ListFound["items"] = [];
|
|
n.forEach((item) => {
|
|
const first = item.firstChild;
|
|
const rest: JSONContent[] = [];
|
|
item.forEach((c, _o, i) => {
|
|
if (i > 0) rest.push(c.toJSON() as JSONContent);
|
|
});
|
|
items.push({ text: first?.textContent ?? "", checked: !!item.attrs.checked, rest });
|
|
});
|
|
return { from: $from.before(d), to: $from.after(d), checks: n.type.name === "taskList", items };
|
|
}
|
|
}
|
|
if ($from.depth < 1) return null;
|
|
const from = $from.before(1);
|
|
const to = $to.after(Math.min(1, $to.depth) || 1);
|
|
const items: ListFound["items"] = [];
|
|
$from.doc.nodesBetween(from, to, (n, pos) => {
|
|
if (pos < from || pos >= to) return false;
|
|
if (n.isTextblock && n.textContent.trim()) items.push({ text: n.textContent, checked: false, rest: [] });
|
|
return !n.isTextblock;
|
|
});
|
|
return items.length > 1 ? { from, to, checks: false, items } : null;
|
|
}
|