Add tables, to-dos, callouts and the rest of editor parity

The editor gains the blocks and formatting it lacked next to AFFiNE:

- Tables with a header row, resizable columns, a toolbar to add, delete,
  merge and split, and rows that move by a drag grip, toolbar buttons or
  Ctrl+Alt+Up/Down.
- To-do lists (also from "[] "), callouts with an emoji and colour, and
  headings down to level 6 (Ctrl+Shift+0-6 for text and headings).
- Text colour and highlights from a fixed palette that follows the theme,
  and left, centre and right alignment.
- Optional line numbers on code blocks, with a default hosts can set.
- PDF attachments show their pages inline; pdf.js loads only then, and
  the mobile bundle leaves it out.
- The selection toolbar adds underline, colour, align, inline math, make a
  linked page and copy block link. A grip beside each block drags it and
  opens a menu: turn into, move, duplicate, copy, copy link, delete.
- The slash menu adds Today, Tomorrow, Yesterday, Now and New page.

The web app translates the new words and makes linked pages as children
of the open page. The mobile bridge gets underline, to-do, callout and
table commands, so its protocol moves to version 2 and the bundle is
rebuilt.

docwell-server's converters learn the new nodes: Markdown writes task
lists, GitHub alerts and tables and reads them back; HTML keeps colours
and alignment and reads its own output back; PDF draws tables, to-dos,
callouts and coloured text; Word import keeps tables, alignment, H4-H6
and colours; Notion import turns databases into tables and keeps
callouts and to-dos. Imported tables and H4-H6 headings no longer
collapse into paragraphs and H3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-14 12:20:08 +01:00
1 parent 3c7403ddf9
commit d28f1e02db
44 files changed
+4318 -338

No files matched your search

+233 -21
View File
@@ -3,15 +3,18 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { EditorContent, useEditor } from "@tiptap/vue-3";
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 { palette, type PaletteColor } from "./colors";
import { docwellExtensions, type CollabUser } from "./extensions";
import { findKey } from "./find";
import type { LinkHost } from "./embeds";
import type { FileHost } from "./files";
import { englishLabels, type EditorLabels } from "./labels";
import type { MentionHost } from "./mention";
import type { PageHost } from "./pagelinks";
import { createLinkedPage, type PageHost } from "./pagelinks";
import type { CollabProvider } from "./provider";
const props = withDefaults(
@@ -35,6 +38,8 @@ const props = withDefaults(
labels?: EditorLabels;
/** Shows the Comment button on selections, also when the editor is read-only. */
canComment?: boolean;
/** Whether code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers?: boolean;
}>(),
{ editable: true },
);
@@ -70,6 +75,8 @@ const editor = useEditor({
// The heavy editors load on first use; the mobile bridge leaves them out.
loadMermaid: () => import("mermaid").then((m) => m.default),
loadExcalidraw: () => import("./excalidraw"),
loadPdf: () => import("./pdfjs").then((m) => m.pdf),
codeLineNumbers: props.codeLineNumbers,
onNavigate: (path) => emit("navigate", path),
labels: props.labels,
onCommentSelect: (id) => emit("comment-select", id),
@@ -82,6 +89,9 @@ const editor = useEditor({
found.value = { current: f?.current ?? -1, total: f?.matches.length ?? 0 };
},
onBlur: () => emit("blur"),
onSelectionUpdate: ({ editor }) => {
if (editor.state.selection.empty) panel.value = null;
},
});
watch(
@@ -93,22 +103,58 @@ onBeforeUnmount(() => editor.value?.destroy());
// The selection toolbar: formatting for editors, Comment for anyone allowed.
type Tool = { id: string; icon: IconName; label: string; active: () => boolean; run: () => void };
/** The colour or alignment choices open under the toolbar, if any. */
const panel = ref<"color" | "align" | null>(null);
const togglePanel = (p: "color" | "align") => (panel.value = panel.value === p ? null : p);
const alignment = (e: Editor) =>
String(e.getAttributes("paragraph").textAlign ?? e.getAttributes("heading").textAlign ?? "left");
const alignIcons: Record<string, IconName> = { left: "align-left", center: "align-center", right: "align-right" };
const alignLabel = (a: string) =>
labels.value.format[a === "center" ? "alignCenter" : a === "right" ? "alignRight" : "alignLeft"];
const tools = computed<Tool[]>(() => {
const e = editor.value;
if (!e) return [];
const f = labels.value.format;
const mark = (id: "bold" | "italic" | "strike" | "code", icon: IconName, label: string): Tool => ({
const mark = (id: "bold" | "italic" | "underline" | "strike" | "code", icon: IconName, label: string): Tool => ({
id,
icon,
label,
active: () => e.isActive(id),
run: () => e.chain().focus().toggleMark(id).run(),
});
return [
const list: Tool[] = [
mark("bold", "bold", f.bold),
mark("italic", "italic", f.italic),
mark("underline", "underline", f.underline),
mark("strike", "strike", f.strike),
mark("code", "code", f.code),
{
id: "color",
icon: "palette",
label: f.color,
active: () => panel.value === "color" || e.isActive("textColor") || e.isActive("highlight"),
run: () => togglePanel("color"),
},
{
id: "align",
icon: alignIcons[alignment(e)] ?? "align-left",
label: f.align,
active: () => panel.value === "align",
run: () => togglePanel("align"),
},
{
id: "math",
icon: "sigma",
label: f.math,
active: () => false,
run: () => {
const { from, to } = e.state.selection;
const latex = e.state.doc.textBetween(from, to, " ").trim() || "x";
e.chain().focus().deleteSelection().insertInlineMath({ latex }).run();
},
},
{
id: "link",
icon: "link",
@@ -123,8 +169,85 @@ const tools = computed<Tool[]>(() => {
},
},
];
const pages = props.pages;
if (pages?.create) {
list.push({
id: "linkedPage",
icon: "page-plus",
label: f.linkedPage,
active: () => false,
run: () => void createLinkedPage(e, pages, "").catch((err) => emit("error", err)),
});
}
const blockLink = props.blockLink;
if (blockLink) {
list.push({
id: "blockLink",
icon: "share",
label: labels.value.blocks.copyBlockLink,
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),
);
},
});
}
return list;
});
function setColor(kind: "text" | "highlight", color: PaletteColor | null) {
const c = editor.value?.chain().focus();
if (!c) return;
if (kind === "text") (color ? c.setTextColor(color) : c.unsetTextColor()).run();
else (color ? c.setHighlight({ color }) : c.unsetHighlight()).run();
}
function setAlign(a: "left" | "center" | "right") {
editor.value?.chain().focus().setTextAlign(a).run();
panel.value = null;
}
// The table toolbar sits above the table the cursor is in.
type TableTool = {
id: Exclude<keyof EditorLabels["table"], "toolbar" | "dragRow">;
run: (e: Editor) => boolean;
danger?: boolean;
};
const tableTools: TableTool[] = [
{ id: "addRowBefore", run: (e) => e.chain().focus().addRowBefore().run() },
{ id: "addRowAfter", run: (e) => e.chain().focus().addRowAfter().run() },
{ id: "addColumnBefore", run: (e) => e.chain().focus().addColumnBefore().run() },
{ 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: "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() },
{ id: "mergeCells", run: (e) => e.chain().focus().mergeCells().run() },
{ id: "splitCell", run: (e) => e.chain().focus().splitCell().run() },
{ id: "deleteTable", run: (e) => e.chain().focus().deleteTable().run(), danger: true },
];
function showTableMenu({ editor: e }: { editor: Editor }) {
if (!e.isEditable || !e.isActive("table")) return false;
return e.state.selection.empty || e.state.selection instanceof CellSelection;
}
/** The table around the selection, which the table toolbar is placed against. */
function tableElement() {
const e = editor.value;
if (!e) return null;
const { node } = e.view.domAtPos(e.state.selection.from);
const el = (node instanceof HTMLElement ? node : node.parentElement)?.closest("table");
return el ? { getBoundingClientRect: () => el.getBoundingClientRect() } : null;
}
function comment() {
const e = editor.value;
if (!e) return;
@@ -147,7 +270,7 @@ function shouldShow({ editor: e, from, to }: { editor: Editor; from: number; to:
"embed",
"linkCard",
];
if (from === to || blocks.some((b) => e.isActive(b))) return false;
if (from === to || blocks.some((b) => e.isActive(b)) || e.state.selection instanceof CellSelection) return false;
return e.isEditable || props.canComment;
}
@@ -308,35 +431,124 @@ defineExpose({ editor, openFind });
v-if="editor"
:editor="editor"
:should-show="shouldShow"
class="flex items-center gap-0.5 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
class="flex flex-col gap-1 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
data-testid="bubble-menu"
>
<template v-if="editor.isEditable">
<div class="flex items-center gap-0.5">
<template v-if="editor.isEditable">
<button
v-for="t in tools"
:key="t.id"
type="button"
class="grid size-7 cursor-pointer place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'bg-surface-hover text-ink': t.active() }"
:aria-label="t.label"
:title="t.label"
:aria-pressed="t.active()"
@mousedown.prevent
@click="t.run()"
>
<DwIcon :name="t.icon" :size="16" />
</button>
</template>
<button
v-for="t in tools"
:key="t.id"
v-if="canComment"
type="button"
class="flex h-7 cursor-pointer items-center gap-1 rounded-sm px-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'ml-0.5 border-l border-line pl-2': editor.isEditable }"
data-testid="comment-selection"
@mousedown.prevent
@click="comment"
>
<DwIcon name="comment" :size="16" />{{ labels.format.comment }}
</button>
</div>
<div
v-if="editor.isEditable && panel === 'color'"
class="flex flex-col gap-1 border-t border-line px-1 pt-1.5 pb-0.5"
data-testid="color-panel"
>
<div
v-for="kind in ['text', 'highlight'] as const"
:key="kind"
class="flex items-center gap-1"
role="group"
:aria-label="kind === 'text' ? labels.format.textColor : labels.format.highlight"
>
<span class="w-20 shrink-0 text-ui-xs text-ink-muted">{{
kind === "text" ? labels.format.textColor : labels.format.highlight
}}</span>
<button
type="button"
class="dw-swatch"
:class="kind === 'text' ? 'dw-swatch--text' : 'dw-swatch--none'"
:aria-label="labels.format.noColor"
:title="labels.format.noColor"
@mousedown.prevent
@click="setColor(kind, null)"
>
{{ kind === "text" ? "A" : "" }}
</button>
<button
v-for="c in palette"
:key="c"
type="button"
class="dw-swatch"
:class="kind === 'text' ? 'dw-swatch--text' : 'dw-swatch--fill'"
:data-color="c"
:aria-label="labels.colors[c] ?? c"
:title="labels.colors[c] ?? c"
:aria-pressed="editor.isActive(kind === 'text' ? 'textColor' : 'highlight', { color: c })"
@mousedown.prevent
@click="setColor(kind, c)"
>
{{ kind === "text" ? "A" : "" }}
</button>
</div>
</div>
<div
v-if="editor.isEditable && panel === 'align'"
class="flex items-center gap-0.5 border-t border-line px-1 pt-1"
data-testid="align-panel"
>
<button
v-for="a in ['left', 'center', 'right'] as const"
:key="a"
type="button"
class="grid size-7 cursor-pointer place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'bg-surface-hover text-ink': t.active() }"
:aria-label="t.label"
:title="t.label"
:aria-pressed="t.active()"
:class="{ 'bg-surface-hover text-ink': alignment(editor) === a }"
:aria-label="alignLabel(a)"
:title="alignLabel(a)"
:aria-pressed="alignment(editor) === a"
@mousedown.prevent
@click="t.run()"
@click="setAlign(a)"
>
<DwIcon :name="t.icon" :size="16" />
<DwIcon :name="alignIcons[a] ?? 'align-left'" :size="16" />
</button>
</template>
</div>
</BubbleMenu>
<BubbleMenu
v-if="editor"
:editor="editor"
plugin-key="tableMenu"
:should-show="showTableMenu"
:get-referenced-virtual-element="tableElement"
:options="{ placement: 'top-start', offset: 6 }"
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"
data-testid="table-menu"
>
<button
v-if="canComment"
v-for="t in tableTools"
:key="t.id"
type="button"
class="flex h-7 cursor-pointer items-center gap-1 rounded-sm px-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'ml-0.5 border-l border-line pl-2': editor.isEditable }"
data-testid="comment-selection"
class="h-7 cursor-pointer rounded-sm px-2 text-ui-xs font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'text-danger hover:text-danger': t.danger }"
@mousedown.prevent
@click="comment"
@click="t.run(editor)"
>
<DwIcon name="comment" :size="16" />{{ labels.format.comment }}
{{ labels.table[t.id] }}
</button>
</BubbleMenu>
<EditorContent :editor="editor" />
+120 -40
View File
@@ -2,8 +2,9 @@
import { Extension, type Editor } from "@tiptap/core";
import type { Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { NodeSelection, Plugin, PluginKey } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import { blockActions, openBlockMenu } from "./blockmenu";
import type { EditorLabels } from "./labels";
/** Blocks a link can point at. */
@@ -14,6 +15,9 @@ const linkable = [
"codeBlock",
"bulletList",
"orderedList",
"taskList",
"callout",
"table",
"details",
"image",
"embed",
@@ -41,6 +45,21 @@ function newBlockId(): string {
return [...bytes].map((b) => (b % 36).toString(36)).join("");
}
/**
* The id of the block at pos, giving it one first when the view can be
* edited; null when it has none and cannot get one.
*/
export function ensureBlockId(view: EditorView, pos: number): string | null {
const node = view.state.doc.nodeAt(pos);
if (!node) return null;
const id = node.attrs.blockId as string | null;
if (id) return id;
if (!view.editable || !linkable.includes(node.type.name)) return null;
const fresh = newBlockId();
view.dispatch(view.state.tr.setNodeAttribute(pos, "blockId", fresh));
return fresh;
}
function findBlock(doc: PMNode, id: string): number {
let found = -1;
doc.descendants((node, pos) => {
@@ -79,9 +98,10 @@ export interface BlockLinkOptions {
}
/**
* Links to single blocks. A block gets a short id the first time someone
* copies a link to it, from the button beside it in the margin. Readers can
* copy links to blocks that already have one.
* Links to single blocks, and the handle beside each block. A block gets a
* short id the first time someone copies a link to it. Readers can copy
* links to blocks that already have one. Editors also get a grip that drags
* the block and opens its actions menu (see blockmenu.ts).
*/
export const BlockLinks = Extension.create<BlockLinkOptions>({
name: "blockLinks",
@@ -113,67 +133,96 @@ export const BlockLinks = Extension.create<BlockLinkOptions>({
addProseMirrorPlugins() {
const { link, onCopied } = this.options;
const labels = this.options.labels!;
if (!link) return [];
const editor = this.editor;
return [
new Plugin({
key: new PluginKey("blockLinks"),
view: (view) => new BlockHandle(view, labels.blocks.copyBlockLink, link, onCopied),
view: (view) => new BlockHandle(view, editor, labels, link, onCopied),
}),
];
},
});
/** The "copy link" button that follows the pointer from block to block. */
// The editor package draws its handles itself, without the icon set's layout.
const linkGlyph =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.5-1.5"/></svg>';
const gripGlyph =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="9" cy="6" r="1.6"/><circle cx="15" cy="6" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="18" r="1.6"/><circle cx="15" cy="18" r="1.6"/></svg>';
/** The buttons that follow the pointer from block to block: copy link, and the grip. */
class BlockHandle {
private button = document.createElement("button");
private gutter = document.createElement("div");
private linkButton = document.createElement("button");
private grip = document.createElement("button");
private pos = -1;
private closeMenu: (() => void) | null = null;
constructor(
private view: EditorView,
label: string,
private link: (hash: string) => string,
private editor: Editor,
private labels: EditorLabels,
private link?: (hash: string) => string,
private onCopied?: (url: string) => void,
) {
const b = this.button;
const g = this.gutter;
g.className = "dw-block-gutter";
g.contentEditable = "false";
g.hidden = true;
g.addEventListener("mouseleave", this.leave);
const b = this.linkButton;
b.type = "button";
b.className = "dw-block-handle";
b.setAttribute("aria-label", label);
b.title = label;
b.contentEditable = "false";
// A chain-link glyph; the editor package draws no icons of its own.
b.innerHTML =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.5-1.5"/></svg>';
b.hidden = true;
b.setAttribute("aria-label", labels.blocks.copyBlockLink);
b.title = labels.blocks.copyBlockLink;
b.innerHTML = linkGlyph;
b.addEventListener("mousedown", (e) => e.preventDefault());
b.addEventListener("click", () => void this.copy());
b.addEventListener("mouseleave", this.leave);
const grip = this.grip;
grip.type = "button";
grip.className = "dw-block-handle dw-block-grip";
grip.setAttribute("aria-label", labels.blockMenu.open);
grip.setAttribute("aria-haspopup", "menu");
grip.setAttribute("aria-expanded", "false");
grip.title = labels.blockMenu.open;
grip.innerHTML = gripGlyph;
grip.draggable = true;
grip.addEventListener("click", this.openMenu);
grip.addEventListener("dragstart", this.dragStart);
grip.addEventListener("dragend", () => this.hide());
if (link) g.append(b);
g.append(grip);
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
}
/** The element around the editor, which the button sits in. Hosts may move the editor after creating it. */
/** The element around the editor, which the buttons sit in. Hosts may move the editor after creating it. */
private get host(): HTMLElement | null {
const host = this.view.dom.parentElement;
if (host && this.button.parentElement !== host) {
if (host && this.gutter.parentElement !== host) {
host.classList.add("dw-block-host");
host.append(this.button);
host.append(this.gutter);
}
return host;
}
private hide = () => {
this.button.hidden = true;
if (this.closeMenu) return;
this.gutter.hidden = true;
this.pos = -1;
};
// Moving from the text onto the button keeps it.
// Moving from the text onto the buttons keeps them.
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.button.contains(to) || this.view.dom.contains(to))) return;
if (to && (this.gutter.contains(to) || this.view.dom.contains(to))) return;
this.hide();
};
private move = (e: MouseEvent) => {
if (this.closeMenu) return;
// The top-level block under the pointer.
let el = e.target as HTMLElement | null;
while (el && el.parentElement !== this.view.dom) el = el.parentElement;
@@ -188,26 +237,56 @@ class BlockHandle {
const $pos = this.view.state.doc.resolve(Math.min(pos, this.view.state.doc.content.size));
const start = $pos.depth >= 1 ? $pos.before(1) : pos;
const node = this.view.state.doc.nodeAt(start);
if (!node) return this.hide();
// Readers can only copy links that exist; only editors can add an id.
if (!node || !linkable.includes(node.type.name) || (!node.attrs.blockId && !this.view.editable)) {
return this.hide();
}
const canLink = !!this.link && linkable.includes(node.type.name) && (!!node.attrs.blockId || this.view.editable);
const canEdit = this.view.editable;
if (!canLink && !canEdit) return this.hide();
this.linkButton.hidden = !canLink;
this.grip.hidden = !canEdit;
this.pos = start;
const box = el.getBoundingClientRect();
const hostBox = host.getBoundingClientRect();
this.button.style.top = `${box.top - hostBox.top + Math.min(box.height / 2, 14) - 11}px`;
this.button.hidden = false;
this.gutter.style.top = `${box.top - hostBox.top + Math.min(box.height / 2, 14) - 11}px`;
this.gutter.hidden = false;
};
private async copy() {
const node = this.pos >= 0 ? this.view.state.doc.nodeAt(this.pos) : null;
if (!node) return;
let id = node.attrs.blockId as string | null;
if (!id) {
if (!this.view.editable) return;
id = newBlockId();
this.view.dispatch(this.view.state.tr.setNodeAttribute(this.pos, "blockId", id));
private openMenu = () => {
if (this.closeMenu) {
this.closeMenu();
return;
}
const pos = this.pos;
if (pos < 0 || !this.view.editable) return;
const node = this.view.state.doc.nodeAt(pos);
const canLink = !!this.link && !!node && linkable.includes(node.type.name);
const actions = blockActions(this.editor, pos, this.labels, canLink ? () => void this.copy(pos) : undefined);
this.grip.setAttribute("aria-expanded", "true");
this.closeMenu = openBlockMenu(this.grip, actions, this.labels.blockMenu.open, () => {
this.closeMenu = null;
this.grip.setAttribute("aria-expanded", "false");
this.hide();
});
};
/** Drags the whole block, the way ProseMirror drags a selected node. */
private dragStart = (e: DragEvent) => {
const pos = this.pos;
if (pos < 0 || !e.dataTransfer) return;
this.closeMenu?.();
const sel = NodeSelection.create(this.view.state.doc, pos);
this.view.dispatch(this.view.state.tr.setSelection(sel));
e.dataTransfer.effectAllowed = "copyMove";
e.dataTransfer.setData("text/plain", sel.node.textContent);
const dom = this.view.nodeDOM(pos);
if (dom instanceof HTMLElement) e.dataTransfer.setDragImage(dom, 0, 0);
this.view.dragging = { slice: sel.content(), move: true };
};
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);
@@ -223,8 +302,9 @@ class BlockHandle {
}
destroy() {
this.button.parentElement?.classList.remove("dw-block-host");
this.button.remove();
this.closeMenu?.();
this.gutter.parentElement?.classList.remove("dw-block-host");
this.gutter.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
}
+285
View File
@@ -0,0 +1,285 @@
// 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 (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;
}
+173
View File
@@ -0,0 +1,173 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor, type JSONContent } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { blockActions } from "./blockmenu";
import { showsLineNumbers } from "./codeblock";
import { docwellExtensions } from "./extensions";
import { englishLabels } from "./labels";
import { filterCommands, slashCommands } from "./slash";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
function setup(content: string | JSONContent, opts: Parameters<typeof docwellExtensions>[0] = {}) {
editor = new Editor({ extensions: docwellExtensions(opts), content });
return editor;
}
const types = (e: Editor) => (e.getJSON().content ?? []).map((n) => n.type);
const action = (e: Editor, pos: number, id: string) => {
const all = blockActions(e, pos, englishLabels);
return all.find((a) => a.id === id) ?? all.flatMap((a) => a.children ?? []).find((a) => a.id === id);
};
describe("new blocks", () => {
it("reads callouts, to-dos and tables back from their HTML", () => {
const e = setup(
'<aside data-type="callout" data-emoji="🔥" data-color="red"><p>Hot</p></aside>' +
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>Done</p></li></ul>' +
"<table><tr><th><p>A</p></th><th><p>B</p></th></tr><tr><td><p>1</p></td><td><p>2</p></td></tr></table>",
);
const [callout, tasks, table] = e.getJSON().content as JSONContent[];
expect(callout).toMatchObject({ type: "callout", attrs: { emoji: "🔥", color: "red" } });
expect(tasks?.content?.[0]).toMatchObject({ type: "taskItem", attrs: { checked: true } });
expect(table?.content?.[0]?.content?.[0]?.type).toBe("tableHeader");
expect(table?.content?.[1]?.content?.[1]?.type).toBe("tableCell");
});
it("reads a callout from the server's HTML export without its emoji in the text", () => {
const e = setup(
'<aside data-type="callout" data-emoji="🔥" data-color="red"><span class="callout-emoji">🔥</span>' +
'<div class="callout-body"><p>Careful</p></div></aside>',
);
expect(e.getJSON().content![0]).toEqual({
type: "callout",
attrs: { emoji: "🔥", color: "red", blockId: null },
content: [
{ type: "paragraph", attrs: { textAlign: null, blockId: null }, content: [{ type: "text", text: "Careful" }] },
],
});
});
it("keeps only palette colours on text and highlights", () => {
const e = setup('<p><span data-color="green">ok</span><span data-color="#f00">no</span><mark>hi</mark></p>');
const runs = e.getJSON().content![0]!.content!;
expect(runs[0]).toMatchObject({ text: "ok", marks: [{ type: "textColor", attrs: { color: "green" } }] });
expect(runs[1]).toEqual({ type: "text", text: "no" });
expect(runs[2]?.marks?.[0]?.type).toBe("highlight");
});
it("has headings down to level 6 and aligns text", () => {
const e = setup("<h5>Small</h5>");
expect(e.getJSON().content![0]).toMatchObject({ type: "heading", attrs: { level: 5 } });
e.chain().setTextSelection(1).setTextAlign("center").run();
expect(e.getJSON().content![0]!.attrs!.textAlign).toBe("center");
});
it("turns '[] ' at the start of a line into a to-do list", () => {
const e = setup("<p></p>");
e.commands.focus();
// Input rules run on typed text; the space is "typed", the brackets inserted.
e.commands.insertContent("[]");
e.view.someProp("handleTextInput", (f) => f(e.view, 3, 3, " ", () => e.state.tr));
expect(types(e)).toContain("taskList");
});
it("follows the default for line numbers until a block picks", () => {
expect(showsLineNumbers(null, true)).toBe(true);
expect(showsLineNumbers(false, true)).toBe(false);
const e = setup("<pre><code>a\nb</code></pre>", { codeLineNumbers: true });
e.chain().setTextSelection(1).toggleCodeLineNumbers().run();
expect(e.getJSON().content![0]!.attrs!.lineNumbers).toBe(false);
});
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"]) {
expect(ids).toContain(id);
}
expect(filterCommands(slashCommands(englishLabels), "other").map((c) => c.id)).toEqual(["h4", "h5", "h6"]);
expect(ids).not.toContain("newPage");
const withPages = slashCommands(englishLabels, undefined, undefined, {
search: async () => [],
create: async () => ({ id: "x", title: "" }),
});
expect(withPages.map((c) => c.id)).toContain("newPage");
});
});
describe("blockActions", () => {
const doc = "<p>one</p><p>two</p><p>three</p>";
it("moves blocks up and down", () => {
const e = setup(doc);
const second = e.state.doc.child(0).nodeSize;
action(e, second, "moveUp")!.run!();
expect(e.getText({ blockSeparator: "|" })).toBe("two|one|three");
action(e, 0, "moveDown")!.run!();
expect(e.getText({ blockSeparator: "|" })).toBe("one|two|three");
});
it("has no move up for the first block and no move down for the last", () => {
const e = setup(doc);
expect(action(e, 0, "moveUp")).toBeUndefined();
const last = e.state.doc.content.size - e.state.doc.lastChild!.nodeSize;
expect(action(e, last, "moveDown")).toBeUndefined();
});
it("duplicates a block without its link id", () => {
const e = setup({
type: "doc",
content: [{ type: "paragraph", attrs: { blockId: "abcdef12" }, content: [{ type: "text", text: "x" }] }],
});
action(e, 0, "duplicate")!.run!();
const [a, b] = e.getJSON().content!;
expect(a!.attrs!.blockId).toBe("abcdef12");
expect(b!.attrs!.blockId).toBeNull();
expect(b!.content).toEqual(a!.content);
});
it("turns a paragraph into other blocks and back", () => {
const e = setup(doc);
action(e, 0, "todo")!.run!();
expect(types(e)[0]).toBe("taskList");
action(e, 0, "callout")!.run!();
expect(types(e)[0]).toBe("callout");
action(e, 0, "h2")!.run!();
expect(e.getJSON().content![0]).toMatchObject({ type: "heading", attrs: { level: 2 } });
action(e, 0, "text")!.run!();
expect(types(e)).toEqual(["paragraph", "paragraph", "paragraph"]);
});
it("keeps a heading, list or code block as it is inside a new callout", () => {
const e = setup("<h2>Title</h2><ul><li><p>a</p></li></ul><blockquote><p>q</p></blockquote>");
action(e, 0, "callout")!.run!();
expect(e.getJSON().content![0]).toMatchObject({
type: "callout",
content: [{ type: "heading", attrs: { level: 2 }, content: [{ type: "text", text: "Title" }] }],
});
const list = e.state.doc.child(0).nodeSize;
action(e, list, "callout")!.run!();
expect(e.getJSON().content![1]!.content![0]!.type).toBe("bulletList");
// A quote gives the callout its contents rather than sitting inside it.
const quote = list + e.state.doc.child(1).nodeSize;
action(e, quote, "callout")!.run!();
expect(e.getJSON().content![2]!.content!.map((n) => n.type)).toEqual(["paragraph"]);
});
it("deletes a block", () => {
const e = setup(doc);
action(e, 0, "delete")!.run!();
expect(e.getText({ blockSeparator: "|" })).toBe("two|three");
});
it("switches a PDF between its pages and a card", () => {
const e = setup({
type: "doc",
content: [{ type: "fileAttachment", attrs: { url: "/f", name: "a.pdf", mime: "application/pdf" } }],
});
action(e, 0, "pdfView")!.run!();
expect(e.getJSON().content![0]!.attrs!.view).toBe("preview");
});
});
+47
View File
@@ -0,0 +1,47 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension, type AnyExtension } from "@tiptap/core";
import { TaskItem, TaskList } from "@tiptap/extension-list";
import { TableKit } from "@tiptap/extension-table";
import TextAlign from "@tiptap/extension-text-align";
/**
* To-do lists. Typing "[] " or "[x] " at the start of a line starts one; items
* nest with Tab like other lists.
*/
export function docwellTasks(): AnyExtension[] {
return [TaskList.configure({ HTMLAttributes: { class: "dw-tasks" } }), TaskItem.configure({ nested: true })];
}
/**
* Simple tables: a header row, resizable columns, cells that hold blocks.
* Tab moves between cells and adds a row at the end.
*/
export function docwellTables(): AnyExtension[] {
return [
TableKit.configure({
table: { resizable: true, cellMinWidth: 60, HTMLAttributes: { class: "dw-table" } },
}),
];
}
/** Left, centre and right alignment of text blocks (Ctrl+Shift+L / E / R). */
export const docwellAlign = TextAlign.configure({
types: ["heading", "paragraph"],
alignments: ["left", "center", "right"],
});
/**
* AFFiNE-style shortcuts on top of Tiptap's own: Ctrl+Shift+0 for text and
* Ctrl+Shift+1–6 for headings. Code blocks keep Tiptap's Ctrl+Alt+C.
*/
export const HeadingShortcuts = Extension.create({
name: "headingShortcuts",
addKeyboardShortcuts() {
const out: Record<string, () => boolean> = { "Mod-Shift-0": () => this.editor.commands.setParagraph() };
for (const level of [1, 2, 3, 4, 5, 6] as const) {
out[`Mod-Shift-${level}`] = () => this.editor.commands.toggleHeading({ level });
}
return out;
},
});
+168
View File
@@ -0,0 +1,168 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { mergeAttributes, Node } from "@tiptap/core";
import { isPaletteColor, palette, type PaletteColor } from "./colors";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
callout: {
/** Wraps the selected blocks in a callout. */
setCallout: (attrs?: { emoji?: string; color?: PaletteColor }) => ReturnType;
/** Turns the callout around the selection back into plain blocks. */
unsetCallout: () => ReturnType;
};
}
}
const defaultEmoji = "💡";
/** One emoji or a short symbol; anything longer is not an icon. */
function cleanEmoji(s: string): string {
const t = s.trim();
return t && [...t].length <= 4 ? t : "";
}
/**
* A box set apart by an emoji and a background colour. It holds ordinary
* blocks. Clicking the emoji changes it; the dot next to it steps through
* the colours.
*/
export const Callout = Node.create<{ labels: EditorLabels | null }>({
name: "callout",
group: "block",
content: "block+",
defining: true,
draggable: true,
addOptions() {
return { labels: null };
},
addAttributes() {
return {
emoji: {
default: defaultEmoji,
parseHTML: (el) => cleanEmoji(el.getAttribute("data-emoji") ?? "") || defaultEmoji,
renderHTML: (attrs) => ({ "data-emoji": attrs.emoji }),
},
color: {
default: "blue",
parseHTML: (el) => {
const c = el.getAttribute("data-color");
return isPaletteColor(c) ? c : "blue";
},
renderHTML: (attrs) => ({ "data-color": attrs.color }),
},
};
},
parseHTML() {
return [
{
tag: "aside[data-type=callout]",
// docwell-server's HTML export shows the emoji beside a .callout-body.
contentElement: (el) => el.querySelector<HTMLElement>(":scope > .callout-body") ?? el,
},
];
},
renderHTML({ HTMLAttributes }) {
return ["aside", mergeAttributes(HTMLAttributes, { "data-type": "callout", class: "dw-callout" }), 0];
},
addCommands() {
return {
setCallout:
(attrs) =>
({ commands }) =>
commands.wrapIn(this.name, attrs),
unsetCallout:
() =>
({ commands }) =>
commands.lift(this.name),
};
},
addKeyboardShortcuts() {
return {
// Backspace at the very start of a callout unwraps it, like a quote.
Backspace: ({ editor }) => {
const { $from, empty } = editor.state.selection;
if (!empty || $from.parentOffset > 0) return false;
for (let d = $from.depth - 1; d > 0; d--) {
if ($from.node(d).type.name === this.name) {
if ($from.index(d) !== 0 || $from.start(d + 1) !== $from.start()) return false;
return editor.commands.lift(this.name);
}
if ($from.index(d) !== 0) return false;
}
return false;
},
};
},
addNodeView() {
return ({ node, getPos, editor }) => {
const labels = this.options.labels;
const dom = document.createElement("aside");
dom.className = "dw-callout";
dom.setAttribute("data-type", "callout");
const side = document.createElement("div");
side.className = "dw-callout__side";
side.contentEditable = "false";
const emoji = document.createElement("button");
emoji.type = "button";
emoji.className = "dw-callout__emoji";
const dot = document.createElement("button");
dot.type = "button";
dot.className = "dw-callout__color";
side.append(emoji, dot);
const content = document.createElement("div");
content.className = "dw-callout__body";
dom.append(side, content);
let current = node;
const set = (patch: Record<string, string>) => {
const pos = getPos();
if (typeof pos !== "number" || !editor.isEditable) return;
editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...patch }));
};
emoji.addEventListener("mousedown", (e) => e.preventDefault());
emoji.addEventListener("click", () => {
if (!editor.isEditable) return;
const next = cleanEmoji(window.prompt(labels?.blocks.calloutEmoji ?? "Emoji", current.attrs.emoji) ?? "");
if (next) set({ emoji: next });
});
dot.addEventListener("mousedown", (e) => e.preventDefault());
dot.addEventListener("click", () => {
const i = palette.indexOf(current.attrs.color as PaletteColor);
set({ color: palette[(i + 1) % palette.length]! });
});
const draw = () => {
dom.setAttribute("data-color", String(current.attrs.color));
emoji.textContent = String(current.attrs.emoji);
const label = labels?.blocks.calloutEmoji ?? "Emoji";
emoji.setAttribute("aria-label", label);
emoji.title = label;
const colorLabel = labels?.blocks.calloutColor ?? "Colour";
dot.setAttribute("aria-label", colorLabel);
dot.title = colorLabel;
};
draw();
return {
dom,
contentDOM: content,
update: (n) => {
if (n.type !== node.type) return false;
current = n;
draw();
return true;
},
// Clicks on the emoji and colour buttons are not edits of the text.
stopEvent: (e) => side.contains(e.target as globalThis.Node),
ignoreMutation: (m) => side.contains(m.target),
};
};
},
});
+93
View File
@@ -0,0 +1,93 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import CodeBlock, { type CodeBlockOptions } from "@tiptap/extension-code-block";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
codeLineNumbers: {
/** Shows or hides line numbers on the code block at the selection. */
toggleCodeLineNumbers: () => ReturnType;
};
}
}
/** Whether a code block shows line numbers: its own choice, else the editor's default. */
export function showsLineNumbers(attr: unknown, byDefault: boolean): boolean {
return typeof attr === "boolean" ? attr : byDefault;
}
/**
* Code blocks with optional line numbers. lineNumbers is null until someone
* picks for that block, so it follows the default (lineNumbers option, e.g.
* from a workspace setting) until then.
*/
export const DocwellCodeBlock = CodeBlock.extend<CodeBlockOptions & { lineNumbers: boolean }>({
addOptions() {
return { ...this.parent!(), lineNumbers: false };
},
addAttributes() {
return {
...this.parent?.(),
lineNumbers: {
default: null,
parseHTML: (el) => {
const v = el.getAttribute("data-line-numbers");
return v === "true" ? true : v === "false" ? false : null;
},
renderHTML: (attrs) =>
typeof attrs.lineNumbers === "boolean" ? { "data-line-numbers": String(attrs.lineNumbers) } : {},
},
};
},
addCommands() {
return {
...this.parent?.(),
toggleCodeLineNumbers:
() =>
({ editor, commands }) => {
if (!editor.isActive(this.name)) return false;
const now = showsLineNumbers(editor.getAttributes(this.name).lineNumbers, this.options.lineNumbers);
return commands.updateAttributes(this.name, { lineNumbers: !now });
},
};
},
addNodeView() {
const byDefault = this.options.lineNumbers;
const prefix = this.options.languageClassPrefix ?? "language-";
return ({ node }) => {
const pre = document.createElement("pre");
pre.className = "dw-code";
const gutter = document.createElement("div");
gutter.className = "dw-code__gutter";
gutter.contentEditable = "false";
gutter.setAttribute("aria-hidden", "true");
const code = document.createElement("code");
pre.append(gutter, code);
let lines = -1;
const draw = (n: typeof node) => {
const on = showsLineNumbers(n.attrs.lineNumbers, byDefault);
pre.classList.toggle("dw-code--numbered", on);
code.className = n.attrs.language ? `${prefix}${String(n.attrs.language)}` : "";
const count = on ? n.textContent.split("\n").length : 0;
if (count !== lines) {
lines = count;
gutter.textContent = Array.from({ length: count }, (_, i) => i + 1).join("\n");
}
};
draw(node);
return {
dom: pre,
contentDOM: code,
update: (n) => {
if (n.type !== node.type) return false;
draw(n);
return true;
},
ignoreMutation: (m) => gutter.contains(m.target),
};
};
},
});
+90
View File
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Mark, mergeAttributes } from "@tiptap/core";
import Highlight from "@tiptap/extension-highlight";
/**
* The colours text, highlights and callouts can have. Documents store the
* name, not a value, so the colours follow the theme (editor.css has a light
* and a dark shade of each) and stay readable in exports.
*/
export const palette = ["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"] as const;
export type PaletteColor = (typeof palette)[number];
export const isPaletteColor = (c: unknown): c is PaletteColor =>
typeof c === "string" && (palette as readonly string[]).includes(c);
declare module "@tiptap/core" {
interface Commands<ReturnType> {
textColor: {
setTextColor: (color: PaletteColor) => ReturnType;
unsetTextColor: () => ReturnType;
};
}
}
/** Coloured text: `<span data-color="red">`. */
export const TextColor = Mark.create({
name: "textColor",
addAttributes() {
return {
color: {
default: null,
parseHTML: (el) => {
const c = el.getAttribute("data-color");
return isPaletteColor(c) ? c : null;
},
renderHTML: (attrs) => (attrs.color ? { "data-color": attrs.color } : {}),
},
};
},
parseHTML() {
return [
{ tag: "span[data-color]", getAttrs: (el) => (isPaletteColor(el.getAttribute("data-color")) ? {} : false) },
];
},
renderHTML({ HTMLAttributes }) {
return ["span", mergeAttributes(HTMLAttributes, { class: "dw-text-color" }), 0];
},
addCommands() {
return {
setTextColor:
(color) =>
({ commands }) =>
commands.setMark(this.name, { color }),
unsetTextColor:
() =>
({ commands }) =>
commands.unsetMark(this.name),
};
},
});
/**
* Highlighted text, ==like this== or from the toolbar, with a palette colour
* ("yellow" when none was picked). Stored as the colour name like TextColor.
*/
export const DocwellHighlight = Highlight.extend({
addOptions() {
return { ...this.parent!(), multicolor: true };
},
addAttributes() {
return {
color: {
default: null,
parseHTML: (el) => {
const c = el.getAttribute("data-color");
return isPaletteColor(c) ? c : null;
},
renderHTML: (attrs) => ({ "data-color": isPaletteColor(attrs.color) ? attrs.color : "yellow" }),
},
};
},
renderHTML({ HTMLAttributes }) {
return ["mark", mergeAttributes(HTMLAttributes, { class: "dw-highlight" }), 0];
},
});
+429 -7
View File
@@ -20,7 +20,7 @@
.dw-prose > * + * {
margin-top: 8px;
}
.dw-prose > :is(h1, h2, h3) {
.dw-prose > :is(h1, h2, h3, h4, h5, h6) {
margin-top: 20px;
}
.dw-prose h1 {
@@ -102,7 +102,7 @@
border-radius: var(--radius-md);
}
.dw-prose img.ProseMirror-selectednode,
.dw-prose .dw-file.ProseMirror-selectednode,
.dw-prose .dw-file-block.ProseMirror-selectednode .dw-file,
.dw-prose .ProseMirror-selectednode:is(.dw-mermaid, .dw-diagram, .dw-toc, .tiptap-mathematics-render) {
outline: 2px solid var(--color-focus-ring);
outline-offset: 2px;
@@ -609,9 +609,17 @@
.dw-block-host {
position: relative;
}
.dw-block-handle {
.dw-block-gutter {
position: absolute;
left: -30px;
right: calc(100% + 6px);
display: flex;
gap: 2px;
}
.dw-block-gutter[hidden],
.dw-block-handle[hidden] {
display: none;
}
.dw-block-handle {
display: grid;
place-items: center;
width: 22px;
@@ -628,7 +636,7 @@
}
/* Phones have no margin to spare and no hover. */
@media (max-width: 640px), (hover: none) {
.dw-block-handle {
.dw-block-gutter {
display: none;
}
}
@@ -706,10 +714,424 @@
/* The page's body font, chosen per page; headings follow it too. */
.dw-font-serif .dw-prose,
.dw-font-serif .dw-prose :is(h1, h2, h3) {
.dw-font-serif .dw-prose :is(h1, h2, h3, h4, h5, h6) {
font-family: var(--font-serif);
}
.dw-font-mono .dw-prose,
.dw-font-mono .dw-prose :is(h1, h2, h3) {
.dw-font-mono .dw-prose :is(h1, h2, h3, h4, h5, h6) {
font-family: var(--font-mono);
}
/* ---- Headings 4–6 ("Other headings") ---- */
.dw-prose h4 {
font-size: var(--text-doc-body);
line-height: var(--text-doc-body--line-height);
font-weight: 600;
}
.dw-prose h5 {
font-size: var(--text-ui-md);
font-weight: 600;
}
.dw-prose h6 {
font-size: var(--text-ui-sm);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-ink-muted);
}
/* ---- Palette colours (colors.ts): text, highlight and callout shades ---- */
:root {
--dw-c-gray: #6b6f6d;
--dw-c-red: #c0392b;
--dw-c-orange: #c2571a;
--dw-c-yellow: #9a7400;
--dw-c-green: #3d7a1f;
--dw-c-teal: #1f7f79;
--dw-c-blue: #2f6fbf;
--dw-c-purple: #7c5cc4;
--dw-c-pink: #b8327a;
--dw-bg-gray: #ecece9;
--dw-bg-red: #fbe3df;
--dw-bg-orange: #fbe7d7;
--dw-bg-yellow: #fbf1c7;
--dw-bg-green: #e4f1d8;
--dw-bg-teal: #d9efec;
--dw-bg-blue: #dfe9f7;
--dw-bg-purple: #ebe4f7;
--dw-bg-pink: #f8e0ec;
}
.dark {
--dw-c-gray: #a3a8a5;
--dw-c-red: #f08a7e;
--dw-c-orange: #f0a26a;
--dw-c-yellow: #e5c454;
--dw-c-green: #93c96b;
--dw-c-teal: #6cc9bf;
--dw-c-blue: #86b2ec;
--dw-c-purple: #b9a2ec;
--dw-c-pink: #eb8fc0;
--dw-bg-gray: #34383a;
--dw-bg-red: #4a2723;
--dw-bg-orange: #4a3020;
--dw-bg-yellow: #45391a;
--dw-bg-green: #2c3f22;
--dw-bg-teal: #1e3d3a;
--dw-bg-blue: #22334d;
--dw-bg-purple: #352b4d;
--dw-bg-pink: #47263a;
}
[data-color="gray"] {
--dw-c: var(--dw-c-gray);
--dw-bg: var(--dw-bg-gray);
}
[data-color="red"] {
--dw-c: var(--dw-c-red);
--dw-bg: var(--dw-bg-red);
}
[data-color="orange"] {
--dw-c: var(--dw-c-orange);
--dw-bg: var(--dw-bg-orange);
}
[data-color="yellow"] {
--dw-c: var(--dw-c-yellow);
--dw-bg: var(--dw-bg-yellow);
}
[data-color="green"] {
--dw-c: var(--dw-c-green);
--dw-bg: var(--dw-bg-green);
}
[data-color="teal"] {
--dw-c: var(--dw-c-teal);
--dw-bg: var(--dw-bg-teal);
}
[data-color="blue"] {
--dw-c: var(--dw-c-blue);
--dw-bg: var(--dw-bg-blue);
}
[data-color="purple"] {
--dw-c: var(--dw-c-purple);
--dw-bg: var(--dw-bg-purple);
}
[data-color="pink"] {
--dw-c: var(--dw-c-pink);
--dw-bg: var(--dw-bg-pink);
}
.dw-prose .dw-text-color {
color: var(--dw-c);
}
.dw-prose mark.dw-highlight {
background: var(--dw-bg, var(--dw-bg-yellow));
color: inherit;
border-radius: 2px;
padding: 0 1px;
}
/* The swatches in the selection toolbar's colour panel. */
.dw-swatch {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border: 1px solid var(--color-line);
border-radius: var(--radius-xs);
background: var(--color-surface);
font-family: var(--font-sans);
font-size: 12px;
font-weight: 700;
color: var(--dw-c, var(--color-ink));
cursor: pointer;
}
.dw-swatch--fill {
background: var(--dw-bg);
}
.dw-swatch--none {
background: linear-gradient(135deg, transparent 45%, var(--color-danger) 45% 55%, transparent 55%);
}
.dw-swatch[aria-pressed="true"],
.dw-swatch:hover {
outline: 2px solid var(--color-focus-ring);
outline-offset: 1px;
}
/* ---- Callouts ---- */
.dw-prose .dw-callout {
display: flex;
gap: 10px;
padding: 12px 16px 12px 12px;
border-radius: var(--radius-md);
background: var(--dw-bg, var(--dw-bg-blue));
}
.dw-callout__side {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
user-select: none;
}
.dw-callout__emoji {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border: none;
border-radius: var(--radius-sm);
background: none;
font-size: 20px;
line-height: 1;
cursor: pointer;
}
.dw-callout__emoji:hover {
background: color-mix(in srgb, var(--dw-c) 14%, transparent);
}
.dw-callout__color {
width: 12px;
height: 12px;
border: 2px solid var(--color-surface);
border-radius: 50%;
background: var(--dw-c);
cursor: pointer;
opacity: 0;
}
.dw-callout:hover .dw-callout__color,
.dw-callout__color:focus-visible {
opacity: 1;
}
.dw-prose[contenteditable="false"] .dw-callout__color {
display: none;
}
.dw-prose[contenteditable="false"] .dw-callout__emoji {
cursor: default;
}
.dw-callout__body {
flex: 1;
min-width: 0;
padding-top: 2px;
}
.dw-callout__body > * + * {
margin-top: 8px;
}
/* ---- To-do lists ---- */
.dw-prose ul[data-type="taskList"] {
list-style: none;
padding-left: 2px;
}
.dw-prose ul[data-type="taskList"] li {
display: flex;
align-items: flex-start;
gap: 8px;
}
.dw-prose ul[data-type="taskList"] li > label {
flex-shrink: 0;
margin-top: 0.3em;
user-select: none;
}
.dw-prose ul[data-type="taskList"] li > label input {
width: 16px;
height: 16px;
accent-color: var(--color-primary);
cursor: pointer;
}
.dw-prose ul[data-type="taskList"] li > div {
flex: 1;
min-width: 0;
}
.dw-prose ul[data-type="taskList"] li[data-checked="true"] > div > p {
color: var(--color-ink-muted);
text-decoration: line-through;
}
.dw-prose ul[data-type="taskList"] ul[data-type="taskList"] {
margin-top: 4px;
}
/* ---- Tables ---- */
.dw-prose .tableWrapper {
overflow-x: auto;
margin: 12px 0;
}
.dw-prose table {
border-collapse: collapse;
table-layout: fixed;
width: 100%;
overflow: hidden;
}
.dw-prose :is(td, th) {
position: relative;
min-width: 60px;
padding: 6px 10px;
border: 1px solid var(--color-line-strong);
vertical-align: top;
box-sizing: border-box;
}
.dw-prose :is(td, th) > * + * {
margin-top: 6px;
}
.dw-prose th {
background: var(--color-surface-sunken);
font-weight: 600;
text-align: left;
}
.dw-prose .selectedCell::after {
content: "";
position: absolute;
inset: 0;
background: var(--color-selection);
pointer-events: none;
}
.dw-prose .column-resize-handle {
position: absolute;
top: 0;
right: -2px;
bottom: -2px;
width: 4px;
background: var(--color-focus-ring);
pointer-events: none;
}
.dw-prose.resize-cursor {
cursor: col-resize;
}
/* ---- Code line numbers ---- */
.dw-prose pre.dw-code {
display: flex;
gap: 12px;
}
.dw-prose pre.dw-code > code {
flex: 1;
min-width: 0;
}
.dw-prose pre .dw-code__gutter {
display: none;
flex-shrink: 0;
min-width: 1.5em;
padding-right: 10px;
border-right: 1px solid var(--color-line);
color: var(--color-ink-faint);
text-align: right;
/* ProseMirror resets white-space on parts that are not editable. */
white-space: pre;
user-select: none;
}
.dw-prose pre.dw-code--numbered .dw-code__gutter {
display: block;
}
/* ---- PDFs shown inline ---- */
.dw-prose .dw-file-block > * + * {
margin-top: 6px;
}
.dw-pdf {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 560px;
padding: 8px;
overflow-y: auto;
border: 1px solid var(--color-line);
border-radius: var(--radius-md);
background: var(--color-surface-sunken);
}
.dw-pdf:focus-visible {
outline: 2px solid var(--color-focus-ring);
}
.dw-pdf__page {
width: 100%;
background: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
}
.dw-pdf__page canvas {
display: block;
width: 100%;
height: auto;
}
.dw-pdf__status {
padding: 24px;
text-align: center;
font-family: var(--font-sans);
font-size: var(--text-ui-sm);
color: var(--color-ink-muted);
}
/* ---- The block grip and its menu ---- */
.dw-block-grip {
cursor: grab;
}
.dw-block-grip[aria-expanded="true"] {
background: var(--color-surface-hover);
color: var(--color-ink);
}
.dw-block-menu {
width: 15rem;
}
.dw-block-menu .dw-suggest__item {
width: 100%;
border: none;
background: none;
font: inherit;
text-align: left;
cursor: pointer;
}
.dw-block-menu .dw-suggest__item.is-active {
background: var(--color-surface-hover);
}
.dw-block-menu .dw-suggest__item:focus {
outline: none;
}
.dw-block-menu .dw-suggest__item.is-danger :is(.dw-suggest__label, .dw-suggest__icon) {
color: var(--color-danger);
}
.dw-block-menu__more {
margin-left: auto;
color: var(--color-ink-faint);
}
/* ---- Moving table rows (tablerows.ts) ---- */
.dw-row-grip {
position: absolute;
z-index: 5;
display: grid;
place-items: center;
width: 14px;
height: 22px;
padding: 0;
border: 1px solid var(--color-line-strong);
border-radius: var(--radius-xs);
background: var(--color-surface-raised);
color: var(--color-ink-faint);
cursor: grab;
touch-action: none;
}
.dw-row-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 {
color: var(--color-ink);
border-color: var(--color-focus-ring);
}
.dw-row-grip:active {
cursor: grabbing;
}
.dw-row-grip[hidden],
.dw-row-drop[hidden] {
display: none;
}
.dw-row-drop {
position: absolute;
z-index: 5;
height: 2px;
background: var(--color-focus-ring);
pointer-events: none;
}
.dw-prose tr.dw-row-dragging {
opacity: 0.45;
}
@media (max-width: 640px), (hover: none) {
.dw-row-grip {
display: none;
}
}
+22 -2
View File
@@ -6,6 +6,10 @@ import CollaborationCaret from "@tiptap/extension-collaboration-caret";
import { Placeholder } from "@tiptap/extensions";
import StarterKit from "@tiptap/starter-kit";
import { BlockLinks } from "./blocklinks";
import { docwellAlign, docwellTables, docwellTasks, HeadingShortcuts } from "./blocks";
import { Callout } from "./callout";
import { DocwellCodeBlock } from "./codeblock";
import { DocwellHighlight, TextColor } from "./colors";
import { CommentHighlights } from "./comments";
import { DateMention } from "./dates";
import { DrawioBlock, ExcalidrawBlock, type ExcalidrawLoader } from "./diagrams";
@@ -17,8 +21,10 @@ import { docwellMath } from "./math";
import { docwellMention, type MentionHost } from "./mention";
import { MermaidBlock, type MermaidLoader } from "./mermaid";
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 { TableOfContents } from "./toc";
import { docwellToggles } from "./toggle";
@@ -54,6 +60,10 @@ export interface ExtensionOptions {
loadMermaid?: MermaidLoader;
/** Loads the Excalidraw editor; without it drawings show but cannot be edited. */
loadExcalidraw?: ExcalidrawLoader;
/** Loads pdf.js; without it PDF attachments show as download cards. */
loadPdf?: PdfLoader;
/** Whether code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers?: boolean;
labels?: EditorLabels;
/** Clicking highlighted comment text calls this with the comment id. */
onCommentSelect?: (id: string) => void;
@@ -84,14 +94,24 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
const list: AnyExtension[] = [
editorRef,
StarterKit.configure({
heading: { levels: [1, 2, 3] },
heading: { levels: [1, 2, 3, 4, 5, 6] },
codeBlock: false,
link: { openOnClick: false, autolink: true },
// Collaboration brings its own undo history, scoped to the local user.
undoRedo: opts.collab ? false : undefined,
}),
Placeholder.configure({ placeholder: opts.placeholder ?? "Type '/' for commands…" }),
DocwellImage.configure({ host: opts.files }),
FileAttachment.configure({ host: opts.files }),
FileAttachment.configure({ host: opts.files, loadPdf: opts.loadPdf, labels }),
DocwellCodeBlock.configure({ lineNumbers: opts.codeLineNumbers ?? false }),
HeadingShortcuts,
docwellAlign,
TextColor,
DocwellHighlight,
...docwellTasks(),
...docwellTables(),
TableRows.configure({ labels }),
Callout.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
DateMention.configure({ labels, me: () => opts.mentions?.me }),
+86 -7
View File
@@ -3,6 +3,8 @@
import { Extension, Node, mergeAttributes, type Editor } from "@tiptap/core";
import Image from "@tiptap/extension-image";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import type { EditorLabels } from "./labels";
import { isPdf, showPdf, type PdfLoader } from "./pdf";
/**
* How the host app reaches attachments. Documents store a file's API path
@@ -28,7 +30,17 @@ export async function insertFiles(editor: Editor, host: FileHost, files: File[],
const up = await host.upload(file);
const node = up.mime.startsWith("image/")
? { type: "image", attrs: { src: up.url, alt: up.name } }
: { type: "fileAttachment", attrs: { url: up.url, name: up.name, size: up.size, mime: up.mime } };
: {
type: "fileAttachment",
// PDFs show their pages where the host can draw them.
attrs: {
url: up.url,
name: up.name,
size: up.size,
mime: up.mime,
view: isPdf(up.mime, up.name) ? "preview" : "card",
},
};
// Insert after the selection rather than over it: an inserted image is
// left selected, and the next file must not replace it.
editor
@@ -80,15 +92,34 @@ function formatSize(bytes: number): string {
return `${n.toFixed(i && n < 10 ? 1 : 0)} ${units[i]}`;
}
/** A non-image attachment: a download card with the file's name and size. */
export const FileAttachment = Node.create<{ host?: FileHost }>({
declare module "@tiptap/core" {
interface Commands<ReturnType> {
fileAttachment: {
/** Switches the selected PDF between showing its pages and a download card. */
toggleFilePreview: () => ReturnType;
};
}
}
export interface FileAttachmentOptions {
host?: FileHost;
/** Loads pdf.js; without it PDFs show as a download card. */
loadPdf?: PdfLoader;
labels: EditorLabels | null;
}
/**
* A non-image attachment: a download card with the file's name and size.
* A PDF with view "preview" also shows its pages, scrolling in a frame.
*/
export const FileAttachment = Node.create<FileAttachmentOptions>({
name: "fileAttachment",
group: "block",
atom: true,
draggable: true,
addOptions() {
return { host: undefined };
return { host: undefined, loadPdf: undefined, labels: null };
},
addAttributes() {
@@ -97,6 +128,19 @@ export const FileAttachment = Node.create<{ host?: FileHost }>({
name: { default: "file" },
size: { default: 0 },
mime: { default: "" },
view: { default: "card" },
};
},
addCommands() {
return {
toggleFilePreview:
() =>
({ editor, commands }) => {
const a = editor.getAttributes(this.name);
if (!editor.isActive(this.name) || !isPdf(a.mime, a.name)) return false;
return commands.updateAttributes(this.name, { view: a.view === "preview" ? "card" : "preview" });
},
};
},
@@ -109,6 +153,7 @@ export const FileAttachment = Node.create<{ host?: FileHost }>({
name: el.getAttribute("data-name") ?? el.textContent ?? "file",
size: Number(el.getAttribute("data-size") ?? 0),
mime: el.getAttribute("data-mime") ?? "",
view: el.getAttribute("data-view") === "preview" ? "preview" : "card",
}),
},
];
@@ -123,6 +168,7 @@ export const FileAttachment = Node.create<{ host?: FileHost }>({
"data-name": node.attrs.name,
"data-size": node.attrs.size,
"data-mime": node.attrs.mime,
"data-view": node.attrs.view,
}),
["a", { href: node.attrs.url, download: node.attrs.name }, node.attrs.name],
];
@@ -130,23 +176,52 @@ export const FileAttachment = Node.create<{ host?: FileHost }>({
addNodeView() {
return ({ node }) => {
const { host, loadPdf, labels } = this.options;
const dom = document.createElement("div");
dom.className = "dw-file";
dom.className = "dw-file-block";
dom.setAttribute("data-type", "file");
const card = document.createElement("div");
card.className = "dw-file";
const link = document.createElement("a");
link.className = "dw-file__name";
link.target = "_blank";
link.rel = "noopener";
const size = document.createElement("span");
size.className = "dw-file__size";
card.append(link, size);
dom.append(card);
let pages: HTMLDivElement | null = null;
let stop: (() => void) | null = null;
let shown = "";
const draw = (n: typeof node) => {
const url = String(n.attrs.url ?? "");
link.href = this.options.host ? this.options.host.resolve(url) : url;
const href = host ? host.resolve(url) : url;
link.href = href;
link.textContent = String(n.attrs.name ?? "file");
size.textContent = formatSize(Number(n.attrs.size ?? 0));
const preview = n.attrs.view === "preview" && isPdf(n.attrs.mime, n.attrs.name) && !!url;
if (!preview || !loadPdf || !labels) {
stop?.();
stop = null;
pages?.remove();
pages = null;
shown = "";
return;
}
if (shown === href) return;
stop?.();
if (!pages) {
pages = document.createElement("div");
pages.className = "dw-pdf";
pages.tabIndex = 0;
pages.setAttribute("role", "document");
dom.append(pages);
}
pages.setAttribute("aria-label", String(n.attrs.name ?? "PDF"));
shown = href;
stop = showPdf(pages, href, loadPdf, labels);
};
draw(node);
dom.append(link, size);
return {
dom,
update: (n) => {
@@ -154,6 +229,10 @@ export const FileAttachment = Node.create<{ host?: FileHost }>({
draw(n);
return true;
},
// Scrolling and clicking through the pages are not edits.
stopEvent: (e) => !!pages && pages.contains(e.target as globalThis.Node) && e.type !== "mousedown",
ignoreMutation: () => true,
destroy: () => stop?.(),
};
};
},
+120
View File
@@ -18,6 +18,55 @@ export interface EditorLabels {
link: string;
linkPrompt: string;
comment: string;
underline: string;
color: string;
/** Headings of the colour menu's two groups. */
textColor: string;
highlight: string;
/** Takes the colour off again. */
noColor: string;
align: string;
alignLeft: string;
alignCenter: string;
alignRight: string;
/** Turns the selected text into an inline formula. */
math: string;
/** Makes a new page titled like the selection and links the selection to it. */
linkedPage: string;
};
/** Names of the palette colours (colors.ts), by name. */
colors: Record<string, string>;
/** The toolbar shown while the cursor is in a table. */
table: {
toolbar: string;
/** The grip on a row's left edge. */
dragRow: string;
moveRowUp: string;
moveRowDown: string;
addRowBefore: string;
addRowAfter: string;
addColumnBefore: string;
addColumnAfter: string;
deleteRow: string;
deleteColumn: string;
toggleHeaderRow: string;
mergeCells: string;
splitCell: string;
deleteTable: string;
};
/** The menu behind the grip beside each block. */
blockMenu: {
open: string;
turnInto: string;
moveUp: string;
moveDown: string;
duplicate: string;
copy: string;
delete: string;
showLineNumbers: string;
hideLineNumbers: string;
showPages: string;
showAsFile: string;
};
mentions: string;
noPeople: string;
@@ -47,6 +96,11 @@ export interface EditorLabels {
embedInvalid: string;
linkUrl: string;
copyBlockLink: string;
calloutEmoji: string;
calloutColor: string;
pdfLoading: string;
/** One page of a PDF shown inline; {n} is its number. */
pdfPage: string;
};
/** The find and replace bar. count has {current} and {total} in it. */
find: {
@@ -84,8 +138,14 @@ 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" },
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 [])" },
callout: { label: "Callout", description: "Set a note apart with an emoji and colour" },
table: { label: "Table", description: "Rows and columns" },
quote: { label: "Quote", description: "Set text apart as a quote" },
code: { label: "Code block", description: "Monospaced code" },
divider: { label: "Divider", description: "A line between sections" },
@@ -101,6 +161,11 @@ export const englishLabels: EditorLabels = {
toggle: { label: "Toggle", description: "A heading that hides the blocks under it" },
embed: { label: "Embed", description: "A video, design or document from YouTube, Figma and more" },
linkCard: { label: "Link card", description: "A link with its page's title and picture" },
newPage: { label: "New page", description: "Make a page and link it here" },
today: { label: "Today", description: "Insert today's date" },
tomorrow: { label: "Tomorrow", description: "Insert tomorrow's date" },
yesterday: { label: "Yesterday", description: "Insert yesterday's date" },
now: { label: "Now", description: "Insert the date and time" },
},
format: {
bold: "Bold",
@@ -110,6 +175,57 @@ export const englishLabels: EditorLabels = {
link: "Link",
linkPrompt: "Link address (leave empty to remove the link)",
comment: "Comment",
underline: "Underline",
color: "Colour",
textColor: "Text colour",
highlight: "Highlight",
noColor: "Default",
align: "Align",
alignLeft: "Align left",
alignCenter: "Align centre",
alignRight: "Align right",
math: "Inline math",
linkedPage: "Make a linked page",
},
colors: {
gray: "Grey",
red: "Red",
orange: "Orange",
yellow: "Yellow",
green: "Green",
teal: "Teal",
blue: "Blue",
purple: "Purple",
pink: "Pink",
},
table: {
toolbar: "Table",
dragRow: "Drag to move the row",
moveRowUp: "Move row up",
moveRowDown: "Move row down",
addRowBefore: "Add row above",
addRowAfter: "Add row below",
addColumnBefore: "Add column left",
addColumnAfter: "Add column right",
deleteRow: "Delete row",
deleteColumn: "Delete column",
toggleHeaderRow: "Header row",
mergeCells: "Merge cells",
splitCell: "Split cell",
deleteTable: "Delete table",
},
blockMenu: {
open: "Drag to move, click for actions",
turnInto: "Turn into",
moveUp: "Move up",
moveDown: "Move down",
duplicate: "Duplicate",
copy: "Copy",
delete: "Delete",
showLineNumbers: "Show line numbers",
hideLineNumbers: "Hide line numbers",
showPages: "Show pages",
showAsFile: "Show as file",
},
mentions: "Mention someone",
noPeople: "Nobody found",
@@ -137,6 +253,10 @@ export const englishLabels: EditorLabels = {
embedInvalid: "This address can't be embedded.",
linkUrl: "Address of the page to link",
copyBlockLink: "Copy link to this block",
calloutEmoji: "Change emoji",
calloutColor: "Change colour",
pdfLoading: "Loading PDF…",
pdfPage: "Page {n}",
},
find: {
find: "Find in page",
+27
View File
@@ -18,6 +18,11 @@ export interface PageRef {
/** Finds pages for "[[" links; without one, "[[" is just text. */
export interface PageHost {
search(query: string): Promise<PageRef[]>;
/**
* Makes a page titled title next to the page being edited (a child of it,
* where the host allows). Without it the editor cannot make linked pages.
*/
create?(title: string): Promise<PageRef>;
}
/** The app path of a page; page links are ordinary links to it. */
@@ -44,6 +49,28 @@ export function insertPageLink(editor: Editor, range: Range, page: PageRef, unti
.run();
}
/**
* Makes a page through the host and links to it: the selected text becomes
* the link (and the new page's title), or, with nothing selected, a link
* titled like the page is inserted. untitled names a page with no title.
*/
export async function createLinkedPage(editor: Editor, host: PageHost, untitled: string): Promise<void> {
if (!host.create) return;
const { from, to, empty } = editor.state.selection;
const title = empty ? "" : editor.state.doc.textBetween(from, to, " ").trim().slice(0, 200);
const page = await host.create(title);
if (empty || !title) {
insertPageLink(editor, { from, to: from }, page, untitled);
return;
}
editor
.chain()
.focus()
.setTextSelection({ from, to })
.setLink({ href: pagePath(page.id) })
.run();
}
export interface PageLinkOptions {
host?: PageHost;
labels: EditorLabels | null;
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { EditorLabels } from "./labels";
/** The part of pdf.js the viewer uses; hosts load it (see pdfjs.ts) so the bridge can leave it out. */
export interface PdfJs {
getDocument(src: { url: string; withCredentials?: boolean }): {
promise: Promise<PdfDocument>;
destroy(): Promise<void>;
};
}
interface PdfDocument {
numPages: number;
getPage(n: number): Promise<PdfPage>;
}
interface PdfPage {
getViewport(o: { scale: number }): { width: number; height: number };
render(o: { canvas: HTMLCanvasElement; viewport: { width: number; height: number } }): { promise: Promise<void> };
}
export type PdfLoader = () => Promise<PdfJs>;
/** A PDF attachment's file name. */
export const isPdf = (mime: unknown, name: unknown) =>
mime === "application/pdf" || (typeof name === "string" && /\.pdf$/i.test(name));
/**
* Draws the pages of the PDF at url into box, each as it scrolls into view.
* Returns a function that stops loading and frees the document.
*/
export function showPdf(box: HTMLElement, url: string, load: PdfLoader, labels: EditorLabels): () => void {
let stopped = false;
let observer: IntersectionObserver | null = null;
let task: ReturnType<PdfJs["getDocument"]> | null = null;
const status = document.createElement("div");
status.className = "dw-pdf__status";
status.textContent = labels.blocks.pdfLoading;
box.replaceChildren(status);
void (async () => {
try {
const pdfjs = await load();
if (stopped) return;
task = pdfjs.getDocument({ url });
const doc = await task.promise;
if (stopped) return;
status.remove();
const width = Math.max(box.clientWidth - 2, 200);
const ratio = window.devicePixelRatio || 1;
observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const slot = entry.target as HTMLElement;
observer?.unobserve(slot);
void draw(slot, Number(slot.dataset.page));
}
},
{ root: box, rootMargin: "400px 0px" },
);
const first = await doc.getPage(1);
const base = first.getViewport({ scale: 1 });
for (let n = 1; n <= doc.numPages; n++) {
const slot = document.createElement("div");
slot.className = "dw-pdf__page";
slot.dataset.page = String(n);
// Until it is drawn, a page takes the first page's shape.
slot.style.aspectRatio = `${base.width} / ${base.height}`;
slot.setAttribute("aria-label", labels.blocks.pdfPage.replace("{n}", String(n)));
box.append(slot);
observer.observe(slot);
}
async function draw(slot: HTMLElement, n: number) {
const page = await doc.getPage(n);
if (stopped) return;
const scale = width / page.getViewport({ scale: 1 }).width;
const viewport = page.getViewport({ scale: scale * ratio });
const canvas = document.createElement("canvas");
canvas.width = Math.floor(viewport.width);
canvas.height = Math.floor(viewport.height);
slot.style.aspectRatio = `${viewport.width} / ${viewport.height}`;
slot.append(canvas);
await page.render({ canvas, viewport }).promise;
}
} catch {
if (!stopped) status.textContent = labels.blocks.loadFailed;
}
})();
return () => {
stopped = true;
observer?.disconnect();
void task?.destroy();
};
}
+12
View File
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// pdf.js and its worker load only when a page shows a PDF inline.
import { getDocument, GlobalWorkerOptions } from "pdfjs-dist";
import workerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";
import type { PdfJs } from "./pdf";
GlobalWorkerOptions.workerSrc = workerUrl;
/** pdf.js narrowed to what the viewer in pdf.ts uses. */
export const pdf = { getDocument } as unknown as PdfJs;
+38 -1
View File
@@ -4,9 +4,10 @@ import { Extension, type Editor, type Range } from "@tiptap/core";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import type { IconName } from "@docwell/ui/icons";
import { insertDate, isoDate } from "./dates";
import { promptEmbed, promptLinkCard, type LinkHost } from "./embeds";
import { insertFiles, type FileHost } from "./files";
import type { PageHost } from "./pagelinks";
import { createLinkedPage, type PageHost } from "./pagelinks";
import type { EditorLabels } from "./labels";
import { floatingList } from "./suggestion";
@@ -66,10 +67,24 @@ 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("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(),
),
block("todo", "todo", ["task", "checkbox", "checklist", "[]"], (e, r) =>
e.chain().focus().deleteRange(r).toggleTaskList().run(),
),
block("callout", "callout", ["note", "info", "tip", "warning", "aside", "box"], (e, r) =>
e.chain().focus().deleteRange(r).setCallout().run(),
),
block("table", "table", ["grid", "rows", "columns", "spreadsheet"], (e, r) =>
e.chain().focus().deleteRange(r).insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
),
block("quote", "quote", ["blockquote", ">"], (e, r) => e.chain().focus().deleteRange(r).toggleBlockquote().run()),
block("code", "code", ["codeblock", "```", "snippet"], (e, r) =>
e.chain().focus().deleteRange(r).toggleCodeBlock().run(),
@@ -101,12 +116,34 @@ export function slashCommands(
void promptLinkCard(e, l, links, onError);
}),
];
const day = (offset: number) => {
const d = new Date();
return isoDate(new Date(d.getFullYear(), d.getMonth(), d.getDate() + offset));
};
list.push(
block("today", "calendar", ["date", "day"], (e, r) => insertDate(e, r, { date: day(0), remind: false })),
block("tomorrow", "calendar", ["date", "day"], (e, r) => insertDate(e, r, { date: day(1), remind: false })),
block("yesterday", "calendar", ["date", "day"], (e, r) => insertDate(e, r, { date: day(-1), remind: false })),
block("now", "clock", ["time", "date", "timestamp"], (e, r) => {
insertDate(e, r, { date: day(0), remind: false });
const time = new Intl.DateTimeFormat(l.locale, { hour: "numeric", minute: "2-digit" }).format(new Date());
e.chain().focus().insertContent(`${time} `).run();
}),
);
if (pages) {
list.push(
block("pageLink", "link", ["page", "link", "[[", "wiki"], (e, r) =>
e.chain().focus().deleteRange(r).insertContent("[[").run(),
),
);
if (pages.create) {
list.push(
block("newPage", "page-plus", ["page", "doc", "subpage", "create"], (e, r) => {
e.chain().focus().deleteRange(r).run();
void createLinkedPage(e, pages, "").catch(onError);
}),
);
}
}
if (files?.upload) {
const upload = (accept: string) => (e: Editor, r: Range) => {
+72
View File
@@ -0,0 +1,72 @@
// 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
@@ -0,0 +1,242 @@
// 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);
}
}