CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Successful in 1h36m55s
CI / mobile (push) Failing after 1m47s
CI / go (Media) (push) Successful in 19m45s
CI / go (Server) (push) Failing after 26m1s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m49s
CI / docker (push) Failing after 37m4s
Turn into: the selection toolbar starts with the block's kind ("Heading 1")
and opens the list of kinds it can become, with a tick on the current
one. In a list it turns the whole list, as the block menu did; the grip
menu no longer has it.
Page icons: an editor clicks a page's icon in the sidebar tree to pick an
emoji from groups, recent picks or a search by name (any pasted emoji
works too), or to remove it. The emoji now stands in for the page glyph
rather than sitting before the title. Strings in all five languages.
Block handles: the link and grip buttons stay on the block the cursor is
in, which is highlighted while the editor has focus, sit centred on the
block's height, and no longer vanish crossing the gap from the text.
The sidebar shows the Docwell logo above the workspace switcher.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
346 lines
12 KiB
TypeScript
346 lines
12 KiB
TypeScript
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom";
|
|
import type { ChainedCommands, Editor, JSONContent } from "@tiptap/core";
|
|
import { Fragment } from "@tiptap/pm/model";
|
|
import { Selection } from "@tiptap/pm/state";
|
|
import type { IconName } from "@docwell/ui/icons";
|
|
import { showsLineNumbers } from "./codeblock";
|
|
import type { EditorLabels } from "./labels";
|
|
import { isPdf } from "./pdf";
|
|
import { svgIcon } from "./suggestion";
|
|
|
|
/** One row of the block menu; a row with children opens a list of them instead. */
|
|
export interface BlockAction {
|
|
id: string;
|
|
label: string;
|
|
icon: IconName;
|
|
run?: () => void;
|
|
children?: BlockAction[];
|
|
danger?: boolean;
|
|
}
|
|
|
|
/** What a block's text can turn into, as slash-menu ids with the commands that make them. */
|
|
const conversions: [string, IconName, (c: ChainedCommands) => ChainedCommands][] = [
|
|
["text", "text", (c) => c],
|
|
["h1", "heading", (c) => c.setNode("heading", { level: 1 })],
|
|
["h2", "heading", (c) => c.setNode("heading", { level: 2 })],
|
|
["h3", "heading", (c) => c.setNode("heading", { level: 3 })],
|
|
["bullet", "list", (c) => c.toggleBulletList()],
|
|
["ordered", "list-ordered", (c) => c.toggleOrderedList()],
|
|
["todo", "todo", (c) => c.toggleTaskList()],
|
|
["quote", "quote", (c) => c.setBlockquote()],
|
|
["code", "code", (c) => c.setCodeBlock()],
|
|
["callout", "callout", (c) => c.setCallout()],
|
|
];
|
|
|
|
/** Blocks whose text the menu can turn into another kind of block. */
|
|
const convertible = [
|
|
"paragraph",
|
|
"heading",
|
|
"codeBlock",
|
|
"blockquote",
|
|
"bulletList",
|
|
"orderedList",
|
|
"taskList",
|
|
"callout",
|
|
];
|
|
|
|
/** A block's JSON without block ids, so a copy does not share links with the original. */
|
|
function withoutIds(json: JSONContent): JSONContent {
|
|
const out: JSONContent = { ...json };
|
|
if (out.attrs && "blockId" in out.attrs) out.attrs = { ...out.attrs, blockId: null };
|
|
if (out.content) out.content = out.content.map(withoutIds);
|
|
return out;
|
|
}
|
|
|
|
const listTypes = ["bulletList", "orderedList", "taskList"];
|
|
|
|
/**
|
|
* The block "Turn into" acts on for the selection: the list around the
|
|
* cursor's line, or else its own paragraph, heading, quote or code block.
|
|
* -1 when the selection spans blocks or sits somewhere else (a table cell).
|
|
*/
|
|
export function turnIntoTarget(editor: Editor): number {
|
|
const { $from, $to } = editor.state.selection;
|
|
if (!$from.parent.isTextblock) return -1;
|
|
let depth = $from.depth;
|
|
if (depth >= 3 && listTypes.includes($from.node(depth - 2).type.name)) depth -= 2;
|
|
if (depth >= 2 && $from.node(depth - 1).type.name === "blockquote") depth -= 1;
|
|
const node = $from.node(depth);
|
|
if (!convertible.includes(node.type.name)) return -1;
|
|
const pos = $from.before(depth);
|
|
return $to.pos <= pos + node.nodeSize ? pos : -1;
|
|
}
|
|
|
|
/** Which conversion id the block at pos is now, for a tick beside it. */
|
|
export function currentConversion(editor: Editor, pos: number): string | null {
|
|
const node = editor.state.doc.nodeAt(pos);
|
|
if (!node) return null;
|
|
const $pos = editor.state.doc.resolve(pos);
|
|
for (let d = $pos.depth; d >= 1; d--) if ($pos.node(d).type.name === "callout") return "callout";
|
|
switch (node.type.name) {
|
|
case "paragraph":
|
|
return "text";
|
|
case "heading":
|
|
return `h${node.attrs.level}`;
|
|
case "bulletList":
|
|
return "bullet";
|
|
case "orderedList":
|
|
return "ordered";
|
|
case "taskList":
|
|
return "todo";
|
|
case "blockquote":
|
|
return "quote";
|
|
case "codeBlock":
|
|
return "code";
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** The kinds of block the block at pos can turn into, each with what turns it. */
|
|
export function turnIntoActions(editor: Editor, pos: number, labels: EditorLabels): BlockAction[] {
|
|
const node = editor.state.doc.nodeAt(pos);
|
|
if (!node || !convertible.includes(node.type.name)) return [];
|
|
const end = pos + node.nodeSize;
|
|
return 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" || currentConversion(editor, pos) === "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();
|
|
},
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* The actions for the top-level block at pos: move, duplicate, copy, delete,
|
|
* plus block-specific ones (line numbers, PDF pages). Turning a block into
|
|
* another kind is on the selection toolbar.
|
|
*/
|
|
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 (["bulletList", "orderedList", "taskList"].includes(node.type.name)) {
|
|
out.push({
|
|
id: "groupAsDatabase",
|
|
label: labels.database.groupAsDatabase,
|
|
icon: "database",
|
|
run: () => {
|
|
editor
|
|
.chain()
|
|
.focus()
|
|
.setTextSelection(pos + 2)
|
|
.groupAsDatabase()
|
|
.run();
|
|
},
|
|
});
|
|
}
|
|
if (node.type.name === "codeBlock") {
|
|
const byDefault = !!editor.extensionManager.extensions.find((e) => e.name === "codeBlock")?.options.lineNumbers;
|
|
const on = showsLineNumbers(node.attrs.lineNumbers, byDefault);
|
|
out.push({
|
|
id: "lineNumbers",
|
|
label: on ? m.hideLineNumbers : m.showLineNumbers,
|
|
icon: "list-ordered",
|
|
run: () => editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, "lineNumbers", !on)),
|
|
});
|
|
}
|
|
if (node.type.name === "fileAttachment" && isPdf(node.attrs.mime, node.attrs.name)) {
|
|
const preview = node.attrs.view === "preview";
|
|
out.push({
|
|
id: "pdfView",
|
|
label: preview ? m.showAsFile : m.showPages,
|
|
icon: preview ? "paperclip" : "file",
|
|
run: () => editor.view.dispatch(editor.state.tr.setNodeAttribute(pos, "view", preview ? "card" : "preview")),
|
|
});
|
|
}
|
|
if (index > 0) {
|
|
out.push({
|
|
id: "moveUp",
|
|
label: m.moveUp,
|
|
icon: "arrow-up",
|
|
run: () => {
|
|
const prev = editor.state.doc.child(index - 1);
|
|
const tr = editor.state.tr.delete(pos, end).insert(pos - prev.nodeSize, node);
|
|
editor.view.dispatch(tr.scrollIntoView());
|
|
},
|
|
});
|
|
}
|
|
if (index < editor.state.doc.childCount - 1) {
|
|
out.push({
|
|
id: "moveDown",
|
|
label: m.moveDown,
|
|
icon: "arrow-down",
|
|
run: () => {
|
|
const next = editor.state.doc.child(index + 1);
|
|
const tr = editor.state.tr.delete(pos, end).insert(pos + next.nodeSize, node);
|
|
editor.view.dispatch(tr.scrollIntoView());
|
|
},
|
|
});
|
|
}
|
|
out.push(
|
|
{
|
|
id: "duplicate",
|
|
label: m.duplicate,
|
|
icon: "plus",
|
|
run: () => {
|
|
const copy = editor.schema.nodeFromJSON(withoutIds(node.toJSON() as JSONContent));
|
|
editor.view.dispatch(editor.state.tr.insert(end, copy).scrollIntoView());
|
|
},
|
|
},
|
|
{
|
|
id: "copy",
|
|
label: m.copy,
|
|
icon: "copy",
|
|
run: () => {
|
|
// The browser's own copy keeps the block's formatting for pasting elsewhere.
|
|
editor.chain().focus().setNodeSelection(pos).run();
|
|
document.execCommand("copy");
|
|
},
|
|
},
|
|
);
|
|
if (copyLink) out.push({ id: "copyLink", label: labels.blocks.copyBlockLink, icon: "link", run: copyLink });
|
|
out.push({
|
|
id: "delete",
|
|
label: m.delete,
|
|
icon: "trash",
|
|
danger: true,
|
|
run: () => {
|
|
editor.view.dispatch(editor.state.tr.delete(pos, end));
|
|
editor.commands.focus();
|
|
},
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* Shows actions in a menu next to anchor. Arrows move, Enter picks, Escape
|
|
* or a click elsewhere closes it. Returns a function that closes it.
|
|
*/
|
|
export function openBlockMenu(anchor: HTMLElement, actions: BlockAction[], label: string, onClose?: () => void) {
|
|
const box = document.createElement("div");
|
|
box.className = "dw-suggest dw-block-menu";
|
|
box.setAttribute("role", "menu");
|
|
box.setAttribute("aria-label", label);
|
|
let list = actions;
|
|
let active = 0;
|
|
let stack: BlockAction[][] = [];
|
|
|
|
const draw = () => {
|
|
box.replaceChildren();
|
|
list.forEach((a, i) => {
|
|
const row = document.createElement("button");
|
|
row.type = "button";
|
|
row.className = `dw-suggest__item${i === active ? " is-active" : ""}${a.danger ? " is-danger" : ""}`;
|
|
row.setAttribute("role", "menuitem");
|
|
row.tabIndex = -1;
|
|
if (a.children) row.setAttribute("aria-haspopup", "menu");
|
|
const glyph = document.createElement("span");
|
|
glyph.className = "dw-suggest__icon";
|
|
glyph.append(svgIcon(a.icon));
|
|
const text = document.createElement("span");
|
|
text.className = "dw-suggest__label";
|
|
text.textContent = a.label;
|
|
row.append(glyph, text);
|
|
if (a.children) {
|
|
const more = svgIcon("chevron-right", 14);
|
|
more.classList.add("dw-block-menu__more");
|
|
row.append(more);
|
|
}
|
|
row.addEventListener("mousedown", (e) => e.preventDefault());
|
|
row.addEventListener("click", () => pick(i));
|
|
row.addEventListener("mouseenter", () => {
|
|
active = i;
|
|
for (const [j, r] of [...box.children].entries()) r.classList.toggle("is-active", j === i);
|
|
});
|
|
box.append(row);
|
|
});
|
|
(box.children[active] as HTMLElement | undefined)?.focus();
|
|
};
|
|
|
|
const pick = (i: number) => {
|
|
const a = list[i];
|
|
if (!a) return;
|
|
if (a.children) {
|
|
stack.push(list);
|
|
list = a.children;
|
|
active = 0;
|
|
draw();
|
|
return;
|
|
}
|
|
close();
|
|
a.run?.();
|
|
};
|
|
|
|
const onKey = (e: KeyboardEvent) => {
|
|
if (e.key === "Escape" || (e.key === "ArrowLeft" && stack.length)) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (stack.length) {
|
|
list = stack.pop()!;
|
|
active = 0;
|
|
draw();
|
|
} else close();
|
|
return;
|
|
}
|
|
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
active = (active + (e.key === "ArrowDown" ? 1 : -1) + list.length) % list.length;
|
|
draw();
|
|
} else if (e.key === "Enter" || e.key === " " || e.key === "ArrowRight") {
|
|
e.preventDefault();
|
|
if (e.key !== "ArrowRight" || list[active]?.children) pick(active);
|
|
}
|
|
};
|
|
const onDown = (e: MouseEvent) => {
|
|
if (!box.contains(e.target as Node) && !anchor.contains(e.target as Node)) close();
|
|
};
|
|
|
|
document.body.append(box);
|
|
const stop = autoUpdate(anchor, box, () => {
|
|
void computePosition(anchor, box, {
|
|
placement: "bottom-start",
|
|
strategy: "fixed",
|
|
middleware: [offset(4), flip(), shift({ padding: 8 })],
|
|
}).then(({ x, y }) => Object.assign(box.style, { left: `${x}px`, top: `${y}px` }));
|
|
});
|
|
box.addEventListener("keydown", onKey);
|
|
document.addEventListener("mousedown", onDown, true);
|
|
let closed = false;
|
|
function close() {
|
|
if (closed) return;
|
|
closed = true;
|
|
stop();
|
|
box.remove();
|
|
document.removeEventListener("mousedown", onDown, true);
|
|
stack = [];
|
|
onClose?.();
|
|
}
|
|
draw();
|
|
return close;
|
|
}
|