Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve table cell block dragging, clipboard structure and granular undo https://github.com/siyuan-note/siyuan/issues/19188

Danielcfcf4b54b6b4
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scss
index e2abd13b90..13fa231abc 100644
--- a/app/src/assets/scss/protyle/_wysiwyg.scss
+++ b/app/src/assets/scss/protyle/_wysiwyg.scss
@@ -46,7 +46,11 @@
}
[data-node-id],
- [data-table-cell-node] {
+ [data-table-cell-node],
+ td.dragover__top,
+ td.dragover__bottom,
+ th.dragover__top,
+ th.dragover__bottom {
position: relative;
&.protyle-wysiwyg--navigation {
diff --git a/app/src/protyle/render/tableCellRichEditor.ts b/app/src/protyle/render/tableCellRichEditor.ts
index 70083e1aed..39003efda0 100644
--- a/app/src/protyle/render/tableCellRichEditor.ts
+++ b/app/src/protyle/render/tableCellRichEditor.ts
@@ -19,6 +19,7 @@ import {updateTableCellContentLayout} from "../util/tableCellRich";
import {TABLE_CELL_SLASH_IDS} from "../util/tableCellRichMenu";
import {captureRichCellSelection, restoreRichCellSelection} from "../util/tableCellRichSelection";
import {matchHotKey} from "../util/hotKey";
+import {bindTableCellRichDrag} from "../util/tableCellRichDrag";
let activeEditor: {cell: Element, finish: () => void} | undefined;
@@ -129,7 +130,6 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
extend: [{key: "((", hint: hintRef}, {key: "【【", hint: hintRef}, {key: "((", hint: hintRef},
{key: "[[", hint: hintRef}, {key: "/", hint: safeSlash}, {key: "、", hint: safeSlash}],
};
- let timer: number;
let finished = false;
let composing = false;
let finishAfterComposition = false;
@@ -159,15 +159,13 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
onChange: () => {
contentChanged = true;
updateTableCellContentLayout(host, fragment.getBlockHTML());
- window.clearTimeout(timer);
if (!finished && !composing) {
- timer = window.setTimeout(commit, 200);
+ commit();
}
},
});
fragment.protyle.block.rootID = owner.block.rootID;
const commit = () => {
- window.clearTimeout(timer);
if (!cell.isConnected || !table.isConnected || !host.isConnected || owner.disabled || composing) {
return;
}
@@ -230,6 +228,8 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
};
activeEditor = {cell, finish};
const signal = controller.signal;
+ bindTableCellRichDrag(owner, cell, fragment.wysiwyg, finish, signal,
+ target => openTableCellRichEditor(owner, target));
const captureBeforeChange = () => {
if (!contentChanged || serializeTableCellRich(fragment.getBlockHTML()).markdown === source) {
undoSelection = captureRichCellSelection(fragment.wysiwyg, getSelection());
@@ -268,14 +268,20 @@ export const openTableCellRichEditor = (owner: IProtyle, cell: HTMLTableCellElem
commit();
}
}, {signal});
- host.addEventListener("compositionstart", () => composing = true, {signal});
+ host.addEventListener("compositionstart", () => {
+ captureBeforeChange();
+ composing = true;
+ }, {capture: true, signal});
host.addEventListener("compositionend", () => {
- composing = false;
- commit();
- if (finishAfterComposition) {
- finish();
- }
- }, {signal});
+ // 等待内部编辑器处理组合输入,再提交最终文字。
+ queueMicrotask(() => {
+ composing = false;
+ commit();
+ if (finishAfterComposition) {
+ finish();
+ }
+ });
+ }, {capture: true, signal});
host.addEventListener("keydown", event => {
captureBeforeChange();
const keymap = window.siyuan.config.keymap.editor.general;
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index 5dafcfa7fc..a05167512d 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -1,3 +1,4 @@
+import {createListDragTarget} from "./listDragTarget";
import {focusBlock, focusByRange, getRangeByPoint} from "./selection";
import {
getContenteditableElement,
@@ -2243,7 +2244,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
kanbanGroupDragHeight = "";
clearBlockDragoverTarget(document);
});
- let dragCache: { nodeId: string, indent: number, rgb: { r: number, g: number, b: number }, guides: string };
+ const getListDragTarget = createListDragTarget();
let disabledPosition: string;
const getDragTargetText = (element: HTMLElement) => {
const text = getContenteditableElement(element)?.textContent?.trim() || "";
@@ -2253,43 +2254,7 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
// 列表项目标的插入点与提示处理:设置 class、CSS 变量、showDragTip
const applyLiTarget = (htmlTarget: HTMLElement, event: DragEvent, canDropAsSibling = true): void => {
clearBlockDragoverTarget();
- const nodeId = htmlTarget.getAttribute("data-node-id");
- // Cache expensive computations per target element (never changes while hovering same element)
- if (!dragCache || dragCache.nodeId !== nodeId) {
- const contentBlock = Array.from(htmlTarget.children).find(c => c.hasAttribute("data-node-id")) as HTMLElement;
- const indent = contentBlock ? parseFloat(getComputedStyle(contentBlock).marginLeft) || 34 : 34;
- const depth = getListDepth(htmlTarget);
- const computedColor = getComputedStyle(htmlTarget).getPropertyValue("--b3-theme-primary-lighter").trim();
- const rgb = parseHexColor(computedColor) || {r: 53, g: 115, b: 217};
- let siblingGuides = "";
- for (let n = 1; n <= depth; n++) {
- if (siblingGuides) siblingGuides += ", ";
- // guide 竖线透明度从 0.5(最近)渐变到 0.1(最远),均低于插入线(0.6)以突出目标位置
- const opacity = depth <= 1 ? 0.3 : 0.5 - (n - 1) / (depth - 1) * 0.4;
- siblingGuides += `${-n * indent}px 0 0 0 rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity.toFixed(2)})`;
- }
- dragCache = {nodeId, indent, rgb, guides: siblingGuides || "none"};
- }
- const {indent, rgb, guides} = dragCache;
-
- const liRect = htmlTarget.getBoundingClientRect();
- const isRTL = getComputedStyle(htmlTarget).direction === "rtl";
- const offsetX = isRTL ? (liRect.right - event.clientX) : (event.clientX - liRect.left);
- // 用内容块(不含子列表)的 rect 判断上下半,避免有子列表时下半区域过小难以命中
- const contentBlockForRect = Array.from(htmlTarget.children).find(c =>
- c.hasAttribute("data-node-id") && !c.classList.contains("list")) as HTMLElement;
- const contentRect = contentBlockForRect ? contentBlockForRect.getBoundingClientRect() : liRect;
- const isBottom = event.clientY > contentRect.top + contentRect.height / 2;
- // 列表首项的上半保留顶部插入点;其余列表项整个区域统一使用底部插入点,避免下半区域过小难以命中
- const isFirstLi = !htmlTarget.previousElementSibling || !htmlTarget.previousElementSibling.classList.contains("li");
- let position = "bottom";
- if (isFirstLi && !isBottom) {
- position = "top";
- }
- // 有子列表时鼠标无法到达子列表区域(elementFromPoint 会命中子项的 .li),
- // 因此有子列表的列表项内容区域全部作为 sibling(在目标后插入同级),无子列表时用 offsetX 判断 child/sibling
- const hasChildList = !!Array.from(htmlTarget.children).find(c => c.classList.contains("list"));
- const isChild = position === "bottom" && !hasChildList && offsetX >= indent;
+ const {position, isChild, apply} = getListDragTarget(htmlTarget, event);
if (!canDropAsSibling && !isChild) {
hideDragTip();
return;
@@ -2306,20 +2271,9 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
hideDragTip();
return;
}
- const className = `dragover__${position}--${isChild ? "child" : "sibling"}`;
- htmlTarget.classList.add(className);
+ apply();
dragoverElement = htmlTarget;
- htmlTarget.style.setProperty("--drag-indent", `${indent}px`);
- htmlTarget.style.setProperty("--drag-line-left", isChild ? `${indent}px` : "0");
- // guide 竖线在 sibling 和 child 时都显示(sibling 时 ::before 为 transparent 不会与 guide 线重叠)
- htmlTarget.style.setProperty("--drag-guides", guides);
- // ::before 目标标记仅在成为子项时显示,sibling 时由横线独占该区域避免半透明叠加变深
- htmlTarget.style.setProperty("--drag-base-bg",
- isChild ? `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.6)` : "transparent");
- // 横向插入线使用独立颜色,始终显示
- htmlTarget.style.setProperty("--drag-line-bg",
- `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.6)`);
highlightByLevel(editorElement, htmlTarget);
// 提示文案:修饰键显示对应操作,无修饰键显示插入位置
const targetText = getDragTargetText(htmlTarget);
@@ -3184,48 +3138,6 @@ const cleanupDragIndicators = (scope: ParentNode) => {
});
};
-const getListDepth = (liElement: Element): number => {
- let depth = 0;
- let list = liElement.parentElement;
- while (list && list.classList.contains("list")) {
- const parentLi = list.parentElement;
- if (parentLi && parentLi.classList.contains("li")) {
- depth++;
- list = parentLi.parentElement;
- } else {
- break;
- }
- }
- return depth;
-};
-
-const parseHexColor = (color: string): { r: number, g: number, b: number } | null => {
- if (!color) return null;
- const hexMatch = color.match(/^#([0-9a-f]{3,8})$/i);
- if (hexMatch) {
- let hex = hexMatch[1];
- if (hex.length === 3) {
- hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
- }
- if (hex.length >= 6) {
- return {
- r: parseInt(hex.slice(0, 2), 16),
- g: parseInt(hex.slice(2, 4), 16),
- b: parseInt(hex.slice(4, 6), 16),
- };
- }
- }
- const rgbMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
- if (rgbMatch) {
- return {
- r: parseInt(rgbMatch[1]),
- g: parseInt(rgbMatch[2]),
- b: parseInt(rgbMatch[3]),
- };
- }
- return null;
-};
-
const highlightByLevel = (editorElement: HTMLElement, liElement: HTMLElement) => {
editorElement.querySelectorAll(".dragover").forEach((item: HTMLElement) => {
item.classList.remove("dragover");
diff --git a/app/src/protyle/util/listDragTarget.ts b/app/src/protyle/util/listDragTarget.ts
new file mode 100644
index 0000000000..39ad0378f5
--- /dev/null
+++ b/app/src/protyle/util/listDragTarget.ts
@@ -0,0 +1,97 @@
+export const createListDragTarget = () => {
+ let dragCache: {node: HTMLElement, indent: number, rgb: {r: number, g: number, b: number}, guides: string};
+ return (htmlTarget: HTMLElement, event: Pick<DragEvent, "clientX" | "clientY">) => {
+ const node = htmlTarget;
+ if (!dragCache || dragCache.node !== node) {
+ const contentBlock = Array.from(htmlTarget.children).find(c => (c.hasAttribute("data-node-id") || c.hasAttribute("data-table-cell-node"))) as HTMLElement;
+ const indent = contentBlock ? parseFloat(getComputedStyle(contentBlock).marginLeft) || 34 : 34;
+ const depth = getListDepth(htmlTarget);
+ const computedColor = getComputedStyle(htmlTarget).getPropertyValue("--b3-theme-primary-lighter").trim();
+ const rgb = parseHexColor(computedColor) || {r: 53, g: 115, b: 217};
+ let siblingGuides = "";
+ for (let n = 1; n <= depth; n++) {
+ if (siblingGuides) siblingGuides += ", ";
+ // guide 竖线透明度从 0.5(最近)渐变到 0.1(最远),均低于插入线(0.6)以突出目标位置
+ const opacity = depth <= 1 ? 0.3 : 0.5 - (n - 1) / (depth - 1) * 0.4;
+ siblingGuides += `${-n * indent}px 0 0 0 rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity.toFixed(2)})`;
+ }
+ dragCache = {node, indent, rgb, guides: siblingGuides || "none"};
+ }
+ const {indent, rgb, guides} = dragCache;
+
+ const liRect = htmlTarget.getBoundingClientRect();
+ const isRTL = getComputedStyle(htmlTarget).direction === "rtl";
+ const offsetX = isRTL ? (liRect.right - event.clientX) : (event.clientX - liRect.left);
+ // 用内容块(不含子列表)的 rect 判断上下半,避免有子列表时下半区域过小难以命中
+ const contentBlockForRect = Array.from(htmlTarget.children).find(c =>
+ (c.hasAttribute("data-node-id") || c.hasAttribute("data-table-cell-node")) && !c.classList.contains("list")) as HTMLElement;
+ const contentRect = contentBlockForRect ? contentBlockForRect.getBoundingClientRect() : liRect;
+ const isBottom = event.clientY > contentRect.top + contentRect.height / 2;
+ // 列表首项的上半保留顶部插入点;其余列表项整个区域统一使用底部插入点,避免下半区域过小难以命中
+ const isFirstLi = !htmlTarget.previousElementSibling || !htmlTarget.previousElementSibling.classList.contains("li");
+ let position = "bottom";
+ if (isFirstLi && !isBottom) {
+ position = "top";
+ }
+ // 有子列表时鼠标无法到达子列表区域(elementFromPoint 会命中子项的 .li),
+ // 因此有子列表的列表项内容区域全部作为 sibling(在目标后插入同级),无子列表时用 offsetX 判断 child/sibling
+ const hasChildList = !!Array.from(htmlTarget.children).find(c => c.classList.contains("list"));
+ const isChild = position === "bottom" && !hasChildList && offsetX >= indent;
+ const className = `dragover__${position}--${isChild ? "child" : "sibling"}`;
+ return {position, isChild, className, apply: () => {
+ htmlTarget.classList.add(className);
+ htmlTarget.style.setProperty("--drag-indent", `${indent}px`);
+ htmlTarget.style.setProperty("--drag-line-left", isChild ? `${indent}px` : "0");
+ // guide 竖线在 sibling 和 child 时都显示(sibling 时 ::before 为 transparent 不会与 guide 线重叠)
+ htmlTarget.style.setProperty("--drag-guides", guides);
+ // ::before 目标标记仅在成为子项时显示,sibling 时由横线独占该区域避免半透明叠加变深
+ htmlTarget.style.setProperty("--drag-base-bg",
+ isChild ? `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.6)` : "transparent");
+ // 横向插入线使用独立颜色,始终显示
+ htmlTarget.style.setProperty("--drag-line-bg",
+ `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.6)`);
+ }};
+ };
+};
+
+const getListDepth = (liElement: Element): number => {
+ let depth = 0;
+ let list = liElement.parentElement;
+ while (list && list.classList.contains("list")) {
+ const parentLi = list.parentElement;
+ if (parentLi && parentLi.classList.contains("li")) {
+ depth++;
+ list = parentLi.parentElement;
+ } else {
+ break;
+ }
+ }
+ return depth;
+};
+
+const parseHexColor = (color: string): { r: number, g: number, b: number } | null => {
+ if (!color) return null;
+ const hexMatch = color.match(/^#([0-9a-f]{3,8})$/i);
+ if (hexMatch) {
+ let hex = hexMatch[1];
+ if (hex.length === 3) {
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
+ }
+ if (hex.length >= 6) {
+ return {
+ r: parseInt(hex.slice(0, 2), 16),
+ g: parseInt(hex.slice(2, 4), 16),
+ b: parseInt(hex.slice(4, 6), 16),
+ };
+ }
+ }
+ const rgbMatch = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ if (rgbMatch) {
+ return {
+ r: parseInt(rgbMatch[1]),
+ g: parseInt(rgbMatch[2]),
+ b: parseInt(rgbMatch[3]),
+ };
+ }
+ return null;
+};
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index c3a6285e85..4e313abd1a 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -715,6 +715,12 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
siyuanHTML = event.siyuanHTML;
files = event.files;
}
+ // 先提取网页剪贴板中的内部块数据,再执行受限片段校验和清洗。
+ if (blockDOMSanitizer && !siyuanHTML && textHTML) {
+ const clipboard = getTextSiyuanFromTextHTML(textHTML);
+ siyuanHTML = clipboard.textSiyuan;
+ textHTML = clipboard.textHtml;
+ }
if (blockDOMSanitizer && !siyuanHTML && !isProtyleUploadDisabled(protyle)) {
// 受限片段中的图片走附件上传,避免被后续纯文本降级丢弃。
const isImage = (name: string) => Constants.SIYUAN_ASSETS_IMAGE.includes(
diff --git a/app/src/protyle/util/tableCellRichDrag.ts b/app/src/protyle/util/tableCellRichDrag.ts
new file mode 100644
index 0000000000..5302878cc3
--- /dev/null
+++ b/app/src/protyle/util/tableCellRichDrag.ts
@@ -0,0 +1,195 @@
+import {Constants} from "../../constants";
+import {showMessage} from "../../dialog/message";
+import {renderTableCellRichElements} from "../render/tableCellRich";
+import {updateTransaction} from "../wysiwyg/transaction";
+import {hideCaretLine, hideDragTip, showDragTip} from "./dragTip";
+import {createListDragTarget} from "./listDragTarget";
+import {cleanTableCellRichHTML, getTableCellRichBlockDOM, serializeTableCellRich, setTableCellRich} from "./tableCellRich";
+
+export const bindTableCellRichDrag = (owner: IProtyle, cell: HTMLTableCellElement,
+ wysiwyg: HTMLElement, finish: () => void, signal: AbortSignal,
+ focusTarget: (target: HTMLTableCellElement) => void) => {
+ let indicator: HTMLElement;
+ const getListDragTarget = createListDragTarget();
+ const clear = () => {
+ indicator?.classList.remove("dragover", "dragover__top", "dragover__bottom",
+ "dragover__top--sibling", "dragover__bottom--sibling", "dragover__bottom--child");
+ ["--drag-indent", "--drag-line-left", "--drag-guides", "--drag-base-bg", "--drag-line-bg"].forEach(name =>
+ indicator?.style.removeProperty(name));
+ indicator = undefined;
+ };
+ const resolve = (event: DragEvent) => {
+ if (window.siyuan.dragElement !== wysiwyg) {
+ return;
+ }
+ const type = Array.from(event.dataTransfer?.types || []).find(value => value.startsWith(Constants.SIYUAN_DROP_GUTTER));
+ const target = event.target instanceof Element ? event.target : undefined;
+ const targetCell = target?.closest<HTMLTableCellElement>("td, th");
+ if (!type || !targetCell || targetCell === cell ||
+ targetCell.closest(".protyle-wysiwyg") !== owner.wysiwyg.element) {
+ return;
+ }
+ const ids = type.slice(Constants.SIYUAN_DROP_GUTTER.length).split(Constants.ZWSP)[2]?.split(",") || [];
+ const blocks = Array.from(wysiwyg.querySelectorAll<HTMLElement>("[data-node-id]"))
+ .filter(node => ids.includes(node.dataset.nodeId));
+ const selected = blocks.filter(node => !blocks.some(parent => parent !== node && parent.contains(node)));
+ if (!selected.length) {
+ return;
+ }
+ const listItems = selected.every(node => node.dataset.type === "NodeListItem");
+ let anchor = (listItems ? target.closest('[data-type="NodeListItem"]') : undefined) ||
+ target.closest("[data-table-cell-node]");
+ if (anchor && !(listItems && anchor.getAttribute("data-type") === "NodeListItem" &&
+ selected.every(node => node.dataset.subtype === anchor.getAttribute("data-subtype")))) {
+ const preview = targetCell.querySelector(".table__cell-rich");
+ while (anchor.parentElement !== preview && anchor.parentElement?.hasAttribute("data-table-cell-node")) {
+ anchor = anchor.parentElement;
+ }
+ }
+ const listTarget = listItems && anchor?.getAttribute("data-type") === "NodeListItem" &&
+ selected.every(node => node.dataset.subtype === anchor.getAttribute("data-subtype")) ?
+ getListDragTarget(anchor as HTMLElement, event) : undefined;
+ const rect = (anchor || targetCell).getBoundingClientRect();
+ return {targetCell, selected, anchor, listItems, listTarget,
+ before: listTarget ? listTarget.position === "top" : event.clientY < rect.top + rect.height / 2};
+ };
+ owner.wysiwyg.element.addEventListener("dragover", event => {
+ const drop = resolve(event);
+ if (!drop) {
+ clear();
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ hideCaretLine();
+ hideDragTip();
+ event.dataTransfer.dropEffect = event.altKey || event.shiftKey ? "none" : event.ctrlKey ? "copy" : "move";
+ if (event.altKey || event.shiftKey) {
+ clear();
+ } else {
+ clear();
+ indicator = (drop.anchor || drop.targetCell) as HTMLElement;
+ if (drop.listTarget) {
+ drop.listTarget.apply();
+ indicator.classList.add("dragover");
+ } else {
+ indicator.classList.add(drop.before ? "dragover__top" : "dragover__bottom");
+ }
+ if (drop.listTarget) {
+ const text = Array.from(indicator.querySelector("[contenteditable]")?.textContent?.trim() || "");
+ const targetText = text.slice(0, 20).join("") + (text.length > 20 ? "..." : "");
+ const key = drop.listTarget.isChild ? "dragTipListItemChild" :
+ drop.before ? "dragTipListItemBefore" : "dragTipListItemAfter";
+ showDragTip(window.siyuan.dragTitle || "", event.ctrlKey ? window.siyuan.languages.duplicateCopy :
+ window.siyuan.languages[key].replace("${x}", targetText), event.clientX, event.clientY);
+ }
+ }
+ }, {capture: true, signal});
+ owner.wysiwyg.element.addEventListener("drop", event => {
+ const drop = resolve(event);
+ clear();
+ if (!drop) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ hideCaretLine();
+ hideDragTip();
+ if (event.altKey || event.shiftKey || owner.disabled) {
+ return;
+ }
+ try {
+ const source = wysiwyg.cloneNode(true) as HTMLElement;
+ const destination = document.createElement("div");
+ destination.innerHTML = getTableCellRichBlockDOM(drop.targetCell);
+ const anchorIndex = Array.from(drop.targetCell.querySelectorAll("[data-table-cell-node]"))
+ .indexOf(drop.anchor);
+ let anchor = destination.querySelectorAll("[data-node-id]")[anchorIndex];
+ if (destination.childElementCount === 1 && destination.firstElementChild.getAttribute("data-type") === "NodeParagraph" &&
+ !destination.firstElementChild.querySelector('[contenteditable="true"]')?.innerHTML.replaceAll(Constants.ZWSP, "").trim()) {
+ destination.replaceChildren();
+ anchor = undefined;
+ }
+ let nodes = drop.selected.map(node => node.cloneNode(true) as HTMLElement);
+ const mergeList = drop.listItems && anchor?.getAttribute("data-type") === "NodeListItem" &&
+ drop.selected.every(node => node.dataset.subtype === anchor.getAttribute("data-subtype"));
+ if (drop.listItems && !mergeList) {
+ const list = drop.selected[0].parentElement.cloneNode(false) as HTMLElement;
+ list.append(...nodes);
+ nodes = [list];
+ }
+ if (!mergeList) {
+ while (anchor && anchor.parentElement !== destination) {
+ anchor = anchor.parentElement;
+ }
+ }
+ nodes.forEach(node => {
+ node.classList.remove("protyle-wysiwyg--select");
+ node.querySelectorAll(".protyle-wysiwyg--select").forEach(child =>
+ child.classList.remove("protyle-wysiwyg--select"));
+ });
+ if (mergeList && drop.listTarget?.isChild) {
+ const list = drop.selected[0].parentElement.cloneNode(false) as HTMLElement;
+ list.append(...nodes);
+ const attributes = anchor.querySelector(":scope > .protyle-attr");
+ anchor.insertBefore(list, attributes);
+ } else if (anchor) {
+ const content = document.createDocumentFragment();
+ content.append(...nodes);
+ anchor.parentNode.insertBefore(content, drop.before ? anchor : anchor.nextSibling);
+ } else if (drop.before) {
+ destination.prepend(...nodes);
+ } else {
+ destination.append(...nodes);
+ }
+ drop.selected.forEach(node => source.querySelector(`[data-node-id="${node.dataset.nodeId}"]`)?.remove());
+ // 删除失去全部列表项的容器,保留未被拖动的嵌套内容。
+ Array.from(source.querySelectorAll('[data-type="NodeList"]')).reverse().forEach(list => {
+ if (!list.querySelector('[data-type="NodeListItem"]')) {
+ list.remove();
+ }
+ });
+ const targetValue = serializeTableCellRich(destination.innerHTML).markdown;
+ const sourceValue = serializeTableCellRich(source.innerHTML).markdown;
+ finish();
+ const sourceTable = cell.closest('[data-type="NodeTable"]');
+ const targetTable = drop.targetCell.closest('[data-type="NodeTable"]');
+ const oldSource = cleanTableCellRichHTML(sourceTable.outerHTML);
+ const oldTarget = cleanTableCellRichHTML(targetTable.outerHTML);
+ if (!event.ctrlKey) {
+ setTableCellRich(cell, sourceValue);
+ }
+ setTableCellRich(drop.targetCell, targetValue);
+ const additional: {doOperations: IOperation[], undoOperations: IOperation[]} = sourceTable !== targetTable && !event.ctrlKey ? {
+ doOperations: [{action: "update", id: sourceTable.getAttribute("data-node-id"), data: cleanTableCellRichHTML(sourceTable.outerHTML)}],
+ undoOperations: [{action: "update", id: sourceTable.getAttribute("data-node-id"), data: oldSource}],
+ } : undefined;
+ updateTransaction(owner, targetTable, oldTarget, undefined, additional);
+ renderTableCellRichElements(sourceTable);
+ renderTableCellRichElements(targetTable);
+ focusTarget(drop.targetCell);
+ } catch (error) {
+ console.error(error);
+ showMessage(window.siyuan.languages.tableCellRichInvalid);
+ }
+ }, {capture: true, signal});
+ document.addEventListener("dragend", () => {
+ clear();
+ hideDragTip();
+ }, {capture: true, signal});
+ owner.wysiwyg.element.addEventListener("dragleave", event => {
+ if (!indicator) {
+ return;
+ }
+ // 浏览器切换拖放命中节点时可能没有 relatedTarget,按实际命中位置判断是否已离开。
+ const target = event.relatedTarget instanceof Node ? event.relatedTarget :
+ document.elementFromPoint(event.clientX, event.clientY);
+ if (!target || !owner.wysiwyg.element.contains(target)) {
+ clear();
+ hideDragTip();
+ } else {
+ event.stopImmediatePropagation();
+ }
+ }, {capture: true, signal});
+ signal.addEventListener("abort", clear, {once: true});
+};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index ec1b0b3019..945beaeda8 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -3823,12 +3823,15 @@ export class WYSIWYG {
event.stopPropagation();
return;
}
- if (!hasClosestByAttribute(event.target, "contenteditable", "true")) {
+ if (event.target !== this.element && !hasClosestByAttribute(event.target, "contenteditable", "true")) {
event.stopPropagation();
event.preventDefault();
return;
}
- const blockElement = hasClosestBlock(event.target);
+ let blockElement = hasClosestBlock(event.target);
+ if (!blockElement) {
+ blockElement = hasClosestBlock(getEditorRange(protyle.wysiwyg.element).startContainer);
+ }
const calloutTitleElement = hasClosestByClassName(event.target, "callout-title");
if (blockElement && calloutTitleElement) {
const range = getEditorRange(protyle.wysiwyg.element);