Skip to content

Build your personal knowledge base with Trilium Notes

text editor/collapsible: add support for dragging blocks

Adorian Doranf8298d48fb44
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index f0a65a49cf..72eda3492c 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2678,6 +2678,7 @@
"checkbox-tooltip": "Right click for more task states.\nPress {{shortcut}} to cycle between states.",
"collapsible-body-placeholder": "Type the content here...",
"collapsible-button-label": "Collapsible block",
+ "collapsible-select-label": "Select collapsible block",
"collapsible-title-placeholder": "Summary",
"collapsible-toggle-label": "Toggle collapsible block",
"collapsible-tooltip": "Click on the arrow or press {{shortcut}} to collapse/expand.",
diff --git a/packages/ckeditor5-collapsible/src/block-drag-handle.ts b/packages/ckeditor5-collapsible/src/block-drag-handle.ts
new file mode 100644
index 0000000000..ebe1d90993
--- /dev/null
+++ b/packages/ckeditor5-collapsible/src/block-drag-handle.ts
@@ -0,0 +1,174 @@
+import type { Editor } from "ckeditor5";
+
+export interface BlockDragHandleOptions {
+ editor: Editor;
+ /** className for the drop indicator drawn between blocks while dragging. */
+ indicatorClass: string;
+ /**
+ * Re-route a model element under the cursor to a different target before
+ * before/after is decided — e.g. a hit on a <summary> redirects to its
+ * parent <details>. Return the same model to keep it as-is, or a new one
+ * to retarget.
+ */
+ refineTarget?: (model: any) => any;
+ /** Invoked when the user clicks the handle without dragging past the threshold. */
+ onClick?: (model: any) => void;
+}
+
+interface DragState {
+ model: any;
+ startX: number;
+ startY: number;
+ started: boolean;
+ indicator: HTMLElement | null;
+ root: HTMLElement;
+ onMove: (e: MouseEvent) => void;
+ onUp: (e: MouseEvent) => void;
+}
+
+/**
+ * Custom mouse-based drag for moving a model block to a new position. Bypasses
+ * the HTML5 drag API (and therefore CKEditor's clipboard pipeline, which would
+ * otherwise intercept `drop` and try to paste the drag payload at the cursor).
+ *
+ * Usage: instantiate once per plugin, call `start(x, y, model, root)` from a
+ * mousedown handler on the block's drag handle, and `cancel()` from the
+ * plugin's destroy().
+ */
+export default class BlockDragHandle {
+
+ private dragState: DragState | null = null;
+
+ constructor(private readonly opts: BlockDragHandleOptions) {}
+
+ /**
+ * Begin tracking a potential drag. We don't yet commit to "this is a drag"
+ * — that decision happens in `onMove` once the cursor crosses a small
+ * threshold; below the threshold a quick mousedown/mouseup is treated as
+ * a click and invokes `onClick`.
+ */
+ public start(x: number, y: number, model: any, root: HTMLElement): void {
+ this.cancel();
+ const onMove = (e: MouseEvent) => this.onMove(e);
+ const onUp = (e: MouseEvent) => this.onUp(e);
+ this.dragState = {
+ model, startX: x, startY: y, started: false, indicator: null, root, onMove, onUp
+ };
+ const doc = root.ownerDocument;
+ doc.addEventListener("mousemove", onMove, true);
+ doc.addEventListener("mouseup", onUp, true);
+ }
+
+ /** Cancel any active drag. Safe to call when no drag is in progress. */
+ public cancel(): void {
+ const state = this.dragState;
+ if (!state) return;
+ state.indicator?.remove();
+ const doc = state.root.ownerDocument;
+ doc.removeEventListener("mousemove", state.onMove, true);
+ doc.removeEventListener("mouseup", state.onUp, true);
+ this.dragState = null;
+ }
+
+ private onMove(e: MouseEvent): void {
+ const state = this.dragState;
+ if (!state) return;
+ if (!state.started) {
+ const dx = e.clientX - state.startX;
+ const dy = e.clientY - state.startY;
+ // 4px² threshold — below it tiny mouse jitter shouldn't pop the indicator.
+ if (dx * dx + dy * dy < 16) return;
+ state.started = true;
+ const indicator = state.root.ownerDocument.createElement("div");
+ indicator.className = this.opts.indicatorClass;
+ state.root.ownerDocument.body.appendChild(indicator);
+ state.indicator = indicator;
+ }
+ const target = this.findDropTarget(e.clientX, e.clientY, state.root);
+ const dom = target ? this.getDom(target.model) : null;
+ if (!target || !dom || !state.indicator) {
+ if (state.indicator) state.indicator.style.display = "none";
+ return;
+ }
+ const rect = dom.getBoundingClientRect();
+ const top = target.before ? rect.top : rect.bottom;
+ state.indicator.style.display = "block";
+ state.indicator.style.left = `${rect.left}px`;
+ state.indicator.style.top = `${top - 1}px`;
+ state.indicator.style.width = `${rect.width}px`;
+ }
+
+ private onUp(e: MouseEvent): void {
+ const state = this.dragState;
+ if (!state) return;
+ this.cancel();
+ if (!state.started) {
+ this.opts.onClick?.(state.model);
+ return;
+ }
+ const target = this.findDropTarget(e.clientX, e.clientY, state.root);
+ if (!target || target.model === state.model) return;
+ // Reject drops into the dragged block's own subtree (would create a cycle).
+ for (let node: any = target.model; node; node = node.parent) {
+ if (node === state.model) return;
+ }
+ this.opts.editor.model.change(writer => {
+ const pos = target.before
+ ? writer.createPositionBefore(target.model)
+ : writer.createPositionAfter(target.model);
+ writer.move(writer.createRangeOn(state.model), pos);
+ });
+ }
+
+ /**
+ * Map a viewport coordinate to a model insertion target. Walks up the DOM
+ * from the point to find a block-level element that maps to a model
+ * element, then decides "drop before" vs "drop after" based on the
+ * cursor's vertical position relative to the target's midpoint. Falls back
+ * to the nearest top-level child when the cursor lands in margin/empty
+ * space.
+ */
+ private findDropTarget(x: number, y: number, root: HTMLElement): { model: any, before: boolean } | null {
+ let el: HTMLElement | null = root.ownerDocument.elementFromPoint(x, y) as HTMLElement | null;
+ while (el && el !== root) {
+ const view = this.opts.editor.editing.view.domConverter.mapDomToView(el);
+ let model = view ? this.opts.editor.editing.mapper.toModelElement(view as any) : null;
+ let rectEl: HTMLElement = el;
+ if (model && this.opts.refineTarget) {
+ const refined = this.opts.refineTarget(model);
+ if (refined && refined !== model) {
+ model = refined;
+ const refinedDom = this.getDom(refined);
+ if (refinedDom) rectEl = refinedDom;
+ }
+ }
+ if (model?.is?.("element") && model.parent) {
+ const rect = rectEl.getBoundingClientRect();
+ return { model, before: y < rect.top + rect.height / 2 };
+ }
+ el = el.parentElement;
+ }
+
+ // The cursor is over root margins / inter-block whitespace / past the
+ // last block. Fall back to the nearest top-level child by vertical
+ // distance so drops always land somewhere sensible.
+ let closest: { model: any, distance: number, before: boolean } | null = null;
+ for (const child of Array.from(root.children) as HTMLElement[]) {
+ const view = this.opts.editor.editing.view.domConverter.mapDomToView(child);
+ const model = view ? this.opts.editor.editing.mapper.toModelElement(view as any) : null;
+ if (!model?.is?.("element") || !model.parent) continue;
+ const rect = child.getBoundingClientRect();
+ const distance = y < rect.top ? rect.top - y : y > rect.bottom ? y - rect.bottom : 0;
+ if (!closest || distance < closest.distance) {
+ closest = { model, distance, before: y < rect.top + rect.height / 2 };
+ }
+ }
+ return closest;
+ }
+
+ private getDom(model: any): HTMLElement | null {
+ const view = this.opts.editor.editing.mapper.toViewElement(model);
+ const dom = view ? this.opts.editor.editing.view.domConverter.viewToDom(view) : null;
+ return dom instanceof HTMLElement ? dom : null;
+ }
+}
diff --git a/packages/ckeditor5-collapsible/src/collapsible-editing.ts b/packages/ckeditor5-collapsible/src/collapsible-editing.ts
index 953bc1febe..98530fca66 100644
--- a/packages/ckeditor5-collapsible/src/collapsible-editing.ts
+++ b/packages/ckeditor5-collapsible/src/collapsible-editing.ts
@@ -1,5 +1,6 @@
import { Plugin, Enter, Delete, enableViewPlaceholder, getEnvKeystrokeText, type ViewDocumentEnterEvent, type ViewDocumentDeleteEvent, type ViewDocumentArrowKeyEvent } from "ckeditor5";
import { Tooltip } from "bootstrap";
+import BlockDragHandle from "./block-drag-handle.js";
import CollapsibleCommand from "./collapsible-command.js";
type TranslateFn = (key: string, params?: Record<string, unknown>) => string;
@@ -28,6 +29,7 @@ export default class CollapsibleEditing extends Plugin {
private keydownListeners: Array<{ root: HTMLElement, handler: (e: KeyboardEvent) => void }> = [];
private toggleListeners: Array<{ root: HTMLElement, handler: (e: Event) => void }> = [];
private autoOpenTimer?: ReturnType<typeof setTimeout>;
+ private dragHandle!: BlockDragHandle;
/** Summary DOM elements that currently have a Bootstrap tooltip attached. */
private readonly summaryTooltips = new Set<HTMLElement>();
/** The summary tooltip we currently have force-shown because the caret is inside it. */
@@ -35,6 +37,23 @@ export default class CollapsibleEditing extends Plugin {
public init(): void {
this.editor.commands.add("collapsible", new CollapsibleCommand(this.editor));
+ this.dragHandle = new BlockDragHandle({
+ editor: this.editor,
+ indicatorClass: "trilium-collapsible-drop-indicator",
+ // A drop on another collapsible's <summary> should reorder relative
+ // to the whole <details>, not nest inside the body (which the
+ // summary-invariant post-fixer would then have to fight).
+ refineTarget: (model) => {
+ if (model?.is?.("element", "summary") && model.parent?.is("element", "details")) {
+ return model.parent;
+ }
+ return model;
+ },
+ onClick: (model) => {
+ this.editor.model.change(w => w.setSelection(model, "on"));
+ this.editor.editing.view.focus();
+ }
+ });
this.registerSchema();
this.registerConversion();
this.registerBodyPlaceholder();
@@ -64,6 +83,7 @@ export default class CollapsibleEditing extends Plugin {
}
this.summaryTooltips.clear();
this.caretShownTooltip = undefined;
+ this.dragHandle?.cancel();
super.destroy();
}
@@ -114,8 +134,63 @@ export default class CollapsibleEditing extends Plugin {
* doesn't include the arrow so it doesn't pollute saved HTML.
*/
private createEditingSummary(writer: any): any {
+ const editor = this.editor;
+ const plugin = this;
const t = this.translate();
const summary = writer.createContainerElement("summary");
+
+ // Selection / drag handle — non-editable affordance for selecting and
+ // moving the whole <details> as a block (mirrors the table widget's
+ // handle, but works without making the collapsible a widget).
+ const handle = writer.createUIElement("span", {
+ class: "trilium-collapsible-handle",
+ role: "button",
+ tabindex: "0",
+ "aria-label": t("text-editor.collapsible-select-label")
+ }, function(this: any, domDocument: any) {
+ const span: HTMLElement = this.toDomElement(domDocument);
+ const resolveDetails = () => {
+ const detailsDom = span.closest("details");
+ if (!detailsDom) return null;
+ const view = editor.editing.view.domConverter.mapDomToView(detailsDom);
+ return view ? editor.editing.mapper.toModelElement(view as any) : null;
+ };
+ const selectBlock = () => {
+ const model = resolveDetails();
+ if (!model) return;
+ editor.model.change(w => w.setSelection(model, "on"));
+ editor.editing.view.focus();
+ };
+ // Custom drag: mousedown starts tracking, document mousemove/mouseup
+ // (registered by startMouseDrag) decide whether it's a click or a drag.
+ // preventDefault stops the editor from placing a caret on the handle
+ // and from initiating a native text selection drag.
+ span.addEventListener("mousedown", (e: MouseEvent) => {
+ if (e.button !== 0) return;
+ const model = resolveDetails();
+ if (!model) return;
+ const root = span.closest(".ck-editor__editable") as HTMLElement | null;
+ if (!root) return;
+ e.preventDefault();
+ e.stopPropagation();
+ plugin.dragHandle.start(e.clientX, e.clientY, model, root);
+ });
+ // Suppress the trailing click so CKEditor's click handler doesn't
+ // reposition the caret after our mouseup has set the selection.
+ span.addEventListener("click", (e: Event) => {
+ e.stopPropagation();
+ e.preventDefault();
+ });
+ span.addEventListener("keydown", (e: KeyboardEvent) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.stopPropagation();
+ e.preventDefault();
+ selectBlock();
+ }
+ });
+ return span;
+ });
+
const arrow = writer.createUIElement("span", {
class: "trilium-collapsible-arrow",
role: "button",
@@ -148,6 +223,7 @@ export default class CollapsibleEditing extends Plugin {
return span;
});
writer.insert(writer.createPositionAt(summary, 0), arrow);
+ writer.insert(writer.createPositionAt(summary, 0), handle);
// "Title" placeholder shown while the summary is empty. UIElements like the
// arrow above don't count as content for placeholder purposes.
enableViewPlaceholder({
diff --git a/packages/ckeditor5-collapsible/theme/collapsible.css b/packages/ckeditor5-collapsible/theme/collapsible.css
index dd050c567d..5d56c6f9e9 100644
--- a/packages/ckeditor5-collapsible/theme/collapsible.css
+++ b/packages/ckeditor5-collapsible/theme/collapsible.css
@@ -112,6 +112,33 @@
display: none;
}
+ /* Block selection handle (mirror of the table widget's drag handle).
+ * Click selects the whole <details>; movement uses Alt+↑/↓ from there.
+ * Sits in the details' top-left padding area, visible on hover. */
+ > .trilium-collapsible-handle {
+ position: absolute;
+ top: calc(0px - var(--_block-padding) / 2);
+ right: 20px;
+ z-index: 1000;
+ width: 1lh;
+ height: 1lh;
+ cursor: default;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+
+ &::before {
+ position: absolute;
+ inset: 0;
+ content: "\ec6c"; /* U+205E VERTICAL FOUR DOTS — drag-handle glyph */
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-size: 1em;
+ font-family: boxicons;
+ color: var(--muted-text-color, currentColor);
+ }
+ }
+
/* CKEditor's placeholder ::before is positioned absolute left:0 by default —
* push it past the arrow so it aligns with where the typed title will appear. */
&.ck-placeholder::before {
@@ -148,4 +175,23 @@
&[open] > summary > .trilium-collapsible-arrow {
transform: rotate(90deg);
}
+
+ &:hover > summary > .trilium-collapsible-handle,
+ &:focus-within > summary > .trilium-collapsible-handle {
+ opacity: 1;
+ }
+}
+
+/*
+ * Drop indicator drawn while the user drags a collapsible by its handle.
+ * Position is set inline (viewport-relative, from getBoundingClientRect),
+ * so it uses position: fixed to align with those coords.
+ */
+.trilium-collapsible-drop-indicator {
+ position: fixed;
+ height: 2px;
+ background: var(--ck-document-outline-item-active-color);
+ border-radius: 1px;
+ pointer-events: none;
+ z-index: 10000;
}