mirror of
https://github.com/outline/outline.git
synced 2026-11-30 09:00:18 +03:00
Expanding drag handle to all root level block nodes (#12167)
* Expanding drag handle to all root level block nodes * wip * looking good * wip * fix, drag video nodes * fix mermaid * Hide drag handle when printing, adjust heading actions for handle gutter Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * rtl * Passive scroll listener, avoid dispatch on teardown * Guard drag handle from re-showing mid-drag, use semantic button * Align drag handle to first line, hide on layout images, tidy heading controls * Fix stale drag handle target and drag data, rebuild Mermaid in moved containers, remove unused styles * Extract drag handle target resolution into DragTarget class * Move drag handle styles from inline to global CSS * Use EditorStyleHelper class names and named constants in drag handle, translate its label * Hide drag handle on a table that holds the selection * Remove opacity transition from drag handle * Move heading anchor into drag handle slot when read-only * Move drop cursor class name to EditorStyleHelper * Add empty line above comments, document the rule in AGENTS.md * drag handle --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
1 parent
f00ff8e4a1
commit
c10a214075
13 files changed
+1018
-281
No files matched your search
@@ -32,6 +32,7 @@ You're an expert in the following areas:
|
||||
|
||||
- Critical – Do not create new markdown (.md) files.
|
||||
- Use early returns for readability.
|
||||
- Leave an empty line above every comment, unless the comment is the first line in a block.
|
||||
- Emphasize type safety and static analysis.
|
||||
- Follow consistent oxfmt formatting.
|
||||
- Do not replace smart quotes ("") or ('') with simple quotes ("").
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
import { t } from "i18next";
|
||||
import { NodeSelection, Plugin, PluginKey, Selection } from "prosemirror-state";
|
||||
import type { EditorView } from "prosemirror-view";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import type { DragTargetKind } from "~/editor/plugins/DragTarget";
|
||||
import { DragTarget } from "~/editor/plugins/DragTarget";
|
||||
|
||||
const HANDLE_SIZE = 24;
|
||||
|
||||
// Vertical offset of the icon within the handle, matches its mask-position.
|
||||
const ICON_OFFSET_Y = 2;
|
||||
|
||||
// Vertical center of the icon within the handle.
|
||||
const ICON_CENTER_Y = HANDLE_SIZE / 2 + ICON_OFFSET_Y;
|
||||
|
||||
// Tolerance when checking that text is rendered inside its block.
|
||||
const RECT_TOLERANCE = 1;
|
||||
const META_KEY = "drag-handle";
|
||||
|
||||
// Horizontal distance from the block's edge to the handle, per kind of block.
|
||||
const GUTTER_OFFSET: Record<DragTargetKind, number> = {
|
||||
block: 24,
|
||||
listItem: 40,
|
||||
checkboxItem: 0,
|
||||
};
|
||||
|
||||
type PluginState = {
|
||||
pos: number;
|
||||
size: number;
|
||||
} | null;
|
||||
|
||||
const pluginKey = new PluginKey<PluginState>(META_KEY);
|
||||
const HOVER_META_KEY = "drag-handle-hover";
|
||||
const hoverPluginKey = new PluginKey<number | null>(HOVER_META_KEY);
|
||||
|
||||
/**
|
||||
* Renders a floating drag handle to the left of block-level nodes when the
|
||||
* user hovers within the editor, and lets the user drag the block to reorder
|
||||
* it. The handle is a real, always-draggable DOM element rather than a CSS
|
||||
* pseudo on the block, which keeps drag-and-drop working uniformly across
|
||||
* node types regardless of whether the schema declares `draggable: true`.
|
||||
*/
|
||||
export default class DragHandle extends Extension {
|
||||
get name() {
|
||||
return "drag-handle";
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
// Marks the heading that owns the handle, so its level label in the
|
||||
// gutter can be hidden.
|
||||
new Plugin<number | null>({
|
||||
key: hoverPluginKey,
|
||||
state: {
|
||||
init: () => null,
|
||||
apply: (tr, value) => {
|
||||
const meta = tr.getMeta(HOVER_META_KEY) as
|
||||
| { pos: number | null }
|
||||
| undefined;
|
||||
if (meta) {
|
||||
return meta.pos;
|
||||
}
|
||||
if (value !== null && tr.docChanged) {
|
||||
const { pos: newPos, deleted } = tr.mapping.mapResult(value, 1);
|
||||
return !deleted && tr.doc.nodeAt(newPos)?.type.name === "heading"
|
||||
? newPos
|
||||
: null;
|
||||
}
|
||||
return value;
|
||||
},
|
||||
},
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const pos = hoverPluginKey.getState(state) ?? null;
|
||||
const node = pos === null ? null : state.doc.nodeAt(pos);
|
||||
if (pos === null || !node) {
|
||||
return DecorationSet.empty;
|
||||
}
|
||||
return DecorationSet.create(state.doc, [
|
||||
Decoration.node(pos, pos + node.nodeSize, {
|
||||
class: EditorStyleHelper.dragHandleTarget,
|
||||
}),
|
||||
]);
|
||||
},
|
||||
},
|
||||
}),
|
||||
new Plugin<PluginState>({
|
||||
key: pluginKey,
|
||||
state: {
|
||||
init: () => null,
|
||||
apply: (tr, value) => {
|
||||
const meta = tr.getMeta(META_KEY) as
|
||||
| { pos: number | null }
|
||||
| undefined;
|
||||
if (meta) {
|
||||
if (meta.pos === null) {
|
||||
return null;
|
||||
}
|
||||
const node = tr.doc.nodeAt(meta.pos);
|
||||
if (!node) {
|
||||
return null;
|
||||
}
|
||||
return { pos: meta.pos, size: node.nodeSize };
|
||||
}
|
||||
if (value && tr.docChanged) {
|
||||
const newPos = tr.mapping.map(value.pos);
|
||||
const node = tr.doc.nodeAt(newPos);
|
||||
if (!node) {
|
||||
return null;
|
||||
}
|
||||
return { pos: newPos, size: node.nodeSize };
|
||||
}
|
||||
return value;
|
||||
},
|
||||
},
|
||||
appendTransaction: (transactions, oldState, newState) => {
|
||||
const isDrop = transactions.some(
|
||||
(tr) => tr.getMeta("uiEvent") === "drop"
|
||||
);
|
||||
if (!isDrop || !pluginKey.getState(oldState)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ProseMirror selects the dropped content, which would open the
|
||||
// formatting toolbar, so collapse it to a cursor at the end instead.
|
||||
const $end = newState.doc.resolve(newState.selection.to);
|
||||
const selection =
|
||||
Selection.findFrom($end, -1, true) ??
|
||||
Selection.findFrom($end, 1, true);
|
||||
const tr = newState.tr.setMeta(META_KEY, { pos: null });
|
||||
return selection ? tr.setSelection(selection) : tr;
|
||||
},
|
||||
props: {
|
||||
decorations: (state) => {
|
||||
const dragState = pluginKey.getState(state);
|
||||
if (!dragState) {
|
||||
return DecorationSet.empty;
|
||||
}
|
||||
return DecorationSet.create(state.doc, [
|
||||
Decoration.node(dragState.pos, dragState.pos + dragState.size, {
|
||||
class: EditorStyleHelper.draggingSource,
|
||||
}),
|
||||
]);
|
||||
},
|
||||
handleDOMEvents: {
|
||||
dragstart: (view) => {
|
||||
view.dom.classList.add("dragging");
|
||||
return false;
|
||||
},
|
||||
drop: (view) => {
|
||||
view.dom.classList.remove("dragging");
|
||||
return false;
|
||||
},
|
||||
dragend: (view) => {
|
||||
view.dom.classList.remove("dragging");
|
||||
if (pluginKey.getState(view.state)) {
|
||||
view.dispatch(view.state.tr.setMeta(META_KEY, { pos: null }));
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
},
|
||||
view: (view) => {
|
||||
const handle = createHandle();
|
||||
document.body.appendChild(handle);
|
||||
|
||||
let target: DragTarget | null = null;
|
||||
|
||||
const onDragEnd = () => {
|
||||
view.dom.classList.remove("dragging");
|
||||
|
||||
// The handle is outside the editor DOM, so ProseMirror's own
|
||||
// dragend cleanup does not run for it.
|
||||
view.dragging = null;
|
||||
if (pluginKey.getState(view.state)) {
|
||||
view.dispatch(view.state.tr.setMeta(META_KEY, { pos: null }));
|
||||
}
|
||||
};
|
||||
|
||||
const position = (next: DragTarget) => {
|
||||
const rect = next.element.getBoundingClientRect();
|
||||
const offsetX = GUTTER_OFFSET[next.kind];
|
||||
|
||||
// Center the icon on the first line of text when the block has
|
||||
// one, otherwise align it with the top of the block.
|
||||
const lineMiddle =
|
||||
next.element === view.nodeDOM(next.pos)
|
||||
? getFirstLineMiddle(view, next.pos, rect)
|
||||
: null;
|
||||
|
||||
// RTL blocks lay out their gutter on the right, so mirror the
|
||||
// handle to the opposite edge to match the rest of the editor's
|
||||
// :dir(rtl) handling.
|
||||
const isRTL =
|
||||
window.getComputedStyle(next.element).direction === "rtl";
|
||||
handle.style.top =
|
||||
lineMiddle === null
|
||||
? `${rect.top - ICON_OFFSET_Y}px`
|
||||
: `${lineMiddle - ICON_CENTER_Y}px`;
|
||||
handle.style.left = isRTL
|
||||
? `${rect.right + offsetX - HANDLE_SIZE}px`
|
||||
: `${rect.left - offsetX}px`;
|
||||
handle.classList.remove("dragging");
|
||||
handle.classList.add("visible");
|
||||
};
|
||||
|
||||
const show = (next: DragTarget) => {
|
||||
target = next;
|
||||
position(next);
|
||||
setHoveredHeading(
|
||||
view.state.doc.nodeAt(next.pos)?.type.name === "heading"
|
||||
? next.pos
|
||||
: null
|
||||
);
|
||||
};
|
||||
|
||||
const hideHandle = () => {
|
||||
target = null;
|
||||
handle.classList.remove("visible", "dragging");
|
||||
};
|
||||
|
||||
const hide = () => {
|
||||
hideHandle();
|
||||
setHoveredHeading(null);
|
||||
};
|
||||
|
||||
const setHoveredHeading = (pos: number | null) => {
|
||||
if ((hoverPluginKey.getState(view.state) ?? null) === pos) {
|
||||
return;
|
||||
}
|
||||
view.dispatch(view.state.tr.setMeta(HOVER_META_KEY, { pos }));
|
||||
};
|
||||
|
||||
const onMouseMove = (event: MouseEvent) => {
|
||||
if (!view.editable) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
|
||||
// When the cursor is over the handle itself, keep the current
|
||||
// target. Re-resolving from a cursor in the gutter can land on
|
||||
// a different (often parent) block, causing the handle to
|
||||
// flicker between the hovered block and its parent.
|
||||
if (target && isOverElement(handle, event)) {
|
||||
return;
|
||||
}
|
||||
const next = DragTarget.fromEvent(view, event);
|
||||
if (next && !next.hasOwnControls(view.state)) {
|
||||
// Skip repositioning when still hovering the same block —
|
||||
// avoids a getBoundingClientRect and style writes on every
|
||||
// mousemove. Scroll repositioning is handled separately.
|
||||
if (next.equals(target)) {
|
||||
return;
|
||||
}
|
||||
show(next);
|
||||
} else {
|
||||
hide();
|
||||
}
|
||||
};
|
||||
|
||||
const onScroll = () => {
|
||||
// While a drag is in progress the handle is intentionally hidden;
|
||||
// don't let a scroll (trackpad / auto-scroll) reposition and
|
||||
// re-show it mid-drag.
|
||||
if (pluginKey.getState(view.state)) {
|
||||
return;
|
||||
}
|
||||
if (target?.element.isConnected) {
|
||||
show(target);
|
||||
} else {
|
||||
hide();
|
||||
}
|
||||
};
|
||||
|
||||
const onDragStart = (event: DragEvent) => {
|
||||
if (!target || !event.dataTransfer) {
|
||||
return;
|
||||
}
|
||||
const pos = target.pos;
|
||||
if (!view.state.doc.nodeAt(pos)) {
|
||||
return;
|
||||
}
|
||||
const sourceElement = target.element;
|
||||
|
||||
// Snapshot the drag image of the unmodified element first, so
|
||||
// it isn't baked with the dragging-source opacity. Anchor it to
|
||||
// its original screen position by offsetting by the cursor's
|
||||
// location within the block (negative X — the cursor sits in
|
||||
// the gutter to the left of the block).
|
||||
const rect = sourceElement.getBoundingClientRect();
|
||||
event.dataTransfer.setDragImage(
|
||||
sourceElement,
|
||||
event.clientX - rect.left,
|
||||
event.clientY - rect.top
|
||||
);
|
||||
event.dataTransfer.clearData();
|
||||
event.dataTransfer.effectAllowed = "copyMove";
|
||||
|
||||
// Hide the handle for the duration of the drag — keep it
|
||||
// interactive so the in-flight drag isn't cancelled.
|
||||
handle.classList.add("dragging");
|
||||
const selection = NodeSelection.create(view.state.doc, pos);
|
||||
|
||||
// Use the slice from the original NodeSelection rather than
|
||||
// view.state.selection, which prosemirror-tables' tableEditing
|
||||
// normalizes from a NodeSelection on a table into a CellSelection
|
||||
// covering only the cells.
|
||||
const slice = selection.content();
|
||||
const { dom, text } = view.serializeForClipboard(slice);
|
||||
event.dataTransfer.setData("text/html", dom.innerHTML);
|
||||
event.dataTransfer.setData("text/plain", text);
|
||||
|
||||
// Include the original NodeSelection as `node` so ProseMirror's
|
||||
// drop handler removes the source via node.replace(tr) rather
|
||||
// than tr.deleteSelection() (which would operate on the
|
||||
// normalized CellSelection and leave the table behind).
|
||||
const dragging: {
|
||||
slice: typeof slice;
|
||||
move: boolean;
|
||||
node: NodeSelection;
|
||||
} = {
|
||||
slice,
|
||||
move: !event.ctrlKey,
|
||||
node: selection,
|
||||
};
|
||||
view.dragging = dragging;
|
||||
view.dom.classList.add("dragging");
|
||||
view.focus();
|
||||
|
||||
// Apply the source decoration via the plugin's state and set
|
||||
// the NodeSelection in a single transaction so the
|
||||
// dragging-source class survives any DOM re-rendering caused
|
||||
// by selection changes (e.g., tableEditing normalizing a table
|
||||
// NodeSelection into a CellSelection).
|
||||
view.dispatch(
|
||||
view.state.tr.setSelection(selection).setMeta(META_KEY, { pos })
|
||||
);
|
||||
};
|
||||
|
||||
const onClick = () => {
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
view.focus();
|
||||
view.dispatch(
|
||||
view.state.tr.setSelection(
|
||||
NodeSelection.create(view.state.doc, target.pos)
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
window.addEventListener("mousemove", onMouseMove);
|
||||
window.addEventListener("scroll", onScroll, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
handle.addEventListener("dragstart", onDragStart);
|
||||
handle.addEventListener("dragend", onDragEnd);
|
||||
handle.addEventListener("click", onClick);
|
||||
|
||||
return {
|
||||
update: (_view, prevState) => {
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
const docChanged = view.state.doc !== prevState.doc;
|
||||
if (docChanged) {
|
||||
// Positions shift when the document changes, e.g. from a
|
||||
// collaborator's edit, so resolve the target again from its DOM.
|
||||
const next = DragTarget.fromElement(view, target.element);
|
||||
if (!next) {
|
||||
hideHandle();
|
||||
return;
|
||||
}
|
||||
target = next;
|
||||
}
|
||||
|
||||
// Leave the handle alone mid-drag so the drag is not cancelled.
|
||||
if (pluginKey.getState(view.state)) {
|
||||
return;
|
||||
}
|
||||
if (target.hasOwnControls(view.state)) {
|
||||
hideHandle();
|
||||
return;
|
||||
}
|
||||
if (docChanged) {
|
||||
position(target);
|
||||
}
|
||||
},
|
||||
destroy: () => {
|
||||
window.removeEventListener("mousemove", onMouseMove);
|
||||
window.removeEventListener("scroll", onScroll, { capture: true });
|
||||
handle.removeEventListener("dragstart", onDragStart);
|
||||
handle.removeEventListener("dragend", onDragEnd);
|
||||
handle.removeEventListener("click", onClick);
|
||||
handle.remove();
|
||||
|
||||
// Only clean up the DOM class here — the plugin state is
|
||||
// discarded on unmount, so avoid dispatching onto a view that
|
||||
// is being torn down (e.g. unmounted mid-drag).
|
||||
view.dom.classList.remove("dragging");
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function createHandle(): HTMLElement {
|
||||
const handle = document.createElement("button");
|
||||
handle.type = "button";
|
||||
handle.className = EditorStyleHelper.blockDragHandle;
|
||||
handle.draggable = true;
|
||||
handle.contentEditable = "false";
|
||||
handle.setAttribute("aria-label", t("Drag to reorder"));
|
||||
return handle;
|
||||
}
|
||||
|
||||
function isOverElement(element: HTMLElement, event: MouseEvent): boolean {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return (
|
||||
event.clientX >= rect.left &&
|
||||
event.clientX <= rect.right &&
|
||||
event.clientY >= rect.top &&
|
||||
event.clientY <= rect.bottom
|
||||
);
|
||||
}
|
||||
|
||||
function getFirstLineMiddle(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
rect: DOMRect
|
||||
): number | null {
|
||||
// Descend to the first textblock, and only use it when it begins with
|
||||
// text – inline atoms such as images have no meaningful line.
|
||||
let node = view.state.doc.nodeAt(pos);
|
||||
let nodePos = pos;
|
||||
while (node && !node.isTextblock) {
|
||||
node = node.firstChild;
|
||||
nodePos += 1;
|
||||
}
|
||||
if (!node?.firstChild?.isText) {
|
||||
return null;
|
||||
}
|
||||
const textPos = nodePos + 1;
|
||||
|
||||
let coords: { top: number; bottom: number };
|
||||
try {
|
||||
coords = view.coordsAtPos(textPos, 1);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Ignore text that is hidden or rendered outside the block, such as the
|
||||
// source of a rendered math block.
|
||||
if (
|
||||
coords.bottom <= coords.top ||
|
||||
coords.top < rect.top - RECT_TOLERANCE ||
|
||||
coords.bottom > rect.bottom + RECT_TOLERANCE
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return (coords.top + coords.bottom) / 2;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import ClipboardTextSerializer from "~/editor/extensions/ClipboardTextSerializer
|
||||
import CommentGutterExtension from "~/editor/extensions/CommentGutter";
|
||||
import DiagramsExtension from "@shared/editor/extensions/Diagrams";
|
||||
import DocumentMenuExtension from "~/editor/extensions/DocumentMenu";
|
||||
import DragHandle from "~/editor/extensions/DragHandle";
|
||||
import EmojiMenuExtension from "~/editor/extensions/EmojiMenu";
|
||||
import FindAndReplaceExtension from "~/editor/extensions/FindAndReplace";
|
||||
import HoverPreviewsExtension from "~/editor/extensions/HoverPreviews";
|
||||
@@ -30,6 +31,7 @@ export const withUIExtensions = (nodes: Nodes) => [
|
||||
SelectionToolbarExtension,
|
||||
CommentGutterExtension,
|
||||
DiagramsExtension,
|
||||
DragHandle,
|
||||
// Order these default key handlers last
|
||||
PreventTab,
|
||||
Keys,
|
||||
|
||||
@@ -36,6 +36,7 @@ import type { EmbedDescriptor } from "@shared/editor/embeds";
|
||||
import type { CommandFactory, WidgetProps } from "@shared/editor/lib/Extension";
|
||||
import type { AnyExtension, AnyExtensionClass } from "@shared/editor/lib/types";
|
||||
import ExtensionManager from "@shared/editor/lib/ExtensionManager";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { inputRules } from "@shared/editor/lib/inputRules";
|
||||
import type { MarkdownSerializer } from "@shared/editor/lib/markdown/serializer";
|
||||
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
|
||||
@@ -508,7 +509,9 @@ export class Editor extends React.PureComponent<
|
||||
...this.keymaps,
|
||||
anchorPlugin(),
|
||||
dropCursor({
|
||||
color: this.props.theme.cursor,
|
||||
color: this.props.theme.accent,
|
||||
width: 2,
|
||||
class: EditorStyleHelper.dropCursor,
|
||||
}),
|
||||
gapCursor(),
|
||||
inputRules({
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
bulletList,
|
||||
createEditorState,
|
||||
createEditorStateWithSelection,
|
||||
doc,
|
||||
heading,
|
||||
hr,
|
||||
p,
|
||||
schema,
|
||||
table,
|
||||
td,
|
||||
tr,
|
||||
} from "@shared/test/editor";
|
||||
import { DragTarget } from "./DragTarget";
|
||||
|
||||
describe("DragTarget.resolvePos", () => {
|
||||
it("resolves a position in a top-level block to the block", () => {
|
||||
const state = createEditorState(doc([p("one"), heading("two")]));
|
||||
|
||||
// Inside the heading text, which starts after the 5-size paragraph.
|
||||
expect(DragTarget.resolvePos(state, 7)).toEqual({ pos: 5, kind: "block" });
|
||||
});
|
||||
|
||||
it("resolves a position in a list item to the list item", () => {
|
||||
const state = createEditorState(doc([bulletList(["one", "two"])]));
|
||||
const items: number[] = [];
|
||||
state.doc.descendants((node, pos) => {
|
||||
if (node.type.name === "list_item") {
|
||||
items.push(pos);
|
||||
}
|
||||
});
|
||||
expect(DragTarget.resolvePos(state, items[1] + 3)).toEqual({
|
||||
pos: items[1],
|
||||
kind: "listItem",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves a position in a checkbox item to the checkbox item", () => {
|
||||
const list = schema.nodes.checkbox_list.create(null, [
|
||||
schema.nodes.checkbox_item.create(null, p("todo")),
|
||||
]);
|
||||
const state = createEditorState(doc([list]));
|
||||
expect(DragTarget.resolvePos(state, 4)).toEqual({
|
||||
pos: 1,
|
||||
kind: "checkboxItem",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns null for an empty top-level paragraph", () => {
|
||||
const state = createEditorState(doc([p("one"), p("")]));
|
||||
expect(DragTarget.resolvePos(state, 6)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for a paragraph that holds a layout image", () => {
|
||||
const image = schema.nodes.image.create({
|
||||
src: "https://example.com/image.png",
|
||||
layoutClass: "full-width",
|
||||
});
|
||||
const state = createEditorState(
|
||||
doc([p("one"), schema.nodes.paragraph.create(null, image)])
|
||||
);
|
||||
expect(DragTarget.resolvePos(state, 6)).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves a position between top-level atoms to the adjacent atom", () => {
|
||||
const state = createEditorState(doc([p("one"), hr()]));
|
||||
expect(DragTarget.resolvePos(state, 5)).toEqual({ pos: 5, kind: "block" });
|
||||
expect(DragTarget.resolvePos(state, 6)).toEqual({ pos: 5, kind: "block" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("DragTarget#hasOwnControls", () => {
|
||||
const testDoc = doc([p("one"), table([tr([td("a"), td("b")])])]);
|
||||
|
||||
// The table starts after the 5-size paragraph.
|
||||
const target = new DragTarget(5, document.createElement("div"), "block");
|
||||
|
||||
it("returns true when the selection is inside the table", () => {
|
||||
const state = createEditorStateWithSelection(testDoc, 9);
|
||||
expect(target.hasOwnControls(state)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the selection is outside the table", () => {
|
||||
const state = createEditorStateWithSelection(testDoc, 2);
|
||||
expect(target.hasOwnControls(state)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for a block that is not a table", () => {
|
||||
const state = createEditorStateWithSelection(testDoc, 2);
|
||||
const paragraph = new DragTarget(0, document.createElement("div"), "block");
|
||||
expect(paragraph.hasOwnControls(state)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
import type { Node as ProsemirrorNode } from "prosemirror-model";
|
||||
import type { EditorState } from "prosemirror-state";
|
||||
import type { EditorView } from "prosemirror-view";
|
||||
import { findParentNodeClosestToPos } from "@shared/editor/queries/findParentNode";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
|
||||
/** The kind of block that a drag target points at. */
|
||||
export type DragTargetKind = "block" | "listItem" | "checkboxItem";
|
||||
|
||||
/** A document position and the kind of block found there. */
|
||||
export interface ResolvedDragTarget {
|
||||
/** Position of the block in the document. */
|
||||
pos: number;
|
||||
|
||||
/** The kind of block at the position. */
|
||||
kind: DragTargetKind;
|
||||
}
|
||||
|
||||
const LIST_TYPES = ["bullet_list", "ordered_list", "checkbox_list"];
|
||||
|
||||
// Distance outside the content column in which the cursor still finds a block.
|
||||
const GUTTER_HIT_WIDTH = 60;
|
||||
|
||||
// Inset from the content edges, so that posAtCoords lands inside the block.
|
||||
const CONTENT_INSET = 1;
|
||||
|
||||
/**
|
||||
* A block in the editor that the drag handle can attach to. Holds the
|
||||
* position of the block in the document and the DOM element that the handle
|
||||
* aligns with, which is not always the node's own DOM (e.g. Mermaid diagrams).
|
||||
*/
|
||||
export class DragTarget {
|
||||
/** Position of the block in the document. */
|
||||
public readonly pos: number;
|
||||
|
||||
/** The DOM element that the handle aligns with. */
|
||||
public readonly element: HTMLElement;
|
||||
|
||||
/** The kind of block. */
|
||||
public readonly kind: DragTargetKind;
|
||||
|
||||
constructor(pos: number, element: HTMLElement, kind: DragTargetKind) {
|
||||
this.pos = pos;
|
||||
this.element = element;
|
||||
this.kind = kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the block under the cursor, also when the cursor is in the gutter
|
||||
* to the side of the content.
|
||||
*
|
||||
* @param view - the editor view.
|
||||
* @param event - the mouse event.
|
||||
* @returns the target, or null if there is no block under the cursor.
|
||||
*/
|
||||
public static fromEvent(
|
||||
view: EditorView,
|
||||
event: MouseEvent
|
||||
): DragTarget | null {
|
||||
const rect = view.dom.getBoundingClientRect();
|
||||
if (event.clientY < rect.top || event.clientY > rect.bottom) {
|
||||
return null;
|
||||
}
|
||||
const style = window.getComputedStyle(view.dom);
|
||||
const paddingLeft = parseFloat(style.paddingLeft) || 0;
|
||||
const paddingRight = parseFloat(style.paddingRight) || 0;
|
||||
const contentLeft = rect.left + paddingLeft + CONTENT_INSET;
|
||||
const contentRight = rect.right - paddingRight - CONTENT_INSET;
|
||||
if (
|
||||
event.clientX < contentLeft - GUTTER_HIT_WIDTH ||
|
||||
event.clientX > contentRight + GUTTER_HIT_WIDTH
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const projectedX = Math.max(
|
||||
contentLeft,
|
||||
Math.min(contentRight, event.clientX)
|
||||
);
|
||||
|
||||
// Mermaid diagrams hide their source code block and render an SVG widget
|
||||
// next to it — target the underlying code block but anchor the handle to
|
||||
// the visible diagram element.
|
||||
const mermaid = this.mermaidFromEvent(view, event, projectedX);
|
||||
if (mermaid) {
|
||||
return mermaid;
|
||||
}
|
||||
|
||||
const coords = view.posAtCoords({
|
||||
left: projectedX,
|
||||
top: event.clientY,
|
||||
});
|
||||
if (!coords) {
|
||||
return null;
|
||||
}
|
||||
const resolved = this.resolvePos(view.state, coords.pos);
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
const dom = view.nodeDOM(resolved.pos);
|
||||
if (!(dom instanceof HTMLElement)) {
|
||||
return null;
|
||||
}
|
||||
return new DragTarget(resolved.pos, dom, resolved.kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the block that a DOM element renders, e.g. to update a target after
|
||||
* the document changes.
|
||||
*
|
||||
* @param view - the editor view.
|
||||
* @param element - the DOM element that the handle aligns with.
|
||||
* @returns the target, or null if the element is no longer in the editor.
|
||||
*/
|
||||
public static fromElement(
|
||||
view: EditorView,
|
||||
element: HTMLElement
|
||||
): DragTarget | null {
|
||||
if (!element.isConnected) {
|
||||
return null;
|
||||
}
|
||||
if (element.classList.contains(EditorStyleHelper.mermaidDiagram)) {
|
||||
const pos = this.mermaidPos(view, element);
|
||||
return pos === null ? null : new DragTarget(pos, element, "block");
|
||||
}
|
||||
const parent = element.parentNode;
|
||||
if (!parent) {
|
||||
return null;
|
||||
}
|
||||
let pos: number;
|
||||
try {
|
||||
pos = view.posAtDOM(
|
||||
parent,
|
||||
Array.from(parent.childNodes).indexOf(element)
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const node = view.state.doc.nodeAt(pos);
|
||||
if (!node || view.nodeDOM(pos) !== element) {
|
||||
return null;
|
||||
}
|
||||
return new DragTarget(pos, element, this.kindOf(node));
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the draggable block that contains a document position.
|
||||
*
|
||||
* @param state - the editor state.
|
||||
* @param pos - a position in the document.
|
||||
* @returns the block position and kind, or null if there is no draggable block.
|
||||
*/
|
||||
public static resolvePos(
|
||||
state: EditorState,
|
||||
pos: number
|
||||
): ResolvedDragTarget | null {
|
||||
const $pos = state.doc.resolve(pos);
|
||||
|
||||
const listItem = findParentNodeClosestToPos(
|
||||
$pos,
|
||||
(node) => this.kindOf(node) !== "block"
|
||||
);
|
||||
if (listItem) {
|
||||
return { pos: listItem.pos, kind: this.kindOf(listItem.node) };
|
||||
}
|
||||
|
||||
if ($pos.depth >= 1) {
|
||||
const node = $pos.node(1);
|
||||
if (LIST_TYPES.includes(node.type.name)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Skip empty top-level paragraphs — the block menu trigger is shown
|
||||
// there instead.
|
||||
if (node.type.name === "paragraph" && node.content.size === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Floated and full-width images sit outside the content column, so a
|
||||
// handle in the gutter would not line up with them.
|
||||
if (this.hasLayoutImage(node)) {
|
||||
return null;
|
||||
}
|
||||
return { pos: $pos.before(1), kind: "block" };
|
||||
}
|
||||
|
||||
// Hovering on a top-level atom block (video, etc.) — there are no
|
||||
// positions inside an atom, so posAtCoords lands at depth 0 between
|
||||
// siblings of the doc. Pick whichever neighbouring atom block the
|
||||
// position is adjacent to.
|
||||
const after = $pos.nodeAfter;
|
||||
if (after?.isBlock && after.isAtom) {
|
||||
return { pos: $pos.pos, kind: "block" };
|
||||
}
|
||||
const before = $pos.nodeBefore;
|
||||
if (before?.isBlock && before.isAtom) {
|
||||
return { pos: $pos.pos - before.nodeSize, kind: "block" };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the editor shows its own controls for this block, which would
|
||||
* overlap the drag handle, e.g. a table that holds the selection.
|
||||
*
|
||||
* @param state - the editor state.
|
||||
* @returns true if the drag handle should be hidden for this block.
|
||||
*/
|
||||
public hasOwnControls(state: EditorState): boolean {
|
||||
const node = state.doc.nodeAt(this.pos);
|
||||
if (node?.type.name !== "table") {
|
||||
return false;
|
||||
}
|
||||
const { from, to } = state.selection;
|
||||
return from > this.pos && to < this.pos + node.nodeSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this target points at the same block as another target.
|
||||
*
|
||||
* @param other - the target to compare with.
|
||||
* @returns true if both targets have the same position and element.
|
||||
*/
|
||||
public equals(other: DragTarget | null): boolean {
|
||||
return !!other && this.pos === other.pos && this.element === other.element;
|
||||
}
|
||||
|
||||
private static kindOf(node: ProsemirrorNode): DragTargetKind {
|
||||
switch (node.type.name) {
|
||||
case "list_item":
|
||||
return "listItem";
|
||||
case "checkbox_item":
|
||||
return "checkboxItem";
|
||||
default:
|
||||
return "block";
|
||||
}
|
||||
}
|
||||
|
||||
private static hasLayoutImage(node: ProsemirrorNode): boolean {
|
||||
if (!node.isTextblock) {
|
||||
return false;
|
||||
}
|
||||
let found = false;
|
||||
node.forEach((child) => {
|
||||
if (child.type.name === "image" && child.attrs.layoutClass) {
|
||||
found = true;
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
private static mermaidFromEvent(
|
||||
view: EditorView,
|
||||
event: MouseEvent,
|
||||
projectedX: number
|
||||
): DragTarget | null {
|
||||
// Look at the element directly under the cursor, and at the projected X
|
||||
// inside the editor so we still find the diagram when the cursor sits in
|
||||
// the left gutter where the handle is rendered.
|
||||
const eventTarget = event.target instanceof Element ? event.target : null;
|
||||
const projectedTarget =
|
||||
projectedX !== event.clientX
|
||||
? document.elementFromPoint(projectedX, event.clientY)
|
||||
: null;
|
||||
const diagram =
|
||||
eventTarget?.closest<HTMLElement>(
|
||||
`.${EditorStyleHelper.mermaidDiagram}`
|
||||
) ??
|
||||
(projectedTarget instanceof Element
|
||||
? projectedTarget.closest<HTMLElement>(
|
||||
`.${EditorStyleHelper.mermaidDiagram}`
|
||||
)
|
||||
: null);
|
||||
if (!diagram) {
|
||||
return null;
|
||||
}
|
||||
const pos = this.mermaidPos(view, diagram);
|
||||
return pos === null ? null : new DragTarget(pos, diagram, "block");
|
||||
}
|
||||
|
||||
private static mermaidPos(
|
||||
view: EditorView,
|
||||
diagram: HTMLElement
|
||||
): number | null {
|
||||
const codeBlockDom = diagram.previousElementSibling;
|
||||
if (!(codeBlockDom instanceof HTMLElement)) {
|
||||
return null;
|
||||
}
|
||||
let pos: number;
|
||||
try {
|
||||
pos = view.posAtDOM(codeBlockDom, 0);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (pos < 0) {
|
||||
return null;
|
||||
}
|
||||
const $pos = view.state.doc.resolve(pos);
|
||||
const blockPos = $pos.depth > 0 ? $pos.before($pos.depth) : 0;
|
||||
return view.state.doc.nodeAt(blockPos) ? blockPos : null;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { ShrinkIcon, GrowIcon, CloseIcon } from "outline-icons";
|
||||
import styled, { useTheme } from "styled-components";
|
||||
import Icon from "@shared/components/Icon";
|
||||
import { richExtensions } from "@shared/editor/nodes";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { canUseElementFullscreen } from "@shared/utils/browser";
|
||||
import { s, depths, hover } from "@shared/styles";
|
||||
import { cloneDeep } from "es-toolkit/compat";
|
||||
@@ -426,7 +427,7 @@ const SlideContent = styled.div`
|
||||
|
||||
.image-wrapper,
|
||||
.image-wrapper img,
|
||||
.mermaid-diagram-wrapper {
|
||||
.${EditorStyleHelper.mermaidDiagram} {
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
|
||||
@@ -722,13 +722,10 @@ width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&:hover {
|
||||
&:hover,
|
||||
&.${EditorStyleHelper.dragHandleTarget} {
|
||||
.heading-anchor {
|
||||
opacity: 0.75;
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1004,37 +1001,19 @@ th .image .image-wrapper img {
|
||||
caret-color: transparent;
|
||||
}
|
||||
|
||||
.ProseMirror-selectednode {
|
||||
outline: 2px solid
|
||||
${props.readOnly ? "transparent" : props.theme.selected};
|
||||
|
||||
@media print {
|
||||
outline: none;
|
||||
}
|
||||
.ProseMirror.dragging .ProseMirror-selectednode,
|
||||
.ProseMirror .${EditorStyleHelper.draggingSource} {
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
/* Make sure li selections wrap around markers */
|
||||
|
||||
li.ProseMirror-selectednode {
|
||||
outline: none;
|
||||
.ProseMirror.dragging *::selection {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
li.ProseMirror-selectednode {
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -32px;
|
||||
right: -2px;
|
||||
top: -2px;
|
||||
bottom: -2px;
|
||||
border: 2px solid ${props.theme.selected};
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&:dir(rtl)::after {
|
||||
left: -2px;
|
||||
right: -32px;
|
||||
}
|
||||
.ProseMirror.dragging *::-moz-selection {
|
||||
background: transparent;
|
||||
}
|
||||
.ProseMirror.dragging .selectedCell::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
img.ProseMirror-separator {
|
||||
@@ -1174,7 +1153,8 @@ h6:not(.placeholder):not([data-heading-prefix])::before {
|
||||
&:not(.placeholder):not([data-heading-prefix])::before {
|
||||
opacity: 1;
|
||||
}
|
||||
&:hover:not(.placeholder):not([data-heading-prefix])::before {
|
||||
&:hover:not(.placeholder):not([data-heading-prefix])::before,
|
||||
&.${EditorStyleHelper.dragHandleTarget}:not(.placeholder):not([data-heading-prefix])::before {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@@ -1233,13 +1213,16 @@ h6:not(.placeholder):not([data-heading-prefix])::before {
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
margin-left: -26px;
|
||||
width: 26px;
|
||||
|
||||
/* Sit left of the block drag handle, or in its place when read-only. */
|
||||
margin-left: ${props.readOnly ? -26 : -38}px;
|
||||
width: ${props.readOnly ? 26 : 18}px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
user-select: none;
|
||||
color: ${props.theme.text};
|
||||
color: ${props.theme.textTertiary};
|
||||
transition: color 150ms ease-in-out;
|
||||
cursor: var(--pointer);
|
||||
background: none;
|
||||
outline: none;
|
||||
@@ -1253,11 +1236,12 @@ h6:not(.placeholder):not([data-heading-prefix])::before {
|
||||
|
||||
&:hover {
|
||||
opacity: 1;
|
||||
color: ${props.theme.text};
|
||||
}
|
||||
|
||||
&:dir(rtl) {
|
||||
margin-left: 0;
|
||||
margin-right: -26px;
|
||||
margin-right: ${props.readOnly ? -26 : -38}px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1631,65 +1615,6 @@ ul.checkbox_list > li.checked > div > p {
|
||||
color: ${props.theme.textTertiary};
|
||||
}
|
||||
|
||||
ul li,
|
||||
ol li {
|
||||
&::before {
|
||||
background: url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3QgeD0iOCIgeT0iNyIgd2lkdGg9IjMiIGhlaWdodD0iMiIgcng9IjEiIGZpbGw9IiM0RTVDNkUiLz4KPHJlY3QgeD0iOCIgeT0iMTEiIHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHJ4PSIxIiBmaWxsPSIjNEU1QzZFIi8+CjxyZWN0IHg9IjgiIHk9IjE1IiB3aWR0aD0iMyIgaGVpZ2h0PSIyIiByeD0iMSIgZmlsbD0iIzRFNUM2RSIvPgo8cmVjdCB4PSIxMyIgeT0iNyIgd2lkdGg9IjMiIGhlaWdodD0iMiIgcng9IjEiIGZpbGw9IiM0RTVDNkUiLz4KPHJlY3QgeD0iMTMiIHk9IjExIiB3aWR0aD0iMyIgaGVpZ2h0PSIyIiByeD0iMSIgZmlsbD0iIzRFNUM2RSIvPgo8cmVjdCB4PSIxMyIgeT0iMTUiIHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHJ4PSIxIiBmaWxsPSIjNEU1QzZFIi8+Cjwvc3ZnPgo=") no-repeat;
|
||||
background-position: 0 2px;
|
||||
content: "";
|
||||
display: ${props.readOnly ? "none" : "inline-block"};
|
||||
cursor: grab;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
position: absolute;
|
||||
left: -40px;
|
||||
opacity: 0;
|
||||
transition: opacity 200ms ease-in-out;
|
||||
}
|
||||
|
||||
&:dir(rtl)::before {
|
||||
left: auto;
|
||||
right: -40px;
|
||||
}
|
||||
}
|
||||
|
||||
ul li[draggable=true]::before,
|
||||
ol li[draggable=true]::before {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
ul > li.counter-2,
|
||||
ol li.counter-2 {
|
||||
&::before {
|
||||
left: -50px;
|
||||
}
|
||||
&:dir(rtl)::before {
|
||||
left: auto;
|
||||
right: -50px;
|
||||
}
|
||||
}
|
||||
|
||||
ul > li.hovering::before,
|
||||
ol li.hovering::before {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
ul li.ProseMirror-selectednode::after,
|
||||
ol li.ProseMirror-selectednode::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
ul.checkbox_list > li {
|
||||
&::before {
|
||||
left: 0;
|
||||
}
|
||||
|
||||
&:dir(rtl)::before {
|
||||
left: auto;
|
||||
right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
ul.checkbox_list {
|
||||
& > li > span[contenteditable="false"] {
|
||||
cursor: text;
|
||||
@@ -1885,7 +1810,7 @@ mark {
|
||||
}
|
||||
|
||||
&:is(.code-active)
|
||||
+ .mermaid-diagram-wrapper:not(.parse-error):not(.empty) {
|
||||
+ .${EditorStyleHelper.mermaidDiagram}:not(.parse-error):not(.empty) {
|
||||
cursor: zoom-in;
|
||||
}
|
||||
|
||||
@@ -1900,7 +1825,7 @@ mark {
|
||||
&.ProseMirror-selectednode {
|
||||
outline: none;
|
||||
|
||||
& + .mermaid-diagram-wrapper {
|
||||
& + .${EditorStyleHelper.mermaidDiagram} {
|
||||
&:not(.parse-error):not(.empty) {
|
||||
cursor: zoom-in;
|
||||
}
|
||||
@@ -1914,7 +1839,7 @@ mark {
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
|
||||
& + .mermaid-diagram-wrapper:not(.parse-error):not(.empty) {
|
||||
& + .${EditorStyleHelper.mermaidDiagram}:not(.parse-error):not(.empty) {
|
||||
cursor: zoom-in;
|
||||
}
|
||||
}
|
||||
@@ -1930,7 +1855,7 @@ mark {
|
||||
}
|
||||
}
|
||||
|
||||
.mermaid-diagram-wrapper {
|
||||
.${EditorStyleHelper.mermaidDiagram} {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
@@ -2048,7 +1973,7 @@ mark {
|
||||
}
|
||||
}
|
||||
|
||||
.mermaid-diagram-wrapper {
|
||||
.${EditorStyleHelper.mermaidDiagram} {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -2704,7 +2629,9 @@ table {
|
||||
position: absolute;
|
||||
top: -2px;
|
||||
width: 20px;
|
||||
border-top: 1px solid ${props.theme.cursor};
|
||||
height: 2px;
|
||||
background: ${props.theme.accent};
|
||||
border-radius: 1px;
|
||||
animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import { LightboxImageFactory } from "../lib/Lightbox";
|
||||
import { hashString } from "../../utils/string";
|
||||
import { LRUCache } from "../../utils/LRUCache";
|
||||
import { sanitizeUrl } from "../../utils/urls";
|
||||
import { EditorStyleHelper } from "../styles/EditorStyleHelper";
|
||||
import { isModKey } from "../../utils/keyboard";
|
||||
|
||||
export const pluginKey = new PluginKey("mermaid");
|
||||
@@ -98,11 +99,11 @@ class MermaidRenderer {
|
||||
|
||||
constructor() {
|
||||
this.diagramId = uuidv4();
|
||||
this.elementId = `mermaid-diagram-wrapper-${this.diagramId}`;
|
||||
this.elementId = `${EditorStyleHelper.mermaidDiagram}-${this.diagramId}`;
|
||||
this.element =
|
||||
document.getElementById(this.elementId) || document.createElement("div");
|
||||
this.element.id = this.elementId;
|
||||
this.element.classList.add("mermaid-diagram-wrapper");
|
||||
this.element.classList.add(EditorStyleHelper.mermaidDiagram);
|
||||
}
|
||||
|
||||
render = async (block: { node: Node; pos: number }, isDark: boolean) => {
|
||||
@@ -416,9 +417,24 @@ export default function Mermaid({
|
||||
|
||||
const node = state.selection.$head.parent;
|
||||
const previousNode = oldState.selection.$head.parent;
|
||||
|
||||
// For a NodeSelection, $head.parent resolves to the selection's
|
||||
// parent — so also inspect the selected node and its descendants to
|
||||
// catch e.g. drag-and-drop of a container that holds a diagram.
|
||||
const selectedNode =
|
||||
state.selection instanceof NodeSelection
|
||||
? state.selection.node
|
||||
: null;
|
||||
const previousSelectedNode =
|
||||
oldState.selection instanceof NodeSelection
|
||||
? oldState.selection.node
|
||||
: null;
|
||||
const codeBlockChanged =
|
||||
transaction.docChanged &&
|
||||
(isMermaid(node) || isMermaid(previousNode));
|
||||
(isMermaid(node) ||
|
||||
isMermaid(previousNode) ||
|
||||
containsMermaid(selectedNode) ||
|
||||
containsMermaid(previousSelectedNode));
|
||||
|
||||
// @ts-expect-error accessing private field.
|
||||
const isPaste = transaction.meta?.paste;
|
||||
@@ -527,7 +543,9 @@ export default function Mermaid({
|
||||
},
|
||||
mousedown(view, event) {
|
||||
const target = event.target as HTMLElement;
|
||||
const diagram = target?.closest(".mermaid-diagram-wrapper");
|
||||
const diagram = target?.closest(
|
||||
`.${EditorStyleHelper.mermaidDiagram}`
|
||||
);
|
||||
if (!diagram) {
|
||||
return false;
|
||||
}
|
||||
@@ -577,7 +595,9 @@ export default function Mermaid({
|
||||
},
|
||||
mouseup(view, event) {
|
||||
const target = event.target as HTMLElement;
|
||||
const diagram = target?.closest(".mermaid-diagram-wrapper");
|
||||
const diagram = target?.closest(
|
||||
`.${EditorStyleHelper.mermaidDiagram}`
|
||||
);
|
||||
if (!diagram) {
|
||||
return false;
|
||||
}
|
||||
@@ -606,3 +626,21 @@ export default function Mermaid({
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function containsMermaid(node: Node | null): boolean {
|
||||
if (!node) {
|
||||
return false;
|
||||
}
|
||||
if (isMermaid(node)) {
|
||||
return true;
|
||||
}
|
||||
let found = false;
|
||||
node.descendants((child) => {
|
||||
if (found) {
|
||||
return false;
|
||||
}
|
||||
found = isMermaid(child);
|
||||
return !found;
|
||||
});
|
||||
return found;
|
||||
}
|
||||
@@ -8,14 +8,11 @@ import {
|
||||
sinkListItem,
|
||||
liftListItem,
|
||||
} from "prosemirror-schema-list";
|
||||
import type { Transaction, EditorState, Command } from "prosemirror-state";
|
||||
import { Plugin, TextSelection } from "prosemirror-state";
|
||||
import { DecorationSet, Decoration } from "prosemirror-view";
|
||||
import type { Command } from "prosemirror-state";
|
||||
import { TextSelection } from "prosemirror-state";
|
||||
import type { MarkdownSerializerState } from "../lib/markdown/serializer";
|
||||
import { findParentNodeClosestToPos } from "../queries/findParentNode";
|
||||
import { getParentListItem } from "../queries/getParentListItem";
|
||||
import { isInList } from "../queries/isInList";
|
||||
import { isList } from "../queries/isList";
|
||||
import Node from "./Node";
|
||||
|
||||
export default class ListItem extends Node {
|
||||
@@ -33,171 +30,6 @@ export default class ListItem extends Node {
|
||||
};
|
||||
}
|
||||
|
||||
get plugins() {
|
||||
return [
|
||||
new Plugin({
|
||||
state: {
|
||||
init() {
|
||||
return DecorationSet.empty;
|
||||
},
|
||||
apply: (
|
||||
tr: Transaction,
|
||||
set: DecorationSet,
|
||||
oldState: EditorState,
|
||||
newState: EditorState
|
||||
) => {
|
||||
const action = tr.getMeta("li");
|
||||
if (!action && !tr.docChanged) {
|
||||
return set;
|
||||
}
|
||||
|
||||
// Adjust decoration positions to changes made by the transaction
|
||||
set = set.map(tr.mapping, tr.doc);
|
||||
|
||||
switch (action?.event) {
|
||||
case "mouseover": {
|
||||
const result = findParentNodeClosestToPos(
|
||||
newState.doc.resolve(action.pos),
|
||||
(node) =>
|
||||
node.type.name === this.name ||
|
||||
node.type.name === "checkbox_item"
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
return set;
|
||||
}
|
||||
|
||||
const list = findParentNodeClosestToPos(
|
||||
newState.doc.resolve(action.pos),
|
||||
(node) => isList(node, this.editor.schema)
|
||||
);
|
||||
|
||||
if (!list) {
|
||||
return set;
|
||||
}
|
||||
|
||||
const start = list.node.attrs.order || 1;
|
||||
|
||||
let listItemNumber = 0;
|
||||
list.node.content.forEach((li, _, index) => {
|
||||
if (li === result.node) {
|
||||
listItemNumber = index;
|
||||
}
|
||||
});
|
||||
|
||||
const counterLength = String(start + listItemNumber).length;
|
||||
|
||||
return set.add(tr.doc, [
|
||||
Decoration.node(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
{
|
||||
class: `hovering`,
|
||||
},
|
||||
{
|
||||
hover: true,
|
||||
}
|
||||
),
|
||||
Decoration.node(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
{
|
||||
class: `counter-${counterLength}`,
|
||||
}
|
||||
),
|
||||
]);
|
||||
}
|
||||
case "mouseout": {
|
||||
const result = findParentNodeClosestToPos(
|
||||
newState.doc.resolve(action.pos),
|
||||
(node) =>
|
||||
node.type.name === this.name ||
|
||||
node.type.name === "checkbox_item"
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
return set;
|
||||
}
|
||||
|
||||
return set.remove(
|
||||
set.find(
|
||||
result.pos,
|
||||
result.pos + result.node.nodeSize,
|
||||
(spec) => spec.hover
|
||||
)
|
||||
);
|
||||
}
|
||||
default:
|
||||
}
|
||||
|
||||
return set;
|
||||
},
|
||||
},
|
||||
props: {
|
||||
decorations(state) {
|
||||
return this.getState(state);
|
||||
},
|
||||
handleDOMEvents: {
|
||||
mouseover: (view, event) => {
|
||||
if (!view.editable) {
|
||||
return false;
|
||||
}
|
||||
const { state, dispatch } = view;
|
||||
const target = event.target as HTMLElement;
|
||||
const li = target?.closest("li");
|
||||
|
||||
if (!li) {
|
||||
return false;
|
||||
}
|
||||
if (!view.dom.contains(li)) {
|
||||
return false;
|
||||
}
|
||||
const pos = view.posAtDOM(li, 0);
|
||||
if (!pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
dispatch(
|
||||
state.tr.setMeta("li", {
|
||||
event: "mouseover",
|
||||
pos,
|
||||
})
|
||||
);
|
||||
return false;
|
||||
},
|
||||
mouseout: (view, event) => {
|
||||
if (!view.editable) {
|
||||
return false;
|
||||
}
|
||||
const { state, dispatch } = view;
|
||||
const target = event.target as HTMLElement;
|
||||
const li = target?.closest("li");
|
||||
|
||||
if (!li) {
|
||||
return false;
|
||||
}
|
||||
if (!view.dom.contains(li)) {
|
||||
return false;
|
||||
}
|
||||
const pos = view.posAtDOM(li, 0);
|
||||
if (!pos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
dispatch(
|
||||
state.tr.setMeta("li", {
|
||||
event: "mouseout",
|
||||
pos,
|
||||
})
|
||||
);
|
||||
return false;
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
commands({ type }: { type: NodeType }) {
|
||||
return {
|
||||
indentList: () => sinkListItem(type),
|
||||
|
||||
@@ -164,6 +164,25 @@ export class EditorStyleHelper {
|
||||
/** Drag indicator on bottom side of cell */
|
||||
static readonly tableDragIndicatorBottom = "table-drag-indicator-bottom";
|
||||
|
||||
// Drag and drop
|
||||
|
||||
/** Line that shows where dragged content will be dropped */
|
||||
static readonly dropCursor = "drop-cursor";
|
||||
|
||||
/** Floating handle shown beside the hovered block to drag it */
|
||||
static readonly blockDragHandle = "block-drag-handle";
|
||||
|
||||
/** Block that the drag handle is currently attached to */
|
||||
static readonly dragHandleTarget = "drag-handle-target";
|
||||
|
||||
/** Block that is being dragged */
|
||||
static readonly draggingSource = "dragging-source";
|
||||
|
||||
// Diagrams
|
||||
|
||||
/** Container for a rendered Mermaid diagram */
|
||||
static readonly mermaidDiagram = "mermaid-diagram-wrapper";
|
||||
|
||||
// Global
|
||||
|
||||
/** Minimum padding around editor */
|
||||
|
||||
@@ -726,6 +726,7 @@
|
||||
"More options": "More options",
|
||||
"Type '/' to insert": "Type '/' to insert",
|
||||
"Keep typing to filter": "Keep typing to filter",
|
||||
"Drag to reorder": "Drag to reorder",
|
||||
"Replace file": "Replace file",
|
||||
"Delete file": "Delete file",
|
||||
"Show preview": "Show preview",
|
||||
|
||||
@@ -8,6 +8,9 @@ type Props = {
|
||||
useCursorPointer?: boolean;
|
||||
};
|
||||
|
||||
const dragHandleIcon =
|
||||
"data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3QgeD0iOCIgeT0iNyIgd2lkdGg9IjMiIGhlaWdodD0iMiIgcng9IjEiIGZpbGw9IiM0RTVDNkUiLz4KPHJlY3QgeD0iOCIgeT0iMTEiIHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHJ4PSIxIiBmaWxsPSIjNEU1QzZFIi8+CjxyZWN0IHg9IjgiIHk9IjE1IiB3aWR0aD0iMyIgaGVpZ2h0PSIyIiByeD0iMSIgZmlsbD0iIzRFNUM2RSIvPgo8cmVjdCB4PSIxMyIgeT0iNyIgd2lkdGg9IjMiIGhlaWdodD0iMiIgcng9IjEiIGZpbGw9IiM0RTVDNkUiLz4KPHJlY3QgeD0iMTMiIHk9IjExIiB3aWR0aD0iMyIgaGVpZ2h0PSIyIiByeD0iMSIgZmlsbD0iIzRFNUM2RSIvPgo8cmVjdCB4PSIxMyIgeT0iMTUiIHdpZHRoPSIzIiBoZWlnaHQ9IjIiIHJ4PSIxIiBmaWxsPSIjNEU1QzZFIi8+Cjwvc3ZnPgo=";
|
||||
|
||||
export default createGlobalStyle<Props>`
|
||||
${styledNormalize}
|
||||
|
||||
@@ -168,4 +171,53 @@ export default createGlobalStyle<Props>`
|
||||
&.${EditorStyleHelper.resizeDragging} *::after {
|
||||
cursor: var(--resize-drag-cursor) !important;
|
||||
}
|
||||
|
||||
/* prosemirror-dropcursor renders adjacent to the editor (in view.dom.offsetParent), outside
|
||||
the styled EditorContainer scope, so this rule has to live globally. */
|
||||
.${EditorStyleHelper.dropCursor} {
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
/* Block drag handle is appended to document.body, outside the styled
|
||||
EditorContainer scope, so its rules have to live globally. */
|
||||
.${EditorStyleHelper.blockDragHandle} {
|
||||
appearance: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
position: fixed;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
cursor: grab;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: background-color 150ms ease-in-out;
|
||||
background-color: ${s("textTertiary")};
|
||||
mask-image: url("${dragHandleIcon}");
|
||||
mask-repeat: no-repeat;
|
||||
mask-position: 0 2px;
|
||||
z-index: 1;
|
||||
|
||||
&:hover {
|
||||
background-color: ${s("text")};
|
||||
}
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
&.visible.dragging {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
.${EditorStyleHelper.blockDragHandle} {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
`;
|
||||
Reference in new issue
Block a user