Files
Docwell/Packages/editor/src/blockmenu.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

301 lines
10 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
import type { ChainedCommands, Editor, JSONContent } from "@tiptap/core";
import { Fragment } from "@tiptap/pm/model";
import { Selection } from "@tiptap/pm/state";
import type { IconName } from "@docwell/ui/icons";
import { showsLineNumbers } from "./codeblock";
import type { EditorLabels } from "./labels";
import { isPdf } from "./pdf";
import { svgIcon } from "./suggestion";
/** One row of the block menu; a row with children opens a list of them instead. */
export interface BlockAction {
id: string;
label: string;
icon: IconName;
run?: () => void;
children?: BlockAction[];
danger?: boolean;
}
/** What a block's text can turn into, as slash-menu ids with the commands that make them. */
const conversions: [string, IconName, (c: ChainedCommands) => ChainedCommands][] = [
["text", "text", (c) => c],
["h1", "heading", (c) => c.setNode("heading", { level: 1 })],
["h2", "heading", (c) => c.setNode("heading", { level: 2 })],
["h3", "heading", (c) => c.setNode("heading", { level: 3 })],
["bullet", "list", (c) => c.toggleBulletList()],
["ordered", "list-ordered", (c) => c.toggleOrderedList()],
["todo", "todo", (c) => c.toggleTaskList()],
["quote", "quote", (c) => c.setBlockquote()],
["code", "code", (c) => c.setCodeBlock()],
["callout", "callout", (c) => c.setCallout()],
];
/** Blocks whose text the menu can turn into another kind of block. */
const convertible = [
"paragraph",
"heading",
"codeBlock",
"blockquote",
"bulletList",
"orderedList",
"taskList",
"callout",
];
/** A block's JSON without block ids, so a copy does not share links with the original. */
function withoutIds(json: JSONContent): JSONContent {
const out: JSONContent = { ...json };
if (out.attrs && "blockId" in out.attrs) out.attrs = { ...out.attrs, blockId: null };
if (out.content) out.content = out.content.map(withoutIds);
return out;
}
/**
* The actions for the top-level block at pos: turn into, move, duplicate,
* copy, delete, plus block-specific ones (line numbers, PDF pages).
*/
export function blockActions(editor: Editor, pos: number, labels: EditorLabels, copyLink?: () => void): BlockAction[] {
const node = editor.state.doc.nodeAt(pos);
if (!node) return [];
const m = labels.blockMenu;
const end = pos + node.nodeSize;
const index = editor.state.doc.resolve(pos).index(0);
const out: BlockAction[] = [];
if (convertible.includes(node.type.name)) {
out.push({
id: "turnInto",
label: m.turnInto,
icon: "text",
children: conversions.map(([id, icon, make]) => ({
id,
icon,
label: labels.slash[id]?.label ?? id,
run: () => {
if (id === "callout") {
// A callout holds any block, so the block goes in as it is (a
// heading stays a heading); a quote gives it its contents.
if (node.type.name === "callout") return;
const inner = node.type.name === "blockquote" ? node.content : Fragment.from(node);
const callout = editor.schema.nodes.callout!.create(null, inner);
const tr = editor.state.tr.replaceWith(pos, end, callout);
editor.view.dispatch(tr.setSelection(Selection.near(tr.doc.resolve(pos + 1))).scrollIntoView());
editor.commands.focus();
return;
}
// Select the block's text from its first to its last line (lists and
// callouts hold it deeper down), then make plain paragraphs of it, so
// every kind starts from the same place.
const doc = editor.state.doc;
const from = Selection.findFrom(doc.resolve(pos), 1, true)?.from ?? pos + 1;
const to = Selection.findFrom(doc.resolve(end), -1, true)?.to ?? end - 1;
const chain = editor.chain().focus().setTextSelection({ from, to }).clearNodes();
make(chain).run();
},
})),
});
}
if (["bulletList", "orderedList", "taskList"].includes(node.type.name)) {
out.push({
id: "groupAsDatabase",
label: labels.database.groupAsDatabase,
icon: "database",
run: () => {
editor
.chain()
.focus()
.setTextSelection(pos + 2)
.groupAsDatabase()
.run();
},
});
}
if (node.type.name === "codeBlock") {
const byDefault = !!editor.extensionManager.extensions.find((e) => e.name === "codeBlock")?.options.lineNumbers;
const on = showsLineNumbers(node.attrs.lineNumbers, byDefault);
out.push({
id: "lineNumbers",
label: on ? m.hideLineNumbers : m.showLineNumbers,
icon: "list-ordered",
run: () => editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, "lineNumbers", !on)),
});
}
if (node.type.name === "fileAttachment" && isPdf(node.attrs.mime, node.attrs.name)) {
const preview = node.attrs.view === "preview";
out.push({
id: "pdfView",
label: preview ? m.showAsFile : m.showPages,
icon: preview ? "paperclip" : "file",
run: () => editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, "view", preview ? "card" : "preview")),
});
}
if (index > 0) {
out.push({
id: "moveUp",
label: m.moveUp,
icon: "arrow-up",
run: () => {
const prev = editor.state.doc.child(index - 1);
const tr = editor.state.tr.delete(pos, end).insert(pos - prev.nodeSize, node);
editor.view.dispatch(tr.scrollIntoView());
},
});
}
if (index < editor.state.doc.childCount - 1) {
out.push({
id: "moveDown",
label: m.moveDown,
icon: "arrow-down",
run: () => {
const next = editor.state.doc.child(index + 1);
const tr = editor.state.tr.delete(pos, end).insert(pos + next.nodeSize, node);
editor.view.dispatch(tr.scrollIntoView());
},
});
}
out.push(
{
id: "duplicate",
label: m.duplicate,
icon: "plus",
run: () => {
const copy = editor.schema.nodeFromJSON(withoutIds(node.toJSON() as JSONContent));
editor.view.dispatch(editor.state.tr.insert(end, copy).scrollIntoView());
},
},
{
id: "copy",
label: m.copy,
icon: "copy",
run: () => {
// The browser's own copy keeps the block's formatting for pasting elsewhere.
editor.chain().focus().setNodeSelection(pos).run();
document.execCommand("copy");
},
},
);
if (copyLink) out.push({ id: "copyLink", label: labels.blocks.copyBlockLink, icon: "link", run: copyLink });
out.push({
id: "delete",
label: m.delete,
icon: "trash",
danger: true,
run: () => {
editor.view.dispatch(editor.state.tr.delete(pos, end));
editor.commands.focus();
},
});
return out;
}
/**
* Shows actions in a menu next to anchor. Arrows move, Enter picks, Escape
* or a click elsewhere closes it. Returns a function that closes it.
*/
export function openBlockMenu(anchor: HTMLElement, actions: BlockAction[], label: string, onClose?: () => void) {
const box = document.createElement("div");
box.className = "dw-suggest dw-block-menu";
box.setAttribute("role", "menu");
box.setAttribute("aria-label", label);
let list = actions;
let active = 0;
let stack: BlockAction[][] = [];
const draw = () => {
box.replaceChildren();
list.forEach((a, i) => {
const row = document.createElement("button");
row.type = "button";
row.className = `dw-suggest__item${i === active ? " is-active" : ""}${a.danger ? " is-danger" : ""}`;
row.setAttribute("role", "menuitem");
row.tabIndex = -1;
if (a.children) row.setAttribute("aria-haspopup", "menu");
const glyph = document.createElement("span");
glyph.className = "dw-suggest__icon";
glyph.append(svgIcon(a.icon));
const text = document.createElement("span");
text.className = "dw-suggest__label";
text.textContent = a.label;
row.append(glyph, text);
if (a.children) {
const more = svgIcon("chevron-right", 14);
more.classList.add("dw-block-menu__more");
row.append(more);
}
row.addEventListener("mousedown", (e) => e.preventDefault());
row.addEventListener("click", () => pick(i));
row.addEventListener("mouseenter", () => {
active = i;
for (const [j, r] of [...box.children].entries()) r.classList.toggle("is-active", j === i);
});
box.append(row);
});
(box.children[active] as HTMLElement | undefined)?.focus();
};
const pick = (i: number) => {
const a = list[i];
if (!a) return;
if (a.children) {
stack.push(list);
list = a.children;
active = 0;
draw();
return;
}
close();
a.run?.();
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape" || (e.key === "ArrowLeft" && stack.length)) {
e.preventDefault();
e.stopPropagation();
if (stack.length) {
list = stack.pop()!;
active = 0;
draw();
} else close();
return;
}
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
active = (active + (e.key === "ArrowDown" ? 1 : -1) + list.length) % list.length;
draw();
} else if (e.key === "Enter" || e.key === " " || e.key === "ArrowRight") {
e.preventDefault();
if (e.key !== "ArrowRight" || list[active]?.children) pick(active);
}
};
const onDown = (e: MouseEvent) => {
if (!box.contains(e.target as Node) && !anchor.contains(e.target as Node)) close();
};
document.body.append(box);
const stop = autoUpdate(anchor, box, () => {
void computePosition(anchor, box, {
placement: "bottom-start",
strategy: "fixed",
middleware: [offset(4), flip(), shift({ padding: 8 })],
}).then(({ x, y }) => Object.assign(box.style, { left: `${x}px`, top: `${y}px` }));
});
box.addEventListener("keydown", onKey);
document.addEventListener("mousedown", onDown, true);
let closed = false;
function close() {
if (closed) return;
closed = true;
stop();
box.remove();
document.removeEventListener("mousedown", onDown, true);
stack = [];
onClose?.();
}
draw();
return close;
}