Files
Docwell/Packages/editor/src/columns.ts
T
tajniak81andClaude Opus 5.5 e441880f2f
CI / desktop (ubuntu-latest) (push) Successful in 1h15m48s
CI / mobile (push) Failing after 3m6s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 10m21s
CI / go (Server) (push) Failing after 19m16s
CI / go (Web-App) (push) Successful in 10m27s
CI / frontend (push) Failing after 7m25s
CI / docker (push) Successful in 46m48s
Add the block types Docmost has and Docwell lacked
The slash menu gains Video, Audio, Page break, Footnote, Tabs, Status,
Emoji, Subpages, Synced block and a fifth column size:
- Video and audio upload a file that plays on the page.
- Page breaks show as a labelled line and start a new page in print,
  Word and PDF.
- Footnotes are numbered in reading order and listed at the end of the
  page. Their notes hold bold, italic, code and links, with a plain copy
  kept for search.
- Tabs hold blocks on several named tabs; which one shows is each
  reader's own choice.
- Status badges are coloured words in the text.
- Typing ":" and a word picks an emoji, from the list the page icon
  picker uses, now kept in the editor package.
- Subpages lists the page's child pages, read afresh from the page tree.
- A synced block is a synced page that shows one block of another page,
  made from a copied block link.

Exports (HTML, Markdown, Word, PDF) and search handle every new block.
Page and space exports list a page's subpages. Labels are translated in
all five languages.

The phone toolbar gets Tabs, Footnote, Status, Emoji, Subpages and Page
break, and the app answers the editor's request for the page's
subpages. The bridge protocol goes to version 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:37:32 +01:00

341 lines
13 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { mergeAttributes, Node, type Editor } from "@tiptap/core";
import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
import { TextSelection } from "@tiptap/pm/state";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
columns: {
/** Puts a row of empty columns where the selection is. */
insertColumns: (count?: number) => ReturnType;
/** Adds an empty column after the one holding the selection. */
addColumn: () => ReturnType;
/** Turns the columns around the selection back into blocks, one column after another. */
unsetColumns: () => ReturnType;
};
}
}
export const minColumns = 2;
export const maxColumns = 5;
/** No column gets narrower than this share of the row (percent). */
const minWidth = 10;
/** A column's width in percent, or null for an equal share. */
function cleanWidth(v: unknown): number | null {
const n = typeof v === "string" ? parseFloat(v) : typeof v === "number" ? v : NaN;
return Number.isFinite(n) && n > 0 && n <= 100 ? Math.round(n * 10) / 10 : null;
}
/** The widths of a row's columns in percent, equal shares filled in, adding up to 100. */
export function columnWidths(row: PMNode): number[] {
const set = [] as (number | null)[];
row.forEach((c) => set.push(cleanWidth(c.attrs.width)));
const known = set.reduce<number>((s, w) => s + (w ?? 0), 0);
const unknown = set.filter((w) => w === null).length;
const share = unknown ? Math.max(100 - known, unknown * minWidth) / unknown : 0;
const widths = set.map((w) => w ?? share);
const total = widths.reduce((s, w) => s + w, 0) || 1;
return widths.map((w) => (w * 100) / total);
}
/** The depth of the nearest row of columns around the selection, or -1. */
function rowDepth(editor: Editor): number {
const { $from } = editor.state.selection;
for (let d = $from.depth; d > 0; d--) if ($from.node(d).type.name === "columns") return d;
return -1;
}
/** A column holding one empty paragraph. */
function emptyColumn(editor: Editor, width: number | null = null): PMNode {
const { schema } = editor.state;
return schema.nodes.column!.create({ width }, schema.nodes.paragraph!.create());
}
/** Whether a column holds nothing but one empty paragraph. */
function isEmptyColumn(col: PMNode): boolean {
return col.childCount === 1 && col.firstChild!.type.name === "paragraph" && col.firstChild!.content.size === 0;
}
/**
* Side-by-side columns: a row ("columns") of two to five columns, each
* holding ordinary blocks. Columns share the width equally until someone
* drags the line between two of them. On narrow screens they stack.
* Backspace in an empty column removes it, and a row left with one column
* turns back into plain blocks.
*/
export const Columns = Node.create<{ labels: EditorLabels | null }>({
name: "columns",
group: "block",
content: `column{${minColumns},${maxColumns}}`,
defining: true,
isolating: true,
draggable: true,
addOptions() {
return { labels: null };
},
parseHTML() {
return [{ tag: "div[data-type=columns]" }];
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-type": "columns", class: "dw-columns" }), 0];
},
addCommands() {
return {
insertColumns:
(count = 2) =>
({ editor, tr, dispatch }) => {
const n = Math.min(Math.max(Math.round(count), minColumns), maxColumns);
const row = editor.schema.nodes.columns!.create(
null,
Array.from({ length: n }, () => emptyColumn(editor)),
);
if (!dispatch) return true;
const from = tr.selection.from;
tr.replaceSelectionWith(row);
// The caret goes into the first column; the row starts at or just after from.
let start = -1;
tr.doc.nodesBetween(from, Math.min(from + row.nodeSize + 2, tr.doc.content.size), (node, pos) => {
if (start < 0 && node.type.name === "columns") start = pos;
return start < 0;
});
if (start >= 0) tr.setSelection(TextSelection.create(tr.doc, start + 3));
tr.scrollIntoView();
return true;
},
addColumn:
() =>
({ editor, tr, dispatch }) => {
const d = rowDepth(editor);
if (d < 0) return false;
const { $from } = tr.selection;
const row = $from.node(d);
if (row.childCount >= maxColumns) return false;
if (!dispatch) return true;
const index = $from.index(d);
const rowPos = $from.before(d);
// The new column is an equal share; the others shrink to make room.
const widths = columnWidths(row);
const share = 100 / (row.childCount + 1);
const scale = (100 - share) / 100;
let pos = rowPos + 1;
row.forEach((col, _o, i) => {
tr.setNodeMarkup(tr.mapping.map(pos), undefined, { ...col.attrs, width: widths[i]! * scale });
pos += col.nodeSize;
});
let at = rowPos + 1;
for (let i = 0; i <= index; i++) at += row.child(i).nodeSize;
const mapped = tr.mapping.map(at);
tr.insert(mapped, emptyColumn(editor, share));
tr.setSelection(TextSelection.create(tr.doc, mapped + 2));
return true;
},
unsetColumns:
() =>
({ editor, tr, dispatch }) => {
const d = rowDepth(editor);
if (d < 0) return false;
if (!dispatch) return true;
const { $from } = tr.selection;
const row = $from.node(d);
const blocks: PMNode[] = [];
row.forEach((col) => {
if (!isEmptyColumn(col)) col.forEach((b) => blocks.push(b));
});
if (!blocks.length) blocks.push(editor.schema.nodes.paragraph!.create());
const start = $from.before(d);
tr.replaceWith(start, start + row.nodeSize, Fragment.from(blocks));
tr.setSelection(TextSelection.near(tr.doc.resolve(start + 1)));
return true;
},
};
},
addKeyboardShortcuts() {
return {
// Backspace in an empty column removes it; one column left becomes plain blocks.
Backspace: ({ editor }) => {
const { $from, empty } = editor.state.selection;
if (!empty || $from.parentOffset > 0) return false;
const d = rowDepth(editor);
if (d < 0 || $from.depth !== d + 2) return false;
const row = $from.node(d);
const col = $from.node(d + 1);
if (!isEmptyColumn(col)) return false;
if (row.childCount <= minColumns) return editor.commands.unsetColumns();
const index = $from.index(d);
const colPos = $from.before(d + 1);
const tr = editor.state.tr.delete(colPos, colPos + col.nodeSize);
// The others share the freed width; the caret goes to the end of the column before.
const rowPos = $from.before(d);
const left = tr.doc.nodeAt(rowPos)!;
const widths = columnWidths(left);
let pos = rowPos + 1;
left.forEach((c, _o, i) => {
tr.setNodeMarkup(pos, undefined, { ...c.attrs, width: widths[i] });
pos += c.nodeSize;
});
const target = Math.max(index - 1, 0);
let end = rowPos + 1;
for (let i = 0; i <= target; i++) end += tr.doc.nodeAt(rowPos)!.child(i).nodeSize;
tr.setSelection(TextSelection.near(tr.doc.resolve(end - 1), -1));
editor.view.dispatch(tr.scrollIntoView());
return true;
},
"Mod-Alt-ArrowRight": ({ editor }) => editor.commands.addColumn(),
};
},
});
/** One column of a row; its width is a share of the row in percent. */
export const Column = Node.create<{ labels: EditorLabels | null }>({
name: "column",
content: "block+",
isolating: true,
addOptions() {
return { labels: null };
},
addAttributes() {
return {
width: {
default: null,
parseHTML: (el) => cleanWidth(el.getAttribute("data-width")),
renderHTML: (attrs) => (attrs.width == null ? {} : { "data-width": String(cleanWidth(attrs.width)) }),
},
};
},
parseHTML() {
return [{ tag: "div[data-type=column]" }];
},
renderHTML({ HTMLAttributes }) {
return ["div", mergeAttributes(HTMLAttributes, { "data-type": "column", class: "dw-column" }), 0];
},
addNodeView() {
return ({ node, getPos, editor }) => {
const labels = this.options.labels;
const dom = document.createElement("div");
dom.className = "dw-column";
dom.setAttribute("data-type", "column");
const content = document.createElement("div");
content.className = "dw-column__body";
// The line on the right edge, dragged to share width with the next column.
const handle = document.createElement("div");
handle.className = "dw-column__resize";
handle.contentEditable = "false";
handle.setAttribute("role", "separator");
handle.setAttribute("aria-orientation", "vertical");
// The button that adds a column after this one.
const add = document.createElement("button");
add.type = "button";
add.className = "dw-column__add";
add.contentEditable = "false";
add.textContent = "+";
dom.append(content, handle, add);
const place = () => {
const pos = getPos();
if (typeof pos !== "number") return null;
const $pos = editor.state.doc.resolve(pos);
const row = $pos.parent;
if (row.type.name !== "columns") return null;
return { row, index: $pos.index(), rowPos: $pos.before() };
};
const draw = () => {
const p = place();
const widths = p ? columnWidths(p.row) : [100];
const w = p ? widths[p.index]! : 100;
dom.style.flexGrow = String(w);
const last = !p || p.index === p.row.childCount - 1;
handle.hidden = last;
add.hidden = !p || p.row.childCount >= maxColumns;
const resize = labels?.blocks.resizeColumn ?? "Drag to resize";
handle.title = resize;
handle.setAttribute("aria-label", resize);
const addLabel = labels?.blocks.addColumn ?? "Add a column";
add.title = addLabel;
add.setAttribute("aria-label", addLabel);
};
draw();
add.addEventListener("mousedown", (e) => e.preventDefault());
add.addEventListener("click", () => {
const pos = getPos();
if (typeof pos !== "number" || !editor.isEditable) return;
editor
.chain()
.setTextSelection(pos + 2)
.addColumn()
.focus()
.run();
});
handle.addEventListener("pointerdown", (e) => {
const p = place();
if (!p || !editor.isEditable || p.index >= p.row.childCount - 1) return;
e.preventDefault();
const rowEl = dom.parentElement;
const next = dom.nextElementSibling as HTMLElement | null;
if (!rowEl || !next) return;
const total = rowEl.getBoundingClientRect().width || 1;
const widths = columnWidths(p.row);
const pair = widths[p.index]! + widths[p.index + 1]!;
const startX = e.clientX;
const startW = widths[p.index]!;
let w = startW;
handle.setPointerCapture(e.pointerId);
dom.classList.add("is-resizing");
const move = (ev: PointerEvent) => {
w = Math.min(Math.max(startW + ((ev.clientX - startX) * 100) / total, minWidth), pair - minWidth);
dom.style.flexGrow = String(w);
next.style.flexGrow = String(pair - w);
};
const up = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", up);
handle.removeEventListener("pointercancel", up);
dom.classList.remove("is-resizing");
const now = place();
if (!now || Math.abs(w - startW) < 0.5) return draw();
const all = columnWidths(now.row);
all[now.index] = w;
all[now.index + 1] = pair - w;
const tr = editor.state.tr;
let pos = now.rowPos + 1;
now.row.forEach((col, _o, i) => {
tr.setNodeMarkup(pos, undefined, { ...col.attrs, width: Math.round(all[i]! * 10) / 10 });
pos += col.nodeSize;
});
editor.view.dispatch(tr);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", up);
handle.addEventListener("pointercancel", up);
});
return {
dom,
contentDOM: content,
update: (n) => {
if (n.type !== node.type) return false;
draw();
return true;
},
stopEvent: (e) => handle.contains(e.target as globalThis.Node) || add.contains(e.target as globalThis.Node),
ignoreMutation: (m) =>
handle.contains(m.target) || add.contains(m.target) || (m.type === "attributes" && m.target === dom),
};
};
},
});