Add Word export, column dragging and the rest of editor parity
CI / go (Server) (push) Failing after 8m51s
CI / go (Web-App) (push) Successful in 11m46s
CI / mobile (push) Failing after 3m44s
CI / docker (push) Successful in 54m15s
Docs / build (push) Successful in 12m28s
Docs / deploy (push) Skipped
CI / frontend (push) Failing after 7m47s
CI / desktop (ubuntu-latest) (push) Successful in 1h27m22s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

Word export: pages download as .docx from the page menu and from
GET /pages/{id}/export?format=docx. The file keeps headings, alignment,
lists, to-dos, quotes, callouts, code, tables with a repeating header
row, text formatting, colours, highlights, links and the page's images.
Word import now reads callouts, to-dos and shaded highlights, so a page
exported to Word imports back as it was. The user guide says how to move
pages to Notion, whose Import reads Word and Markdown files.

Editor:
- Columns move like rows: a grip on the column's top edge drags it, and
  the table toolbar and Ctrl+Alt+Left/Right move it from the keyboard.
  Row and column moving share tablemove.ts.
- Ctrl+Shift+C copies a link to the block the cursor is in.
- Headings 4 to 6 sit under "Other headings" in the slash menu; a search
  still finds them directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-14 13:01:06 +01:00
1 parent d28f1e02db
commit 3dea2bb2f4
28 files changed
+1630 -432

No files matched your search

+7 -10
View File
@@ -6,7 +6,7 @@ import { BubbleMenu } from "@tiptap/vue-3/menus";
import { CellSelection } from "@tiptap/pm/tables";
import { DwIcon, type IconName } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { blockHash, ensureBlockId } from "./blocklinks";
import { copyBlockLink } from "./blocklinks";
import { palette, type PaletteColor } from "./colors";
import { docwellExtensions, type CollabUser } from "./extensions";
import { findKey } from "./find";
@@ -188,13 +188,8 @@ const tools = computed<Tool[]>(() => {
active: () => false,
run: () => {
const $from = e.state.selection.$from;
const id = $from.depth >= 1 ? ensureBlockId(e.view, $from.before(1)) : null;
if (!id) return;
const url = blockLink(blockHash(id));
navigator.clipboard.writeText(url).then(
() => emit("block-link-copied", url),
() => window.prompt("", url),
);
if ($from.depth >= 1)
void copyBlockLink(e.view, $from.before(1), blockLink, (url) => emit("block-link-copied", url));
},
});
}
@@ -215,7 +210,7 @@ function setAlign(a: "left" | "center" | "right") {
// The table toolbar sits above the table the cursor is in.
type TableTool = {
id: Exclude<keyof EditorLabels["table"], "toolbar" | "dragRow">;
id: Exclude<keyof EditorLabels["table"], "toolbar" | "dragRow" | "dragColumn">;
run: (e: Editor) => boolean;
danger?: boolean;
};
@@ -226,6 +221,8 @@ const tableTools: TableTool[] = [
{ id: "addColumnAfter", run: (e) => e.chain().focus().addColumnAfter().run() },
{ id: "moveRowUp", run: (e) => e.chain().focus().moveTableRow(-1).run() },
{ id: "moveRowDown", run: (e) => e.chain().focus().moveTableRow(1).run() },
{ id: "moveColumnLeft", run: (e) => e.chain().focus().moveTableColumn(-1).run() },
{ id: "moveColumnRight", run: (e) => e.chain().focus().moveTableColumn(1).run() },
{ id: "deleteRow", run: (e) => e.chain().focus().deleteRow().run() },
{ id: "deleteColumn", run: (e) => e.chain().focus().deleteColumn().run() },
{ id: "toggleHeaderRow", run: (e) => e.chain().focus().toggleHeaderRow().run() },
@@ -533,7 +530,7 @@ defineExpose({ editor, openFind });
plugin-key="tableMenu"
:should-show="showTableMenu"
:get-referenced-virtual-element="tableElement"
:options="{ placement: 'top-start', offset: 6 }"
:options="{ placement: 'top-start', offset: 12 }"
class="flex max-w-[calc(100vw-16px)] flex-wrap items-center gap-0.5 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
role="toolbar"
:aria-label="labels.table.toolbar"
+43 -10
View File
@@ -60,6 +60,28 @@ export function ensureBlockId(view: EditorView, pos: number): string | null {
return fresh;
}
/**
* Copies the full address of a link to the block at pos, giving the block an
* id first if it needs one. Returns false when the block cannot be linked.
*/
export async function copyBlockLink(
view: EditorView,
pos: number,
link: (hash: string) => string,
onCopied?: (url: string) => void,
): Promise<boolean> {
const id = ensureBlockId(view, pos);
if (!id) return false;
const url = link(blockHash(id));
try {
await navigator.clipboard.writeText(url);
onCopied?.(url);
} catch {
window.prompt("", url);
}
return true;
}
function findBlock(doc: PMNode, id: string): number {
let found = -1;
doc.descendants((node, pos) => {
@@ -130,6 +152,26 @@ export const BlockLinks = Extension.create<BlockLinkOptions>({
];
},
addKeyboardShortcuts() {
const { link, onCopied } = this.options;
return {
// Ctrl+Shift+C (as in AFFiNE): copy a link to the block the cursor is in.
// Some browsers keep the key for their developer tools; the toolbar
// and margin buttons do the same everywhere.
"Mod-Shift-c": ({ editor }) => {
if (!link) return false;
const $from = editor.state.selection.$from;
if ($from.depth < 1) return false;
const pos = $from.before(1);
const node = editor.state.doc.nodeAt(pos);
if (!node || !linkable.includes(node.type.name)) return false;
if (!node.attrs.blockId && !editor.isEditable) return false;
void copyBlockLink(editor.view, pos, link, onCopied);
return true;
},
};
},
addProseMirrorPlugins() {
const { link, onCopied } = this.options;
const labels = this.options.labels!;
@@ -284,16 +326,7 @@ class BlockHandle {
};
private async copy(at = this.pos) {
if (at < 0 || !this.link) return;
const id = ensureBlockId(this.view, at);
if (!id) return;
const url = this.link(blockHash(id));
try {
await navigator.clipboard.writeText(url);
this.onCopied?.(url);
} catch {
window.prompt("", url);
}
if (at >= 0 && this.link) await copyBlockLink(this.view, at, this.link, this.onCopied);
}
update() {
+33 -2
View File
@@ -84,10 +84,18 @@ describe("new blocks", () => {
it("offers the new blocks and date shortcuts in the slash menu", () => {
const ids = filterCommands(slashCommands(englishLabels), "").map((c) => c.id);
for (const id of ["h4", "h5", "h6", "todo", "callout", "table", "today", "tomorrow", "yesterday", "now"]) {
for (const id of ["otherHeadings", "todo", "callout", "table", "today", "tomorrow", "yesterday", "now"]) {
expect(ids).toContain(id);
}
expect(filterCommands(slashCommands(englishLabels), "other").map((c) => c.id)).toEqual(["h4", "h5", "h6"]);
// H4-H6 sit in a group, which a search looks into.
const all = slashCommands(englishLabels);
expect(all.find((c) => c.id === "otherHeadings")!.children!.map((c) => c.id)).toEqual(["h4", "h5", "h6"]);
expect(ids).not.toContain("h4");
expect(filterCommands(all, "other").map((c) => c.id)).toEqual(["otherHeadings"]);
expect(filterCommands(all, "h5").map((c) => c.id)).toEqual(["h5"]);
const headings = filterCommands(all, "heading").map((c) => c.id);
expect(headings).toEqual(expect.arrayContaining(["h1", "h4", "h5", "h6"]));
expect(headings).not.toContain("otherHeadings");
expect(ids).not.toContain("newPage");
const withPages = slashCommands(englishLabels, undefined, undefined, {
search: async () => [],
@@ -97,6 +105,29 @@ describe("new blocks", () => {
});
});
describe("Ctrl+Shift+C", () => {
it("copies a link to the block the cursor is in, giving it an id", async () => {
const written: string[] = [];
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: async (s: string) => void written.push(s) },
});
const copied: string[] = [];
const e = setup("<p>one</p><p>two</p>", {
blockLink: (hash) => `https://docwell.test/p/x${hash}`,
onBlockLinkCopied: (url) => copied.push(url),
});
e.commands.setTextSelection(e.state.doc.child(0).nodeSize + 2);
expect(e.commands.keyboardShortcut("Mod-Shift-c")).toBe(true);
await Promise.resolve();
const id = e.state.doc.child(1).attrs.blockId as string;
expect(id).toMatch(/^[a-z0-9]{8}$/);
expect(written).toEqual([`https://docwell.test/p/x#b-${id}`]);
expect(copied).toEqual(written);
expect(e.state.doc.child(0).attrs.blockId).toBeNull();
});
});
describe("blockActions", () => {
const doc = "<p>one</p><p>two</p><p>three</p>";
+20 -12
View File
@@ -1081,13 +1081,14 @@
.dw-block-menu .dw-suggest__item.is-danger :is(.dw-suggest__label, .dw-suggest__icon) {
color: var(--color-danger);
}
.dw-suggest__more,
.dw-block-menu__more {
margin-left: auto;
color: var(--color-ink-faint);
}
/* ---- Moving table rows (tablerows.ts) ---- */
.dw-row-grip {
/* ---- Moving table rows and columns (tablemove.ts) ---- */
.dw-table-grip {
position: absolute;
z-index: 5;
display: grid;
@@ -1102,36 +1103,43 @@
cursor: grab;
touch-action: none;
}
.dw-row-grip::before {
.dw-table-grip--column {
width: 22px;
height: 14px;
}
.dw-table-grip::before {
content: "";
width: 4px;
height: 10px;
background: radial-gradient(circle, currentColor 1px, transparent 1.5px) 0 0 / 4px 4px;
}
.dw-row-grip:hover,
.dw-row-grip:active {
.dw-table-grip--column::before {
width: 10px;
height: 4px;
}
.dw-table-grip:hover,
.dw-table-grip:active {
color: var(--color-ink);
border-color: var(--color-focus-ring);
}
.dw-row-grip:active {
.dw-table-grip:active {
cursor: grabbing;
}
.dw-row-grip[hidden],
.dw-row-drop[hidden] {
.dw-table-grip[hidden],
.dw-table-drop[hidden] {
display: none;
}
.dw-row-drop {
.dw-table-drop {
position: absolute;
z-index: 5;
height: 2px;
background: var(--color-focus-ring);
pointer-events: none;
}
.dw-prose tr.dw-row-dragging {
.dw-prose .dw-table-dragging {
opacity: 0.45;
}
@media (max-width: 640px), (hover: none) {
.dw-row-grip {
.dw-table-grip {
display: none;
}
}
+2 -2
View File
@@ -24,7 +24,7 @@ import { PageLinks, type PageHost } from "./pagelinks";
import type { PdfLoader } from "./pdf";
import { SlashMenu, slashCommands } from "./slash";
import type { CollabProvider } from "./provider";
import { TableRows } from "./tablerows";
import { TableMove } from "./tablemove";
import { TableOfContents } from "./toc";
import { docwellToggles } from "./toggle";
@@ -110,7 +110,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
DocwellHighlight,
...docwellTasks(),
...docwellTables(),
TableRows.configure({ labels }),
TableMove.configure({ labels }),
Callout.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
+11 -3
View File
@@ -41,8 +41,12 @@ export interface EditorLabels {
toolbar: string;
/** The grip on a row's left edge. */
dragRow: string;
/** The grip on a column's top edge. */
dragColumn: string;
moveRowUp: string;
moveRowDown: string;
moveColumnLeft: string;
moveColumnRight: string;
addRowBefore: string;
addRowAfter: string;
addColumnBefore: string;
@@ -138,9 +142,10 @@ export const englishLabels: EditorLabels = {
h1: { label: "Heading 1", description: "Big section heading" },
h2: { label: "Heading 2", description: "Medium section heading" },
h3: { label: "Heading 3", description: "Small section heading" },
h4: { label: "Heading 4", description: "Other headings: level 4" },
h5: { label: "Heading 5", description: "Other headings: level 5" },
h6: { label: "Heading 6", description: "Other headings: level 6" },
otherHeadings: { label: "Other headings", description: "Headings 4 to 6" },
h4: { label: "Heading 4", description: "A heading below level 3" },
h5: { label: "Heading 5", description: "A heading below level 4" },
h6: { label: "Heading 6", description: "The smallest heading" },
bullet: { label: "Bulleted list", description: "A simple list" },
ordered: { label: "Numbered list", description: "A list with numbers" },
todo: { label: "To-do list", description: "Tasks to tick off (or type [])" },
@@ -201,8 +206,11 @@ export const englishLabels: EditorLabels = {
table: {
toolbar: "Table",
dragRow: "Drag to move the row",
dragColumn: "Drag to move the column",
moveRowUp: "Move row up",
moveRowDown: "Move row down",
moveColumnLeft: "Move column left",
moveColumnRight: "Move column right",
addRowBefore: "Add row above",
addRowAfter: "Add row below",
addColumnBefore: "Add column left",
+22 -9
View File
@@ -20,6 +20,8 @@ export interface SlashCommand {
/** Extra words the filter matches, e.g. "h1" for Heading 1. */
keywords: string[];
run: (editor: Editor, range: Range) => void;
/** A group: picking it opens these instead of running. A search finds them directly too. */
children?: SlashCommand[];
}
/** Opens the system file picker and resolves with the chosen files. */
@@ -67,11 +69,14 @@ export function slashCommands(
block("h3", "heading", ["heading", "###"], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level: 3 }).run(),
),
...([4, 5, 6] as const).map((level) =>
block(`h${level}`, "heading", ["heading", "other headings", "#".repeat(level)], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level }).run(),
{
...block("otherHeadings", "heading", ["other", "more headings", "smaller"], () => {}),
children: ([4, 5, 6] as const).map((level) =>
block(`h${level}`, "heading", ["heading", "#".repeat(level)], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level }).run(),
),
),
),
},
block("bullet", "list", ["list", "ul", "-"], (e, r) => e.chain().focus().deleteRange(r).toggleBulletList().run()),
block("ordered", "list-ordered", ["list", "ol", "1."], (e, r) =>
e.chain().focus().deleteRange(r).toggleOrderedList().run(),
@@ -168,14 +173,21 @@ export function slashCommands(
return list;
}
/** Filters commands by what follows the "/": label, id or keywords. */
/**
* Filters commands by what follows the "/": label, id or keywords. With a
* query, the commands inside groups are matched and listed on their own.
*/
export function filterCommands(commands: SlashCommand[], query: string): SlashCommand[] {
const q = query.trim().toLowerCase();
if (!q) return commands;
return commands.filter(
(c) =>
c.label.toLowerCase().includes(q) || c.id.startsWith(q) || c.keywords.some((k) => k.toLowerCase().startsWith(q)),
);
const matches = (c: SlashCommand) =>
c.label.toLowerCase().includes(q) || c.id.startsWith(q) || c.keywords.some((k) => k.toLowerCase().startsWith(q));
return commands.flatMap((c) => {
// A search finds the commands in a group; the group itself when none of them match.
const inside = c.children?.filter(matches) ?? [];
if (inside.length) return inside;
return matches(c) ? [c] : [];
});
}
/** Typing "/" at the start of a word opens the block menu. */
@@ -205,6 +217,7 @@ export const SlashMenu = Extension.create<{ commands: SlashCommand[]; labels: Ed
empty: this.options.labels.noMatches,
showQuery: true,
toItem: (c) => ({ label: c.label, description: c.description, icon: c.icon }),
children: (c) => c.children,
pick: (p, c) => c.run(p.editor, p.range),
}),
}),
+48 -6
View File
@@ -49,16 +49,29 @@ export function floatingList<T>(opts: {
toItem: (item: T) => ListItem;
pick: (props: SuggestionProps<T>, item: T) => void;
showQuery?: boolean;
/** An item that opens a list of its own instead of being picked ("Other headings"). */
children?: (item: T) => T[] | undefined;
}) {
return () => {
let box: HTMLDivElement | null = null;
let stop: (() => void) | null = null;
let current: SuggestionProps<T> | null = null;
let active = 0;
// The list of a group the user opened, with the group, until the query changes.
let sub: { parent: T; items: T[] } | null = null;
const items = () => sub?.items ?? current?.items ?? [];
const choose = (i: number) => {
const item = current?.items[i];
if (current && item !== undefined) opts.pick(current, item);
const item = items()[i];
if (!current || item === undefined) return;
const kids = opts.children?.(item);
if (kids?.length) {
sub = { parent: item, items: kids };
active = 0;
draw();
return;
}
opts.pick(current, item);
};
const draw = () => {
@@ -71,7 +84,15 @@ export function floatingList<T>(opts: {
q.textContent = `/${p.query}`;
box.append(q);
}
if (!p.items.length) {
if (sub) {
// The open group, which ArrowLeft or Escape leaves.
const head = document.createElement("div");
head.className = "dw-suggest__query";
head.textContent = `‹ ${opts.toItem(sub.parent).label}`;
box.append(head);
}
const list = items();
if (!list.length) {
const empty = document.createElement("div");
empty.className = "dw-suggest__empty";
empty.setAttribute("role", "status");
@@ -79,7 +100,7 @@ export function floatingList<T>(opts: {
box.append(empty);
return;
}
p.items.forEach((raw, i) => {
list.forEach((raw, i) => {
const it = opts.toItem(raw);
const row = document.createElement("div");
row.className = i === active ? "dw-suggest__item is-active" : "dw-suggest__item";
@@ -106,6 +127,12 @@ export function floatingList<T>(opts: {
text.append(desc);
}
row.append(glyph, text);
if (opts.children?.(raw)?.length) {
row.setAttribute("aria-haspopup", "listbox");
const more = svgIcon("chevron-right", 14);
more.classList.add("dw-suggest__more");
row.append(more);
}
box!.append(row);
});
box.querySelector(".is-active")?.scrollIntoView({ block: "nearest" });
@@ -139,6 +166,7 @@ export function floatingList<T>(opts: {
onStart(p: SuggestionProps<T>) {
current = p;
active = 0;
sub = null;
box = document.createElement("div");
box.className = "dw-suggest";
box.setAttribute("role", "listbox");
@@ -148,13 +176,27 @@ export function floatingList<T>(opts: {
place();
},
onUpdate(p: SuggestionProps<T>) {
if (p.items !== current?.items) active = 0;
if (p.items !== current?.items) {
active = 0;
sub = null;
}
current = p;
draw();
place();
},
onKeyDown({ event }: SuggestionKeyDownProps) {
const n = current?.items.length ?? 0;
const n = items().length;
if (sub && (event.key === "Escape" || event.key === "ArrowLeft")) {
sub = null;
active = 0;
draw();
return true;
}
const at = items()[active];
if (event.key === "ArrowRight" && at !== undefined && opts.children?.(at)?.length) {
choose(active);
return true;
}
if (event.key === "Escape") {
close();
return true;
+118
View File
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { docwellExtensions } from "./extensions";
import { moveInTable } from "./tablemove";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
/** A table after a paragraph; each row is its cells' text. */
const table = (rows: string[][]) =>
`<p>before</p><table>${rows.map((r) => `<tr>${r.map((c) => `<td><p>${c}</p></td>`).join("")}</tr>`).join("")}</table>`;
function setup(html: string) {
editor = new Editor({ extensions: docwellExtensions(), content: html });
return editor;
}
const grid = (e: Editor) => {
const out: string[][] = [];
e.state.doc.descendants((n) => {
if (n.type.name === "tableRow") out.push(Array.from({ length: n.childCount }, (_, i) => n.child(i).textContent));
return n.type.name !== "tableRow";
});
return out;
};
const tablePos = (e: Editor) => e.state.doc.child(0).nodeSize;
/** A position inside the cell at row, column. */
function inCell(e: Editor, row: number, column: number) {
let pos = -1;
let r = 0;
e.state.doc.descendants((n, p) => {
if (pos >= 0) return false;
if (n.type.name !== "tableRow") return true;
if (r++ === row) {
pos = p + 1;
for (let i = 0; i < column; i++) pos += n.child(i).nodeSize;
pos += 2;
}
return false;
});
return pos;
}
const abc = [
["a", "a2"],
["b", "b2"],
["c", "c2"],
];
describe("moving table rows", () => {
it("moves a row to another place and keeps the cursor in it", () => {
const e = setup(table(abc));
e.view.dispatch(moveInTable(e.state, tablePos(e), "row", 0, 2)!);
expect(grid(e).map((r) => r[0])).toEqual(["b", "c", "a"]);
expect(e.state.selection.$from.parent.textContent).toBe("a");
});
it("moves the cursor's row up and down with the commands", () => {
const e = setup(table(abc));
e.commands.setTextSelection(inCell(e, 1, 0));
expect(e.commands.moveTableRow(-1)).toBe(true);
expect(grid(e).map((r) => r[0])).toEqual(["b", "a", "c"]);
expect(e.commands.moveTableRow(-1)).toBe(false);
e.commands.moveTableRow(1);
e.commands.moveTableRow(1);
expect(grid(e).map((r) => r[0])).toEqual(["a", "c", "b"]);
expect(e.commands.moveTableRow(1)).toBe(false);
});
it("does nothing outside a table, or where a cell spans rows", () => {
const e = setup(
"<p>before</p><table><tr><td rowspan='2'><p>x</p></td><td><p>a</p></td></tr><tr><td><p>b</p></td></tr></table>",
);
expect(moveInTable(e.state, tablePos(e), "row", 0, 1)).toBeNull();
e.commands.setTextSelection(2);
expect(e.commands.moveTableRow(1)).toBe(false);
});
});
describe("moving table columns", () => {
const cols = [
["n", "r", "x"],
["ada", "lead", "1"],
];
it("moves a column in every row and keeps the cursor in its cell", () => {
const e = setup(table(cols));
e.view.dispatch(moveInTable(e.state, tablePos(e), "column", 0, 2, 1)!);
expect(grid(e)).toEqual([
["r", "x", "n"],
["lead", "1", "ada"],
]);
expect(e.state.selection.$from.parent.textContent).toBe("ada");
});
it("moves the cursor's column left and right with the commands", () => {
const e = setup(table(cols));
e.commands.setTextSelection(inCell(e, 1, 1));
expect(e.commands.moveTableColumn(1)).toBe(true);
expect(grid(e)[0]).toEqual(["n", "x", "r"]);
expect(e.state.selection.$from.parent.textContent).toBe("lead");
expect(e.commands.moveTableColumn(1)).toBe(false);
e.commands.moveTableColumn(-1);
e.commands.moveTableColumn(-1);
expect(grid(e)[1]).toEqual(["lead", "ada", "1"]);
});
it("does nothing where a cell spans columns", () => {
const e = setup(
"<p>before</p><table><tr><td colspan='2'><p>x</p></td></tr><tr><td><p>a</p></td><td><p>b</p></td></tr></table>",
);
expect(moveInTable(e.state, tablePos(e), "column", 0, 1)).toBeNull();
});
});
+344
View File
@@ -0,0 +1,344 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension } from "@tiptap/core";
import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey, Selection, type EditorState, type Transaction } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
tableMove: {
/** Moves the table row the selection is in one place up (-1) or down (1). */
moveTableRow: (direction: -1 | 1) => ReturnType;
/** Moves the table column the selection is in one place left (-1) or right (1). */
moveTableColumn: (direction: -1 | 1) => ReturnType;
};
}
}
export type Axis = "row" | "column";
/**
* Whether rows (or columns) can move: cells spanning several of them would
* be pulled apart, and columns need every row to have the same cells.
*/
export function movable(table: PMNode, axis: Axis): boolean {
let ok = true;
const width = table.firstChild?.childCount ?? 0;
table.forEach((row) => {
if (axis === "column" && row.childCount !== width) ok = false;
row.forEach((cell) => {
const span = axis === "row" ? cell.attrs.rowspan : cell.attrs.colspan;
if ((span ?? 1) > 1) ok = false;
});
});
return ok;
}
function moved<T>(list: T[], from: number, to: number): T[] {
const out = [...list];
const [item] = out.splice(from, 1);
out.splice(to, 0, item!);
return out;
}
const children = (n: PMNode) => {
const out: PMNode[] = [];
n.forEach((c) => out.push(c));
return out;
};
/**
* A transaction that moves row (or column) from of the table at tablePos to
* index to, as an index in the table as it will be, leaving the cursor in
* the moved row or column. Null when nothing would change or it cannot move.
*/
export function moveInTable(
state: EditorState,
tablePos: number,
axis: Axis,
from: number,
to: number,
/** The row the cursor goes to when a column moves. */
cursorRow = 0,
): Transaction | null {
const table = state.doc.nodeAt(tablePos);
if (!table || table.type.name !== "table" || !movable(table, axis)) return null;
const rows = children(table);
const count = axis === "row" ? rows.length : (rows[0]?.childCount ?? 0);
if (from === to || from < 0 || to < 0 || from >= count || to >= count) return null;
const newRows =
axis === "row" ? moved(rows, from, to) : rows.map((r) => r.copy(Fragment.fromArray(moved(children(r), from, to))));
const tr = state.tr.replaceWith(tablePos, tablePos + table.nodeSize, table.copy(Fragment.fromArray(newRows)));
// The cell to put the cursor in: the moved row's first, or the moved column's in cursorRow.
const [row, col] = axis === "row" ? [to, 0] : [Math.min(cursorRow, newRows.length - 1), to];
let pos = tablePos + 1;
for (let i = 0; i < row; i++) pos += newRows[i]!.nodeSize;
pos += 1;
for (let i = 0; i < col; i++) pos += newRows[row]!.child(i).nodeSize;
return tr.setSelection(Selection.near(tr.doc.resolve(pos + 1))).scrollIntoView();
}
/** The table around pos, and the row and column pos is in, or null. */
function cellAt(state: EditorState, pos: number): { tablePos: number; row: number; column: number } | null {
const $pos = state.doc.resolve(pos);
for (let d = $pos.depth; d > 0; d--) {
if ($pos.node(d).type.name === "table") {
return { tablePos: $pos.before(d), row: $pos.index(d), column: d + 1 <= $pos.depth ? $pos.index(d + 1) : 0 };
}
}
return null;
}
/**
* Moving table rows and columns: grips on the left edge of the row and the
* top edge of the column under the pointer drag them to another place, and
* the commands move them from the keyboard (Ctrl+Alt+arrows) or a toolbar.
*/
export const TableMove = Extension.create<{ labels: EditorLabels | null }>({
name: "tableMove",
addOptions() {
return { labels: null };
},
addCommands() {
const command =
(axis: Axis) =>
(direction: -1 | 1) =>
({ state, dispatch }: { state: EditorState; dispatch?: (tr: Transaction) => void }) => {
const at = cellAt(state, state.selection.from);
if (!at) return false;
const index = axis === "row" ? at.row : at.column;
const tr = moveInTable(state, at.tablePos, axis, index, index + direction, at.row);
if (!tr) return false;
dispatch?.(tr);
return true;
};
return { moveTableRow: command("row"), moveTableColumn: command("column") };
},
addKeyboardShortcuts() {
return {
"Mod-Alt-ArrowUp": () => this.editor.commands.moveTableRow(-1),
"Mod-Alt-ArrowDown": () => this.editor.commands.moveTableRow(1),
"Mod-Alt-ArrowLeft": () => this.editor.commands.moveTableColumn(-1),
"Mod-Alt-ArrowRight": () => this.editor.commands.moveTableColumn(1),
};
},
addProseMirrorPlugins() {
const t = this.options.labels?.table;
return [
new Plugin({
key: new PluginKey("tableMove"),
view: (view) =>
new TableGrips(view, {
row: t?.dragRow ?? "Drag to move the row",
column: t?.dragColumn ?? "Drag to move the column",
}),
}),
];
},
});
interface Drag {
axis: Axis;
tablePos: number;
from: number;
/** The rows, or the first row's cells, as they are on screen. */
slots: HTMLElement[];
/** The cells being moved, dimmed while dragging. */
dimmed: HTMLElement[];
to: number;
cursorRow: number;
}
/** The grips beside the row and column under the pointer, and the line showing where a dragged one will go. */
class TableGrips {
private grips: Record<Axis, HTMLButtonElement> = {
row: document.createElement("button"),
column: document.createElement("button"),
};
private line = document.createElement("div");
private cell: HTMLTableCellElement | null = null;
private drag: Drag | null = null;
constructor(
private view: EditorView,
labels: Record<Axis, string>,
) {
for (const axis of ["row", "column"] as const) {
const g = this.grips[axis];
g.type = "button";
g.className = `dw-table-grip dw-table-grip--${axis}`;
g.contentEditable = "false";
g.setAttribute("aria-label", labels[axis]);
g.title = labels[axis];
g.hidden = true;
// Keyboard and screen reader users move rows and columns with the table toolbar or Ctrl+Alt+arrows.
g.tabIndex = -1;
g.addEventListener("pointerdown", (e) => this.start(e, axis));
g.addEventListener("mouseleave", this.leave);
}
this.line.className = "dw-table-drop";
this.line.hidden = true;
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
}
private get host(): HTMLElement | null {
const host = this.view.dom.parentElement;
if (host && this.line.parentElement !== host) {
host.classList.add("dw-block-host");
host.append(this.grips.row, this.grips.column, this.line);
}
return host;
}
private hide = () => {
if (this.drag) return;
this.grips.row.hidden = true;
this.grips.column.hidden = true;
this.cell = null;
};
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.grips.row.contains(to) || this.grips.column.contains(to) || this.view.dom.contains(to))) return;
this.hide();
};
private move = (e: MouseEvent) => {
if (this.drag) return;
const cell = (e.target as HTMLElement | null)?.closest?.("td, th");
const host = this.host;
if (!this.view.editable || !host || !(cell instanceof HTMLTableCellElement) || !this.view.dom.contains(cell)) {
return this.hide();
}
const at = this.locate(cell);
const table = at && this.view.state.doc.nodeAt(at.tablePos);
if (!at || !table) return this.hide();
this.cell = cell;
const hostBox = host.getBoundingClientRect();
const tableBox = cell.closest("table")!.getBoundingClientRect();
const rowBox = cell.parentElement!.getBoundingClientRect();
const cellBox = cell.getBoundingClientRect();
const showRow = table.childCount > 1 && movable(table, "row");
const showColumn = (table.firstChild?.childCount ?? 0) > 1 && movable(table, "column");
Object.assign(this.grips.row.style, {
top: `${rowBox.top - hostBox.top + rowBox.height / 2 - 11}px`,
left: `${tableBox.left - hostBox.left - 7}px`,
});
Object.assign(this.grips.column.style, {
top: `${tableBox.top - hostBox.top - 7}px`,
left: `${cellBox.left - hostBox.left + cellBox.width / 2 - 11}px`,
});
this.grips.row.hidden = !showRow;
this.grips.column.hidden = !showColumn;
};
private locate(cell: HTMLTableCellElement) {
try {
return cellAt(this.view.state, this.view.posAtDOM(cell, 0));
} catch {
return null;
}
}
private start(e: PointerEvent, axis: Axis) {
const cell = this.cell;
if (!cell || e.button !== 0) return;
const at = this.locate(cell);
const tbody = cell.parentElement?.parentElement;
if (!at || !tbody) return;
e.preventDefault();
const grip = this.grips[axis];
grip.setPointerCapture(e.pointerId);
const rows = [...tbody.children].filter((r): r is HTMLTableRowElement => r instanceof HTMLTableRowElement);
const from = axis === "row" ? at.row : at.column;
const slots = axis === "row" ? rows : ([...(rows[0]?.children ?? [])] as HTMLElement[]);
const dimmed = axis === "row" ? [rows[from]!] : rows.map((r) => r.children[from] as HTMLElement).filter(Boolean);
for (const el of dimmed) el.classList.add("dw-table-dragging");
this.drag = { axis, tablePos: at.tablePos, from, slots, dimmed, to: from, cursorRow: at.row };
grip.addEventListener("pointermove", this.dragMove);
grip.addEventListener("pointerup", this.drop);
grip.addEventListener("pointercancel", this.cancel);
}
/** Shows the line at the gap nearest the pointer. */
private dragMove = (e: PointerEvent) => {
const d = this.drag;
const host = this.host;
if (!d || !host) return;
const rowAxis = d.axis === "row";
const point = rowAxis ? e.clientY : e.clientX;
let gap = d.slots.length;
for (const [i, el] of d.slots.entries()) {
const b = el.getBoundingClientRect();
if (point < (rowAxis ? b.top + b.height / 2 : b.left + b.width / 2)) {
gap = i;
break;
}
}
// A gap next to the moving one itself leaves it where it is.
d.to = gap > d.from ? gap - 1 : gap;
const hostBox = host.getBoundingClientRect();
const table = d.slots[0]!.closest("table")!.getBoundingClientRect();
const last = d.slots.at(-1)!.getBoundingClientRect();
const next = d.slots[gap]?.getBoundingClientRect();
const edge = rowAxis ? (next?.top ?? last.bottom) : (next?.left ?? last.right);
Object.assign(
this.line.style,
rowAxis
? {
top: `${edge - hostBox.top - 1}px`,
left: `${table.left - hostBox.left}px`,
width: `${table.width}px`,
height: "2px",
}
: {
top: `${table.top - hostBox.top}px`,
left: `${edge - hostBox.left - 1}px`,
width: "2px",
height: `${table.height}px`,
},
);
this.line.hidden = d.to === d.from;
};
private drop = () => {
const d = this.drag;
this.cancel();
if (!d || d.to === d.from) return;
const tr = moveInTable(this.view.state, d.tablePos, d.axis, d.from, d.to, d.cursorRow);
if (tr) this.view.dispatch(tr);
this.view.focus();
};
private cancel = () => {
const d = this.drag;
for (const el of d?.dimmed ?? []) el.classList.remove("dw-table-dragging");
this.drag = null;
this.line.hidden = true;
for (const g of Object.values(this.grips)) {
g.removeEventListener("pointermove", this.dragMove);
g.removeEventListener("pointerup", this.drop);
g.removeEventListener("pointercancel", this.cancel);
}
this.hide();
};
update() {
if (this.cell && !this.cell.isConnected) this.hide();
}
destroy() {
this.cancel();
for (const g of Object.values(this.grips)) g.remove();
this.line.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
}
}
-72
View File
@@ -1,72 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { docwellExtensions } from "./extensions";
import { moveRow } from "./tablerows";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
const table = (rows: string[]) =>
`<p>before</p><table>${rows.map((r) => `<tr><td><p>${r}</p></td><td><p>${r}2</p></td></tr>`).join("")}</table>`;
function setup(html: string) {
editor = new Editor({ extensions: docwellExtensions(), content: html });
return editor;
}
const rowTexts = (e: Editor) => {
const out: string[] = [];
e.state.doc.descendants((n) => {
if (n.type.name === "tableRow") out.push(n.firstChild!.textContent);
return n.type.name !== "tableRow";
});
return out;
};
const tablePos = (e: Editor) => e.state.doc.child(0).nodeSize;
/** A position inside the first cell of row index. */
function inRow(e: Editor, index: number) {
let pos = -1;
let seen = 0;
e.state.doc.descendants((n, p) => {
if (pos >= 0) return false;
if (n.type.name === "tableRow" && seen++ === index) pos = p + 3;
return true;
});
return pos;
}
describe("moving table rows", () => {
it("moves a row to another place and keeps the cursor in it", () => {
const e = setup(table(["a", "b", "c"]));
e.view.dispatch(moveRow(e.state, tablePos(e), 0, 2)!);
expect(rowTexts(e)).toEqual(["b", "c", "a"]);
expect(e.state.selection.$from.parent.textContent).toBe("a");
e.view.dispatch(moveRow(e.state, tablePos(e), 2, 1)!);
expect(rowTexts(e)).toEqual(["b", "a", "c"]);
});
it("moves the cursor's row up and down from the keyboard command", () => {
const e = setup(table(["a", "b", "c"]));
e.commands.setTextSelection(inRow(e, 1));
expect(e.commands.moveTableRow(-1)).toBe(true);
expect(rowTexts(e)).toEqual(["b", "a", "c"]);
expect(e.commands.moveTableRow(-1)).toBe(false);
e.commands.moveTableRow(1);
e.commands.moveTableRow(1);
expect(rowTexts(e)).toEqual(["a", "c", "b"]);
expect(e.commands.moveTableRow(1)).toBe(false);
});
it("does nothing outside a table, or where a cell spans rows", () => {
const e = setup(
"<p>before</p><table><tr><td rowspan='2'><p>x</p></td><td><p>a</p></td></tr><tr><td><p>b</p></td></tr></table>",
);
expect(moveRow(e.state, tablePos(e), 0, 1)).toBeNull();
e.commands.setTextSelection(2);
expect(e.commands.moveTableRow(1)).toBe(false);
});
});
-242
View File
@@ -1,242 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension } from "@tiptap/core";
import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey, Selection, type EditorState, type Transaction } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
tableRows: {
/** Moves the table row the selection is in one place up (-1) or down (1). */
moveTableRow: (direction: -1 | 1) => ReturnType;
};
}
}
/** Whether a row can move: rows joined by a cell spanning several rows cannot be pulled apart. */
export function rowsMovable(table: PMNode): boolean {
let ok = true;
table.forEach((row) => row.forEach((cell) => (ok &&= (cell.attrs.rowspan ?? 1) <= 1)));
return ok;
}
/**
* A transaction that moves row from of the table at tablePos to index to (an
* index in the table as it will be), leaving the cursor in the moved row.
* Null when nothing would change or the rows cannot move.
*/
export function moveRow(state: EditorState, tablePos: number, from: number, to: number): Transaction | null {
const table = state.doc.nodeAt(tablePos);
if (!table || table.type.name !== "table" || !rowsMovable(table)) return null;
const rows: PMNode[] = [];
table.forEach((r) => rows.push(r));
if (from === to || from < 0 || to < 0 || from >= rows.length || to >= rows.length) return null;
const [row] = rows.splice(from, 1);
rows.splice(to, 0, row!);
const tr = state.tr.replaceWith(tablePos, tablePos + table.nodeSize, table.copy(Fragment.fromArray(rows)));
let rowStart = tablePos + 1;
for (let i = 0; i < to; i++) rowStart += rows[i]!.nodeSize;
return tr.setSelection(Selection.near(tr.doc.resolve(rowStart + 1))).scrollIntoView();
}
/** The table around $pos and the index of the row $pos is in, or null. */
function rowAt(state: EditorState, pos: number): { tablePos: number; index: number } | null {
const $pos = state.doc.resolve(pos);
for (let d = $pos.depth; d > 0; d--) {
if ($pos.node(d).type.name === "table") return { tablePos: $pos.before(d), index: $pos.index(d) };
}
return null;
}
/**
* Moving table rows: a grip on the left edge of the row under the pointer
* drags the row to another place, and moveTableRow moves it from the
* keyboard or a toolbar.
*/
export const TableRows = Extension.create<{ labels: EditorLabels | null }>({
name: "tableRows",
addOptions() {
return { labels: null };
},
addCommands() {
return {
moveTableRow:
(direction) =>
({ state, dispatch }) => {
const at = rowAt(state, state.selection.from);
if (!at) return false;
const tr = moveRow(state, at.tablePos, at.index, at.index + direction);
if (!tr) return false;
dispatch?.(tr);
return true;
},
};
},
addKeyboardShortcuts() {
return {
"Mod-Alt-ArrowUp": () => this.editor.commands.moveTableRow(-1),
"Mod-Alt-ArrowDown": () => this.editor.commands.moveTableRow(1),
};
},
addProseMirrorPlugins() {
const label = this.options.labels?.table.dragRow ?? "Drag to move the row";
return [new Plugin({ key: new PluginKey("tableRows"), view: (view) => new RowGrip(view, label) })];
},
});
/** The grip beside the table row under the pointer, and the line showing where a dragged row will go. */
class RowGrip {
private grip = document.createElement("button");
private line = document.createElement("div");
private row: HTMLTableRowElement | null = null;
private drag: { tablePos: number; from: number; rows: HTMLTableRowElement[]; to: number } | null = null;
constructor(
private view: EditorView,
label: string,
) {
const g = this.grip;
g.type = "button";
g.className = "dw-row-grip";
g.contentEditable = "false";
g.setAttribute("aria-label", label);
g.title = label;
g.hidden = true;
// Keyboard and screen reader users move rows with the table toolbar or Ctrl+Alt+arrows.
g.tabIndex = -1;
g.addEventListener("pointerdown", this.start);
g.addEventListener("mouseleave", this.leave);
this.line.className = "dw-row-drop";
this.line.hidden = true;
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
}
private get host(): HTMLElement | null {
const host = this.view.dom.parentElement;
if (host && this.grip.parentElement !== host) {
host.classList.add("dw-block-host");
host.append(this.grip, this.line);
}
return host;
}
private hide = () => {
if (this.drag) return;
this.grip.hidden = true;
this.row = null;
};
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.grip.contains(to) || this.view.dom.contains(to))) return;
this.hide();
};
private move = (e: MouseEvent) => {
if (this.drag) return;
const tr = (e.target as HTMLElement | null)?.closest?.("tr");
const host = this.host;
if (!this.view.editable || !host || !(tr instanceof HTMLTableRowElement) || !this.view.dom.contains(tr)) {
return this.hide();
}
const at = this.locate(tr);
const table = at && this.view.state.doc.nodeAt(at.tablePos);
if (!at || !table || table.childCount < 2 || !rowsMovable(table)) return this.hide();
this.row = tr;
const box = tr.getBoundingClientRect();
const hostBox = host.getBoundingClientRect();
Object.assign(this.grip.style, {
top: `${box.top - hostBox.top + box.height / 2 - 11}px`,
left: `${box.left - hostBox.left - 7}px`,
});
this.grip.hidden = false;
};
private locate(tr: HTMLTableRowElement) {
try {
return rowAt(this.view.state, this.view.posAtDOM(tr, 0));
} catch {
return null;
}
}
private start = (e: PointerEvent) => {
if (!this.row || e.button !== 0) return;
const at = this.locate(this.row);
const tbody = this.row.parentElement;
if (!at || !tbody) return;
e.preventDefault();
this.grip.setPointerCapture(e.pointerId);
const rows = [...tbody.children].filter((r): r is HTMLTableRowElement => r instanceof HTMLTableRowElement);
this.drag = { tablePos: at.tablePos, from: at.index, rows, to: at.index };
this.row.classList.add("dw-row-dragging");
this.grip.addEventListener("pointermove", this.dragMove);
this.grip.addEventListener("pointerup", this.drop);
this.grip.addEventListener("pointercancel", this.cancel);
};
/** Shows the line at the gap between rows nearest the pointer. */
private dragMove = (e: PointerEvent) => {
const d = this.drag;
const host = this.host;
if (!d || !host) return;
let gap = d.rows.length;
for (const [i, r] of d.rows.entries()) {
const b = r.getBoundingClientRect();
if (e.clientY < b.top + b.height / 2) {
gap = i;
break;
}
}
// A gap next to the row itself leaves it where it is.
d.to = gap > d.from ? gap - 1 : gap;
const hostBox = host.getBoundingClientRect();
const first = d.rows[0]!.getBoundingClientRect();
const edge =
gap < d.rows.length ? d.rows[gap]!.getBoundingClientRect().top : d.rows.at(-1)!.getBoundingClientRect().bottom;
Object.assign(this.line.style, {
top: `${edge - hostBox.top - 1}px`,
left: `${first.left - hostBox.left}px`,
width: `${first.width}px`,
});
this.line.hidden = d.to === d.from;
};
private drop = () => {
const d = this.drag;
this.cancel();
if (!d || d.to === d.from) return;
const tr = moveRow(this.view.state, d.tablePos, d.from, d.to);
if (tr) this.view.dispatch(tr);
this.view.focus();
};
private cancel = () => {
this.row?.classList.remove("dw-row-dragging");
this.drag = null;
this.line.hidden = true;
this.grip.removeEventListener("pointermove", this.dragMove);
this.grip.removeEventListener("pointerup", this.drop);
this.grip.removeEventListener("pointercancel", this.cancel);
this.hide();
};
update() {
if (this.row && !this.row.isConnected) this.hide();
}
destroy() {
this.cancel();
this.grip.remove();
this.line.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
}
}