Skip to content

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

:sparkles: Support wheel scrolling while dragging editor blocks https://github.com/siyuan-note/siyuan/issues/10096

Daniel7abafe4c62db
diff --git a/app/electron/main.js b/app/electron/main.js
index 65189caa24..ee454d5226 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -92,6 +92,250 @@ let workspaces = []; // workspaceDir, id, port, webContentsId, browserWindow, tr
const windowKernelTargets = new Map();
const initializedWindowIds = new Set();
const pendingRemoteOpenURLs = [];
+const blockDragSessions = new Map();
+const blockDragWindowFocusOrder = new Map();
+let blockDragWindowFocusSequence = 0;
+
+const getBlockDragSessionKey = (sourceWebContentsId, dragId) => {
+ return sourceWebContentsId + ":" + dragId;
+};
+
+const getBlockDragWindow = (webContentsId) => {
+ return BrowserWindow.getAllWindows().find((item) => !item.isDestroyed() &&
+ !item.webContents.isDestroyed() && item.webContents.id === webContentsId);
+};
+
+const sendBlockDragMessage = (webContentsId, data) => {
+ const targetWindow = getBlockDragWindow(webContentsId);
+ if (!targetWindow) {
+ return false;
+ }
+ try {
+ targetWindow.webContents.send("siyuan-block-drag", data);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const normalizeBlockDragPoint = (point) => {
+ if (!point || typeof point !== "object" || !Number.isFinite(point.screenX) ||
+ !Number.isFinite(point.screenY)) {
+ return;
+ }
+ return {
+ ...point,
+ screenX: point.screenX,
+ screenY: point.screenY,
+ clientX: Number.isFinite(point.clientX) ? point.clientX : 0,
+ clientY: Number.isFinite(point.clientY) ? point.clientY : 0,
+ altKey: !!point.altKey,
+ ctrlKey: !!point.ctrlKey,
+ metaKey: !!point.metaKey,
+ sequence: Number.isSafeInteger(point.sequence) ? point.sequence : 0,
+ shiftKey: !!point.shiftKey,
+ };
+};
+
+const normalizeBlockDragPayload = (payload) => {
+ if (!payload || typeof payload !== "object" || !Array.isArray(payload.items) ||
+ !payload.items.every((item) => item && typeof item.type === "string" && typeof item.data === "string")) {
+ return;
+ }
+ const normalizedPayload = {
+ items: payload.items.map((item) => ({type: item.type, data: item.data})),
+ dragTitle: typeof payload.dragTitle === "string" ? payload.dragTitle : "",
+ };
+ if (typeof payload.effectAllowed === "string") {
+ normalizedPayload.effectAllowed = payload.effectAllowed;
+ }
+ return normalizedPayload;
+};
+
+const isPointInBounds = (point, bounds) => {
+ return point.screenX >= bounds.x && point.screenX < bounds.x + bounds.width &&
+ point.screenY >= bounds.y && point.screenY < bounds.y + bounds.height;
+};
+
+const getBlockDragTarget = (dragSession) => {
+ if (!dragSession.point) {
+ return;
+ }
+ const sourceWindow = getBlockDragWindow(dragSession.sourceWebContentsId);
+ if (!sourceWindow) {
+ return;
+ }
+ const sourceContainsPoint = isPointInBounds(dragSession.point, sourceWindow.getBounds());
+ const candidates = BrowserWindow.getAllWindows().filter((item) => {
+ if (item.isDestroyed() || item.webContents.isDestroyed() ||
+ item.webContents.id === dragSession.sourceWebContentsId ||
+ !initializedWindowIds.has(item.webContents.id) || !item.isVisible() || item.isMinimized()) {
+ return false;
+ }
+ const kernelTarget = windowKernelTargets.get(item.webContents.id);
+ return kernelTarget?.origin === dragSession.kernelOrigin && isPointInBounds(dragSession.point,
+ item.getContentBounds());
+ });
+ candidates.sort((first, second) => {
+ const alwaysOnTopDiff = Number(second.isAlwaysOnTop()) - Number(first.isAlwaysOnTop());
+ if (alwaysOnTopDiff !== 0) {
+ return alwaysOnTopDiff;
+ }
+ return (blockDragWindowFocusOrder.get(second.webContents.id) || 0) -
+ (blockDragWindowFocusOrder.get(first.webContents.id) || 0);
+ });
+ const targetWindow = candidates[0];
+ if (!targetWindow || (sourceContainsPoint &&
+ (sourceWindow.isAlwaysOnTop() || !targetWindow.isAlwaysOnTop()))) {
+ // 普通目标窗口位于源窗口后方时,不应让指针穿透源窗口。
+ return;
+ }
+ const contentBounds = targetWindow.getContentBounds();
+ const zoomFactor = targetWindow.webContents.getZoomFactor() || 1;
+ return {
+ webContentsId: targetWindow.webContents.id,
+ point: {
+ ...dragSession.point,
+ clientX: (dragSession.point.screenX - contentBounds.x) / zoomFactor,
+ clientY: (dragSession.point.screenY - contentBounds.y) / zoomFactor,
+ },
+ };
+};
+
+const leaveBlockDragTarget = (dragSession) => {
+ if (!dragSession.targetWebContentsId) {
+ return;
+ }
+ sendBlockDragMessage(dragSession.targetWebContentsId, {
+ phase: "leave",
+ dragId: dragSession.dragId,
+ });
+ dragSession.targetWebContentsId = undefined;
+};
+
+const sendBlockDragRoute = (dragSession, remote, sequence = dragSession.point?.sequence) => {
+ sendBlockDragMessage(dragSession.sourceWebContentsId, {
+ phase: "route",
+ dragId: dragSession.dragId,
+ remote,
+ sequence,
+ });
+};
+
+const routeBlockDragMove = (dragSession, notifySource = true) => {
+ const target = getBlockDragTarget(dragSession);
+ if (!target) {
+ leaveBlockDragTarget(dragSession);
+ if (notifySource) {
+ sendBlockDragRoute(dragSession, false);
+ }
+ return;
+ }
+ if (!dragSession.payload) {
+ if (!dragSession.payloadRequested && sendBlockDragMessage(dragSession.sourceWebContentsId, {
+ phase: "request",
+ dragId: dragSession.dragId,
+ })) {
+ dragSession.payloadRequested = true;
+ }
+ if (notifySource) {
+ sendBlockDragRoute(dragSession, true);
+ }
+ return {target, ready: false};
+ }
+ if (dragSession.targetWebContentsId !== target.webContentsId) {
+ leaveBlockDragTarget(dragSession);
+ dragSession.targetWebContentsId = target.webContentsId;
+ if (!sendBlockDragMessage(target.webContentsId, {
+ phase: "enter",
+ dragId: dragSession.dragId,
+ point: target.point,
+ payload: dragSession.payload,
+ })) {
+ dragSession.targetWebContentsId = undefined;
+ if (notifySource) {
+ sendBlockDragRoute(dragSession, false);
+ }
+ return;
+ }
+ }
+ if (!sendBlockDragMessage(target.webContentsId, {
+ phase: "move",
+ dragId: dragSession.dragId,
+ point: target.point,
+ })) {
+ dragSession.targetWebContentsId = undefined;
+ if (notifySource) {
+ sendBlockDragRoute(dragSession, false);
+ }
+ return;
+ }
+ if (notifySource) {
+ sendBlockDragRoute(dragSession, true);
+ }
+ return {target, ready: true};
+};
+
+const dispatchBlockDragDrop = (dragSession) => {
+ const dragRoute = routeBlockDragMove(dragSession, false);
+ if (dragRoute?.target && !dragRoute.ready) {
+ dragSession.waitingForDropPayload = true;
+ return;
+ }
+ dragSession.waitingForDropPayload = false;
+ if (dragRoute?.ready && dragRoute.target.webContentsId === dragSession.targetWebContentsId &&
+ dragSession.payload) {
+ if (sendBlockDragMessage(dragRoute.target.webContentsId, {
+ phase: "drop",
+ dragId: dragSession.dragId,
+ point: dragRoute.target.point,
+ payload: dragSession.payload,
+ sequence: dragSession.pendingDropSequence,
+ sourceWebContentsId: dragSession.sourceWebContentsId,
+ })) {
+ dragSession.dropSent = true;
+ return;
+ }
+ leaveBlockDragTarget(dragSession);
+ }
+ const dropSequence = dragSession.pendingDropSequence;
+ dragSession.pendingDropSequence = undefined;
+ sendBlockDragRoute(dragSession, false, dropSequence);
+};
+
+const finishBlockDragSession = (sessionKey, dragSession) => {
+ if (dragSession.targetWebContentsId) {
+ sendBlockDragMessage(dragSession.targetWebContentsId, {
+ phase: "end",
+ dragId: dragSession.dragId,
+ });
+ }
+ blockDragSessions.delete(sessionKey);
+};
+
+const cleanupBlockDragSessions = (webContentsId) => {
+ for (const [sessionKey, dragSession] of blockDragSessions) {
+ if (dragSession.sourceWebContentsId === webContentsId) {
+ finishBlockDragSession(sessionKey, dragSession);
+ } else if (dragSession.targetWebContentsId === webContentsId) {
+ // 目标渲染上下文失效后保留源窗口的拖拽会话,以便指针继续进入其他窗口。
+ dragSession.targetWebContentsId = undefined;
+ if (dragSession.dropping) {
+ if (dragSession.pendingDropSequence !== undefined) {
+ sendBlockDragRoute(dragSession, !!dragSession.dropSent, dragSession.pendingDropSequence);
+ dragSession.pendingDropSequence = undefined;
+ }
+ } else {
+ routeBlockDragMove(dragSession);
+ }
+ }
+ }
+};
+
+const cleanupBlockDragWindow = (webContentsId) => {
+ blockDragWindowFocusOrder.delete(webContentsId);
+ cleanupBlockDragSessions(webContentsId);
+};
const flushPendingRemoteOpenURLs = (window) => {
if (!window || window.isDestroyed()) {
@@ -898,6 +1142,10 @@ const getKernelTarget = (target = kernelPort) => {
const rememberWindowKernelTarget = (window, target) => {
const webContentsId = window.webContents.id;
windowKernelTargets.set(webContentsId, target);
+ blockDragWindowFocusOrder.set(webContentsId, ++blockDragWindowFocusSequence);
+ window.on("focus", () => {
+ blockDragWindowFocusOrder.set(webContentsId, ++blockDragWindowFocusSequence);
+ });
if (target.mode === "remote") {
window.webContents.on("will-frame-navigate", (event) => {
if (shouldBlockRemoteFrameNavigation({isMainFrame: event.isMainFrame})) {
@@ -913,11 +1161,17 @@ const rememberWindowKernelTarget = (window, target) => {
window.webContents.on("did-start-navigation", (details) => {
if (details.isMainFrame && !details.isSameDocument) {
initializedWindowIds.delete(webContentsId);
+ cleanupBlockDragSessions(webContentsId);
}
});
+ window.webContents.on("render-process-gone", () => {
+ initializedWindowIds.delete(webContentsId);
+ cleanupBlockDragSessions(webContentsId);
+ });
window.webContents.once("destroyed", () => {
initializedWindowIds.delete(webContentsId);
windowKernelTargets.delete(webContentsId);
+ cleanupBlockDragWindow(webContentsId);
});
};
@@ -2384,6 +2638,7 @@ app.whenReady().then(() => {
// 渲染进程崩溃监听,只有工作空间主窗口的非预期崩溃才会触发安全模式。
app.on("render-process-gone", (event, webContents, details) => {
writeLog("Render process gone [reason=" + details.reason + ", exitCode=" + details.exitCode + "]");
+ cleanupBlockDragSessions(webContents.id);
if (updateInstallPromise) {
writeLog("ignore renderer exit during update [webContentsId=" + webContents.id + "]");
return;
@@ -3335,6 +3590,92 @@ app.whenReady().then(() => {
item.webContents.send("siyuan-send-windows", data);
});
});
+ ipcMain.on("siyuan-block-drag", (event, data) => {
+ if (!data || typeof data !== "object" || typeof data.dragId !== "string" || !data.dragId ||
+ !["begin", "move", "payload", "drop", "drop-ack", "end"].includes(data.phase)) {
+ return;
+ }
+ if (data.phase === "drop-ack") {
+ if (!Number.isSafeInteger(data.sourceWebContentsId) || !Number.isSafeInteger(data.sequence)) {
+ return;
+ }
+ const sourceSessionKey = getBlockDragSessionKey(data.sourceWebContentsId, data.dragId);
+ const sourceDragSession = blockDragSessions.get(sourceSessionKey);
+ if (!sourceDragSession || sourceDragSession.targetWebContentsId !== event.sender.id ||
+ sourceDragSession.pendingDropSequence !== data.sequence) {
+ return;
+ }
+ sourceDragSession.pendingDropSequence = undefined;
+ sourceDragSession.waitingForDropPayload = false;
+ sendBlockDragRoute(sourceDragSession, true, data.sequence);
+ return;
+ }
+ const sourceWebContentsId = event.sender.id;
+ const sessionKey = getBlockDragSessionKey(sourceWebContentsId, data.dragId);
+ if (data.phase === "begin") {
+ const kernelTarget = windowKernelTargets.get(sourceWebContentsId);
+ if (!kernelTarget || !initializedWindowIds.has(sourceWebContentsId)) {
+ return;
+ }
+ for (const [activeSessionKey, activeSession] of blockDragSessions) {
+ if (activeSession.sourceWebContentsId === sourceWebContentsId) {
+ finishBlockDragSession(activeSessionKey, activeSession);
+ }
+ }
+ const point = normalizeBlockDragPoint(data.point);
+ const payload = normalizeBlockDragPayload(data.payload);
+ blockDragSessions.set(sessionKey, {
+ dragId: data.dragId,
+ sourceWebContentsId,
+ kernelOrigin: kernelTarget.origin,
+ point,
+ payload,
+ payloadRequested: false,
+ targetWebContentsId: undefined,
+ });
+ return;
+ }
+ const dragSession = blockDragSessions.get(sessionKey);
+ if (!dragSession) {
+ return;
+ }
+ if (dragSession.dropping && data.phase !== "end" &&
+ !(data.phase === "payload" && dragSession.waitingForDropPayload)) {
+ return;
+ }
+ const point = normalizeBlockDragPoint(data.point);
+ if (point) {
+ dragSession.point = point;
+ }
+ if (data.payload !== undefined) {
+ const payload = normalizeBlockDragPayload(data.payload);
+ if (payload) {
+ dragSession.payload = payload;
+ dragSession.payloadRequested = false;
+ }
+ }
+ switch (data.phase) {
+ case "move":
+ routeBlockDragMove(dragSession);
+ break;
+ case "payload":
+ if (dragSession.dropping) {
+ dispatchBlockDragDrop(dragSession);
+ } else {
+ routeBlockDragMove(dragSession);
+ }
+ break;
+ case "drop": {
+ dragSession.dropping = true;
+ dragSession.pendingDropSequence = dragSession.point?.sequence;
+ dispatchBlockDragDrop(dragSession);
+ break;
+ }
+ case "end":
+ finishBlockDragSession(sessionKey, dragSession);
+ break;
+ }
+ });
ipcMain.on("siyuan-auto-launch", (event, data) => {
const kernelTarget = getWindowKernelTarget(event.sender.id);
const args = [];
diff --git a/app/src/constants.ts b/app/src/constants.ts
index 8d0940a989..9bee67d933 100644
--- a/app/src/constants.ts
+++ b/app/src/constants.ts
@@ -46,6 +46,7 @@ export abstract class Constants {
public static readonly SIYUAN_INIT: string = "siyuan-init";
public static readonly SIYUAN_READY_TO_SHOW: string = "siyuan-ready-to-show";
public static readonly SIYUAN_SEND_WINDOWS: string = "siyuan-send-windows"; // 主窗口和各新窗口之间的通信
+ public static readonly SIYUAN_BLOCK_DRAG: string = "siyuan-block-drag"; // 跨窗口块拖拽通信
public static readonly SIYUAN_AUTO_LAUNCH: string = "siyuan-auto-launch";
public static readonly SIYUAN_OPEN_WORKSPACE: string = "siyuan-open-workspace";
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 5b266470b8..ea60c3cc75 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -312,6 +312,7 @@ export class Gutter {
setDragTipGhost(ghostElement, 0, 0);
event.dataTransfer.setDragImage(ghostElement, 0, 0);
if (window.siyuan.touchDragActive) {
+ // 合成拖拽保留 DOM ghost 供指针跟随。
window.siyuan.touchDragGhost = ghostElement;
} else {
setTimeout(() => {
@@ -352,7 +353,11 @@ export class Gutter {
once: true,
signal: cleanupController.signal,
});
- window.addEventListener("blur", restoreGutter, {once: true, signal: cleanupController.signal});
+ window.addEventListener("blur", () => {
+ if (!window.siyuan.touchDragActive) {
+ restoreGutter();
+ }
+ }, {once: true, signal: cleanupController.signal});
setTimeout(() => {
if (isGutterDragging && dragCleanupController === cleanupController) {
this.element.classList.add("protyle-gutters--dragging");
diff --git a/app/src/protyle/scroll/index.ts b/app/src/protyle/scroll/index.ts
index bbb5c8c8aa..a781eeea4a 100644
--- a/app/src/protyle/scroll/index.ts
+++ b/app/src/protyle/scroll/index.ts
@@ -17,6 +17,7 @@ import {
} from "./dynamicLoadState";
import {saveScroll} from "./saveScroll";
import {getScrollIndexFromPointer} from "./slider";
+import {refreshSyntheticDragTarget} from "../../util/touchDragBridge";
export class Scroll {
public element: HTMLElement;
@@ -243,6 +244,7 @@ export class Scroll {
this.dynamicLoadFinish = undefined;
protyle.wysiwyg.element.removeAttribute("data-top");
onFinish?.(success);
+ refreshSyntheticDragTarget();
}
private async loadUntilBoundary(protyle: IProtyle, rootID: string, mode: TDynamicLoadMode, size: number) {
diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.ts
index e459c0ae80..6e29fe4074 100644
--- a/app/src/protyle/util/editorCommonEvent.ts
+++ b/app/src/protyle/util/editorCommonEvent.ts
@@ -3088,11 +3088,16 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {
hideDragTip();
}
});
- editorElement.addEventListener("dragenter", (event) => {
+ editorElement.addEventListener("dragenter", (event: DragEvent) => {
event.preventDefault();
+ if (!event.isTrusted) {
+ // 合成拖拽会在动态加载后重新命中节点,不依赖已被移除节点的 dragleave 来平衡计数。
+ counter = 0;
+ }
counter++;
});
editorElement.addEventListener("dragend", () => {
+ counter = 0;
if (window.siyuan.dragElement) {
window.siyuan.dragElement.style.opacity = "";
window.siyuan.dragElement = undefined;
diff --git a/app/src/util/touchDragBridge.ts b/app/src/util/touchDragBridge.ts
index 55596c30b4..e673ac65e7 100644
--- a/app/src/util/touchDragBridge.ts
+++ b/app/src/util/touchDragBridge.ts
@@ -1,8 +1,12 @@
import {stopScrollAnimation} from "../boot/globalEvent/dragover";
import {Constants} from "../constants";
import {isInAndroid} from "../plugin/platformUtils";
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
import {
completeDrag,
+ createDragRefreshQueue,
dispatchWithNativeDragEnabled,
restoreNativeDrag,
shouldSuppressNativeContextMenu,
@@ -58,26 +62,87 @@ const shouldYieldToScroll = (gate: LongPressGate, clientX: number, clientY: numb
interface DragPoint {
clientX: number;
clientY: number;
+ screenX?: number;
+ screenY?: number;
+ altKey?: boolean;
+ ctrlKey?: boolean;
+ metaKey?: boolean;
+ sequence?: number;
+ shiftKey?: boolean;
+}
+
+interface SerializedDataTransferItem {
+ type: string;
+ data: string;
+}
+
+interface BlockDragRelayPayload {
+ items: SerializedDataTransferItem[];
+ dragTitle: string;
+ effectAllowed: DataTransfer["effectAllowed"];
+}
+
+interface BlockDragRelayMessage {
+ phase: "request" | "route" | "enter" | "move" | "leave" | "drop" | "drop-ack" | "end";
+ dragId: string;
+ point?: DragPoint;
+ payload?: BlockDragRelayPayload;
+ remote?: boolean;
+ sequence?: number;
+ sourceWebContentsId?: number;
}
interface DragState {
dataTransfer: DataTransfer | null;
+ dragEnteredEditor?: HTMLElement;
ghostElement: HTMLElement | null;
+ idleTimeout?: number;
isDragging: boolean;
draggableElement: HTMLElement;
inputType: "touch" | "pointer";
pointerId?: number;
+ lastPoint?: DragPoint;
+ relayId?: string;
+ relayRemote?: boolean;
+ relaySequence?: number;
+ pendingDropPoint?: DragPoint;
+ pendingDropSequence?: number;
+ pendingDropTimeout?: number;
restoreDraggable?: boolean;
}
+interface ForeignDragState {
+ dataTransfer: DataTransfer;
+ dragId: string;
+ dropped: boolean;
+ idleTimeout?: number;
+ lastDragOverElement: Element | null;
+ lastPoint?: DragPoint;
+}
+
let dragState: (DragState & LongPressGate) | null = null;
let lastDragOverElement: Element | null = null;
+let foreignDragState: ForeignDragState | null = null;
+let dragRelaySequence = 0;
+const DRAG_IDLE_TIMEOUT = 30000;
let manualState: (LongPressGate) | null = null;
// 最近一次 pointerdown 的输入源,pointerType 是唯一可靠区分 mouse/touch/pen 的字段
let lastPointerType: string = "";
+const copyDragPoint = (point: DragPoint): DragPoint => ({
+ clientX: point.clientX,
+ clientY: point.clientY,
+ screenX: point.screenX,
+ screenY: point.screenY,
+ altKey: !!point.altKey,
+ ctrlKey: !!point.ctrlKey,
+ metaKey: !!point.metaKey,
+ sequence: point.sequence,
+ shiftKey: !!point.shiftKey,
+});
+
// 判定当前输入源是否为鼠标:部分平板 WebView 会把鼠标合成成 touch 事件
// pointerType === "mouse" 且接触面积为 0(radiusX/radiusY 为 0)时判定为鼠标
// radiusX > 0 单向可信:非零一定是真手指,据此否决鼠标判断,避免把手指误判成鼠标跳过长按
@@ -270,6 +335,12 @@ const createDragState = (draggableElement: HTMLElement, point: DragPoint, inputT
let suppressMouseClick = false;
+const isDesktopBlockGutter = (draggable: HTMLElement) => {
+ const gutterElement = draggable.closest(".protyle-gutters");
+ const buttonElement = draggable.parentElement;
+ return !!gutterElement && buttonElement?.tagName === "BUTTON" && !buttonElement.dataset.rowId;
+};
+
const handlePointerDown = (event: PointerEvent) => {
if (event.pointerType !== "mouse" || event.button !== 0 || dragState || manualState ||
!(event.target instanceof Element) ||
@@ -278,13 +349,18 @@ const handlePointerDown = (event: PointerEvent) => {
}
const draggable = getDraggableAncestor(event.target);
- if (!draggable) {
+ if (!draggable || (!isInAndroid() && !isDesktopBlockGutter(draggable))) {
return;
}
dragState = createDragState(draggable, event, "pointer", true, event.pointerId);
- // Android WebView 会在原生 dragstart 后取消 Pointer 流,临时关闭 draggable 以保留 pointermove 和 pointerup。
+ // 原生 dragstart 会取消 Pointer 流,临时关闭 draggable 以保留 pointermove 和 pointerup。
suspendNativeDrag(dragState);
+ try {
+ draggable.setPointerCapture(event.pointerId);
+ } catch {
+ // 指针可能已由系统取消,此时后续 Pointer 事件会负责清理。
+ }
};
const handlePointerMove = (event: PointerEvent) => {
@@ -292,7 +368,11 @@ const handlePointerMove = (event: PointerEvent) => {
return;
}
if ((event.buttons & 1) === 0) {
- completeBridgeDrag(event, true);
+ if (dragState.relayId) {
+ requestBlockDragDrop(event);
+ } else {
+ completeBridgeDrag(event, true);
+ }
return;
}
if (!dragState.isDragging) {
@@ -315,7 +395,11 @@ const handlePointerUp = (event: PointerEvent) => {
if (isDragging) {
event.preventDefault();
}
- completeBridgeDrag(event, false);
+ if (isDragging && dragState.relayId) {
+ requestBlockDragDrop(event);
+ } else {
+ completeBridgeDrag(event, false);
+ }
if (isDragging) {
suppressMouseClick = true;
setTimeout(() => {
@@ -338,15 +422,15 @@ const handleMouseClick = (event: MouseEvent) => {
}
};
-const getElementUnderPoint = (clientX: number, clientY: number): Element | null => {
- if (dragState?.ghostElement) {
- dragState.ghostElement.style.display = "none";
+const getElementUnderPoint = (point: DragPoint, ghostElement?: HTMLElement | null): Element | null => {
+ if (ghostElement) {
+ ghostElement.style.display = "none";
}
- const el = document.elementFromPoint(clientX, clientY);
- if (dragState?.ghostElement) {
- dragState.ghostElement.style.display = "";
+ const element = document.elementFromPoint(point.clientX, point.clientY);
+ if (ghostElement) {
+ ghostElement.style.display = "";
}
- return el;
+ return element;
};
const positionGhost = (clientX: number, clientY: number) => {
@@ -363,24 +447,123 @@ const clearDragoverClasses = () => {
});
};
-const startBridgeDrag = (touch: DragPoint) => {
+const createBridgeDragEvent = (type: string, point: DragPoint, dataTransfer: DataTransfer, bubbles = true) => {
+ return new DragEvent(type, {
+ bubbles,
+ cancelable: true,
+ clientX: point.clientX,
+ clientY: point.clientY,
+ screenX: point.screenX || 0,
+ screenY: point.screenY || 0,
+ altKey: !!point.altKey,
+ ctrlKey: !!point.ctrlKey,
+ metaKey: !!point.metaKey,
+ shiftKey: !!point.shiftKey,
+ dataTransfer,
+ view: window,
+ });
+};
+
+const dispatchBridgeDragOver = (dataTransfer: DataTransfer, point: DragPoint,
+ previousElement: Element | null, ghostElement?: HTMLElement | null) => {
+ const elementUnderPoint = getElementUnderPoint(point, ghostElement);
+
+ // 仅在目标元素的父容器变化时派发 dragenter 和 dragleave,避免同级元素之间移动时闪烁。
+ if (elementUnderPoint !== previousElement) {
+ const previousContainer = previousElement?.parentElement;
+ const currentContainer = elementUnderPoint?.parentElement;
+ if (previousContainer !== currentContainer || (!previousContainer && currentContainer) ||
+ (previousContainer && !currentContainer)) {
+ previousElement?.dispatchEvent(createBridgeDragEvent("dragleave", point, dataTransfer));
+ elementUnderPoint?.dispatchEvent(createBridgeDragEvent("dragenter", point, dataTransfer));
+ }
+ }
+
+ elementUnderPoint?.dispatchEvent(createBridgeDragEvent("dragover", point, dataTransfer));
+ return elementUnderPoint;
+};
+
+const serializeDataTransfer = (dataTransfer: DataTransfer): BlockDragRelayPayload => {
+ const items = Array.from(dataTransfer.types)
+ .filter(type => type === Constants.SIYUAN_DROP_BLOCK || type.startsWith(Constants.SIYUAN_DROP_GUTTER))
+ .map(type => ({
+ type,
+ data: dataTransfer.getData(type),
+ }));
+ return {
+ items,
+ dragTitle: window.siyuan.dragTitle || "",
+ effectAllowed: dataTransfer.effectAllowed,
+ };
+};
+
+const sendBlockDragRelay = (data: object) => {
+ /// #if !BROWSER
+ ipcRenderer.send(Constants.SIYUAN_BLOCK_DRAG, data);
+ /// #endif
+};
+
+const isClearlyInsideWindow = (point: DragPoint) => point.clientX > 1 && point.clientY > 1 &&
+ point.clientX < window.innerWidth - 1 && point.clientY < window.innerHeight - 1;
+
+const sendBlockDragRelayMove = (point: DragPoint) => {
+ if (!dragState?.relayId || dragState.pendingDropPoint) {
+ return;
+ }
+ if (isClearlyInsideWindow(point)) {
+ dragState.relayRemote = false;
+ }
+ dragState.relaySequence = (dragState.relaySequence || 0) + 1;
+ const relayPoint = copyDragPoint(point);
+ relayPoint.sequence = dragState.relaySequence;
+ sendBlockDragRelay({
+ phase: "move",
+ dragId: dragState.relayId,
+ point: relayPoint,
+ });
+};
+
+const requestBlockDragDrop = (point: DragPoint) => {
+ if (!dragState?.relayId || !dragState.dataTransfer || dragState.pendingDropPoint) {
+ return;
+ }
+ dragState.relaySequence = (dragState.relaySequence || 0) + 1;
+ const relayPoint = copyDragPoint(point);
+ relayPoint.sequence = dragState.relaySequence;
+ dragState.pendingDropPoint = copyDragPoint(point);
+ dragState.pendingDropSequence = relayPoint.sequence;
+ sendBlockDragRelay({
+ phase: "drop",
+ dragId: dragState.relayId,
+ point: relayPoint,
+ });
+ dragState.pendingDropTimeout = window.setTimeout(() => {
+ if (!dragState?.pendingDropPoint || dragState.pendingDropSequence !== relayPoint.sequence) {
+ return;
+ }
+ const pendingPoint = dragState.pendingDropPoint;
+ // 主进程未确认落点时不在源窗口补发 drop,避免目标已处理但回执延迟导致重复移动。
+ completeBridgeDrag(pendingPoint, false, true);
+ }, Constants.TIMEOUT_LOAD);
+};
+
+const startBridgeDrag = (point: DragPoint) => {
+ if (!dragState) {
+ return;
+ }
const dt = new DataTransfer();
dragState.dataTransfer = dt;
dragState.isDragging = true;
+ dragState.lastPoint = copyDragPoint(point);
- const editorElement = dragState.draggableElement.closest(".protyle-wysiwyg") as HTMLElement;
+ const closestEditorElement = dragState.draggableElement.closest(".protyle-wysiwyg") as HTMLElement;
+ dragState.dragEnteredEditor = closestEditorElement ||
+ dragState.draggableElement.closest(".protyle")?.querySelector<HTMLElement>(".protyle-wysiwyg");
window.siyuan.touchDragActive = true;
window.siyuan.touchDragGhost = null;
- const dragStartEvent = new DragEvent("dragstart", {
- bubbles: true,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dt,
- view: window,
- });
+ const dragStartEvent = createBridgeDragEvent("dragstart", point, dt);
// 部分拖拽处理会在 dragstart 中再次检查 draggable 属性,派发合成事件时短暂恢复。
dispatchWithNativeDragEnabled(dragState, () => dragState.draggableElement.dispatchEvent(dragStartEvent));
@@ -389,132 +572,352 @@ const startBridgeDrag = (touch: DragPoint) => {
dragState.ghostElement.style.pointerEvents = "none";
dragState.ghostElement.style.zIndex = (++window.siyuan.zIndex).toString();
// 先定位再显示,避免拖拽影像在错误位置闪现。
- positionGhost(touch.clientX, touch.clientY);
+ positionGhost(point.clientX, point.clientY);
dragState.ghostElement.style.opacity = "0.6";
}
- if (editorElement) {
- const dragEnterEvent = new DragEvent("dragenter", {
- bubbles: false,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dt,
- view: window,
- });
- editorElement.dispatchEvent(dragEnterEvent);
+ if (closestEditorElement) {
+ closestEditorElement.dispatchEvent(createBridgeDragEvent("dragenter", point, dt, false));
}
-};
-
-const continueBridgeDrag = (touch: DragPoint) => {
- if (!dragState.isDragging) return;
- const elementUnderTouch = getElementUnderPoint(touch.clientX, touch.clientY);
-
- // 仅在目标元素的父容器变化时派发 dragenter 和 dragleave,避免同级元素之间移动时闪烁。
- if (elementUnderTouch !== lastDragOverElement) {
- const prevContainer = lastDragOverElement?.parentElement;
- const currContainer = elementUnderTouch?.parentElement;
- if (prevContainer !== currContainer || (!prevContainer && currContainer) || (prevContainer && !currContainer)) {
- if (lastDragOverElement) {
- const dragLeaveEvent = new DragEvent("dragleave", {
- bubbles: true,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dragState.dataTransfer,
- view: window,
- });
- lastDragOverElement.dispatchEvent(dragLeaveEvent);
- }
- if (elementUnderTouch) {
- const dragEnterEvent = new DragEvent("dragenter", {
- bubbles: true,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dragState.dataTransfer,
- view: window,
- });
- elementUnderTouch.dispatchEvent(dragEnterEvent);
- }
- }
- lastDragOverElement = elementUnderTouch;
+ /// #if !BROWSER
+ if (dragState.inputType === "pointer" && dt.types.includes(Constants.SIYUAN_DROP_BLOCK)) {
+ dragState.relayId = `${Date.now()}-${++dragRelaySequence}`;
+ sendBlockDragRelay({phase: "begin", dragId: dragState.relayId});
+ sendBlockDragRelayMove(point);
}
+ /// #endif
+ resetLocalDragIdleTimeout();
+};
- if (elementUnderTouch) {
- const dragOverEvent = new DragEvent("dragover", {
- bubbles: true,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dragState.dataTransfer,
- view: window,
- });
- elementUnderTouch.dispatchEvent(dragOverEvent);
+const continueBridgeDrag = (point: DragPoint, relay = true) => {
+ if (!dragState?.isDragging || !dragState.dataTransfer) {
+ return;
}
- positionGhost(touch.clientX, touch.clientY);
+ dragState.lastPoint = copyDragPoint(point);
+ resetLocalDragIdleTimeout();
+ lastDragOverElement = dispatchBridgeDragOver(
+ dragState.dataTransfer,
+ dragState.lastPoint,
+ lastDragOverElement,
+ dragState.ghostElement,
+ );
+ positionGhost(point.clientX, point.clientY);
+ if (relay) {
+ sendBlockDragRelayMove(point);
+ }
};
-const dispatchBridgeDrop = (touch: DragPoint) => {
- if (!dragState.isDragging) return;
+const dispatchBridgeDrop = (point: DragPoint) => {
+ if (!dragState?.isDragging || !dragState.dataTransfer) return;
- const elementUnderTouch = getElementUnderPoint(touch.clientX, touch.clientY);
- if (elementUnderTouch) {
- const dropEvent = new DragEvent("drop", {
- bubbles: true,
- cancelable: true,
- clientX: touch.clientX,
- clientY: touch.clientY,
- dataTransfer: dragState.dataTransfer,
- view: window,
- });
- elementUnderTouch.dispatchEvent(dropEvent);
- }
+ const elementUnderPoint = getElementUnderPoint(point, dragState.ghostElement);
+ elementUnderPoint?.dispatchEvent(createBridgeDragEvent("drop", point, dragState.dataTransfer));
};
const dispatchBridgeDragEnd = (point?: DragPoint) => {
- if (!dragState?.isDragging) return;
+ if (!dragState?.isDragging || !dragState.dataTransfer) return;
- const dragEndEvent = new DragEvent("dragend", {
- bubbles: true,
- cancelable: true,
- clientX: point?.clientX ?? dragState.startX,
- clientY: point?.clientY ?? dragState.startY,
- dataTransfer: dragState.dataTransfer,
- view: window,
- });
+ const dragEndPoint = point || dragState.lastPoint || {clientX: dragState.startX, clientY: dragState.startY};
+ const dragEndEvent = createBridgeDragEvent("dragend", dragEndPoint, dragState.dataTransfer);
+ if (dragState.dragEnteredEditor && !dragState.dragEnteredEditor.contains(dragState.draggableElement)) {
+ dragState.dragEnteredEditor.dispatchEvent(createBridgeDragEvent("dragend", dragEndPoint,
+ dragState.dataTransfer, false));
+ }
dragState.draggableElement.dispatchEvent(dragEndEvent);
};
-const completeBridgeDrag = (point: DragPoint | undefined, canceled: boolean) => {
+const completeBridgeDrag = (point: DragPoint | undefined, canceled: boolean, remoteDrop = false) => {
+ const relayId = dragState?.relayId;
+ if (dragState?.pendingDropTimeout) {
+ window.clearTimeout(dragState.pendingDropTimeout);
+ }
+ if ((canceled || remoteDrop) && dragState?.dataTransfer && dragState.lastPoint && lastDragOverElement) {
+ lastDragOverElement.dispatchEvent(createBridgeDragEvent("dragleave", dragState.lastPoint,
+ dragState.dataTransfer));
+ lastDragOverElement = null;
+ }
completeDrag(!!dragState?.isDragging, canceled, {
drop: () => {
- if (point) {
+ if (point && !remoteDrop) {
+ continueBridgeDrag(point, false);
dispatchBridgeDrop(point);
}
},
dragEnd: () => dispatchBridgeDragEnd(point),
cleanup: cleanupDrag,
});
+ if (relayId) {
+ sendBlockDragRelay({phase: "end", dragId: relayId});
+ }
};
const cleanupDrag = () => {
+ const completedState = dragState;
+ dragState = null;
stopScrollAnimation();
clearDragoverClasses();
+ dragRefreshQueue.cancel();
+ stopScrollAfterRefresh = false;
- restoreNativeDrag(dragState);
- if (dragState?.ghostElement) {
- dragState.ghostElement.remove();
+ if (completedState?.idleTimeout) {
+ window.clearTimeout(completedState.idleTimeout);
+ }
+ restoreNativeDrag(completedState);
+ if (completedState?.pointerId !== undefined) {
+ try {
+ if (completedState.draggableElement.hasPointerCapture(completedState.pointerId)) {
+ completedState.draggableElement.releasePointerCapture(completedState.pointerId);
+ }
+ } catch {
+ // Pointer 流可能已由系统取消,此时无需再次释放。
+ }
+ }
+ if (completedState?.ghostElement) {
+ completedState.ghostElement.remove();
}
window.siyuan.touchDragActive = false;
window.siyuan.touchDragGhost = null;
- dragState = null;
lastDragOverElement = null;
};
+const resetLocalDragIdleTimeout = () => {
+ const currentState = dragState;
+ if (!currentState?.isDragging) {
+ return;
+ }
+ if (currentState.idleTimeout) {
+ window.clearTimeout(currentState.idleTimeout);
+ }
+ currentState.idleTimeout = window.setTimeout(() => {
+ if (dragState === currentState) {
+ completeBridgeDrag(undefined, true);
+ }
+ }, DRAG_IDLE_TIMEOUT);
+};
+
+const createForeignDataTransfer = (payload?: BlockDragRelayPayload) => {
+ if (!payload || !Array.isArray(payload.items)) {
+ return;
+ }
+ const dataTransfer = new DataTransfer();
+ payload.items.forEach(item => {
+ if (typeof item?.type === "string" && typeof item.data === "string" &&
+ (item.type === Constants.SIYUAN_DROP_BLOCK || item.type.startsWith(Constants.SIYUAN_DROP_GUTTER))) {
+ dataTransfer.setData(item.type, item.data);
+ }
+ });
+ if (!dataTransfer.types.includes(Constants.SIYUAN_DROP_BLOCK) ||
+ !dataTransfer.types.some(type => type.startsWith(Constants.SIYUAN_DROP_GUTTER))) {
+ return;
+ }
+ try {
+ dataTransfer.effectAllowed = payload.effectAllowed;
+ } catch {
+ // 部分 WebView 不允许在合成拖拽上设置 effectAllowed。
+ }
+ return dataTransfer;
+};
+
+const cleanupForeignDrag = (type: "leave" | "end", point?: DragPoint) => {
+ if (!foreignDragState) {
+ return;
+ }
+ const dragPoint = point || foreignDragState.lastPoint || {clientX: 0, clientY: 0};
+ const target = (foreignDragState.lastDragOverElement?.isConnected ? foreignDragState.lastDragOverElement :
+ getElementUnderPoint(dragPoint)) || document.body;
+ if (type === "leave" || !foreignDragState.dropped) {
+ target.dispatchEvent(createBridgeDragEvent("dragleave", dragPoint, foreignDragState.dataTransfer));
+ }
+ target.dispatchEvent(createBridgeDragEvent("dragend", dragPoint, foreignDragState.dataTransfer));
+ if (foreignDragState.idleTimeout) {
+ window.clearTimeout(foreignDragState.idleTimeout);
+ }
+ stopScrollAnimation();
+ clearDragoverClasses();
+ dragRefreshQueue.cancel();
+ stopScrollAfterRefresh = false;
+ window.siyuan.dragTitle = "";
+ foreignDragState = null;
+};
+
+const resetForeignDragIdleTimeout = () => {
+ const currentState = foreignDragState;
+ if (!currentState) {
+ return;
+ }
+ if (currentState.idleTimeout) {
+ window.clearTimeout(currentState.idleTimeout);
+ }
+ currentState.idleTimeout = window.setTimeout(() => {
+ if (foreignDragState === currentState) {
+ cleanupForeignDrag("end");
+ }
+ }, DRAG_IDLE_TIMEOUT);
+};
+
+const handleBlockDragRelay = (message: BlockDragRelayMessage) => {
+ if (!message || typeof message.dragId !== "string") {
+ return;
+ }
+ if (message.phase === "request") {
+ if (dragState?.relayId === message.dragId && dragState.dataTransfer) {
+ sendBlockDragRelay({
+ phase: "payload",
+ dragId: message.dragId,
+ payload: serializeDataTransfer(dragState.dataTransfer),
+ });
+ }
+ return;
+ }
+ if (message.phase === "route") {
+ if (dragState?.relayId === message.dragId && dragState.pendingDropPoint &&
+ message.sequence === dragState.pendingDropSequence) {
+ dragState.relayRemote = !!message.remote;
+ const pendingPoint = dragState.pendingDropPoint;
+ completeBridgeDrag(pendingPoint, false, !!message.remote);
+ } else if (dragState?.relayId === message.dragId && !dragState.pendingDropPoint &&
+ message.sequence === dragState.relaySequence) {
+ dragState.relayRemote = !!message.remote;
+ }
+ return;
+ }
+ if (message.phase === "enter") {
+ const dataTransfer = createForeignDataTransfer(message.payload);
+ if (!dataTransfer) {
+ return;
+ }
+ if (foreignDragState) {
+ cleanupForeignDrag("end");
+ }
+ window.siyuan.dragElement = undefined;
+ window.siyuan.dragTitle = message.payload.dragTitle || "";
+ foreignDragState = {
+ dataTransfer,
+ dragId: message.dragId,
+ dropped: false,
+ lastDragOverElement: null,
+ };
+ resetForeignDragIdleTimeout();
+ }
+ if (!foreignDragState || foreignDragState.dragId !== message.dragId) {
+ return;
+ }
+ if (message.phase === "move" && message.point) {
+ resetForeignDragIdleTimeout();
+ foreignDragState.lastPoint = copyDragPoint(message.point);
+ foreignDragState.lastDragOverElement = dispatchBridgeDragOver(
+ foreignDragState.dataTransfer,
+ foreignDragState.lastPoint,
+ foreignDragState.lastDragOverElement,
+ );
+ } else if (message.phase === "leave") {
+ cleanupForeignDrag("leave", message.point);
+ } else if (message.phase === "drop" && message.point) {
+ resetForeignDragIdleTimeout();
+ foreignDragState.lastPoint = copyDragPoint(message.point);
+ foreignDragState.lastDragOverElement = dispatchBridgeDragOver(
+ foreignDragState.dataTransfer,
+ foreignDragState.lastPoint,
+ foreignDragState.lastDragOverElement,
+ );
+ const target = getElementUnderPoint(foreignDragState.lastPoint);
+ target?.dispatchEvent(createBridgeDragEvent("drop", foreignDragState.lastPoint,
+ foreignDragState.dataTransfer));
+ foreignDragState.dropped = !!target;
+ if (message.sourceWebContentsId !== undefined && message.sequence !== undefined) {
+ sendBlockDragRelay({
+ phase: "drop-ack",
+ dragId: message.dragId,
+ sequence: message.sequence,
+ sourceWebContentsId: message.sourceWebContentsId,
+ });
+ }
+ } else if (message.phase === "end") {
+ cleanupForeignDrag("end", message.point);
+ }
+};
+
+let stopScrollAfterRefresh = false;
+const dragRefreshQueue = createDragRefreshQueue(() => {
+ if (dragState?.isDragging && dragState.lastPoint) {
+ continueBridgeDrag(dragState.lastPoint, false);
+ }
+ if (foreignDragState?.lastPoint) {
+ foreignDragState.lastDragOverElement = dispatchBridgeDragOver(
+ foreignDragState.dataTransfer,
+ foreignDragState.lastPoint,
+ foreignDragState.lastDragOverElement,
+ );
+ }
+ if (stopScrollAfterRefresh) {
+ stopScrollAfterRefresh = false;
+ stopScrollAnimation();
+ }
+}, callback => window.requestAnimationFrame(callback), handle => window.cancelAnimationFrame(handle));
+
+export const refreshSyntheticDragTarget = () => {
+ if (dragState?.isDragging || foreignDragState) {
+ dragRefreshQueue.schedule();
+ }
+};
+
+const handleDragWheel = () => {
+ if (!dragState?.isDragging && !foreignDragState) {
+ return;
+ }
+ stopScrollAfterRefresh = true;
+ stopScrollAnimation();
+ resetLocalDragIdleTimeout();
+ resetForeignDragIdleTimeout();
+ dragRefreshQueue.schedule();
+};
+
+const handleDragScroll = () => {
+ refreshSyntheticDragTarget();
+};
+
+const handleDragKey = (event: KeyboardEvent) => {
+ if (!dragState?.isDragging || !dragState.lastPoint) {
+ return;
+ }
+ event.preventDefault();
+ if (!["Alt", "Control", "Meta", "Shift"].includes(event.key)) {
+ event.stopImmediatePropagation();
+ }
+ if (dragState.pendingDropPoint) {
+ return;
+ }
+ if (event.type === "keydown" && event.key === "Escape") {
+ completeBridgeDrag(undefined, true);
+ return;
+ }
+ dragState.lastPoint.altKey = event.altKey;
+ dragState.lastPoint.ctrlKey = event.ctrlKey;
+ dragState.lastPoint.metaKey = event.metaKey;
+ dragState.lastPoint.shiftKey = event.shiftKey;
+ resetLocalDragIdleTimeout();
+ sendBlockDragRelayMove(dragState.lastPoint);
+ dragRefreshQueue.schedule();
+};
+
+const handleLostPointerCapture = (event: PointerEvent) => {
+ if (dragState?.inputType === "pointer" && dragState.pointerId === event.pointerId &&
+ !dragState.pendingDropPoint) {
+ completeBridgeDrag(undefined, true);
+ }
+};
+
+const handleVisibilityChange = () => {
+ if (!document.hidden) {
+ return;
+ }
+ completeBridgeDrag(undefined, true);
+ cleanupForeignDrag("end");
+};
+
const handleCancel = () => {
// touchcancel 时两条路径都需无条件清理(cleanupDrag/cancelManualTouch 内部均做空状态处理)
completeBridgeDrag(undefined, true);
@@ -531,26 +934,54 @@ export const cancelManualTouch = () => {
window.siyuan.touchDragActive = false;
};
+let bridgeInitialized = false;
+
export const initTouchDragBridge = () => {
+ if (bridgeInitialized) {
+ return;
+ }
+ bridgeInitialized = true;
+
// 所有平台都需记录输入源,供 Touch 回调识别鼠标合成事件。
document.addEventListener("pointerdown", (event: PointerEvent) => {
lastPointerType = event.pointerType;
}, {capture: true, passive: true});
- if (isInAndroid()) {
- // Android 外接鼠标由 Pointer 路径驱动,避免原生 Drag API 在 dragstart 后取消事件流且不派发 drop。
+ let enablePointerBridge = !!isInAndroid();
+ /// #if !BROWSER
+ enablePointerBridge = true;
+ ipcRenderer.on(Constants.SIYUAN_BLOCK_DRAG, (event, message: BlockDragRelayMessage) => {
+ handleBlockDragRelay(message);
+ });
+ /// #endif
+ if (enablePointerBridge) {
+ // Android 外接鼠标和桌面普通块标由 Pointer 路径驱动,避免原生 dragstart 取消事件流。
document.addEventListener("pointerdown", handlePointerDown, {capture: true, passive: true});
document.addEventListener("pointermove", handlePointerMove, {capture: true, passive: false});
document.addEventListener("pointerup", handlePointerUp, {capture: true, passive: false});
document.addEventListener("pointercancel", handlePointerCancel, {capture: true, passive: true});
+ document.addEventListener("lostpointercapture", handleLostPointerCapture, {capture: true, passive: true});
document.addEventListener("click", handleMouseClick, {capture: true, passive: false});
window.addEventListener("blur", () => {
- if (dragState?.inputType === "pointer") {
+ if (isInAndroid() && dragState?.inputType === "pointer") {
completeBridgeDrag(undefined, true);
+ return;
}
+ window.setTimeout(() => {
+ if (dragState?.inputType === "pointer" && !dragState.relayRemote &&
+ !dragState.pendingDropPoint) {
+ completeBridgeDrag(undefined, true);
+ }
+ }, Constants.TIMEOUT_MOUSE_DRAG_DELAY);
});
}
+ document.addEventListener("wheel", handleDragWheel, {capture: true, passive: true});
+ document.addEventListener("scroll", handleDragScroll, {capture: true, passive: true});
+ document.addEventListener("keydown", handleDragKey, {capture: true});
+ document.addEventListener("keyup", handleDragKey, {capture: true});
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+
// 触摸事件桥接:原生 Drag API(draggable="true")与手动 mousedown 拖拽(dock/outline/resize 把手)统一入口
document.addEventListener("touchstart", handleTouchStart, {passive: false});
document.addEventListener("touchmove", handleTouchMove, {passive: false});
diff --git a/app/src/util/touchDragBridgeCore.test.ts b/app/src/util/touchDragBridgeCore.test.ts
index f7441516df..ed73f25ffe 100644
--- a/app/src/util/touchDragBridgeCore.test.ts
+++ b/app/src/util/touchDragBridgeCore.test.ts
@@ -2,6 +2,7 @@ import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {
completeDrag,
+ createDragRefreshQueue,
dispatchWithNativeDragEnabled,
restoreNativeDrag,
shouldSuppressNativeContextMenu,
@@ -86,6 +87,79 @@ describe("touch drag completion", () => {
});
});
+describe("touch drag refresh queue", () => {
+ const createFrameHarness = () => {
+ let nextHandle = 0;
+ const callbacks = new Map<number, FrameRequestCallback>();
+ const canceled: number[] = [];
+ return {
+ requestFrame: (callback: FrameRequestCallback) => {
+ const handle = ++nextHandle;
+ callbacks.set(handle, callback);
+ return handle;
+ },
+ cancelFrame: (handle: number) => {
+ canceled.push(handle);
+ },
+ runFrame: (handle: number) => callbacks.get(handle)?.(0),
+ getRequestedCount: () => callbacks.size,
+ getCanceled: () => canceled,
+ };
+ };
+
+ it("coalesces refreshes scheduled in the same frame", () => {
+ const frames = createFrameHarness();
+ let refreshCount = 0;
+ const queue = createDragRefreshQueue(
+ () => refreshCount++,
+ frames.requestFrame,
+ frames.cancelFrame,
+ );
+
+ queue.schedule();
+ queue.schedule();
+
+ assert.equal(frames.getRequestedCount(), 1);
+ frames.runFrame(1);
+ assert.equal(refreshCount, 1);
+ });
+
+ it("does not refresh after canceling a scheduled frame", () => {
+ const frames = createFrameHarness();
+ let refreshCount = 0;
+ const queue = createDragRefreshQueue(
+ () => refreshCount++,
+ frames.requestFrame,
+ frames.cancelFrame,
+ );
+
+ queue.schedule();
+ queue.cancel();
+ frames.runFrame(1);
+
+ assert.deepEqual(frames.getCanceled(), [1]);
+ assert.equal(refreshCount, 0);
+ });
+
+ it("allows scheduling again after a refresh", () => {
+ const frames = createFrameHarness();
+ let refreshCount = 0;
+ const queue = createDragRefreshQueue(
+ () => refreshCount++,
+ frames.requestFrame,
+ frames.cancelFrame,
+ );
+
+ queue.schedule();
+ frames.runFrame(1);
+ queue.schedule();
+ frames.runFrame(2);
+
+ assert.equal(refreshCount, 2);
+ assert.equal(frames.getRequestedCount(), 2);
+ });
+});
+
describe("touch drag context menu", () => {
it("only suppresses a trusted native menu during an active gesture", () => {
assert.equal(shouldSuppressNativeContextMenu(true, true), true);
diff --git a/app/src/util/touchDragBridgeCore.ts b/app/src/util/touchDragBridgeCore.ts
index 9e5bc9b8a2..f8021e9a4c 100644
--- a/app/src/util/touchDragBridgeCore.ts
+++ b/app/src/util/touchDragBridgeCore.ts
@@ -9,6 +9,44 @@ interface DragCompletionCallbacks {
cleanup: () => void;
}
+export const createDragRefreshQueue = (
+ refresh: () => void,
+ requestFrame: (callback: FrameRequestCallback) => number,
+ cancelFrame: (handle: number) => void,
+) => {
+ let scheduled = false;
+ let frameHandle = 0;
+ let generation = 0;
+
+ return {
+ schedule: () => {
+ if (scheduled) {
+ return;
+ }
+ scheduled = true;
+ const currentGeneration = ++generation;
+ const handle = requestFrame(() => {
+ if (!scheduled || generation !== currentGeneration) {
+ return;
+ }
+ scheduled = false;
+ refresh();
+ });
+ if (scheduled && generation === currentGeneration) {
+ frameHandle = handle;
+ }
+ },
+ cancel: () => {
+ if (!scheduled) {
+ return;
+ }
+ scheduled = false;
+ generation++;
+ cancelFrame(frameHandle);
+ },
+ };
+};
+
export const suspendNativeDrag = (state: NativeDragGuard) => {
state.draggableElement.setAttribute("draggable", "false");
state.restoreDraggable = true;