An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Avoid hover delays during document panel touch interactions https://github.com/siyuan-note/siyuan/issues/20324
Daniel4dd5b12fd4a4
diff --git a/app/src/assets/scss/component/_tooltips.scss b/app/src/assets/scss/component/_tooltips.scssindex 768b5d4c50..7b94107fab 100644--- a/app/src/assets/scss/component/_tooltips.scss+++ b/app/src/assets/scss/component/_tooltips.scss@@ -181,6 +181,16 @@}}+.body--touch-input {+ .tooltip--hover {+ display: none;+ }++ .b3-tooltips::after {+ content: none;+ }+}+@media screen and (max-width: 520px) {.b3-tooltips::after {content: none;diff --git a/app/src/assets/scss/main/_main.scss b/app/src/assets/scss/main/_main.scssindex 61ac4765cc..587aa97a3f 100644--- a/app/src/assets/scss/main/_main.scss+++ b/app/src/assets/scss/main/_main.scss@@ -413,6 +413,24 @@ html[data-frontend="browser-desktop"] {}}+// 触摸操作直接显示文档面板按钮,避免悬停显现动画延迟点击。+.body--touch-input .sy__file {+ .block__icons:not(.protyle-wysiwyg *) .block__icon:not(.backlinkList__toggle) {+ display: flex;+ opacity: 1;+ transition: none;+ }++ .block__icons:not(.protyle-wysiwyg *) .block__icon[disabled]:not(.backlinkList__toggle) {+ opacity: .38;+ }++ .block__icons:not(.protyle-wysiwyg *) .fn__space {+ display: block;+ transition: none;+ }+}+.body--windows .sy__file .b3-list-item__icon {font-size: 16px;}diff --git a/app/src/block/popover.ts b/app/src/block/popover.tsindex e53f676446..caad0ab0f0 100644--- a/app/src/block/popover.ts+++ b/app/src/block/popover.ts@@ -22,6 +22,7 @@ import {setPopoverCancellationHandler,} from "./popoverLifecycle";import {isBlockPanelTargetAvailable} from "./panelOwnership";+import {isTouchHoverInput} from "../util/hoverInput";/// #if !MOBILEimport {getInstanceById} from "../layout/util";import {Editor} from "../editor";@@ -144,9 +145,12 @@ export const initBlockPopover = (app: App) => {pointerX = event.clientX;pointerY = event.clientY;}- if (!window.siyuan.config || !window.siyuan.menus ||+ if (isTouchHoverInput() || !window.siyuan.config || !window.siyuan.menus ||// 拖拽时禁止isPopoverSuspended()) {+ cancelPopoverTimers();+ tooltipAbortController?.abort();+ tooltipAbortController = null;hideTooltip();return;}@@ -326,7 +330,7 @@ export const initBlockPopover = (app: App) => {if (signal.aborted) {return;}- showTooltip(escapeLessThans(response.data), tab.headElement);+ showTooltip(escapeLessThans(response.data), tab.headElement, undefined, event);tab.headElement.setAttribute("aria-label", escapeLessThans(response.data));if (tooltipAbortController === capturedController) {tooltipAbortController = null;@@ -350,7 +354,7 @@ export const initBlockPopover = (app: App) => {}const boxData = response.data.boxInfo;const tip = `${boxData.name} <small class='ft__on-surface'>${boxData.hSize}</small>${boxData.docCount !== 0 ? window.siyuan.languages.includeSubFile.replace("x", boxData.docCount) : ""}<br>${window.siyuan.languages.modifiedAt} ${boxData.hMtime}<br>${window.siyuan.languages.createdAt} ${boxData.hCtime}`;- showTooltip(tip, notebookItemElement as Element);+ showTooltip(tip, notebookItemElement as Element, undefined, event);(notebookItemElement as HTMLElement).setAttribute("aria-label", tip);if (tooltipAbortController === capturedController) {tooltipAbortController = null;diff --git a/app/src/block/popoverInteraction.test.ts b/app/src/block/popoverInteraction.test.tsindex a662401758..51ee2d6eb4 100644--- a/app/src/block/popoverInteraction.test.ts+++ b/app/src/block/popoverInteraction.test.ts@@ -131,6 +131,7 @@ const createHarness = (android = false) => {"../dialog/tooltip": {hideTooltip() {}, showTooltip() {}},"../constants": {Constants: {TIMEOUT_INPUT: 5}},"../util/functions": {isTouchDevice: () => touch},+ "../util/hoverInput": {isTouchHoverInput: () => touch},"../protyle/wysiwyg/listContext": {isListItemActionElement: () => false},"../util/zIndex": {isAbove: () => false},}) as unknown as typeof import("./popover");@@ -166,9 +167,26 @@ const createHarness = (android = false) => {lifecycle.setPopoverMenuOpen(menu as unknown as HTMLElement, false);};return {element, ref, fire, advance, api, lifecycle, panels, requests, siyuan, handlers, open, close,+ pendingTimers: () => timers.size,setTouch: (value: boolean) => { touch = value; }};};+test("touch-generated mouseover does not schedule hover timers and cancels pending previews", async () => {+ const h = createHarness();+ h.fire("mouseover");+ assert.ok(h.pendingTimers() > 0);+ h.setTouch(true);+ const more = h.element({"aria-label": "More"}, ["ariaLabel"]);+ h.fire("mouseover", more);+ assert.equal(h.pendingTimers(), 0);+ await h.advance();+ assert.equal(h.requests.length, 0);+ assert.equal(h.panels.length, 0);+ h.setTouch(false);+ h.fire("mouseover");+ assert.ok(h.pendingTimers() > 0);+});+test("clicks cancel pending previews until actual motion, including within the same target", async () => {for (const button of [0, 1, 2]) {const h = createHarness();diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.tsindex 5ce299bdf3..4ec7147b4a 100644--- a/app/src/boot/globalEvent/event.ts+++ b/app/src/boot/globalEvent/event.ts@@ -20,10 +20,12 @@ import {clearDragTipGhost, hideDragTip} from "../../protyle/util/dragTip";import {formatPainter} from "../../protyle/toolbar/FormatPainter";import {SELECTION_TOOLBAR_SUB_ELEMENT_SOURCE} from "../../protyle/toolbar/subElementLifecycle";import {initKeyboardDiagnostics} from "../../util/keyboardDiagnostic";+import {initHoverInput} from "../../util/hoverInput";const KANBAN_GROUP_DRAG_TYPE = `${Constants.SIYUAN_DROP_GUTTER}NodeAttributeView${Constants.ZWSP}Group${Constants.ZWSP}`.toLowerCase();export const initWindowEvent = (app: App) => {+ initHoverInput();initKeyboardDiagnostics("desktop");initHarmonyTextSelectionMenu();let lastEncryptedNotebookTouch = 0;diff --git a/app/src/dialog/tooltip.ts b/app/src/dialog/tooltip.tsindex 7713c60d20..b4330baa8f 100644--- a/app/src/dialog/tooltip.ts+++ b/app/src/dialog/tooltip.ts@@ -1,9 +1,14 @@import {isMobile} from "../util/functions";import {emitToPlugins, forEachPluginSubscriber} from "../plugin/EventBusCore";+import {initHoverInput, isTouchHoverInput} from "../util/hoverInput";// 无编辑器的窗口复用提示框渲染,不注册块预览事件。export const initTooltips = () => {+ initHoverInput();document.addEventListener("mouseover", (event: MouseEvent) => {+ if (isTouchHoverInput()) {+ return;+ }const target = (event.target as Element).closest(".ariaLabel");if (target && !target.classList.contains("b3-tooltips")) {let message = target.getAttribute("aria-label") || "";@@ -33,7 +38,7 @@ export const showTooltip = (space: number = 0.5,positionOverride?: string,) => {- if (isMobile() || !message) {+ if (isMobile() || !message || (isTouchHoverInput() && event && tooltipClass !== "error")) {return;}const messageElement = document.getElementById("tooltip");@@ -75,6 +80,7 @@ export const showTooltip = (return;}messageElement.className = tooltipClass ? `tooltip tooltip--${tooltipClass}` : "tooltip";+ messageElement.classList.toggle("tooltip--hover", !!event && tooltipClass !== "error");messageElement.innerHTML = window.DOMPurify.sanitize(message);// 避免原本的 top 和 left 影响计算messageElement.removeAttribute("style");diff --git a/app/src/dialog/tooltipInput.test.ts b/app/src/dialog/tooltipInput.test.tsnew file mode 100644index 0000000000..afe7f6c954--- /dev/null+++ b/app/src/dialog/tooltipInput.test.ts@@ -0,0 +1,133 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {compileString} from "sass";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sources: string[], css: string) => {+ const check: typeof assert = require("node:assert/strict");+ document.body.innerHTML = `<style>${css}+.fn__none {display:none!important}.fn__flex-1 {flex:1;min-width:0}+body {margin:0}.file-tree {position:absolute;top:40px;left:40px;width:232px}+.block__logo {overflow:hidden}#tooltip {--b3-tooltips-color:black;--b3-tooltips-background:white}+</style><div class="file-tree sy__file"><div class="block__icons">+<div class="block__logo fn__flex-1">Documents</div><div class="fn__space"></div>+<div data-type="more" class="block__icon ariaLabel" aria-label="More"><svg></svg></div>+<div class="block__icon fn__none" id="hidden"><svg></svg></div>+<div class="block__icon" disabled id="disabled"><svg></svg></div>+</div><span class="b3-tooltips" aria-label="More">More</span></div>+<div id="tooltip" class="tooltip fn__none"></div>`;+ const input = {} as typeof import("../util/hoverInput");+ new Function("exports", sources[0])(input);+ let pluginShows = 0;+ const tooltip = {} as typeof import("./tooltip");+ window.DOMPurify = {sanitize: (value: string) => value} as typeof window.DOMPurify;+ new Function("exports", "require", sources[1])(tooltip, (id: string) => {+ if (id === "../util/hoverInput") { return input; }+ return {isMobile: () => false, emitToPlugins: () => { pluginShows++; }, forEachPluginSubscriber() {}};+ });+ tooltip.initTooltips();+ input.initHoverInput();+ const more = document.querySelector<HTMLElement>('[data-type="more"]');+ const tip = document.getElementById("tooltip");+ const touch = (type = "pointerdown", pointerType = "touch") => {+ const event = new PointerEvent(type, {bubbles: true, cancelable: true, pointerType});+ more.dispatchEvent(event);+ check.equal(event.defaultPrevented, false, "input tracking leaves scrolling and activation untouched");+ };+ const hover = () => more.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));+ const assertTouch = () => {+ check.equal(input.isTouchHoverInput(), true);+ check.equal(getComputedStyle(more).display, "flex");+ check.equal(getComputedStyle(more).opacity, "1");+ check.equal(getComputedStyle(more).transitionDuration, "0s");+ check.equal(getComputedStyle(document.getElementById("hidden")).display, "none");+ check.equal(getComputedStyle(document.getElementById("disabled")).opacity, "0.38");+ check.equal(getComputedStyle(document.querySelector(".b3-tooltips"), "::after").content, "none");+ };+ check.equal(matchMedia("(hover: none)").matches, true);+ assertTouch();+ hover();+ check.equal(pluginShows, 0, "touch-generated mouseover does not build a tooltip");+ tooltip.showTooltip("Late hover", more, undefined, new MouseEvent("mouseover"));+ check.equal(pluginShows, 0, "late hover callbacks stay suppressed after touch input");+ tooltip.showTooltip("Invalid name", more, "error");+ check.equal(tip.classList.contains("tooltip--error"), true);+ check.notEqual(getComputedStyle(tip).display, "none", "validation errors remain visible");+ tooltip.showTooltip("Scroll position", more);+ check.notEqual(getComputedStyle(tip).display, "none", "explicit position feedback remains visible");+ touch("pointerover", "mouse");+ check.equal(input.isTouchHoverInput(), false);+ await new Promise(resolve => setTimeout(resolve, 350));+ check.equal(getComputedStyle(more).display, "none", "mouse input restores the toolbar hover behavior");+ await require("electron").ipcRenderer.invoke("hover", 80, 60);+ await new Promise(resolve => setTimeout(resolve, 350));+ check.equal(getComputedStyle(more).display, "flex", "real mouse hover reveals the toolbar");+ hover();+ check.equal(tip.innerHTML, "More");+ check.equal(tip.classList.contains("tooltip--hover"), true);+ touch();+ assertTouch();+ check.equal(getComputedStyle(tip).display, "none", "touch immediately hides an existing hover tooltip");+ for (const width of [200, 232, 400]) {+ const panel = document.querySelector<HTMLElement>(".file-tree");+ panel.style.width = width + "px";+ panel.style.fontSize = "32px";+ check.ok(more.getBoundingClientRect().right <= panel.getBoundingClientRect().right);+ check.equal(more.getBoundingClientRect().width, 24, "touch uses the existing control dimensions");+ }+ touch("pointerover", "pen");+ check.equal(input.isTouchHoverInput(), false, "pen hover remains available");+ touch("pointermove", "touch");+ assertTouch();+ return "Touch hover input cases passed";+};++test("touch hover suppression preserves mouse, validation feedback and toolbar layout", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const sources = ["src/util/hoverInput.ts", "src/dialog/tooltip.ts"].map(file =>+ transpileModule(readFileSync(file, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText);+ const css = ["business/_block.scss", "component/_tooltips.scss", "main/_main.scss"]+ .map(file => compileString(readFileSync("src/assets/scss/" + file, "utf8")).css).join("\n");+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-touch-hover-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow, ipcMain} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show:false,width:800,height:600,+ webPreferences:{nodeIntegration:true,contextIsolation:false,offscreen:true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ win.webContents.debugger.attach("1.3");+ await win.webContents.debugger.sendCommand("Emulation.setTouchEmulationEnabled", {enabled:true});+ ipcMain.handle("hover", (_event, x, y) => win.webContents.debugger.sendCommand("Input.dispatchMouseEvent",+ {type:"mouseMoved",x,y}));+ const result = await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(sources) + "," + JSON.stringify(css) + ")")});+ if (result !== "Touch hover input cases passed") {throw new Error(result);}+ console.log(result);+ win.destroy();app.exit(0);+ } catch(error) {console.error(error);win.destroy();app.exit(1);}+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script],+ {env, timeout: 25000, windowsHide: true});+ assert.match(result.stdout, /Touch hover input cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-touch-hover-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/layout/dock/index.test.ts b/app/src/layout/dock/index.test.tsindex 3ef6db6969..0095aaca34 100644--- a/app/src/layout/dock/index.test.ts+++ b/app/src/layout/dock/index.test.ts@@ -7,7 +7,8 @@ import * as ts from "typescript";import {resolveDockPanelVisibility} from "./panelVisibility";const loadDockPrototype = (frames: Array<() => void>, document: object, adjustLayout: () => void,- resizeTabs: () => void) => {+ resizeTabs: () => void, isTouchHoverInput = () => false,+ timers: Array<() => void> = []) => {const exports: {Dock?: {prototype: object}} = {};const source = ts.transpileModule(readFileSync(join(__dirname, "index.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},@@ -15,7 +16,7 @@ const loadDockPrototype = (frames: Array<() => void>, document: object, adjustLarunInNewContext(source, {exports,document,- window: {setTimeout: () => 0},+ window: {setTimeout: (callback: () => void) => timers.push(callback), clearTimeout() {}},requestAnimationFrame: (callback: () => void) => frames.push(callback),require: (name: string) => {if (name === "../util") {@@ -31,7 +32,10 @@ const loadDockPrototype = (frames: Array<() => void>, document: object, adjustLareturn {resolveDockPanelVisibility};}if (name.endsWith("/constants")) {- return {Constants: {TIMEOUT_TRANSITION: 200}};+ return {Constants: {TIMEOUT_TRANSITION: 200, TIMEOUT_DOCK_TOGGLE: 150}};+ }+ if (name.endsWith("/hoverInput")) {+ return {isTouchHoverInput};}return {};},@@ -39,6 +43,25 @@ const loadDockPrototype = (frames: Array<() => void>, document: object, adjustLareturn exports.Dock.prototype;};+it("touch compatibility hover skips dock timers while mouse hover remains available", () => {+ let touch = true;+ const timers: Array<() => void> = [];+ const prototype = loadDockPrototype([], {}, () => {}, () => {}, () => touch, timers);+ const style = {opacity: "0"};+ const dock = Object.assign(Object.create(prototype), {+ panelVisible: true, showDockTimeout: 0, hideDockTimeout: 0,+ layout: {element: {style}}, isFloating: () => true,+ }) as {showDockByHover(): void, hideDockByHover(): void};+ dock.showDockByHover();+ dock.hideDockByHover();+ assert.equal(timers.length, 0);+ touch = false;+ dock.showDockByHover();+ style.opacity = "1";+ dock.hideDockByHover();+ assert.equal(timers.length, 2);+});+describe("dock panel opening", () => {it("shows a panel after responsive layout changes it to floating", () => {const frames: Array<() => void> = [];diff --git a/app/src/layout/dock/index.ts b/app/src/layout/dock/index.tsindex 2c2caf339c..1cdfa87ed9 100644--- a/app/src/layout/dock/index.ts+++ b/app/src/layout/dock/index.ts@@ -33,6 +33,7 @@ import {resolveDockPanelVisibility} from "./panelVisibility";import {syncDockEntryOrders} from "../../config/entryVisibility/runtime";import {isWindow} from "../../util/functions";import {bindPanelTransitionGuard} from "../../util/panelTransition";+import {isTouchHoverInput} from "../../util/hoverInput";const TYPES = ["file", "outline", "inbox", "bookmark", "tag", "graph", "globalGraph", "backlink", "agentChat"];const DEFAULT_DOCK_SIZE = 232;@@ -546,7 +547,7 @@ export class Dock {public showDockByHover() {window.clearTimeout(this.hideDockTimeout);this.hideDockTimeout = 0;- if (!this.panelVisible || this.showDockTimeout || !this.isFloating() ||+ if (isTouchHoverInput() || !this.panelVisible || this.showDockTimeout || !this.isFloating() ||this.layout.element.style.opacity === "1") {return;}@@ -559,7 +560,7 @@ export class Dock {public hideDockByHover() {window.clearTimeout(this.showDockTimeout);this.showDockTimeout = 0;- if (!this.panelVisible || this.hideDockTimeout || !this.isFloating() ||+ if (isTouchHoverInput() || !this.panelVisible || this.hideDockTimeout || !this.isFloating() ||this.layout.element.style.opacity === "0") {return;}diff --git a/app/src/util/hoverInput.ts b/app/src/util/hoverInput.tsnew file mode 100644index 0000000000..6109563826--- /dev/null+++ b/app/src/util/hoverInput.ts@@ -0,0 +1,20 @@+let initialized = false;++export const isTouchHoverInput = () => document.body.classList.contains("body--touch-input");++// 按实际输入切换悬停行为,触屏设备连接鼠标后仍可恢复鼠标提示和工具栏显隐。+export const initHoverInput = () => {+ if (initialized) {+ return;+ }+ initialized = true;+ document.body.classList.toggle("body--touch-input", window.matchMedia("(hover: none)").matches);+ const update = (event: PointerEvent) => {+ if (["mouse", "touch", "pen"].includes(event.pointerType)) {+ document.body.classList.toggle("body--touch-input", event.pointerType === "touch");+ }+ };+ ["pointerover", "pointerdown", "pointermove"].forEach(type => {+ document.addEventListener(type, update, {capture: true, passive: true});+ });+};