Files
Docwell/Packages/editor/src/slash.ts
T
tajniak81andClaude Opus 5.5 3dea2bb2f4
CI / go (Server) (push) Failing after 8m51s
CI / go (Web-App) (push) Successful in 11m46s
CI / mobile (push) Failing after 3m44s
CI / docker (push) Successful in 54m15s
Docs / build (push) Successful in 12m28s
Docs / deploy (push) Skipped
CI / frontend (push) Failing after 7m47s
CI / desktop (ubuntu-latest) (push) Successful in 1h27m22s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add Word export, column dragging and the rest of editor parity
Word export: pages download as .docx from the page menu and from
GET /pages/{id}/export?format=docx. The file keeps headings, alignment,
lists, to-dos, quotes, callouts, code, tables with a repeating header
row, text formatting, colours, highlights, links and the page's images.
Word import now reads callouts, to-dos and shaded highlights, so a page
exported to Word imports back as it was. The user guide says how to move
pages to Notion, whose Import reads Word and Markdown files.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:01:06 +01:00

227 lines
9.0 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
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 { createLinkedPage, type PageHost } from "./pagelinks";
import type { EditorLabels } from "./labels";
import { floatingList } from "./suggestion";
/** One "/" command. */
export interface SlashCommand {
id: string;
label: string;
description: string;
icon: IconName;
/** Extra words the filter matches, e.g. "h1" for Heading 1. */
keywords: string[];
run: (editor: Editor, range: Range) => void;
/** A group: picking it opens these instead of running. A search finds them directly too. */
children?: SlashCommand[];
}
/** Opens the system file picker and resolves with the chosen files. */
function pickFiles(accept: string): Promise<File[]> {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = accept;
input.multiple = true;
input.onchange = () => resolve([...(input.files ?? [])]);
input.click();
});
}
/** The block commands, in menu order. */
export function slashCommands(
l: EditorLabels,
files?: FileHost,
onError?: (e: unknown) => void,
pages?: PageHost,
excalidraw = false,
links?: LinkHost,
): SlashCommand[] {
const block = (
id: string,
icon: IconName,
keywords: string[],
apply: (e: Editor, r: Range) => void,
): SlashCommand => ({
id,
icon,
keywords,
label: l.slash[id]?.label ?? id,
description: l.slash[id]?.description ?? "",
run: apply,
});
const list: SlashCommand[] = [
block("text", "text", ["paragraph", "p"], (e, r) => e.chain().focus().deleteRange(r).setParagraph().run()),
block("h1", "heading", ["heading", "title", "#"], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level: 1 }).run(),
),
block("h2", "heading", ["heading", "subtitle", "##"], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level: 2 }).run(),
),
block("h3", "heading", ["heading", "###"], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level: 3 }).run(),
),
{
...block("otherHeadings", "heading", ["other", "more headings", "smaller"], () => {}),
children: ([4, 5, 6] as const).map((level) =>
block(`h${level}`, "heading", ["heading", "#".repeat(level)], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level }).run(),
),
),
},
block("bullet", "list", ["list", "ul", "-"], (e, r) => e.chain().focus().deleteRange(r).toggleBulletList().run()),
block("ordered", "list-ordered", ["list", "ol", "1."], (e, r) =>
e.chain().focus().deleteRange(r).toggleOrderedList().run(),
),
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(),
),
block("toggle", "chevron-right", ["details", "collapse", "expand", "fold", ">"], (e, r) =>
e.chain().focus().deleteRange(r).setDetails().run(),
),
block("divider", "divider", ["hr", "rule", "line", "---"], (e, r) =>
e.chain().focus().deleteRange(r).setHorizontalRule().run(),
),
block("toc", "list", ["contents", "outline", "headings", "index"], (e, r) =>
e.chain().focus().deleteRange(r).insertTableOfContents().run(),
),
block("math", "sigma", ["latex", "formula", "equation", "katex", "$$"], (e, r) =>
e.chain().focus().deleteRange(r).insertBlockMath({ latex: "E = mc^2" }).run(),
),
block("mathInline", "sigma", ["latex", "formula", "equation", "$"], (e, r) =>
e.chain().focus().deleteRange(r).insertInlineMath({ latex: "x^2" }).run(),
),
block("mermaid", "diagram", ["diagram", "flowchart", "chart", "sequence", "graph"], (e, r) =>
e.chain().focus().deleteRange(r).insertMermaid().run(),
),
block("embed", "video", ["video", "youtube", "vimeo", "figma", "loom", "iframe", "map"], (e, r) => {
e.chain().focus().deleteRange(r).run();
void promptEmbed(e, l, links, onError);
}),
block("linkCard", "link", ["bookmark", "preview", "card", "url", "web"], (e, r) => {
e.chain().focus().deleteRange(r).run();
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) => {
e.chain().focus().deleteRange(r).run();
void pickFiles(accept).then((picked) => insertFiles(e, files, picked).catch(onError));
};
list.push(
block("image", "image", ["picture", "photo", "img"], upload("image/*")),
block("file", "paperclip", ["attachment", "upload", "pdf"], upload("")),
block("drawio", "diagram", ["diagram", "diagrams.net", "draw", "chart", "uml"], (e, r) =>
e.chain().focus().deleteRange(r).insertDiagram("drawio").run(),
),
);
if (excalidraw) {
list.push(
block("excalidraw", "pencil", ["drawing", "sketch", "whiteboard", "draw"], (e, r) =>
e.chain().focus().deleteRange(r).insertDiagram("excalidraw").run(),
),
);
}
}
return list;
}
/**
* Filters commands by what follows the "/": label, id or keywords. With a
* query, the commands inside groups are matched and listed on their own.
*/
export function filterCommands(commands: SlashCommand[], query: string): SlashCommand[] {
const q = query.trim().toLowerCase();
if (!q) return commands;
const matches = (c: SlashCommand) =>
c.label.toLowerCase().includes(q) || c.id.startsWith(q) || c.keywords.some((k) => k.toLowerCase().startsWith(q));
return commands.flatMap((c) => {
// A search finds the commands in a group; the group itself when none of them match.
const inside = c.children?.filter(matches) ?? [];
if (inside.length) return inside;
return matches(c) ? [c] : [];
});
}
/** Typing "/" at the start of a word opens the block menu. */
export const SlashMenu = Extension.create<{ commands: SlashCommand[]; labels: EditorLabels }>({
name: "slashMenu",
addOptions() {
return { commands: [], labels: undefined as unknown as EditorLabels };
},
addProseMirrorPlugins() {
return [
Suggestion<SlashCommand>({
editor: this.editor,
pluginKey: new PluginKey("slashMenu"),
char: "/",
allowSpaces: false,
startOfLine: false,
// Not inside code, where "/" is just a character.
allow: ({ state, range }) => {
const $from = state.doc.resolve(range.from);
return !$from.parent.type.spec.code;
},
items: ({ query }) => filterCommands(this.options.commands, query),
render: floatingList<SlashCommand>({
label: this.options.labels.slashMenu,
empty: this.options.labels.noMatches,
showQuery: true,
toItem: (c) => ({ label: c.label, description: c.description, icon: c.icon }),
children: (c) => c.children,
pick: (p, c) => c.run(p.editor, p.range),
}),
}),
];
},
});