Records are bars from the view's date property to an end date property (chosen in the view's settings; without one a bar lasts a day), by days, weeks or months. Dragging a bar moves both dates; its right edge changes the end. Records without a start are listed below, like on the calendar. Bars stop the browser's own drag of the surrounding block. Also fixes the view settings panel: the properties list cleared the whole panel when it drew, so a calendar never showed its date property. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
782 lines
29 KiB
TypeScript
782 lines
29 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 type { PageHost } from "../pagelinks";
|
|
import type { SyncedPageHost } from "../syncedpage";
|
|
import type { CollabProvider } from "../provider";
|
|
import { computeLinked, relationIds, 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, openRecord as openRecordIn, recordHash, type OpenRecordDetail } from "./links";
|
|
|
|
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;
|
|
/**
|
|
* The full address of a link to a record, from its "#r-…" fragment
|
|
* (links.ts). Without it records have no "Copy link".
|
|
*/
|
|
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" {
|
|
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,
|
|
recordLink: undefined,
|
|
onLinkCopied: undefined,
|
|
linkedPages: undefined,
|
|
pages: undefined,
|
|
onNavigate: undefined,
|
|
recordPage: 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 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;
|
|
};
|
|
/** A store for database t when this editor can change it: this one, or another on this page. */
|
|
const storeFor = (t: RelationTarget): DbStore | null => {
|
|
if (!canEdit() || !doc || !isSelf(t.page)) return null;
|
|
if (t.database === id()) return store;
|
|
const m = blocksOf(doc).get(t.database);
|
|
return m instanceof Y.Map ? new DbStore(doc, m, () => opts.me?.() ?? null) : null;
|
|
};
|
|
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,
|
|
pointsHere: (t, rel) => {
|
|
if (rel.database !== id()) return false;
|
|
// rel.page is relative to database t's page: "" (or its id) when t is here.
|
|
if (isSelf(t.page)) return isSelf(rel.page);
|
|
return !!opts.linkedPages?.self && rel.page === opts.linkedPages.self;
|
|
},
|
|
writable: (t) => !!storeFor(t),
|
|
link: (t, row, other, on) => {
|
|
const st = storeFor(t);
|
|
const back = t.back;
|
|
if (!st || !back) return false;
|
|
const r = st.snapshot().rows.find((x) => x.id === other);
|
|
if (!r) return false;
|
|
const ids = relationIds(r.cells[back]).filter((x) => x !== row);
|
|
if (on) ids.push(row);
|
|
st.setCell(other, back, ids.length ? ids : null);
|
|
return true;
|
|
},
|
|
addBack: (t, col, name) => {
|
|
const st = storeFor(t);
|
|
if (!st) return false;
|
|
st.tx(() => {
|
|
const c = st.addColumn("relation", name);
|
|
st.setRelation(c, { page: "", database: id(), back: col });
|
|
});
|
|
return true;
|
|
},
|
|
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,
|
|
locale: labels.locale,
|
|
files: opts.files,
|
|
people: opts.people,
|
|
store,
|
|
linked,
|
|
});
|
|
|
|
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 link = opts.recordLink;
|
|
const copyLink = link
|
|
? (rowId: string) => {
|
|
const url = link(recordHash(id(), rowId));
|
|
void copyText(url).then((ok) => ok && opts.onLinkCopied?.(url));
|
|
}
|
|
: undefined;
|
|
|
|
// A link to one of this database's records (links.ts) opens it.
|
|
wrap.addEventListener(OPEN_RECORD, (e) => {
|
|
const detail = (e as CustomEvent<OpenRecordDetail>).detail;
|
|
const db = snapshot();
|
|
if (!db.rows.some((r) => r.id === detail.row)) return;
|
|
detail.found = true;
|
|
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 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 = () => {
|
|
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], pageMode);
|
|
};
|
|
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,
|
|
copyLink,
|
|
},
|
|
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?.();
|
|
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);
|
|
},
|
|
};
|
|
};
|
|
},
|
|
});
|
|
|
|
/** 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;
|
|
}
|