An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: https://github.com/siyuan-note/siyuan/issues/9521
Vanessa189d5ae8506a
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex c1870fb19b..cc84c494c5 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -278,7 +278,8 @@&[data-sb-layout="col"] {flex-direction: row;flex-wrap: wrap;- justify-content: space-between;+ // flex-start 替代 space-between:拖拽后子块设 flex:none 时,多余空间留在末尾而非均匀分配到子块与手柄之间,避免手柄两侧出现随拖拽增大的空隙+ justify-content: flex-start;& > div {flex: 1 0 10%;diff --git a/app/src/block/util.ts b/app/src/block/util.tsindex e3f26ea3bd..93591f7b08 100644--- a/app/src/block/util.ts+++ b/app/src/block/util.ts@@ -20,6 +20,8 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:nodeElement.removeAttribute("select-start");nodeElement.removeAttribute("select-end");const id = nodeElement.getAttribute("data-node-id");+ // 先清理拖拽手柄,避免手柄被克隆进撤销用的 SB 副本,导致恢复后残留多余手柄+ nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());const sbElement = nodeElement.cloneNode() as HTMLElement;sbElement.innerHTML = nodeElement.lastElementChild.outerHTML;let parentID = getParentBlock(nodeElement)?.getAttribute("data-node-id");@@ -40,8 +42,6 @@ export const cancelSB = async (protyle: IProtyle, nodeElement: Element, range?:previousID: previousId,parentID,});- // 移出子块前先清理拖拽手柄,避免手柄(无 data-node-id)被遍历成 id 为空的 move 操作- nodeElement.querySelectorAll(".sb__resize").forEach(handle => handle.remove());Array.from(nodeElement.children).forEach((item, index) => {if (index === nodeElement.childElementCount - 1) {doOperations.push({@@ -114,6 +114,69 @@ export const refreshSbResize = (sbElement: Element) => {}};+// 子块进出超级块后,重新分配所有子块的宽度(按比例均摊 gap),避免 gap 不均或换行+// 仅当超级块中已有子块设置了宽度时才调整(否则保持 CSS 默认等分)+// 返回被改动的块信息(id + 改前 HTML),供调用方持久化+export const rebalanceSbWidth = (sbElement: Element): Array<{id: string, oldHTML: string}> => {+ if (!sbElement || sbElement.getAttribute("data-sb-layout") !== "col") {+ return [];+ }+ const children = Array.from(sbElement.querySelectorAll(":scope > [data-node-id]")) as HTMLElement[];+ if (children.length < 2) {+ return [];+ }+ // 没有任何子块设了宽度,保持 CSS 默认等分+ if (!children.some(c => c.style.width)) {+ return [];+ }+ // 读取手柄实际占用宽度(width + margin)+ const handle = sbElement.querySelector(":scope > .sb__resize") as HTMLElement;+ let gapPx = 20;+ if (handle) {+ const hs = getComputedStyle(handle);+ gapPx = handle.offsetWidth + parseFloat(hs.marginLeft) + parseFloat(hs.marginRight);+ }+ const childCount = children.length;+ const gapShare = ((childCount - 1) * gapPx) / childCount + 0.5;+ // 读取各块当前比例:有 width 的取 calc 百分比,无 width 的(新移入)按平均比例参与+ const avgRatio = 1 / childCount;+ const ratios: number[] = children.map(c => {+ const match = c.style.width.match(/calc\(([\d.]+)%/);+ return match ? parseFloat(match[1]) / 100 : avgRatio;+ });+ // 归一化到总和 1,使子块填满整个超级块(删除/移入后不留空白)+ const totalRatio = ratios.reduce((s, r) => s + r, 0) || 1;+ // 记录改前 HTML 用于持久化+ const changes: Array<{id: string, oldHTML: string}> = [];+ children.forEach((child, i) => {+ const oldHTML = child.outerHTML;+ const pct = Math.round((ratios[i] / totalRatio) * 100 * 10) / 10;+ child.style.width = `calc(${pct}% - ${gapShare}px)`;+ child.style.flex = "none";+ changes.push({id: child.getAttribute("data-node-id"), oldHTML});+ });+ return changes;+};++// 刷新超级块的拖拽手柄并重新分配子块宽度,把变更持久化到 do/undo operations+// 宽度撤销插入到 undoOperations 头部,确保 update undo 先于 move undo 执行(位置恢复后再还原宽度会错位)+// 已脱离 DOM 的超级块会被跳过(cancelSB 可能已将其删除)+export const refreshSbAndPersistWidth = (sbElement: Element,+ doOperations: IOperation[], undoOperations: IOperation[]) => {+ if (!sbElement || !sbElement.parentElement) {+ return;+ }+ refreshSbResize(sbElement);+ const widthChanges = rebalanceSbWidth(sbElement);+ widthChanges.forEach(change => {+ const targetEl = sbElement.querySelector(`[data-node-id="${change.id}"]`);+ if (targetEl) {+ doOperations.push({action: "update", id: change.id, data: targetEl.outerHTML});+ undoOperations.splice(0, 0, {action: "update", id: change.id, data: change.oldHTML});+ }+ });+};+export const jumpToParent = (protyle: IProtyle, nodeElement: Element, type: "parent" | "next" | "previous") => {fetchPost("/api/block/getBlockSiblingID", {id: nodeElement.getAttribute("data-node-id")}, (response) => {const targetId = response.data[type];diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex d473734a1b..ebf9a9a4a9 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -2378,6 +2378,16 @@ export class Gutter {}private genWidths(nodeElements: Element[], protyle: IProtyle) {+ let isInSb = false;+ nodeElements.find((e: HTMLElement) => {+ if (e.parentElement.classList.contains("sb")) {+ isInSb = true;+ return true;+ }+ });+ if (isInSb) {+ return;+ }let rangeElement: HTMLInputElement;const firstElement = nodeElements[0] as HTMLElement;const styles: IMenu[] = [{diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex 0c818ffe00..d5bb1bb6c0 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -1,5 +1,11 @@import {focusBlock, focusByRange, getRangeByPoint} from "./selection";-import {getContenteditableElement, getParentBlock, getSbChildBlockCount, getTopAloneElement} from "../wysiwyg/getBlock";+import {+ getContenteditableElement,+ getParentBlock,+ getPreviousBlockSibling,+ getSbChildBlockCount,+ getTopAloneElement+} from "../wysiwyg/getBlock";import {hideDragTip, showDragTip, transparentImgSrc} from "./dragTip";import {hasClosestBlock,@@ -11,7 +17,14 @@ import {} from "./hasClosest";import {Constants} from "../../constants";import {paste} from "./paste";-import {cancelSB, genEmptyElement, genSBElement, insertEmptyBlock, refreshSbResize} from "../../block/util";+import {+ cancelSB,+ genEmptyElement,+ genSBElement,+ insertEmptyBlock,+ refreshSbAndPersistWidth,+ refreshSbResize+} from "../../block/util";import {transaction, turnsIntoOneTransaction} from "../wysiwyg/transaction";import {updateListOrder} from "../wysiwyg/list";import {fetchPost, fetchSyncPost} from "../../util/fetch";@@ -40,8 +53,6 @@ import {clearSelect} from "./clear";import {dragoverTab} from "../render/av/view";import {setFold} from "./blockFold";-// position: afterbegin 为拖拽成超级块; "afterend", "beforebegin" 一般拖拽-// position: afterbegin 为拖拽成超级块; "afterend", "beforebegin" 一般拖拽const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElement: Element,isSameDoc: boolean, position: InsertPosition, isCopy: boolean) => {@@ -87,7 +98,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemen}}sourcePositions.set(id, {- previousID: item.previousElementSibling?.getAttribute("data-node-id") || "",+ previousID: getPreviousBlockSibling(item)?.getAttribute("data-node-id") || "",parentID: srcParentID || "",});}@@ -105,7 +116,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenaction: "insert",data: newListElement.outerHTML,id: newListId,- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : tempTargetElement.previousElementSibling?.getAttribute("data-node-id")),+ previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(tempTargetElement)?.getAttribute("data-node-id")),parentID: position === "afterbegin" ? targetId : (getParentBlock(tempTargetElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),});undoOperations.push({@@ -168,7 +179,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenaction: "insert",id: copyNewId,data: copyElement.outerHTML,- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : copyElement.previousElementSibling?.getAttribute("data-node-id")), // 不能使用常量,移动后会被修改+ previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(copyElement)?.getAttribute("data-node-id")), // 不能使用常量,移动后会被修改parentID: position === "afterbegin" ? targetId : (getParentBlock(copyElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),});newSourceElements.push(copyElement);@@ -191,7 +202,7 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemendoOperations.push({action: "move",id,- previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : item.previousElementSibling?.getAttribute("data-node-id")), // 不能使用常量,移动后会被修改+ previousID: position === "afterbegin" ? null : (position === "afterend" ? targetId : getPreviousBlockSibling(item)?.getAttribute("data-node-id")), // 不能使用常量,移动后会被修改parentID: position === "afterbegin" ? targetId : (getParentBlock(item)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID),});newSourceElements.push(item);@@ -369,6 +380,15 @@ const moveTo = async (protyle: IProtyle, sourceElements: Element[], targetElemenconst dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElement: Element, isBottom: boolean,direct: "col" | "row", isCopy: boolean) => {const isSameDoc = protyle.element.contains(sourceElements[0]);+ // 移动前记录源块所在的超级块,移动后刷新其手柄(移出后需重建)https://github.com/siyuan-note/siyuan/issues/9521+ const originSbSet = new Set<Element>();+ sourceElements.forEach(el => {+ const sb = el.closest('[data-type="NodeSuperBlock"]');+ if (sb && sb !== targetElement.closest('[data-type="NodeSuperBlock"]')) {+ // 目标本身不在该超级块内(否则是 SB 内部重排,不必重建)+ originSbSet.add(sb);+ }+ });// 把列表块中的唯一一个列表项块拖拽到列表块的左侧 https://github.com/siyuan-note/siyuan/issues/16315if (isSameDoc && sourceElements[0].classList.contains("li") && targetElement === sourceElements[0].parentElement &&targetElement.childElementCount === sourceElements.length + 1) {@@ -388,7 +408,7 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemenremoveFold: "true"},id: targetElement.getAttribute("data-node-id"),- previousID: targetElement.previousElementSibling?.getAttribute("data-node-id"),+ previousID: getPreviousBlockSibling(targetElement)?.getAttribute("data-node-id"),parentID: getParentBlock(targetElement)?.getAttribute("data-node-id") || protyle.block.parentID || protyle.block.rootID};const sbElement = genSBElement(direct);@@ -469,6 +489,9 @@ const dragSb = async (protyle: IProtyle, sourceElements: Element[], targetElemenundoOperations.splice(0, 0, ...foldOperations.undoOperations);});refreshSbResize(sbElement);+ originSbSet.forEach(sb => {+ refreshSbAndPersistWidth(sb, doOperations, undoOperations);+ });if (isSameDoc || isCopy) {transaction(protyle, doOperations, undoOperations);} else {@@ -486,6 +509,14 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElemconst isSameDoc = protyle.element.contains(sourceElements[0]);const doOperations: IOperation[] = [];const undoOperations: IOperation[] = [];+ // 移动前记录源块所在的超级块,移动后刷新其手柄(移出后需重建)+ const originSbSet = new Set<Element>();+ sourceElements.forEach(el => {+ const sb = el.closest('[data-type="NodeSuperBlock"]');+ if (sb) {+ originSbSet.add(sb);+ }+ });const moveToResult = await moveTo(protyle, sourceElements, targetElement, isSameDoc, isBottom ? "afterend" : "beforebegin", isCopy);doOperations.push(...moveToResult.doOperations);@@ -548,15 +579,17 @@ const dragSame = async (protyle: IProtyle, sourceElements: Element[], targetElemreturn true;}});- // 移入/移出超级块后刷新拖拽手柄(如 A 拖到超级块内 B 前面,需在 A、B 间补手柄)- const dragSbSet = new Set<Element>();+ // 移入/移出超级块后刷新拖拽手柄并重新分配宽度(如 A 拖到超级块内 B 前面,需在 A、B 间补手柄)+ const dragSbSet = new Set<Element>(originSbSet);[newSourceParentElement[0], targetElement].forEach(el => {const sb = el?.closest('[data-type="NodeSuperBlock"]');if (sb) {dragSbSet.add(sb);}});- dragSbSet.forEach(sb => refreshSbResize(sb));+ dragSbSet.forEach(sb => {+ refreshSbAndPersistWidth(sb, doOperations, undoOperations);+ });if (isSameDoc || isCopy) {transaction(protyle, doOperations, undoOperations);} else {diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 013b6cf86b..1f612143f6 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -790,48 +790,95 @@ export class WYSIWYG {const mostBottom = protyleRect.bottom;const y = event.clientY;const contentRect = protyle.contentElement.getBoundingClientRect();- // 超级块横向布局下拖拽调整子块宽度 https://github.com/siyuan-note/siyuan/issues/9521+ // 超级块横向布局下拖拽调整子块宽度if (!protyle.disabled && target.classList.contains("sb__resize")) {const sbElement = target.parentElement;const previousElement = target.previousElementSibling as HTMLElement;+ // 取手柄右侧的下一个块(跳过手柄等装饰元素)+ let nextElement = target.nextElementSibling as HTMLElement;+ while (nextElement && !nextElement.hasAttribute("data-node-id")) {+ nextElement = nextElement.nextElementSibling as HTMLElement;+ }if (!sbElement || !previousElement || !previousElement.hasAttribute("data-node-id") ||- sbElement.getAttribute("data-sb-layout") !== "col") {+ !nextElement || sbElement.getAttribute("data-sb-layout") !== "col") {return;}const x = event.clientX;const sbWidth = sbElement.clientWidth;- const oldWidth = previousElement.clientWidth;- const oldHTML = previousElement.outerHTML;+ // 使用 getBoundingClientRect 获取精确浮点宽度,避免 clientWidth(整数取整)作为+ // 拖拽起始值带入累积误差+ const oldLeftWidth = previousElement.getBoundingClientRect().width;+ const oldRightWidth = nextElement.getBoundingClientRect().width;+ // 读取手柄实际占用宽度(width + margin),这才是子块间的真实间距,用于 calc 补偿避免换行+ const handleStyle = getComputedStyle(target);+ const gapPx = target.offsetWidth + parseFloat(handleStyle.marginLeft) + parseFloat(handleStyle.marginRight);+ const minWidth = 20;target.classList.add("sb__resize--drag");+ // 拖拽时禁止换行,避免最后一个子块因宽度溢出而换行+ sbElement.style.flexWrap = "nowrap";// @ts-ignorepreviousElement.style.webkitUserModify = "read-only";+ // @ts-ignore+ nextElement.style.webkitUserModify = "read-only";+ // 记录最终拖拽宽度,供 mouseup 精确计算百分比,避免从 clientWidth(整数取整)+ // 反推导致每次拖拽累积误差+ let finalLeft = oldLeftWidth;+ let finalRight = oldRightWidth;documentSelf.onmousemove = (moveEvent: MouseEvent) => {- let newWidth = oldWidth + (moveEvent.clientX - x);- // 最小宽度限制为超级块宽度的 10%- const minWidth = sbWidth * 0.1;- // 最大宽度限制为超级块宽度减去最小宽度(保证至少还有一个兄弟块的空间)- const maxWidth = sbWidth * 0.9;- newWidth = Math.max(minWidth, Math.min(maxWidth, newWidth));- // 用 style.width + flex:none,与 genWidths 菜单、图片缩放一致,菜单可自动回显/持久化- previousElement.style.width = newWidth + "px";+ // 左右两块等量交换宽度,不影响其他子块+ const delta = moveEvent.clientX - x;+ let newLeftWidth = oldLeftWidth + delta;+ let newRightWidth = oldRightWidth - delta;+ // 限制最小宽度,避免塌陷+ if (newLeftWidth < minWidth) {+ newLeftWidth = minWidth;+ newRightWidth = oldLeftWidth + oldRightWidth - minWidth;+ }+ if (newRightWidth < minWidth) {+ newRightWidth = minWidth;+ newLeftWidth = oldLeftWidth + oldRightWidth - minWidth;+ }+ finalLeft = newLeftWidth;+ finalRight = newRightWidth;+ previousElement.style.width = newLeftWidth + "px";previousElement.style.flex = "none";+ nextElement.style.width = newRightWidth + "px";+ nextElement.style.flex = "none";};documentSelf.onmouseup = () => {target.classList.remove("sb__resize--drag");+ sbElement.style.flexWrap = "";// @ts-ignorepreviousElement.style.webkitUserModify = "";+ // @ts-ignore+ nextElement.style.webkitUserModify = "";documentSelf.onmousemove = null;documentSelf.onmouseup = null;documentSelf.ondragstart = null;documentSelf.onselectstart = null;documentSelf.onselect = null;- // 转为百分比写入 style.width + flex:none,复用既有 genWidths 菜单的回显与持久化- const finalWidth = previousElement.clientWidth;- const pct = Math.round(finalWidth / sbWidth * 1000) / 10;- previousElement.style.width = pct + "%";- previousElement.style.flex = "none";- previousElement.setAttribute("updated", dayjs().format("YYYYMMDDHHmmss"));- updateTransaction(protyle, previousElement, oldHTML);+ const sbChildren = Array.from(sbElement.querySelectorAll(":scope > [data-node-id]")) as HTMLElement[];+ const oldHTMLs = sbChildren.map(c => c.outerHTML);+ // 只调整左右两块(手柄两侧),其他子块不动,避免影响未拖拽的块+ // 使用 mousemove 记录的精确实时宽度(finalLeft/finalRight)反推百分比,+ // gapHalve 已含 +1px 余量防止亚像素换行,无需再用 *99 缩放(会造成累积收缩)+ const gapHalve = gapPx / 2 + 1;+ let leftPct = Math.round((finalLeft + gapHalve) / sbWidth * 1000) / 10;+ let rightPct = Math.round((finalRight + gapHalve) / sbWidth * 1000) / 10;+ // 防溢出:两块百分比之和超过 99.5% 时等比压缩到 99%,留 1% 缓冲防换行+ const sumPct = leftPct + rightPct;+ if (sumPct > 99.5) {+ const scale = 99 / sumPct;+ leftPct = Math.round(leftPct * scale * 10) / 10;+ rightPct = Math.round(rightPct * scale * 10) / 10;+ }+ const updated = dayjs().format("YYYYMMDDHHmmss");+ previousElement.style.width = `calc(${leftPct}% - ${gapHalve}px)`;+ nextElement.style.width = `calc(${rightPct}% - ${gapHalve}px)`;+ previousElement.setAttribute("updated", updated);+ nextElement.setAttribute("updated", updated);+ updateTransaction(protyle, previousElement, oldHTMLs[sbChildren.indexOf(previousElement)]);+ updateTransaction(protyle, nextElement, oldHTMLs[sbChildren.indexOf(nextElement)]);};this.preventClick = true;event.preventDefault();diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.tsindex e8a12e93a4..6e168ef762 100644--- a/app/src/protyle/wysiwyg/remove.ts+++ b/app/src/protyle/wysiwyg/remove.ts@@ -16,7 +16,7 @@ import {hasPreviousSibling} from "./getBlock";import {transaction, turnsIntoOneTransaction, turnsIntoTransaction, updateTransaction} from "./transaction";-import {cancelSB, genEmptyElement, refreshSbResize} from "../../block/util";+import {cancelSB, genEmptyElement, rebalanceSbWidth, refreshSbResize} from "../../block/util";import {listOutdent, updateListOrder} from "./list";import {zoomOut} from "../../menus/protyle";import {preventScroll} from "../scroll/preventScroll";@@ -44,7 +44,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, ranglet sideElement: Element | boolean;let sideIsNext = false;if (type === "Backspace") {- sideElement = selectElements[0].previousElementSibling;+ sideElement = getPreviousBlockSibling(selectElements[0]);if (!sideElement) {sideIsNext = true;sideElement = selectElements[selectElements.length - 1].nextElementSibling;@@ -54,7 +54,7 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rangsideIsNext = true;if (!sideElement) {sideIsNext = false;- sideElement = selectElements[0].previousElementSibling;+ sideElement = getPreviousBlockSibling(selectElements[0]);}}let listElement: Element;@@ -235,6 +235,14 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang// 超级块删除子块后剩余多个子块时,刷新拖拽手柄(被删块两侧手柄需移除/重建)if (topParentElement && topParentElement.getAttribute("data-type") === "NodeSuperBlock") {refreshSbResize(topParentElement);+ const widthChanges = rebalanceSbWidth(topParentElement);+ widthChanges.forEach(change => {+ const targetEl = topParentElement.querySelector(`[data-node-id="${change.id}"]`);+ if (targetEl) {+ deletes.push({action: "update", id: change.id, data: targetEl.outerHTML});+ inserts.push({action: "update", id: change.id, data: change.oldHTML});+ }+ });}transaction(protyle, deletes, inserts.reverse());}@@ -599,6 +607,15 @@ export const removeBlock = async (protyle: IProtyle, blockElement: Element, rang} else {if (parentElement && parentElement.getAttribute("data-type") === "NodeSuperBlock") {refreshSbResize(parentElement);+ // 删除子块后重新分配剩余块宽度并持久化+ const widthChanges = rebalanceSbWidth(parentElement);+ widthChanges.forEach(change => {+ const targetEl = parentElement.querySelector(`[data-node-id="${change.id}"]`);+ if (targetEl) {+ doOperations.push({action: "update", id: change.id, data: targetEl.outerHTML});+ undoOperations.push({action: "update", id: change.id, data: change.oldHTML});+ }+ });}transaction(protyle, doOperations, undoOperations);}diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 2db8d7ce83..4a68651dab 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -162,6 +162,14 @@ const promiseTransaction = (options: {}}});+ // 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)+ const originSbs: Element[] = [];+ updateElements.forEach(item => {+ const sb = item.closest('[data-type="NodeSuperBlock"]');+ if (sb && !originSbs.includes(sb)) {+ originSbs.push(sb);+ }+ });let hasFind = false;if (operation.previousID && updateElements.length > 0) {Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => {@@ -193,6 +201,8 @@ const promiseTransaction = (options: {removeTopElement(item, protyle);}});+ // 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获)+ refreshSbs(...originSbs);}// 更新嵌入块protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => {@@ -201,15 +211,10 @@ const promiseTransaction = (options: {}});// 移动块(含撤销移动)后刷新相关超级块的拖拽手柄,避免手柄残留/缺失- [operation.id, operation.parentID, operation.previousID].forEach(blockId => {- if (blockId) {- const el = protyle.wysiwyg.element.querySelector(`[data-node-id="${blockId}"]`);- const sbAncestor = el?.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- }- });+ const moveEls = [operation.id, operation.parentID, operation.previousID]+ .map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)+ .filter(Boolean) as Element[];+ refreshSbs(...moveEls);return;}if (operation.action === "insert") {@@ -265,10 +270,7 @@ const promiseTransaction = (options: {});// 插入块后刷新所在超级块的拖拽手柄(本地新块已在 DOM 跳过插入时也需刷新)const insertedEl = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.id}"]`);- const insertedSb = insertedEl?.closest('[data-type="NodeSuperBlock"]');- if (insertedSb) {- refreshSbResize(insertedSb);- }+ refreshSbs(insertedEl);return;}if (operation.action === "setAttrs") {@@ -332,6 +334,20 @@ const promiseTransaction = (options: {});};+// 刷新一组块元素所在超级块的拖拽手柄(自动去重,跳过已脱离 DOM 的)+const refreshSbs = (...elements: (Element | undefined | null)[]) => {+ const sbs = new Set<Element>();+ elements.forEach(el => {+ if (el) {+ const sb = el.closest('[data-type="NodeSuperBlock"]');+ if (sb && sb.parentElement) {+ sbs.add(sb);+ }+ }+ });+ sbs.forEach(sb => refreshSbResize(sb));+};+const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, isUndo: boolean) => {if (isUndo && updateElements[0]) {focusSideBlock(updateElements[0]);@@ -361,12 +377,8 @@ const deleteBlock = (updateElements: Element[], id: string, protyle: IProtyle, iblockRender(protyle, item);}});- // 删除块后刷新所在超级块的拖拽手柄(被删块两侧的手柄需移除/重建)- sbParents.forEach(sb => {- if (sb.parentElement && getSbChildBlockCount(sb) > 1) {- refreshSbResize(sb);- }- });+ // 删除块后刷新所在超级块的拖拽手柄(被删块两侧的手柄需移除/重建,即使只剩 0/1 块也清残留)+ refreshSbs(...sbParents);};const updateBlock = (updateElements: Element[], protyle: IProtyle, operation: IOperation, isUndo: boolean) => {@@ -453,12 +465,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndavRender(protyle.wysiwyg.element, protyle);blockRender(protyle, protyle.wysiwyg.element);// 展开标题插入的块可能落在超级块内,刷新手柄避免与既有手柄重复/错位- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {- const sbAncestor = item.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- });+ refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));}return;}@@ -490,12 +497,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}});// 折叠移除子块后,刷新折叠标题所在超级块的拖拽手柄(子块数变化)- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {- const sbAncestor = item.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- });+ refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));if (protyle.wysiwyg.element.childElementCount === 0) {zoomOut({protyle,@@ -747,6 +749,15 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}}let hasFind = false;+ // 移动前记录源块所在的超级块,移动后刷新其拖拽手柄(移出后手柄需清理)+ // https://github.com/siyuan-note/siyuan/issues/9521+ const originSbs: Element[] = [];+ updateElements.forEach(item => {+ const sb = item.closest('[data-type="NodeSuperBlock"]');+ if (sb && !originSbs.includes(sb)) {+ originSbs.push(sb);+ }+ });if (operation.previousID && updateElements.length > 0) {const previousElement = protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`);if (previousElement.length === 0 && protyle.options.backlinkData && isUndo && getSelection().rangeCount > 0) {@@ -824,15 +835,13 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd}});// 移动块(含重做/同步)后刷新相关超级块的拖拽手柄- [operation.id, operation.parentID, operation.previousID].forEach(blockId => {- if (blockId) {- const el = protyle.wysiwyg.element.querySelector(`[data-node-id="${blockId}"]`);- const sbAncestor = el?.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- }- });+ const moveEls = [operation.id, operation.parentID, operation.previousID]+ .map(id => id ? protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) : null)+ .filter(Boolean) as Element[];+ refreshSbs(...moveEls);+ // 块移出后刷新源超级块的手柄(originSb 在元素被移除前捕获,仅含移出侧的超级块)+ // https://github.com/siyuan-note/siyuan/issues/9521+ refreshSbs(...originSbs);return;}if (operation.action === "insert") {@@ -931,10 +940,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUndavRender(item, protyle);blockRender(protyle, item);// 插入块后刷新所在超级块的拖拽手柄(撤销/重做/同步)- const insertSb = item.closest('[data-type="NodeSuperBlock"]');- if (insertSb) {- refreshSbResize(insertSb);- }+ refreshSbs(item);const wbrElement = item.querySelector("wbr");if (isUndo) {if (operation.context?.setRange === "true") {@@ -1116,13 +1122,13 @@ export const turnsIntoOneTransaction = async (options: {});// 子块移入完成后刷新超级块拖拽手柄if (parentElement.classList.contains("sb")) {- refreshSbResize(parentElement);- } else if (parentElement.parentElement && parentElement.parentElement.classList.contains("sb")) {+ refreshSbs(parentElement);+ } else if (parentElement.parentElement?.classList.contains("sb")) {// 引述/列表/标注嵌入超级块时刷新父超级块- refreshSbResize(parentElement.parentElement);+ refreshSbs(parentElement.parentElement);}if ((["Blocks2Blockquote", "Blocks2Callout"].includes(options.type) || options.type.endsWith("Ls")) &&- parentElement.parentElement.classList.contains("sb") && getSbChildBlockCount(parentElement.parentElement) === 1) {+ parentElement.parentElement?.classList.contains("sb") && getSbChildBlockCount(parentElement.parentElement) === 1) {const cancelOperations = await cancelSB(options.protyle, parentElement.parentElement);doOperations.push(...cancelOperations.doOperations);undoOperations.splice(0, 0, ...cancelOperations.undoOperations);@@ -1498,12 +1504,7 @@ const processFold = (operation: IOperation, protyle: IProtyle) => {avRender(protyle.wysiwyg.element, protyle);blockRender(protyle, protyle.wysiwyg.element);// 展开标题插入的块可能落在超级块内,刷新手柄避免与既有手柄重复/错位- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {- const sbAncestor = item.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- });+ refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));if (operation.context?.focusId) {const focusElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${operation.context.focusId}"]`);focusBlock(focusElement);@@ -1522,12 +1523,7 @@ const processFold = (operation: IOperation, protyle: IProtyle) => {}});// 折叠移除子块后,刷新折叠标题所在超级块的拖拽手柄(子块数变化)- protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {- const sbAncestor = item.closest('[data-type="NodeSuperBlock"]');- if (sbAncestor) {- refreshSbResize(sbAncestor);- }- });+ refreshSbs(...Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)));// 折叠标题后未触发动态加载 https://github.com/siyuan-note/siyuan/issues/4168if (protyle.wysiwyg.element.lastElementChild.getAttribute("data-eof") !== "2" &&!protyle.scroll.element.classList.contains("fn__none") &&