Skip to content

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

:bug: Stabilize iPad keyboard and touch interactions https://github.com/siyuan-note/siyuan/issues/20006

Vanessaf1cd8b3698db
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index b45fa3d814..755b4f3511 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -147,6 +147,8 @@
box-sizing: border-box;
z-index: 1;
text-align: center;
+ // 块标会随指针重新定位,使用自身悬停反馈,避免系统触摸高亮留在原位置。
+ -webkit-tap-highlight-color: transparent;
// 横向超级块的块标需高于分栏宽度调节杆,避免重叠区域被调节杆截获点击
&--sb-column {
@@ -165,6 +167,11 @@
cursor: pointer;
position: relative;
+ // 块标自身区域优先接收点击,插入框线和加号的扩展命中区仅在外侧生效。
+ &:not(.protyle-gutters__line):not(.protyle-gutters__plus) {
+ z-index: 5;
+ }
+
&:hover svg {
color: var(--b3-theme-on-surface);
}
@@ -215,7 +222,7 @@
}
// 块标边缘框线(悬浮块标显示),与 .protyle-gutters 同为 fixed 坐标系,由 JS 贴块标边缘定位
-// 选择器带 button 标签提升特异性,覆盖 .protyle-gutters button 的 position:relative;z-index 高于块标 span 覆盖层
+// 选择器带 button 标签提升特异性,覆盖 .protyle-gutters button 的 position:relative;块标自身位于框线上方
.protyle-gutters button.protyle-gutters__line {
position: fixed;
z-index: 3;
diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.ts
index 544436ffdf..9711d3644a 100644
--- a/app/src/boot/globalEvent/command/global.ts
+++ b/app/src/boot/globalEvent/command/global.ts
@@ -74,7 +74,7 @@ export const globalCommand = (command: string, app: App, range?: Range, openOnly
popMenu();
return true;
case "globalSearch":
- popSearch(app);
+ popSearch(app, undefined, openOnly);
return true;
case "recentDocs":
getRecentDocs(app);
@@ -109,6 +109,7 @@ export const globalCommand = (command: string, app: App, range?: Range, openOnly
openSearch({
app,
hotkey: Constants.DIALOG_GLOBALSEARCH,
+ focusInput: openOnly,
key: getSelectionText(range)
});
return true;
diff --git a/app/src/boot/globalEvent/commonHotkey.ts b/app/src/boot/globalEvent/commonHotkey.ts
index 8b76a0735f..bb0dbb93cc 100644
--- a/app/src/boot/globalEvent/commonHotkey.ts
+++ b/app/src/boot/globalEvent/commonHotkey.ts
@@ -11,7 +11,6 @@ import {isMac, isNotCtrl, isOnlyMeta} from "../../protyle/util/compatibility";
import {showPopover} from "../../block/popover";
import {clearDisallowedKeymapItems} from "../../util/hotKeyPolicy";
import {getHostCapabilities} from "../../util/hostCapabilities";
-import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
const matchKeymap = (keymap: Config.IKeys, key1: "general" | "editor", key2?: "general" | "insert" | "heading" | "list" | "table") => {
if (key1 === "general") {
@@ -200,8 +199,6 @@ export const syncAppMenuShortcuts = (suspended = false) => {
export const filterHotkey = (event: KeyboardEvent, app: App) => {
// https://github.com/siyuan-note/siyuan/issues/9848 忘记为什么要阻止了 .av__mask 的情况,测了下没问题就先移除
if (document.getElementById("progress") || document.getElementById("errorLog") || event.isComposing) {
- logKeyboardDiagnostic("filter-stop", event, document.getElementById("progress") ? "progress" :
- document.getElementById("errorLog") ? "error-log" : "composing");
return true;
}
const target = event.target as HTMLElement;
@@ -221,7 +218,6 @@ export const filterHotkey = (event: KeyboardEvent, app: App) => {
cardElement = document.querySelector(`.layout__wnd--active div[data-key="${Constants.DIALOG_OPENCARD}"]:not(.fn__none)`);
}
if (cardElement) {
- logKeyboardDiagnostic("filter-stop", event, "card-key");
event.preventDefault();
cardElement.firstElementChild.dispatchEvent(new CustomEvent("click", {detail: event.key.toLowerCase()}));
return true;
@@ -234,7 +230,6 @@ export const filterHotkey = (event: KeyboardEvent, app: App) => {
Constants.KEYCODELIST[event.keyCode] !== "PageDown" &&
event.key !== "Home" && event.key !== "End" &&
!/^F\d{1,2}$/.test(event.key) && event.key.indexOf("Arrow") === -1 && event.key !== "Enter" && event.key !== "Backspace" && event.key !== "Delete") {
- logKeyboardDiagnostic("filter-stop", event, "plain-key");
return true;
}
diff --git a/app/src/boot/globalEvent/event.ts b/app/src/boot/globalEvent/event.ts
index 4ec7147b4a..1a5e76435e 100644
--- a/app/src/boot/globalEvent/event.ts
+++ b/app/src/boot/globalEvent/event.ts
@@ -19,14 +19,14 @@ import {initHarmonyTextSelectionMenu} from "../../util/harmonyTextSelectionMenu"
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";
+import {bindGutterPointerLeave} from "./gutterPointerLeave";
+import {isInIOS} from "../../protyle/util/compatibility";
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;
const touchEncryptedNotebooks = () => {
@@ -44,7 +44,7 @@ export const initWindowEvent = (app: App) => {
window.addEventListener("keydown", touchEncryptedNotebooks);
document.addEventListener("touchstart", touchEncryptedNotebooks, {passive: true});
- document.body.addEventListener("mouseleave", () => {
+ bindGutterPointerLeave(document.body, () => {
if (window.siyuan.layout.leftDock) {
window.siyuan.layout.leftDock.hideDockByHover();
window.siyuan.layout.rightDock.hideDockByHover();
@@ -55,7 +55,7 @@ export const initWindowEvent = (app: App) => {
item.innerHTML = "";
});
hideTooltip();
- });
+ }, !!isInIOS());
window.addEventListener("mousemove", (event: MouseEvent & { target: HTMLElement }) => {
windowMouseMove(event);
diff --git a/app/src/boot/globalEvent/gutterMargin.test.ts b/app/src/boot/globalEvent/gutterMargin.test.ts
new file mode 100644
index 0000000000..cfeeb98d3a
--- /dev/null
+++ b/app/src/boot/globalEvent/gutterMargin.test.ts
@@ -0,0 +1,64 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync(__dirname + "/mousemove.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (paddingLeft: string, hasBlock = true) => {
+ const root = {
+ nodeType: 1, style: {},
+ classList: {contains: (cls: string) => cls === "protyle-wysiwyg"},
+ getBoundingClientRect: () => ({left: 100}),
+ };
+ const block = {classList: {contains: () => false}, getBoundingClientRect: () => ({left: 196})};
+ const hits: number[][] = [];
+ const rendered: unknown[] = [];
+ const protyle = {wysiwyg: {element: root}, gutter: {render: (_owner: unknown, target: unknown) => rendered.push(target)}};
+ const exports = {} as typeof import("./mousemove");
+ runInNewContext(compiled, {
+ exports,
+ window: {siyuan: {layout: {}, blockPanels: []}},
+ document: {
+ body: {classList: {contains: () => false}},
+ getElementById: (): null => null,
+ elementFromPoint: (x: number, y: number) => { hits.push([x, y]); return hasBlock ? block : null; },
+ },
+ getComputedStyle: () => ({paddingLeft}),
+ require: () => ({
+ hasClosestBlock: (target: unknown) => target,
+ getAllModels: () => ({editor: [{editor: {protyle}}], backlink: [] as unknown[]}),
+ }),
+ });
+ const move = (x: number) => exports.windowMouseMove({
+ clientX: x, clientY: 210, target: root, composedPath: () => [root],
+ } as unknown as MouseEvent);
+ return {move, hits, rendered, block};
+};
+
+test("hovering either editor margin restores a gutter with stylesheet padding and no inline padding", () => {
+ for (const x of [180, 900]) {
+ const f = fixture("96px");
+ f.move(x);
+ assert.deepEqual(f.hits, [[209, 210]]);
+ assert.deepEqual(f.rendered, [f.block]);
+ }
+});
+
+test("margin hit testing preserves fractional and zero computed padding", () => {
+ for (const [padding, x] of [["24.5px", 137.5], ["0px", 113]] as const) {
+ const f = fixture(padding);
+ f.move(101);
+ assert.deepEqual(f.hits, [[x, 210]]);
+ assert.deepEqual(f.rendered, [f.block]);
+ }
+});
+
+test("blank space below the last block does not invent a gutter target", () => {
+ const f = fixture("96px", false);
+ f.move(180);
+ assert.deepEqual(f.rendered, []);
+});
diff --git a/app/src/boot/globalEvent/gutterPointerLeave.ts b/app/src/boot/globalEvent/gutterPointerLeave.ts
new file mode 100644
index 0000000000..291fa22182
--- /dev/null
+++ b/app/src/boot/globalEvent/gutterPointerLeave.ts
@@ -0,0 +1,23 @@
+// iPad 的鼠标悬停转为触摸前会先报告无坐标离开,保留短暂切换期间的点击目标。
+export const bindGutterPointerLeave = (body: HTMLElement, leave: () => void, deferUnpositionedLeave: boolean) => {
+ const ownerDocument = body.ownerDocument;
+ const ownerWindow = ownerDocument.defaultView;
+ let timeout: number;
+ const cancel = () => {
+ ownerWindow.clearTimeout(timeout);
+ timeout = undefined;
+ };
+ body.addEventListener("pointerleave", (event: PointerEvent) => {
+ if (event.pointerType !== "mouse") {
+ return;
+ }
+ cancel();
+ if (deferUnpositionedLeave && event.clientX < 0 && event.clientY < 0) {
+ timeout = ownerWindow.setTimeout(leave, 100);
+ } else {
+ leave();
+ }
+ });
+ ownerDocument.addEventListener("pointerdown", cancel, {capture: true, passive: true});
+ body.addEventListener("pointerenter", cancel, {passive: true});
+};
diff --git a/app/src/boot/globalEvent/keydown.ts b/app/src/boot/globalEvent/keydown.ts
index 3ea804d5a9..c39a24b4b6 100644
--- a/app/src/boot/globalEvent/keydown.ts
+++ b/app/src/boot/globalEvent/keydown.ts
@@ -1,5 +1,4 @@
import type {BlockQueryRequestInput} from "../../types/api";
-import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
import {isAbove} from "../../util/zIndex";
import {stripSemanticMarkersFromRangeText} from "../../protyle/util/inlineElementMarker";
import {
@@ -1307,9 +1306,7 @@ const panelTreeKeydown = (app: App, event: KeyboardEvent) => {
let switchDialog: Dialog;
export const windowKeyDown = (app: App, event: KeyboardEvent) => {
- logKeyboardDiagnostic("window-enter", event);
if (event.defaultPrevented || filterHotkey(event, app)) {
- logKeyboardDiagnostic("window-stop", event, event.defaultPrevented ? "default-prevented" : "filtered");
return;
}
if (switchDialog &&
@@ -1320,7 +1317,6 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
}
if (searchKeydown(app, event)) {
- logKeyboardDiagnostic("window-stop", event, "search-keydown");
event.preventDefault();
event.stopPropagation();
return;
@@ -1328,13 +1324,11 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
const isTabWindow = isWindow();
if (bindMenuKeydown(event)) {
- logKeyboardDiagnostic("window-stop", event, "menu-keydown");
event.preventDefault();
return;
}
if (bindAVPanelKeydown(event)) {
- logKeyboardDiagnostic("window-stop", event, "av-panel");
event.preventDefault();
return;
}
@@ -1355,7 +1349,6 @@ export const windowKeyDown = (app: App, event: KeyboardEvent) => {
// 只读正文无法获得焦点,跨块选区的 Esc 不应按上一次活动面板分派。
if (!readonlyBlockSelection && !shortcutTarget.closest("input, textarea, .b3-menu, .av__panel, .av__mask")) {
if (shortcutTarget.closest(".protyle") && editKeydown(app, event)) {
- logKeyboardDiagnostic("window-stop", event, "editor-handled");
return;
}
if (!isTabWindow && shortcutTarget.closest(".sy__file") && fileTreeKeydown(app, event)) {
diff --git a/app/src/boot/globalEvent/mousemove.ts b/app/src/boot/globalEvent/mousemove.ts
index 2be4202a27..b6b314f98f 100644
--- a/app/src/boot/globalEvent/mousemove.ts
+++ b/app/src/boot/globalEvent/mousemove.ts
@@ -142,9 +142,11 @@ export const windowMouseMove = (event: MouseEvent) => {
// gutter
const eventPath0 = event.composedPath()[0] as HTMLElement;
- if (eventPath0 && eventPath0.nodeType !== 3 && eventPath0.classList.contains("protyle-wysiwyg") && eventPath0.style.paddingLeft) {
+ if (eventPath0 && eventPath0.nodeType !== 3 && eventPath0.classList.contains("protyle-wysiwyg")) {
// 光标在编辑器右边也需要进行显示
- const mouseElement = document.elementFromPoint(eventPath0.getBoundingClientRect().left + parseInt(eventPath0.style.paddingLeft) + 13, event.clientY);
+ // 平板布局的边距可能来自样式表,按实际内容边界寻找鼠标所在行的块。
+ const paddingLeft = parseFloat(getComputedStyle(eventPath0).paddingLeft) || 0;
+ const mouseElement = document.elementFromPoint(eventPath0.getBoundingClientRect().left + paddingLeft + 13, event.clientY);
const blockElement = hasClosestBlock(mouseElement);
if (blockElement) {
const targetBlockElement = getRightBlock(blockElement, blockElement.getBoundingClientRect().left + 1, event.clientY);
diff --git a/app/src/boot/globalEvent/pointerLeave.test.ts b/app/src/boot/globalEvent/pointerLeave.test.ts
new file mode 100644
index 0000000000..07a67d3c57
--- /dev/null
+++ b/app/src/boot/globalEvent/pointerLeave.test.ts
@@ -0,0 +1,54 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {bindGutterPointerLeave} from "./gutterPointerLeave";
+
+const fixture = (ios = true) => {
+ const timers = new Map<number, () => void>();
+ const ownerDocument = new EventTarget();
+ Object.assign(ownerDocument, {defaultView: {
+ setTimeout: (callback: () => void) => { timers.set(1, callback); return 1; },
+ clearTimeout: (id: number) => timers.delete(id),
+ }});
+ const body = Object.assign(new EventTarget(), {ownerDocument});
+ let hidden = 0;
+ bindGutterPointerLeave(body as unknown as HTMLElement, () => hidden++, ios);
+ const send = (type: string, pointerType: string, x = -1, y = -1) => {
+ const event = new Event(type);
+ Object.defineProperties(event, {pointerType: {value: pointerType}, clientX: {value: x}, clientY: {value: y}});
+ (type === "pointerdown" ? ownerDocument : body).dispatchEvent(event);
+ };
+ return {send, hidden: () => hidden, flush: () => { timers.forEach(callback => callback()); timers.clear(); }};
+};
+
+test("iPad mouse leave followed by touch down preserves the gutter hit target", () => {
+ const f = fixture();
+ f.send("pointerleave", "mouse");
+ assert.equal(f.hidden(), 0);
+ f.send("pointerdown", "touch", 361.5, 257.5);
+ f.send("pointerleave", "touch", 361.5, 257.5);
+ f.flush();
+ assert.equal(f.hidden(), 0);
+});
+
+test("a genuine iPad pointer exit clears the gutter after the transition interval", () => {
+ const f = fixture();
+ f.send("pointerleave", "mouse");
+ f.flush();
+ assert.equal(f.hidden(), 1);
+});
+
+test("pointer reentry cancels a pending clear before another hover target is shown", () => {
+ const f = fixture();
+ f.send("pointerleave", "mouse");
+ f.send("pointerenter", "mouse", 100, 200);
+ f.flush();
+ assert.equal(f.hidden(), 0);
+});
+
+test("positioned mouse exits and desktop exits retain immediate cleanup", () => {
+ for (const [ios, x, y] of [[true, 0, 200], [false, -1, -1]] as const) {
+ const f = fixture(ios);
+ f.send("pointerleave", "mouse", x, y);
+ assert.equal(f.hidden(), 1);
+ }
+});
diff --git a/app/src/boot/globalEvent/readonlyKeydown.test.ts b/app/src/boot/globalEvent/readonlyKeydown.test.ts
index 71492e8743..6723354e96 100644
--- a/app/src/boot/globalEvent/readonlyKeydown.test.ts
+++ b/app/src/boot/globalEvent/readonlyKeydown.test.ts
@@ -13,7 +13,7 @@ const loadFunction = (path: string, name: string, globals: Record<string, unknow
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
const exports: any = {};
- runInNewContext(compiled, {exports, logKeyboardDiagnostic: (): void => undefined,
+ runInNewContext(compiled, {exports,
handleDocumentBoundaryHotkey: () => false, ...globals});
return exports.subject;
};
diff --git a/app/src/command/executor.ts b/app/src/command/executor.ts
index f72d1ad9c0..c7e951363c 100644
--- a/app/src/command/executor.ts
+++ b/app/src/command/executor.ts
@@ -5,7 +5,6 @@ import {executeLegacyNativeCommand} from "./nativeRuntime";
import {getCommandRegistry} from "./service";
import {ensureContextCommands} from "./contextCommands";
import type {ICommandContextSnapshot, TCommandSource} from "./types";
-import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
interface IExecByCommandOptions {
command: string;
@@ -31,8 +30,6 @@ export const executeCommandById = (
) => ensureCommandSystem(app).execute(commandId, context, args);
export const execByCommand = async (options: IExecByCommandOptions) => {
- const trace = createKeyboardSearchTrace(options.command);
- trace("command-enter");
const app = options.app || window.siyuan.ws.app;
const context = options.context || captureCommandContext({
app,
@@ -42,17 +39,9 @@ export const execByCommand = async (options: IExecByCommandOptions) => {
fileLiElements: options.fileLiElements,
});
const commandId = getNativeCommandId(options.command);
- try {
- if (commandId) {
- const result = await ensureCommandSystem(app).execute(commandId, context);
- trace("command-result", result.status);
- return result;
- }
- await executeLegacyNativeCommand(options.command, context);
- trace("command-result", "executed");
- return {status: "executed" as const};
- } catch (error) {
- trace("command-error", "exception");
- throw error;
+ if (commandId) {
+ return ensureCommandSystem(app).execute(commandId, context);
}
+ await executeLegacyNativeCommand(options.command, context);
+ return {status: "executed" as const};
};
diff --git a/app/src/command/nativeRuntime.ts b/app/src/command/nativeRuntime.ts
index c9f6707d0a..9e335c7199 100644
--- a/app/src/command/nativeRuntime.ts
+++ b/app/src/command/nativeRuntime.ts
@@ -9,7 +9,7 @@ import {fetchSyncPost} from "../util/fetch";
import {globalCommand} from "../boot/globalEvent/command/global";
import {onlyProtyleCommand} from "../boot/globalEvent/command/protyle";
import type {ICommandContextSnapshot} from "./types";
-import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
+import {isInIOS} from "../protyle/util/compatibility";
/// #if MOBILE
import {popSearch} from "../mobile/menu/search";
/// #else
@@ -29,6 +29,18 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
const range = context.range;
const fileLiElements = context.fileTree?.elements;
+ /// #if MOBILE
+ if (!isFileFocus && protyle && isInIOS() && openOnly && ["search", "replace"].includes(command)) {
+ popSearch(app, {
+ page: 1,
+ hasReplace: command === "replace",
+ hPath: getNotebookName(protyle.notebookId),
+ idPath: [pathPosix().join(protyle.notebookId, protyle.path)],
+ }, true);
+ return;
+ }
+ /// #endif
+
if (!isFileFocus && protyle && onlyProtyleCommand({
command,
previousRange: range,
@@ -43,9 +55,10 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
(isMobile() && !document.getElementById("empty")?.classList.contains("fn__none"))) {
if (command === "replace") {
/// #if MOBILE
- popSearch(app, {hasReplace: true, page: 1});
+ popSearch(app, {hasReplace: true, page: 1}, openOnly);
/// #else
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_REPLACE,
key: range?.toString() || "",
@@ -53,9 +66,10 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
/// #endif
} else if (command === "search") {
/// #if MOBILE
- popSearch(app, {hasReplace: false, page: 1});
+ popSearch(app, {hasReplace: false, page: 1}, openOnly);
/// #else
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_SEARCH,
key: range?.toString() || "",
@@ -84,6 +98,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
});
/// #else
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_REPLACE,
key: range?.toString() || "",
@@ -102,6 +117,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
const isFile = fileLiElements[0].getAttribute("data-type") === "navigation-file";
if (isFile) {
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_REPLACE,
notebookId,
@@ -109,6 +125,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
});
} else {
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_REPLACE,
notebookId,
@@ -120,17 +137,10 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
case "search":
if (!isFileFocus) {
/// #if MOBILE
- const trace = createKeyboardSearchTrace("search");
- trace("search-enter");
- trace("path-start");
const response = await fetchSyncPost("/api/filetree/getHPathByPath", {
notebook: protyle.notebookId,
path: protyle.path.endsWith(".sy") ? protyle.path : protyle.path + ".sy",
- }).catch(error => {
- trace("path-error", "exception");
- throw error;
});
- trace("path-result", typeof response.data === "string" ? "string" : "invalid-data", response.code);
if (response.code !== 0 || typeof response.data !== "string") {
return;
}
@@ -140,9 +150,9 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
hPath: pathPosix().join(getNotebookName(protyle.notebookId), response.data),
idPath: [pathPosix().join(protyle.notebookId, protyle.path)],
});
- trace("dialog-created", "mobile");
/// #else
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_SEARCH,
key: range?.toString() || "",
@@ -161,6 +171,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
const isFile = fileLiElements[0].getAttribute("data-type") === "navigation-file";
if (isFile) {
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_SEARCH,
notebookId,
@@ -168,6 +179,7 @@ export const executeLegacyNativeCommand = async (command: string, context: IComm
});
} else {
openSearch({
+ focusInput: openOnly,
app,
hotkey: Constants.DIALOG_SEARCH,
notebookId,
diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.ts
index 9a9f2d5ee1..8cfdb7fa7d 100644
--- a/app/src/config/tabs/appTab.ts
+++ b/app/src/config/tabs/appTab.ts
@@ -30,7 +30,6 @@ import {genConfigItemMainHtml, genConfigItemName} from "../render/fragments";
import {sendAppSetting} from "./appRuntime";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {genWorkspaceStorageHtml, mountWorkspaceStorage} from "./workspaceStorage";
-import {flushKeyboardDiagnostics} from "../../util/keyboardDiagnostic";
/// #if MOBILE
const registerAppWorkspaceGroup = (tab: SettingTabBuilder) => {
@@ -589,8 +588,7 @@ const registerAppMaintenanceGroup = (tab: SettingTabBuilder) => {
label: window.siyuan.languages.export,
icon: "iconUpload",
afterMount: (root) => {
- root.querySelector("#exportLog")?.addEventListener("click", async () => {
- await flushKeyboardDiagnostics();
+ root.querySelector("#exportLog")?.addEventListener("click", () => {
fetchPost("/api/system/exportLog", {}, (response) => {
void saveExportFile(response.data.zip);
});
diff --git a/app/src/dialog/tooltipInput.test.ts b/app/src/dialog/tooltipInput.test.ts
index da1f3bbd56..3902010430 100644
--- a/app/src/dialog/tooltipInput.test.ts
+++ b/app/src/dialog/tooltipInput.test.ts
@@ -22,7 +22,7 @@ body {margin:0}.file-tree {position:absolute;top:40px;left:40px;width:232px}
</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);
+ new Function("exports", "require", sources[0])(input, () => ({isInIOS: () => false}));
let pluginShows = 0;
const tooltip = {} as typeof import("./tooltip");
window.DOMPurify = {sanitize: (value: string) => value} as typeof window.DOMPurify;
diff --git a/app/src/menus/index.ts b/app/src/menus/index.ts
index 70da198325..a65cb29f5a 100644
--- a/app/src/menus/index.ts
+++ b/app/src/menus/index.ts
@@ -17,12 +17,14 @@ import type {App} from "../index";
import {Constants} from "../constants";
import {textMenu} from "./text";
import {hideTooltip} from "../dialog/tooltip";
+import {bindTouchMenuDismiss} from "./menuClick";
export class Menus {
public menu: Menu;
constructor(app: App) {
this.menu = new Menu();
+ bindTouchMenuDismiss();
/// #if !MOBILE
window.addEventListener("contextmenu", (event) => {
if (event.shiftKey) {
diff --git a/app/src/menus/menuClick.ts b/app/src/menus/menuClick.ts
index 9c98ee72c9..28bcfa7a2a 100644
--- a/app/src/menus/menuClick.ts
+++ b/app/src/menus/menuClick.ts
@@ -1,5 +1,20 @@
import {hasClosestByAttribute} from "../protyle/util/hasClosest";
+export const bindTouchMenuDismiss = () => {
+ // 原生文字选择可能不派发 click;在捕获阶段关闭外部触摸对应的弹出菜单,保留编辑器的默认输入行为。
+ document.addEventListener("pointerdown", (event: PointerEvent) => {
+ if (event.pointerType !== "touch" && event.pointerType !== "pen") {
+ return;
+ }
+ const menu = window.siyuan.menus?.menu;
+ if (!menu || menu.element.classList.contains("fn__none") ||
+ menu.element.classList.contains("b3-menu--fullscreen")) {
+ return;
+ }
+ globalClickHideMenu(event.target as HTMLElement);
+ }, {capture: true, passive: true});
+};
+
export const globalClickHideMenu = (element: HTMLElement) => {
if (!window.siyuan.menus.menu.element.contains(element) && !hasClosestByAttribute(element, "data-menu", "true")) {
if (getSelection().rangeCount > 0 && window.siyuan.menus.menu.element.contains(getSelection().getRangeAt(0).startContainer) &&
diff --git a/app/src/menus/touchMenuDismiss.test.ts b/app/src/menus/touchMenuDismiss.test.ts
new file mode 100644
index 0000000000..522237a594
--- /dev/null
+++ b/app/src/menus/touchMenuDismiss.test.ts
@@ -0,0 +1,97 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compile = (file: string) => transpileModule(readFileSync(__dirname + file, "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+const source = compile("/menuClick.ts");
+const closestSource = compile("/../protyle/util/hasClosest.ts");
+
+const fixture = () => {
+ class Element {
+ nodeType = 1;
+ classes = new Set<string>();
+ attributes = new Map<string, string>();
+ classList = {contains: (name: string) => this.classes.has(name)};
+ constructor(public parentElement?: Element) {}
+ getAttribute(name: string) { return this.attributes.get(name); }
+ contains(target: Element): boolean {
+ return target === this || Boolean(target?.parentElement && this.contains(target.parentElement));
+ }
+ }
+ const menuElement = new Element();
+ const inside = new Element(menuElement);
+ const editor = new Element();
+ editor.classes.add("protyle-wysiwyg");
+ const content = new Element(editor);
+ const keeper = new Element();
+ keeper.attributes.set("data-menu", "true");
+ const keeperChild = new Element(keeper);
+ let removed = 0;
+ let handler: (event: PointerEvent) => void;
+ const document = {
+ activeElement: content,
+ addEventListener(type: string, callback: typeof handler, options: AddEventListenerOptions) {
+ assert.equal(type, "pointerdown");
+ assert.equal(options.capture, true);
+ assert.equal(options.passive, true);
+ handler = callback;
+ },
+ };
+ const menu = {element: menuElement, remove: () => removed++};
+ const window = {siyuan: {menus: {menu}}};
+ const selection = {rangeCount: 0, getRangeAt: () => ({startContainer: inside})};
+ const closest = {};
+ runInNewContext(closestSource, {exports: closest});
+ const exports = {} as typeof import("./menuClick");
+ runInNewContext(source, {exports, document, window, getSelection: () => selection, require: () => closest});
+ exports.bindTouchMenuDismiss();
+ const down = (target = content, pointerType = "touch") => {
+ const event = new Event("pointerdown", {cancelable: true});
+ Object.defineProperties(event, {target: {value: target}, pointerType: {value: pointerType}});
+ handler(event as PointerEvent);
+ assert.equal(event.defaultPrevented, false);
+ };
+ return {down, menuElement, inside, editor, content, keeperChild, document, selection, removed: () => removed};
+};
+
+test("outside touch and pen presses dismiss popups without a compatibility click", () => {
+ for (const pointerType of ["touch", "pen"]) {
+ const f = fixture();
+ f.down(f.content, pointerType);
+ f.down(f.editor, pointerType);
+ assert.equal(f.removed(), 2);
+ assert.equal(f.document.activeElement, f.content);
+ }
+});
+
+test("mouse presses, menu items and data-menu controls preserve their existing handlers", () => {
+ const f = fixture();
+ f.down(f.content, "mouse");
+ f.down(f.inside);
+ f.down(f.keeperChild);
+ assert.equal(f.removed(), 0);
+});
+
+test("hidden and fullscreen menus retain their dedicated lifecycle", () => {
+ for (const cls of ["fn__none", "b3-menu--fullscreen"]) {
+ const f = fixture();
+ f.menuElement.classes.add(cls);
+ f.down();
+ assert.equal(f.removed(), 0);
+ }
+});
+
+test("selection inside a focused menu retains the existing dismissal guard", () => {
+ const f = fixture();
+ f.selection.rangeCount = 1;
+ f.document.activeElement = f.inside;
+ f.down();
+ assert.equal(f.removed(), 0);
+ f.document.activeElement = f.content;
+ f.down();
+ assert.equal(f.removed(), 1);
+});
diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.ts
index b795e3bc1d..ecb4cf6b98 100644
--- a/app/src/mobile/index.ts
+++ b/app/src/mobile/index.ts
@@ -79,7 +79,6 @@ import {initializeEnglishCommandTranslations} from "../command/english";
import {loadLanguages} from "../boot/loadLanguages";
import {scrollInputIntoView} from "./util/visibleViewport";
import {installPluginStorageFetchAppId} from "../util/fetchAppId";
-import {initKeyboardDiagnostics} from "../util/keyboardDiagnostic";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -287,7 +286,6 @@ class App {
setWebViewFocusable();
});
// 移动端删除键 https://github.com/siyuan-note/siyuan/issues/9259
- initKeyboardDiagnostics("mobile");
window.addEventListener("keydown", (event) => {
mobileKeydown(siyuanApp, event);
if (getSelection().rangeCount > 0) {
diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.ts
index ead99d4b31..ea38014cfa 100644
--- a/app/src/mobile/menu/search.ts
+++ b/app/src/mobile/menu/search.ts
@@ -1,18 +1,19 @@
import {closePanel} from "../util/closePanel";
import {updateSearchMethodControls} from "../../search/methodCapabilities";
-import {buildSearchRequest} from "../../search/config";
+import {buildSearchRequest, refreshSearchConfigHPath} from "../../search/config";
+import {resolveCurrentSearchHPath} from "../../search/path";
+import {focusSearchInput} from "../../search/focus";
import {getAttr} from "../../search/attrs";
import type {APICallbackResponse, APIPOSTRoutes} from "../../types/api";
import {getCurrentEditor, openMobileFileById} from "../editor";
import {Constants} from "../../constants";
-import {createKeyboardSearchTrace} from "../../util/keyboardDiagnostic";
import {fetchPost} from "../../util/fetch";
import {getIconByType} from "../../editor/getIcon";
import {preventScroll} from "../../protyle/scroll/preventScroll";
import {openModel} from "./model";
import {getDisplayName, getNotebookIcon, getNotebookName, isEncryptedBox, movePathTo, pathPosix} from "../../util/pathName";
import {getKeyByLiElement, initCriteriaMenu, moreMenu} from "../../search/menu";
-import {isDisabledFeature, setStorageVal} from "../../protyle/util/compatibility";
+import {isDisabledFeature, isInIOS, setStorageVal} from "../../protyle/util/compatibility";
import {escapeHtml} from "../../util/escape";
import {unicode2Emoji} from "../../emoji";
import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";
@@ -769,9 +770,7 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTab
return () => clearTimeout(focusTimeout);
};
-export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig) => {
- const trace = createKeyboardSearchTrace(searchConfig ? "search" : "globalSearch");
- trace("search-enter");
+export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig, focusInput = false) => {
const config: Config.IUILayoutTabSearchConfig = JSON.parse(JSON.stringify(window.siyuan.storage[Constants.LOCAL_SEARCHDATA]));
const currentEditor = getCurrentEditor();
if (currentEditor && isEncryptedBox(currentEditor.protyle.notebookId)) {
@@ -811,6 +810,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf
});
let destroySearchEvent: (() => void) | undefined;
+ let destroyed = false;
openModel({
title: `<div class="toolbar__search">
<span data-menu="true" class="toolbar__icon toolbar__icon--history" data-type="history">
@@ -906,6 +906,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf
<div class="fn__loading"><img width="120px" src="/stage/loading-pure.svg"></div>
</div>`,
destroyCallback() {
+ destroyed = true;
destroySearchEvent?.();
activeBlur(true);
cancelSearchRequest(document.getElementById("modelMain"));
@@ -919,10 +920,23 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf
toggleSearchHistory(document.querySelector("#model"), config, undefined, element);
});
destroySearchEvent = initSearchEvent(app, element, config);
+ if (focusInput && isInIOS()) {
+ focusSearchInput(document.querySelector("#toolbarSearch"));
+ // 快捷键先同步打开搜索,路径名称随后补全,保留用户已经切换的搜索范围。
+ void refreshSearchConfigHPath({
+ config,
+ resolveHPath: resolveCurrentSearchHPath,
+ isCurrent: () => !destroyed && element.isConnected,
+ render: hPath => {
+ const pathElement = element.querySelector("#searchPath");
+ pathElement.classList.remove("fn__none");
+ pathElement.innerHTML = `<div class="b3-chip b3-chip--middle">${escapeHtml(hPath)}<svg data-type="remove-path" class="b3-chip__close"><use xlink:href="#iconClose"></use></svg></div>`;
+ },
+ });
+ }
updateSearchResult(config, element);
}
});
- trace("dialog-created", "mobile");
};
const goAsset = () => {
diff --git a/app/src/mobile/util/keydown.ts b/app/src/mobile/util/keydown.ts
index 8c6e4a75a5..6000e50e91 100644
--- a/app/src/mobile/util/keydown.ts
+++ b/app/src/mobile/util/keydown.ts
@@ -4,15 +4,11 @@ import {matchHotKey} from "../../protyle/util/hotKey";
import {getCurrentEditor} from "../editor";
import {filterHotkey} from "../../boot/globalEvent/commonHotkey";
import {captureShortcutContext, dispatchPluginShortcut} from "../../command/shortcutRuntime";
-import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
import {handleDocumentBoundaryHotkey} from "../../protyle/util/documentBoundaryHotkey";
export const mobileKeydown = (app: App, event: KeyboardEvent) => {
- logKeyboardDiagnostic("mobile-enter", event);
// 移动端输入框默认填充无 event.key
if (!event.key || event.defaultPrevented || filterHotkey(event, app)) {
- logKeyboardDiagnostic("mobile-stop", event, !event.key ? "missing-key" :
- event.defaultPrevented ? "default-prevented" : "filtered");
return;
}
const editor = getCurrentEditor();
diff --git a/app/src/mobile/util/tabShortcut.test.ts b/app/src/mobile/util/tabShortcut.test.ts
index 6050c36e10..7c6c0bab7c 100644
--- a/app/src/mobile/util/tabShortcut.test.ts
+++ b/app/src/mobile/util/tabShortcut.test.ts
@@ -12,7 +12,6 @@ it("does not consume the desktop tab menu binding on mobile", () => {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
}).outputText;
const dependencies: Record<string, object> = {
- "../../util/keyboardDiagnostic": {logKeyboardDiagnostic: (): void => undefined},
"../../boot/globalEvent/commonHotkey": {filterHotkey: () => false},
"../../protyle/util/hotKey": {matchHotKey: () => true},
"../../command/executor": {execByCommand: () => calls.push("native")},
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 9923e63a81..deebf8d100 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -683,7 +683,12 @@ export class Gutter {
(item as HTMLElement).style.display = "none";
});
};
- this.element.addEventListener("mouseleave", (event: MouseEvent & { target: HTMLInputElement }) => {
+ this.element.addEventListener("pointerdown", () => window.clearTimeout(hidePlusTimeout), {passive: true});
+ this.element.addEventListener("pointerleave", (event: PointerEvent & { target: HTMLInputElement }) => {
+ // 鼠标悬停后可能收到模拟触摸,保留按下时的命中元素直到点击完成。
+ if (event.pointerType !== "mouse") {
+ return;
+ }
// 鼠标移向框线或+号时不隐藏(它们定位在容器外侧,移出容器几何范围会触发 mouseleave)
const related = event.relatedTarget as HTMLElement;
if (related && (related.classList.contains("protyle-gutters__line") || related.classList.contains("protyle-gutters__plus"))) {
@@ -700,9 +705,8 @@ export class Gutter {
});
// 双元素交互:悬浮块标显示框线(贴边不动),悬浮框线显示+号(独立元素外偏定位)
this.element.addEventListener("pointermove", (event: PointerEvent & { target: HTMLElement }) => {
- // 仅鼠标悬浮显示插入控件,避免触摸合成的鼠标事件让透明框线覆盖块标。
+ // 触摸不改变已有悬停控件,避免按下与松开命中不同元素而丢失点击。
if (event.pointerType !== "mouse") {
- hideInsert();
return;
}
const lineBefore = this.element.querySelector('.protyle-gutters__line[data-type="gutterLineBefore"]') as HTMLElement;
diff --git a/app/src/protyle/gutter/pointerHover.test.ts b/app/src/protyle/gutter/pointerHover.test.ts
new file mode 100644
index 0000000000..919ffa57ec
--- /dev/null
+++ b/app/src/protyle/gutter/pointerHover.test.ts
@@ -0,0 +1,53 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {createSourceFile, forEachChild, isCallExpression, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("index.ts", readFileSync(__dirname + "/index.ts", "utf8"), ScriptTarget.ES2021, true);
+const listeners: string[] = [];
+const collect = (node: import("typescript").Node) => {
+ if (isCallExpression(node) && node.expression.getText(source) === "this.element.addEventListener" &&
+ ["\"mouseleave\"", "\"pointerleave\"", "\"pointermove\"", "\"pointerdown\""].includes(node.arguments[0].getText(source))) {
+ if (node.arguments[0].getText(source) === "\"pointerdown\"" && !node.getText(source).includes("hidePlusTimeout")) {
+ return;
+ }
+ listeners.push(node.getText(source));
+ }
+ forEachChild(node, collect);
+};
+collect(source);
+
+test("touch after mouse hover preserves gutter targets until click", () => {
+ const element = new EventTarget();
+ let hidden = 0;
+ const timers: (() => void)[] = [];
+ const js = transpileModule("let hidePlusTimeout;\n" + listeners.join("\n"), {
+ compilerOptions: {target: ScriptTarget.ES2021}
+ }).outputText;
+ new Function("hideInsert", "window", "protyle", js).call({element}, () => hidden++, {
+ clearTimeout: () => timers.splice(0),
+ setTimeout: (callback: () => void) => timers.push(callback)
+ }, {wysiwyg: {element: {querySelectorAll: (): Element[] => []}}});
+ const dispatch = (type: string, pointerType?: string) => {
+ const event = new Event(type);
+ Object.defineProperty(event, "pointerType", {value: pointerType});
+ element.dispatchEvent(event);
+ };
+ dispatch("pointerdown", "touch");
+ dispatch("mouseleave");
+ dispatch("pointermove", "touch");
+ dispatch("pointerup", "touch");
+ dispatch("pointerleave", "touch");
+ timers.forEach(callback => callback());
+ assert.equal(hidden, 0);
+ assert.equal(timers.length, 0);
+ dispatch("click");
+ dispatch("pointerleave", "mouse");
+ assert.equal(timers.length, 1);
+ timers.forEach(callback => callback());
+ assert.equal(hidden, 1);
+ dispatch("pointerleave", "mouse");
+ dispatch("pointerdown", "touch");
+ timers.forEach(callback => callback());
+ assert.equal(hidden, 1, "touch cancels the pending insertion-control hide before a longer tap");
+});
diff --git a/app/src/protyle/util/contextMenuHotkey.test.ts b/app/src/protyle/util/contextMenuHotkey.test.ts
index 5cfc224c97..86bdee399a 100644
--- a/app/src/protyle/util/contextMenuHotkey.test.ts
+++ b/app/src/protyle/util/contextMenuHotkey.test.ts
@@ -114,7 +114,6 @@ test("mobile leaves unhandled context menu shortcuts available to plugin dispatc
window: {siyuan: {config: {keymap: {general: {openContextMenu: {custom: "⌘/"}}}}}},
filterHotkey: () => false,
matchHotKey: () => { throw new Error("Context menu must be handled locally"); },
- logKeyboardDiagnostic: () => {},
captureShortcutContext: () => ({}),
dispatchPluginShortcut: () => { dispatched++; },
});
diff --git a/app/src/protyle/util/documentBoundaryHotkey.test.ts b/app/src/protyle/util/documentBoundaryHotkey.test.ts
index d6650f6cd7..dac0a9381b 100644
--- a/app/src/protyle/util/documentBoundaryHotkey.test.ts
+++ b/app/src/protyle/util/documentBoundaryHotkey.test.ts
@@ -103,7 +103,6 @@ test("editable and readonly bodies handle configured navigation before local car
const editor = {...f.protyle, disabled: false, wysiwyg: {element: body}};
const module = loadModule("src/protyle/wysiwyg/keydown.ts", {window: f.window}, {
"../util/documentBoundaryHotkey": f.helper,
- "../../util/keyboardDiagnostic": {logKeyboardDiagnostic: (): void => undefined},
"./verticalNavigation": {bindVerticalNavigationReset: (): void => undefined},
"../util/hasClosest": {hasClosestByAttribute: () => false},
"../render/av/attributeValue": {getAVTemplateInteractiveElement: () => false},
@@ -123,7 +122,6 @@ test("mobile navigation is limited to the current editor and does not dispatch t
keymapBindings.setKeymapBindings(f.general.goToDocumentEnd, ["End"]);
const module = loadModule("src/mobile/util/keydown.ts", {window: f.window}, {
"../../protyle/util/documentBoundaryHotkey": f.helper,
- "../../util/keyboardDiagnostic": {logKeyboardDiagnostic: (): void => undefined},
"../../boot/globalEvent/commonHotkey": {filterHotkey: () => false},
"../editor": {getCurrentEditor: () => ({protyle: f.protyle})},
"../../command/shortcutRuntime": {dispatchPluginShortcut: () => f.calls.push("plugin")},
diff --git a/app/src/protyle/util/hotKey.test.ts b/app/src/protyle/util/hotKey.test.ts
new file mode 100644
index 0000000000..074b9d9a96
--- /dev/null
+++ b/app/src/protyle/util/hotKey.test.ts
@@ -0,0 +1,78 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import * as keymapBindings from "../../util/keymapBindings";
+
+const compiled = transpileModule(readFileSync("src/protyle/util/hotKey.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (ios = true, mac = true) => {
+ const exports: any = {};
+ const dependencies: Record<string, object> = {
+ "../../util/keymapBindings": keymapBindings,
+ "../../constants": {Constants: {KEYCODELIST: {70: "F", 80: "P"}}},
+ "./compatibility": {
+ isInIOS: () => ios,
+ isMac: () => mac,
+ isNotCtrl: (event: KeyboardEvent) => !event.ctrlKey && !event.metaKey,
+ isOnlyMeta: (event: KeyboardEvent) => mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey,
+ },
+ };
+ runInNewContext(compiled, {exports, require: (name: string) => dependencies[name]});
+ return exports.matchHotKey as (binding: string | keymapBindings.IShortcutKeymap, event: KeyboardEvent) => boolean;
+};
+
+const event = (key: string, overrides: Partial<KeyboardEvent> = {}) => ({
+ key, code: `Key${key.toUpperCase()}`, keyCode: 229,
+ metaKey: true, ctrlKey: false, altKey: false, shiftKey: false, isComposing: false,
+ ...overrides,
+} as KeyboardEvent);
+
+test("iOS Chinese input matches Command search keys before composition starts", () => {
+ const match = fixture();
+ for (const key of ["f", "p", "F", "P"]) {
+ const input = event(key);
+ assert.equal(match(`⌘${key.toUpperCase()}`, input), true);
+ assert.equal(match(key.toLowerCase() === "f" ? "⌘P" : "⌘F", input), false);
+ assert.equal(input.keyCode, 229);
+ }
+});
+
+test("iOS Command fallback preserves composition and modifier boundaries", () => {
+ const match = fixture();
+ for (const overrides of [{isComposing: true}, {metaKey: false}, {ctrlKey: true},
+ {altKey: true}, {shiftKey: true}, {key: "Process"}, {key: "Unidentified"}, {key: ""}]) {
+ assert.equal(match("⌘F", event("f", overrides)), false, JSON.stringify(overrides));
+ }
+ assert.equal(match("F", event("f", {metaKey: false})), false);
+ assert.equal(match("⇧F", event("F", {metaKey: false, shiftKey: true})), false);
+ assert.equal(match("⇧⌘F", event("F", {shiftKey: true})), true);
+ assert.equal(match("⌥⌘P", event("p", {altKey: true})), true);
+});
+
+test("fallback follows custom and multiple bindings, including explicit unbinding", () => {
+ const match = fixture();
+ const binding = {default: "⌘F", custom: "⌘F"};
+ keymapBindings.setKeymapBindings(binding, ["⌘K", "⇧⌘P"]);
+ assert.equal(match(binding, event("f")), false);
+ assert.equal(match(binding, event("k")), true);
+ assert.equal(match(binding, event("P", {shiftKey: true})), true);
+ keymapBindings.setKeymapBindings(binding, []);
+ assert.equal(match(binding, event("f")), false);
+ assert.equal(match(binding, event("k")), false);
+});
+
+test("ordinary key codes and non-iOS platform matching remain unchanged", () => {
+ for (const ios of [false, true]) {
+ const match = fixture(ios);
+ assert.equal(match("⌘F", event("f", {keyCode: 70})), true);
+ assert.equal(match("⌘P", event("p", {keyCode: 80})), true);
+ }
+ assert.equal(fixture(false)("⌘F", event("f")), false);
+ const windows = fixture(false, false);
+ assert.equal(windows("⌘F", event("f", {keyCode: 70, metaKey: false, ctrlKey: true})), true);
+ assert.equal(windows("⌘F", event("f", {metaKey: false, ctrlKey: true})), false);
+});
diff --git a/app/src/protyle/util/hotKey.ts b/app/src/protyle/util/hotKey.ts
index b4fdc04eab..762c4cdc1c 100644
--- a/app/src/protyle/util/hotKey.ts
+++ b/app/src/protyle/util/hotKey.ts
@@ -1,4 +1,4 @@
-import {isMac, isNotCtrl, isOnlyMeta} from "./compatibility";
+import {isInIOS, isMac, isNotCtrl, isOnlyMeta} from "./compatibility";
import {Constants} from "../../constants";
import {getKeymapBindings, IShortcutKeymap, normalizeShortcutKey, visitKeymapItems} from "../../util/keymapBindings";
@@ -59,9 +59,13 @@ export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEve
return false;
}
+ // iOS 中文输入法可能将未组词的 Command 字母键标记为 229,此时按实际字母匹配。
+ const eventKey = event.keyCode === 229 && event.metaKey && !event.isComposing &&
+ /^[a-z]$/i.test(event.key) && isInIOS() ? event.key.toUpperCase() : Constants.KEYCODELIST[event.keyCode];
+
// []
if (hotKey.indexOf("⇧") === -1 && hotKey.indexOf("⌘") === -1 && hotKey.indexOf("⌥") === -1 && hotKey.indexOf("⌃") === -1) {
- if (isNotCtrl(event) && !event.altKey && !event.shiftKey && hotKey === Constants.KEYCODELIST[event.keyCode]) {
+ if (isNotCtrl(event) && !event.altKey && !event.shiftKey && hotKey === eventKey) {
return true;
}
return false;
@@ -81,7 +85,7 @@ export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEve
// 是否匹配 ⇧[]
if (hotKey.startsWith("⇧") && hotKeys.length === 2) {
- if (isNotCtrl(event) && !event.altKey && event.shiftKey && hotKeys[1] === Constants.KEYCODELIST[event.keyCode]) {
+ if (isNotCtrl(event) && !event.altKey && event.shiftKey && hotKeys[1] === eventKey) {
return true;
}
return false;
@@ -92,7 +96,7 @@ export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEve
if (hotKeys.length === 4) {
keyCode = hotKeys[3];
}
- const isMatchKey = keyCode === Constants.KEYCODELIST[event.keyCode];
+ const isMatchKey = keyCode === eventKey;
// 是否匹配 ⌥[] / ⌥⌘[]
if (isMatchKey && event.altKey && !event.shiftKey && hotKeys.length < 4 &&
(hotKeys.length === 3 ? (isOnlyMeta(event) && hotKey.startsWith("⌥⌘")) : isNotCtrl(event))) {
@@ -123,7 +127,7 @@ export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEve
keyCode = hotKeys[4];
}
- const isMatchKey = keyCode === Constants.KEYCODELIST[event.keyCode];
+ const isMatchKey = keyCode === eventKey;
// 是否匹配 ⌃[] / ⌃⌘[]
if (isMatchKey && event.ctrlKey && !event.altKey && !event.shiftKey && hotKeys.length < 4 &&
(hotKeys.length === 3 ? (event.metaKey && hotKey.startsWith("⌃⌘")) : !event.metaKey)) {
@@ -160,7 +164,7 @@ export const matchHotKey = (hotKey: string | IShortcutKeymap, event: KeyboardEve
// 是否匹配 ⇧⌘[] / ⌘[]
const hasShift = hotKeys.length > 2 && (hotKeys[0] === "⇧");
if (isOnlyMeta(event) && !event.altKey && ((!hasShift && !event.shiftKey) || (hasShift && event.shiftKey))) {
- return (hasShift ? hotKeys[2] : hotKeys[1]) === Constants.KEYCODELIST[event.keyCode];
+ return (hasShift ? hotKeys[2] : hotKeys[1]) === eventKey;
}
return false;
};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 9ff5a21f5b..f50547ab5b 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -12,6 +12,7 @@ import {isTabTextBoundary} from "./tabsBoundary";
import {captureCompositionText} from "./compositionCaret";
import {isCommittedTextInput} from "./compositionInput";
import {bindIOSTouchCaret} from "./touchCaret";
+import {clearTouchBlockSelection} from "./touchBlockSelection";
import {isDirectMathClick} from "../util/mathClick";
import {
beforePaste,
@@ -3926,7 +3927,8 @@ export class WYSIWYG {
}
});
- this.element.addEventListener("pointerdown", () => {
+ this.element.addEventListener("pointerdown", (event: PointerEvent) => {
+ clearTouchBlockSelection(protyle, event);
if (getSelection().rangeCount > 0) {
beforeContextmenuRange = getSelection().getRangeAt(0);
} else {
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index cd812d6bd4..1071cf34c5 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -1,6 +1,5 @@
import type {BlockQueryRequestInput} from "../../types/api";
import {handleReadonlyAttributeHotkey} from "../util/attributeHotkey";
-import {logKeyboardDiagnostic} from "../../util/keyboardDiagnostic";
import {isProtyleListItemFragment} from "../runtimeCapabilities";
import {toggleListMindmap} from "../render/listMindmap";
import {hideElements} from "../ui/hideElements";
@@ -302,18 +301,15 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
bindVerticalNavigationReset(editorElement);
editorElement.addEventListener("keydown", async (event: KeyboardEvent & { target: HTMLElement }) => {
if (event.target.localName === "protyle-html" || event.target.localName === "input") {
- logKeyboardDiagnostic("editor-stop", event, "input-target");
event.stopPropagation();
return;
}
if (getAVTemplateInteractiveElement(event.target)) {
- logKeyboardDiagnostic("editor-stop", event, "av-interactive");
event.stopPropagation();
return;
}
// 组合输入期间保留浏览器的原生选区,避免读取选区时修复光标而打断输入法。
if (event.isComposing) {
- logKeyboardDiagnostic("editor-stop", event, "composing");
event.stopPropagation();
return;
}
diff --git a/app/src/protyle/wysiwyg/listShortcut.dom.test.ts b/app/src/protyle/wysiwyg/listShortcut.dom.test.ts
index ee5750dc96..8ec611cbad 100644
--- a/app/src/protyle/wysiwyg/listShortcut.dom.test.ts
+++ b/app/src/protyle/wysiwyg/listShortcut.dom.test.ts
@@ -24,8 +24,9 @@ const browserCases = async (source: string) => {
const dependencies = {
Constants: {KEYCODELIST: {27: "Escape", 38: "↑", 74: "J", 76: "L"}, MENU_BLOCK_MULTI: "multi",
CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap"},
- bindVerticalNavigationReset: noop, logKeyboardDiagnostic: noop, getAVTemplateInteractiveElement: noop,
+ bindVerticalNavigationReset: noop, getAVTemplateInteractiveElement: noop,
handleDocumentBoundaryHotkey: noop,
+ handleReadonlyAttributeHotkey: () => false,
prepareVerticalNavigation: noop, avKeydown: noop, fixTable: noop, commonHotkey: noop,
countBlockWord: noop, clearAtomicFocus: noop,
setInsertWbrHTML: noop, getAtomicVerticalNavigationOwner: noop, revealTabsForTarget: noop,
diff --git a/app/src/protyle/wysiwyg/menuKeyboardLifecycle.test.ts b/app/src/protyle/wysiwyg/menuKeyboardLifecycle.test.ts
index fdae107bb8..ee2de73ab4 100644
--- a/app/src/protyle/wysiwyg/menuKeyboardLifecycle.test.ts
+++ b/app/src/protyle/wysiwyg/menuKeyboardLifecycle.test.ts
@@ -200,7 +200,7 @@ const historyFixture = (menuHidden = false) => {
const bind = compile(`${keydownDeclaration.getText(keydownSource)}\nexports.subject = keydown;`, {
bindVerticalNavigationReset: (): void => undefined,
handleDocumentBoundaryHotkey: () => false,
- logKeyboardDiagnostic: (): void => undefined,
+ handleReadonlyAttributeHotkey: () => false,
getAVTemplateInteractiveElement: () => false,
hasClosestByAttribute: () => false,
matchHotKey: (binding: string, event: KeyboardEvent) => binding === event.key,
diff --git a/app/src/protyle/wysiwyg/touchBlockDragSelect.test.ts b/app/src/protyle/wysiwyg/touchBlockDragSelect.test.ts
new file mode 100644
index 0000000000..e25b09c0aa
--- /dev/null
+++ b/app/src/protyle/wysiwyg/touchBlockDragSelect.test.ts
@@ -0,0 +1,68 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {getBlockDragSelectContentBounds} from "./blockDragSelect";
+
+const compiled = transpileModule(readFileSync(__dirname + "/touchBlockDragSelect.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (enabled = true) => {
+ const calls: string[] = [];
+ const element = Object.assign(new EventTarget(), {
+ closest: (selector: string): unknown => selector === ".protyle-wysiwyg" ? element : null,
+ getBoundingClientRect: () => ({left: 0, right: 500}),
+ });
+ class MouseEvent extends Event {
+ constructor(type: string, options: MouseEventInit) {
+ super(type, options);
+ Object.defineProperty(this, "clientX", {value: options.clientX});
+ }
+ }
+ ["mousedown", "mousemove", "mouseup", "click"].forEach(type => element.addEventListener(type, () => calls.push(type)));
+ const exports = {} as typeof import("./touchBlockDragSelect");
+ runInNewContext(compiled, {
+ exports, MouseEvent, window: {},
+ document: {elementFromPoint: () => element},
+ getComputedStyle: () => ({paddingLeft: "50px", paddingRight: "50px"}),
+ require: () => ({getBlockDragSelectContentBounds}),
+ });
+ exports.bindTouchBlockDragSelect(element as unknown as HTMLElement, () => enabled);
+ const send = (type: string, clientX: number) => {
+ const event = new Event(type, {cancelable: true});
+ const touch = {identifier: 1, clientX, clientY: 30};
+ Object.defineProperties(event, {touches: {value: [touch]}, changedTouches: {value: [touch]}});
+ element.dispatchEvent(event);
+ return event;
+ };
+ return {calls, send};
+};
+
+test("touching either editor margin forwards mouse selection without synthesizing a click", () => {
+ for (const x of [20, 480]) {
+ const {calls, send} = fixture();
+ assert.equal(send("touchstart", x).defaultPrevented, true);
+ assert.equal(send("touchend", x).defaultPrevented, true);
+ assert.deepEqual(calls, ["mousedown", "mouseup"]);
+ }
+});
+
+test("margin dragging still forwards movement and cleans up cancellation", () => {
+ const {calls, send} = fixture();
+ send("touchstart", 20);
+ send("touchmove", 25);
+ send("touchcancel", 25);
+ send("touchend", 25);
+ assert.deepEqual(calls, ["mousedown", "mousemove", "mouseup"]);
+});
+
+test("content touches and disabled margin gestures retain their native event handling", () => {
+ for (const [enabled, x] of [[true, 100], [false, 20]] as const) {
+ const {calls, send} = fixture(enabled);
+ assert.equal(send("touchstart", x).defaultPrevented, false);
+ assert.equal(send("touchend", x).defaultPrevented, false);
+ assert.deepEqual(calls, []);
+ }
+});
diff --git a/app/src/protyle/wysiwyg/touchBlockSelection.test.ts b/app/src/protyle/wysiwyg/touchBlockSelection.test.ts
new file mode 100644
index 0000000000..d358386c07
--- /dev/null
+++ b/app/src/protyle/wysiwyg/touchBlockSelection.test.ts
@@ -0,0 +1,52 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const compiled = transpileModule(readFileSync(__dirname + "/touchBlockSelection.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
+
+const fixture = (multi = false, editable = true, nested = false) => {
+ const calls: string[] = [];
+ const highlight = {classList: {remove: () => calls.push("highlight")}};
+ const root = {querySelector: () => ({}), querySelectorAll: () => [highlight]};
+ const target = {isContentEditable: editable, closest: () => nested ? {} : root};
+ const protyle = {wysiwyg: {element: root}, toolbar: {isMultiSelectMode: () => multi}};
+ const exports = {} as typeof import("./touchBlockSelection");
+ runInNewContext(compiled, {
+ exports,
+ require: () => ({hideElements: () => calls.push("selection"), countBlockWord: () => calls.push("status")}),
+ });
+ return {calls, down: (overrides: Partial<PointerEvent> = {}) => {
+ exports.clearTouchBlockSelection(protyle as unknown as IProtyle, {
+ target, pointerType: "touch", button: 0, ...overrides,
+ } as unknown as PointerEvent);
+ }};
+};
+
+test("native content touch without mouse events clears block selection and hover feedback", () => {
+ for (const pointerType of ["touch", "pen"]) {
+ const f = fixture();
+ f.down({pointerType});
+ assert.deepEqual(f.calls, ["selection", "status", "highlight"]);
+ }
+});
+
+test("mouse and modified gestures retain their selection handling", () => {
+ for (const event of [{pointerType: "mouse"}, {button: 2}, {ctrlKey: true}, {metaKey: true},
+ {altKey: true}, {shiftKey: true}]) {
+ const f = fixture();
+ f.down(event);
+ assert.deepEqual(f.calls, []);
+ }
+});
+
+test("multi-select mode, noneditable controls and nested editors keep their selections", () => {
+ for (const args of [[true, true, false], [false, false, false], [false, true, true]]) {
+ const f = fixture(...args);
+ f.down();
+ assert.deepEqual(f.calls, []);
+ }
+});
diff --git a/app/src/protyle/wysiwyg/touchBlockSelection.ts b/app/src/protyle/wysiwyg/touchBlockSelection.ts
new file mode 100644
index 0000000000..507df2f39e
--- /dev/null
+++ b/app/src/protyle/wysiwyg/touchBlockSelection.ts
@@ -0,0 +1,19 @@
+import {hideElements} from "../ui/hideElements";
+import {countBlockWord} from "../../layout/status";
+
+// 原生触摸可能只更新文字光标而不派发鼠标事件,进入正文编辑时先清理块选择反馈。
+export const clearTouchBlockSelection = (protyle: IProtyle, event: PointerEvent) => {
+ const root = protyle.wysiwyg.element;
+ const target = event.target as HTMLElement;
+ if (!["touch", "pen"].includes(event.pointerType) || event.button !== 0 ||
+ event.ctrlKey || event.metaKey || event.altKey || event.shiftKey ||
+ protyle.toolbar.isMultiSelectMode() || !target.isContentEditable ||
+ target.closest(".protyle-wysiwyg") !== root) {
+ return;
+ }
+ if (root.querySelector(".protyle-wysiwyg--select")) {
+ hideElements(["select"], protyle);
+ countBlockWord([], protyle);
+ }
+ root.querySelectorAll(".protyle-wysiwyg--hl").forEach(item => item.classList.remove("protyle-wysiwyg--hl"));
+};
diff --git a/app/src/search/focus.ts b/app/src/search/focus.ts
new file mode 100644
index 0000000000..1fb186c8cc
--- /dev/null
+++ b/app/src/search/focus.ts
@@ -0,0 +1,54 @@
+import {isInIOS} from "../protyle/util/compatibility";
+
+export const focusSearchInput = (input: HTMLInputElement) => {
+ const nativeComposition = isInIOS() && window.webkit?.messageHandlers.finishKeyboardComposition;
+ if (nativeComposition) {
+ const value = input.value;
+ const inputEvents = ["beforeinput", "input", "compositionstart", "compositionupdate", "compositionend"];
+ const endEvents = ["keydown", "keyup", "pointerdown", "blur"];
+ let ignoredInput = false;
+ let finishing = false;
+ let canceled = false;
+ // iOS 可能把触发搜索的快捷键继续交给输入法,忽略下一次用户操作前的残留输入。
+ const ignoreShortcutInput = (event: Event) => {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ ignoredInput = true;
+ };
+ const removeListeners = () => {
+ endEvents.forEach(type => input.removeEventListener(type, cleanup, true));
+ inputEvents.forEach(type => input.removeEventListener(type, ignoreShortcutInput, true));
+ };
+ const cleanup = (event: Event) => {
+ if (finishing) {
+ // 原生输入会话结束时会发出 blur,但网页焦点仍在当前输入框。
+ if (event.type === "blur" && document.activeElement === input) {
+ return;
+ }
+ if (event.type !== "keyup") {
+ canceled = true;
+ removeListeners();
+ }
+ return;
+ }
+ if (!ignoredInput || event.type !== "keyup") {
+ removeListeners();
+ return;
+ }
+ finishing = true;
+ // 原生输入法结束组词后再恢复内容,避免旧候选混入下一次正常输入。
+ void nativeComposition.postMessage("").then(() => {
+ if (!canceled && input.isConnected && document.activeElement === input) {
+ input.value = value;
+ removeListeners();
+ input.blur();
+ input.select();
+ return nativeComposition.postMessage("restore");
+ }
+ }).catch(error => console.error("Unable to finish keyboard composition:", error)).finally(removeListeners);
+ };
+ inputEvents.forEach(type => input.addEventListener(type, ignoreShortcutInput, true));
+ endEvents.forEach(type => input.addEventListener(type, cleanup, true));
+ }
+ input.select();
+};
diff --git a/app/src/search/path.ts b/app/src/search/path.ts
index df857d6a59..a53e45036a 100644
--- a/app/src/search/path.ts
+++ b/app/src/search/path.ts
@@ -27,7 +27,7 @@ export const beginSearchPathRequest = (element: Element) => {
return () => isSearchPathRequestVersionCurrent(element, version) && element.isConnected;
};
-const resolveCurrentSearchHPath = (idPath: string[], notebookNames: Record<string, string> = {}) => {
+export const resolveCurrentSearchHPath = (idPath: string[], notebookNames: Record<string, string> = {}) => {
return resolveSearchHPath(idPath, async (path) => {
const id = getSearchPathID(path);
const notebookHPath = resolveSearchNotebookHPath(path, window.siyuan.notebooks, notebookNames);
diff --git a/app/src/search/spread.ts b/app/src/search/spread.ts
index 9ca6090ea5..f6affcdcde 100644
--- a/app/src/search/spread.ts
+++ b/app/src/search/spread.ts
@@ -13,8 +13,8 @@ import {
setSearchConfigTemporaryPath,
} from "./config";
import {beginSearchPathRequest} from "./path";
-import {isDisabledFeature} from "../protyle/util/compatibility";
-import {createKeyboardSearchTrace} from "../util/keyboardDiagnostic";
+import {isDisabledFeature, isInIOS} from "../protyle/util/compatibility";
+import {focusSearchInput} from "./focus";
let openSearchVersion = 0;
@@ -24,15 +24,15 @@ export const openSearch = async (options: {
key?: string,
notebookId?: string,
notebookIds?: string[],
- searchPath?: string
+ searchPath?: string,
+ focusInput?: boolean,
}) => {
- const trace = createKeyboardSearchTrace(options.hotkey === Constants.DIALOG_SEARCH ? "search" :
- options.hotkey === Constants.DIALOG_GLOBALSEARCH ? "globalSearch" : "");
- trace("search-enter");
if (window.siyuan.isPublish && options.hotkey === Constants.DIALOG_REPLACE) {
return;
}
const version = ++openSearchVersion;
+ const selection = getSelection();
+ const range = selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : undefined;
const existingSearchDialog = window.siyuan.dialogs.find((item) => item.element.querySelector("#searchList"));
const existingSearchElement = existingSearchDialog?.element.querySelector(".b3-dialog__body");
const isCurrentPathRequest = existingSearchElement ? beginSearchPathRequest(existingSearchElement) : undefined;
@@ -46,18 +46,15 @@ export const openSearch = async (options: {
} else if (options.notebookId) {
hPath = getNotebookName(options.notebookId);
idPath.push(options.notebookId);
- if (options.searchPath && options.searchPath !== "/") {
- trace("path-start");
+ if (options.searchPath && options.searchPath !== "/" && isInIOS() && options.focusInput) {
+ // 外接键盘打开搜索时同步切换输入焦点,路径名称由 genSearch 的异步刷新补全。
+ idPath[0] = pathPosix().join(idPath[0], options.searchPath);
+ } else if (options.searchPath && options.searchPath !== "/") {
const response = await fetchSyncPost("/api/filetree/getHPathByPath", {
notebook: options.notebookId,
path: options.searchPath.endsWith(".sy") ? options.searchPath : options.searchPath + ".sy"
- }).catch(error => {
- trace("path-error", "exception");
- throw error;
});
- trace("path-result", typeof response.data === "string" ? "string" : "invalid-data", response.code);
if (version !== openSearchVersion || (isCurrentPathRequest && !isCurrentPathRequest())) {
- trace("path-stale");
return;
}
if (response.code !== 0 || typeof response.data !== "string") {
@@ -128,16 +125,10 @@ export const openSearch = async (options: {
} else if (options.hotkey === Constants.DIALOG_SEARCH) {
const toPath = item.editors.edit.protyle.path;
const toNotebook = item.editors.edit.protyle.notebookId;
- trace("path-start");
- let received = false;
fetchPost("/api/filetree/getHPathsByPaths", {paths: [toPath]}, (response) => {
- received = true;
- trace("path-result", Array.isArray(response.data) && typeof response.data[0] === "string" ?
- "string-array" : "invalid-data", response.code);
if (version !== openSearchVersion || !item.element.isConnected ||
item.element.getAttribute("data-key") !== Constants.DIALOG_SEARCH ||
(isCurrentPathRequest && !isCurrentPathRequest())) {
- trace("path-stale");
return;
}
if (!Array.isArray(response.data) || typeof response.data[0] !== "string") {
@@ -155,23 +146,17 @@ export const openSearch = async (options: {
storageConfig: replaceSearchConfigPath(
currentData, window.siyuan.storage[Constants.LOCAL_SEARCHDATA]),
});
- }).finally(() => {
- if (!received) {
- trace("path-error", "exception");
- }
});
}
return true;
}
});
if (exitDialog) {
- trace("dialog-reused");
+ if (options.focusInput) {
+ focusSearchInput(existingSearchElement.querySelector("#searchInput"));
+ }
return;
}
- let range: Range;
- if (getSelection().rangeCount > 0) {
- range = getSelection().getRangeAt(0);
- }
const dialog = new Dialog({
positionId: options.hotkey,
content: "",
@@ -200,5 +185,7 @@ export const openSearch = async (options: {
dialog.destroy({focus: "false"});
});
dialog.data = config;
- trace("dialog-created");
+ if (options.focusInput) {
+ focusSearchInput(dialog.element.querySelector("#searchInput"));
+ }
};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index c4c0986a24..0df6a87801 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -2244,14 +2244,6 @@ export type SystemImportConfRequestInput = { "file"?: Array<Blob>; };
export type SystemImportFileRequestInput = { "file"?: Blob; };
-export type SystemKeyboardLogEntryInput = { "command"?: string; "detail"?: string; "environment"?: SystemKeyboardLogEnvironmentInput | null; "event"?: number; "keyboard"?: SystemKeyboardLogEventInput | null; "responseCode"?: number | null; "seq": number; "stage": string; "time": number; };
-
-export type SystemKeyboardLogEnvironmentInput = { "frontend": string; "globalSearch": Array<string>; "platform": string; "search": Array<string>; "userAgent": string; "version": string; };
-
-export type SystemKeyboardLogEventInput = { "alt": boolean; "cancelBubble": boolean; "code": string; "composing": boolean; "ctrl": boolean; "defaultPrevented": boolean; "key": string; "keyCode": number; "matchGlobalSearch": boolean; "matchSearch": boolean; "meta": boolean; "repeat": boolean; "shift": boolean; "target": string; "trusted": boolean; };
-
-export type SystemKeyboardLogRequestInput = { "entries": Array<SystemKeyboardLogEntryInput>; "session": string; };
-
export type SystemLANSync = { "enabled": boolean; "maxConcurrentReqs": number; };
export type SystemLang = { "label": string; "name": string; };
@@ -6812,13 +6804,6 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
};
- "/api/system/appendKeyboardLog": {
- request: SystemKeyboardLogRequestInput;
- response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
- body: "json";
- /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
- authorization?: readonly ["authenticated","admin"];
- };
"/api/system/bootProgress": {
request: EmptyRequestInput;
response: { "code": 0; "data": BootProgressData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 636d65b08f..3bbcaed3c0 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -151,6 +151,7 @@ interface Window {
webkit: {
nativeCallbacks: { [key: string]: (id: number) => void },
messageHandlers: {
+ finishKeyboardComposition?: { postMessage: (data: string) => Promise<boolean> }
saveExportFile: { postMessage: (url: string) => void }
saveExportFileV2?: { postMessage: (data: {uri: string, requestID: string}) => void }
openLink: { postMessage: (url: string) => void }
@@ -1679,14 +1680,14 @@ interface ISiYuanUriBlockInfo {
/**
* 是否聚焦该块
- *
+ *
* @defaultValue false
*/
focus: boolean;
/**
* 是否全屏显示该块
- *
+ *
* @defaultValue false
*/
fullscreen: boolean;
diff --git a/app/src/util/hoverInput.ts b/app/src/util/hoverInput.ts
index 6109563826..671f5ca46c 100644
--- a/app/src/util/hoverInput.ts
+++ b/app/src/util/hoverInput.ts
@@ -1,3 +1,6 @@
+import {isInIOS} from "../protyle/util/compatibility";
+import {bindTouchActivation} from "./touchActivation";
+
let initialized = false;
export const isTouchHoverInput = () => document.body.classList.contains("body--touch-input");
@@ -8,6 +11,9 @@ export const initHoverInput = () => {
return;
}
initialized = true;
+ if (isInIOS()) {
+ bindTouchActivation(window);
+ }
document.body.classList.toggle("body--touch-input", window.matchMedia("(hover: none)").matches);
const update = (event: PointerEvent) => {
if (["mouse", "touch", "pen"].includes(event.pointerType)) {
diff --git a/app/src/util/keyboardDiagnostic.test.ts b/app/src/util/keyboardDiagnostic.test.ts
deleted file mode 100644
index c7c3291686..0000000000
--- a/app/src/util/keyboardDiagnostic.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import * as assert from "node:assert/strict";
-import {readFileSync} from "node:fs";
-import {join} from "node:path";
-import {test} from "node:test";
-import {runInNewContext} from "node:vm";
-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
-
-const fixture = (os = "ios", publish = false, send?: (payload: any) => Promise<object>, native = true) => {
- const listeners = new Map<string, (event: any) => void>();
- const timers = new Map<number, {callback: () => void, delay: number}>();
- const requests: any[] = [];
- let timer = 0;
- class Element {
- tagName = "DIV";
- closest() { return this; }
- }
- const exports: any = {};
- const source = transpileModule(readFileSync(join(__dirname, "keyboardDiagnostic.ts"), "utf8"), {
- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
- }).outputText;
- const dependencies: Record<string, object> = {
- "../constants": {Constants: {SIYUAN_VERSION: "test"}},
- "../protyle/util/compatibility": {isInIOS: () => os === "ios" && native},
- "../protyle/util/hotKey": {matchHotKey: (binding: string, event: any) =>
- event.metaKey && binding === (event.keyCode === 70 ? "F" : event.keyCode === 80 ? "P" : "")},
- "./keymapBindings": {getKeymapBindings: (key: string) => [key]},
- "./fetch": {fetchSyncPost: async (url: string, payload: object, headers: object, process: boolean) => {
- assert.equal(url, "/api/system/appendKeyboardLog");
- assert.equal(process, false);
- requests.push(JSON.parse(JSON.stringify(payload)));
- return send ? send(payload) : {code: 0};
- }},
- "./fetchTimeout": {withFetchTimeout: (request: () => Promise<object>) => request()},
- };
- runInNewContext(source, {
- exports, require: (name: string) => dependencies[name], HTMLElement: Element, AbortController,
- clearTimeout: (id: number) => timers.delete(id), queueMicrotask,
- document: {body: {}}, navigator: {platform: "MacIntel", userAgent: "SiYuan iPad"},
- window: {
- siyuan: {isPublish: publish, config: {system: {os}, keymap: {general: {search: "F", globalSearch: "P"}}}},
- setTimeout: (callback: () => void, delay: number) => { timers.set(++timer, {callback, delay}); return timer; },
- addEventListener: (type: string, listener: (event: any) => void, capture: boolean) => {
- assert.equal(capture, true);
- listeners.set(type, listener);
- },
- },
- });
- const event = (values: object = {}) => ({type: "keydown", key: "p", code: "KeyP", keyCode: 80,
- metaKey: true, ctrlKey: false, altKey: false, shiftKey: false, isComposing: false, repeat: false,
- isTrusted: true, defaultPrevented: false, cancelBubble: false, target: new Element(), ...values});
- const settle = () => {
- for (const [id, task] of timers) {
- if (task.delay === 0) {
- timers.delete(id);
- task.callback();
- }
- }
- };
- return {subject: exports, listeners, requests, event, timers, settle};
-};
-
-test("keyboard diagnostics only initialize once in the iOS app", async () => {
- for (const [os, publish] of [["windows", false], ["ios", true]] as const) {
- const value = fixture(os, publish);
- value.subject.initKeyboardDiagnostics("desktop");
- await value.subject.flushKeyboardDiagnostics();
- assert.equal(value.listeners.size, 0);
- assert.equal(value.requests.length, 0);
- }
- const browser = fixture("ios", false, undefined, false);
- browser.subject.initKeyboardDiagnostics("desktop");
- assert.equal(browser.listeners.size, 0);
- const value = fixture();
- value.subject.initKeyboardDiagnostics("mobile");
- value.subject.initKeyboardDiagnostics("mobile");
- await value.subject.flushKeyboardDiagnostics();
- assert.equal(value.requests[0].entries.length, 1);
- assert.equal(value.requests[0].entries[0].environment.frontend, "mobile");
-});
-
-test("captures composing and missing-modifier events without recording composition text", async () => {
- const value = fixture();
- value.subject.initKeyboardDiagnostics("desktop");
- const composing = value.event({key: "private-pinyin", code: "Unknown", keyCode: 229,
- metaKey: false, isComposing: true});
- value.listeners.get("compositionstart")({data: "private-document"});
- value.listeners.get("keydown")(composing);
- value.subject.logKeyboardDiagnostic("editor-stop", composing, "composing");
- composing.cancelBubble = true;
- await Promise.resolve();
- value.settle();
- const ordinary = value.event({metaKey: false});
- value.listeners.get("keydown")(ordinary);
- await Promise.resolve();
- value.settle();
- value.listeners.get("compositionend")({data: "private-document"});
- await value.subject.flushKeyboardDiagnostics();
- const entries = value.requests.flatMap(item => item.entries);
- const capture = entries.find(item => item.stage === "capture");
- const stopped = entries.find(item => item.stage === "editor-stop");
- const settled = entries.find(item => item.stage === "settled");
- assert.equal(capture.keyboard.keyCode, 229);
- assert.equal(capture.keyboard.composing, true);
- assert.equal(capture.keyboard.key, "Other");
- assert.equal(stopped.event, capture.event);
- assert.equal(settled.keyboard.cancelBubble, true);
- assert.equal(entries.filter(item => item.stage === "capture").length, 2);
- assert.equal(JSON.stringify(value.requests).includes("private-"), false);
-});
-
-test("retains event correlation across asynchronous search and flushes queued batches", async () => {
- const value = fixture();
- value.subject.initKeyboardDiagnostics("desktop");
- value.listeners.get("keydown")(value.event());
- const trace = value.subject.createKeyboardSearchTrace("globalSearch");
- trace("command-enter");
- await Promise.resolve();
- const duringDispatch = value.subject.createKeyboardSearchTrace("globalSearch");
- duringDispatch("command-enter");
- value.settle();
- trace("dialog-created");
- for (let index = 0; index < 60; index++) {
- value.listeners.get("compositionstart")({data: ""});
- }
- await value.subject.flushKeyboardDiagnostics();
- const entries = value.requests.flatMap(item => item.entries);
- assert.equal(value.requests.length, 2);
- assert.ok(value.requests.every(item => item.entries.length <= 50));
- const capture = entries.find(item => item.stage === "capture");
- assert.equal(capture.keyboard.matchGlobalSearch, true);
- assert.ok(entries.filter(item => item.stage === "command-enter").every(item => item.event === capture.event));
- assert.equal(entries.find(item => item.stage === "dialog-created").event, capture.event);
- assert.ok(entries.every((item, index) => item.seq === index + 1));
-});
-
-test("bounds memory, total records and failed requests without rejecting the export flush", async () => {
- const value = fixture("ios", false, async () => { throw new Error("offline"); });
- value.subject.initKeyboardDiagnostics("desktop");
- for (let index = 0; index < 1500; index++) {
- value.listeners.get("compositionstart")({data: ""});
- }
- for (let index = 0; index < 4; index++) {
- await value.subject.flushKeyboardDiagnostics();
- }
- assert.equal(value.requests.length, 3);
- assert.equal(value.requests[0].entries[0].seq, 801);
- assert.ok(value.requests.every(item => item.entries.every((entry: any) => entry.seq <= 1000)));
-});
diff --git a/app/src/util/keyboardDiagnostic.ts b/app/src/util/keyboardDiagnostic.ts
deleted file mode 100644
index a9323f1e44..0000000000
--- a/app/src/util/keyboardDiagnostic.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import {Constants} from "../constants";
-import {matchHotKey} from "../protyle/util/hotKey";
-import {isInIOS} from "../protyle/util/compatibility";
-import {getKeymapBindings} from "./keymapBindings";
-import {fetchSyncPost} from "./fetch";
-import {withFetchTimeout} from "./fetchTimeout";
-import type {SystemKeyboardLogEntryInput, SystemKeyboardLogEventInput} from "../types/api";
-
-const MAX_RECORDS = 1000;
-const MAX_PENDING = 200;
-const BATCH_SIZE = 50;
-const session = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
-const events = new WeakMap<KeyboardEvent, number>();
-let enabled = false;
-let sequence = 0;
-let eventSequence = 0;
-let activeEvent = 0;
-let pending: SystemKeyboardLogEntryInput[] = [];
-let timer: number;
-let sending: Promise<void>;
-let failures = 0;
-
-const record = (entry: Omit<SystemKeyboardLogEntryInput, "seq" | "time">) => {
- if (!enabled || sequence >= MAX_RECORDS) {
- return;
- }
- pending.push({...entry, seq: ++sequence, time: Date.now()});
- // 网络不可用时限制内存占用,保留最近的诊断记录。
- if (pending.length > MAX_PENDING) {
- pending.shift();
- }
- if (!timer && !sending && failures < 3) {
- timer = window.setTimeout(() => {
- timer = undefined;
- void flushKeyboardDiagnostics();
- }, 200);
- }
-};
-
-// 将已采集的记录写入系统日志,导出前等待当前批次和后续批次完成。
-export const flushKeyboardDiagnostics = async () => {
- clearTimeout(timer);
- timer = undefined;
- if (sending) {
- await sending;
- if (pending.length && failures < 3) {
- await flushKeyboardDiagnostics();
- }
- return;
- }
- if (!pending.length || failures >= 3) {
- return;
- }
- sending = (async () => {
- while (pending.length && failures < 3) {
- const entries = pending.splice(0, BATCH_SIZE);
- try {
- const response = await withFetchTimeout((signal) => fetchSyncPost(
- "/api/system/appendKeyboardLog", {session, entries}, undefined, false, signal), undefined, 3000);
- if (response.code !== 0) {
- throw new Error("keyboard diagnostic rejected");
- }
- failures = 0;
- } catch {
- failures++;
- pending = [...entries, ...pending].slice(-MAX_PENDING);
- break;
- }
- }
- })();
- await sending;
- sending = undefined;
- if (pending.length && failures < 3) {
- timer = window.setTimeout(() => {
- timer = undefined;
- void flushKeyboardDiagnostics();
- }, 1000);
- }
-};
-
-const snapshot = (event: KeyboardEvent): SystemKeyboardLogEventInput => {
- const target = event.target instanceof HTMLElement ? event.target : undefined;
- return {
- // 只保留目标快捷键和修饰键分类,不记录任意字符或组合输入内容。
- key: ["f", "F", "p", "P", "Meta", "Control", "Unidentified", "Process"].includes(event.key) ? event.key : "Other",
- code: ["KeyF", "KeyP", "MetaLeft", "MetaRight", "ControlLeft", "ControlRight"].includes(event.code) ? event.code : "Other",
- keyCode: event.keyCode,
- meta: event.metaKey,
- ctrl: event.ctrlKey,
- alt: event.altKey,
- shift: event.shiftKey,
- composing: event.isComposing,
- repeat: event.repeat,
- trusted: event.isTrusted,
- defaultPrevented: event.defaultPrevented,
- cancelBubble: event.cancelBubble,
- target: target?.tagName === "INPUT" ? "input" : target?.tagName === "TEXTAREA" ? "textarea" :
- target?.closest(".protyle-wysiwyg") ? "editor" : target === document.body ? "body" : "other",
- matchSearch: matchHotKey(window.siyuan.config.keymap.general.search, event),
- matchGlobalSearch: matchHotKey(window.siyuan.config.keymap.general.globalSearch, event),
- };
-};
-
-export const logKeyboardDiagnostic = (stage: string, event: KeyboardEvent, detail = "") => {
- const id = events.get(event);
- if (id) {
- record({stage, event: id, detail, keyboard: snapshot(event)});
- }
-};
-
-// 在同步分发时保存按键编号,使异步接口返回仍能关联原始按键。
-export const createKeyboardSearchTrace = (command: string) => {
- const event = activeEvent;
- const tracked = enabled && ["search", "globalSearch"].includes(command);
- return (stage: string, detail = "", responseCode?: number) => {
- if (tracked) {
- record({stage, event, command, detail, ...(responseCode === undefined ? {} : {responseCode})});
- }
- };
-};
-
-export const initKeyboardDiagnostics = (frontend: "desktop" | "mobile") => {
- if (enabled || window.siyuan.isPublish || !isInIOS()) {
- return;
- }
- enabled = true;
- record({stage: "environment", environment: {
- version: Constants.SIYUAN_VERSION,
- userAgent: navigator.userAgent.slice(0, 512),
- platform: navigator.platform.slice(0, 64),
- frontend,
- search: getKeymapBindings(window.siyuan.config.keymap.general.search).slice(0, 8).map(key => key.slice(0, 20)),
- globalSearch: getKeymapBindings(window.siyuan.config.keymap.general.globalSearch).slice(0, 8).map(key => key.slice(0, 20)),
- }});
- const capture = (event: KeyboardEvent) => {
- if (sequence >= MAX_RECORDS || !(event.metaKey || event.ctrlKey || event.keyCode === 229 ||
- [70, 80, 91, 93].includes(event.keyCode) || ["KeyF", "KeyP"].includes(event.code) ||
- ["f", "F", "p", "P", "Meta", "Control"].includes(event.key))) {
- return;
- }
- const id = ++eventSequence;
- events.set(event, id);
- if (event.type === "keydown") {
- activeEvent = id;
- }
- logKeyboardDiagnostic("capture", event, event.type);
- // 等待整个事件分发结束后记录最终状态,保留各处理器使用的按键编号。
- window.setTimeout(() => {
- logKeyboardDiagnostic("settled", event, event.type);
- if (activeEvent === id) {
- activeEvent = 0;
- }
- }, 0);
- };
- // 捕获阶段先于编辑器,阻止冒泡的按键仍留下原始状态。
- window.addEventListener("keydown", capture, true);
- window.addEventListener("keyup", capture, true);
- ["compositionstart", "compositionend"].forEach(stage => {
- window.addEventListener(stage, () => record({stage, event: activeEvent}), true);
- });
-};
diff --git a/app/src/util/touchActivation.test.ts b/app/src/util/touchActivation.test.ts
new file mode 100644
index 0000000000..5eb9ecafa5
--- /dev/null
+++ b/app/src/util/touchActivation.test.ts
@@ -0,0 +1,115 @@
+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 {test} from "node:test";
+import * as path from "node:path";
+import {promisify} from "node:util";
+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const browserCases = (source: string) => {
+ const check: typeof assert = require("node:assert/strict");
+ document.body.innerHTML = `<button id="button"><span>Button</span></button>
+<div class="b3-menu__item" id="menu"><span>Submenu</span></div>
+<li role="button" id="tab">Settings</li>
+<label id="label">Switch<input id="switch" type="checkbox"></label>
+<button disabled id="disabled">Disabled</button>
+<div class="b3-menu__item"><input id="text"><select id="select"><option>One</option></select></div>
+<div contenteditable="true" id="editor">Text</div>
+<div class="b3-dialog__scrim" id="dialogScrim"></div><div class="b3-menu__scrim" id="menuScrim"></div>`;
+ window.siyuan = {touchDragActive: false} as typeof window.siyuan;
+ const exports = {} as typeof import("./touchActivation");
+ new Function("exports", "require", source)(exports, () => ({Constants: {SIZE_DRAG_THRESHOLD: 5, TIMEOUT_LONGPRESS: 460}}));
+ let cleaned = false;
+ document.addEventListener("touchend", () => { cleaned = true; });
+ exports.bindTouchActivation(window);
+ let hit: Element;
+ document.elementFromPoint = () => hit;
+ const send = (target: Element, type: string, time = 0, x = 10, count = 1) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const touch = {identifier: 1, clientX: x, clientY: 10};
+ Object.defineProperties(event, {timeStamp: {value: time}, touches: {
+ value: type === "touchend" ? [] : Array(count).fill(touch)}, changedTouches: {value: [touch]}});
+ target.dispatchEvent(event);
+ return event;
+ };
+ for (const id of ["button", "menu", "tab", "switch", "label", "dialogScrim", "menuScrim"]) {
+ const control = document.getElementById(id);
+ const target = id === "button" || id === "menu" ? control.firstElementChild : control;
+ hit = target;
+ let clicks = 0;
+ control.addEventListener("click", event => {
+ if (event.target !== target) return;
+ clicks++;
+ check.equal(cleaned, true, "activation runs after document touch cleanup");
+ });
+ cleaned = false;
+ send(target, "touchstart");
+ check.equal(send(target, "touchend", 3).defaultPrevented, true);
+ check.equal(clicks, 1, id + " activates on the first short tap");
+ }
+ check.equal((document.getElementById("switch") as HTMLInputElement).checked, false,
+ "checkbox and its label each toggle exactly once");
+ for (const id of ["disabled", "text", "select", "editor"]) {
+ const target = document.getElementById(id);
+ hit = target;
+ send(target, "touchstart");
+ check.equal(send(target, "touchend", 3).defaultPrevented, false, id + " retains native handling");
+ }
+ const target = document.getElementById("button");
+ for (const kind of ["move", "long", "cancel", "multi", "miss", "prevented", "drag"]) {
+ hit = target;
+ let clicks = 0;
+ const count = () => { clicks++; };
+ target.addEventListener("click", count);
+ send(target, "touchstart");
+ if (kind === "move") send(target, "touchmove", 1, 16);
+ if (kind === "cancel") send(target, "touchcancel");
+ if (kind === "multi") send(target, "touchstart", 1, 10, 2);
+ if (kind === "miss") hit = null;
+ if (kind === "prevented") target.addEventListener("touchend", event => event.preventDefault(), {once: true});
+ window.siyuan.touchDragActive = kind === "drag";
+ send(target, "touchend", kind === "long" ? 500 : 3);
+ check.equal(clicks, 0, kind);
+ target.removeEventListener("click", count);
+ }
+ window.siyuan.touchDragActive = false;
+ let clicks = 0;
+ target.addEventListener("click", () => { clicks++; });
+ target.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: "mouse"}));
+ target.dispatchEvent(new PointerEvent("pointerup", {bubbles: true, pointerType: "mouse"}));
+ check.equal(clicks, 0, "mouse input is not synthesized");
+ const menu = document.getElementById("menu");
+ const order: string[] = [];
+ ["mouseenter", "mouseover", "click"].forEach(type => menu.addEventListener(type, () => order.push(type)));
+ hit = menu;
+ send(menu, "touchstart");
+ send(menu, "touchend", 3);
+ check.deepEqual(order, ["mouseenter", "mouseover", "click"], "lazy submenus load before activation");
+ return true;
+};
+
+test("iOS short taps activate shared controls once and preserve native gestures", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 30000,
+}, async () => {
+ const source = transpileModule(readFileSync(__dirname + "/touchActivation.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-touch-activation-"));
+ const script = path.join(temporary, "run.cjs");
+ writeFileSync(script, `const {app,BrowserWindow}=require("electron");
+app.setPath("userData",${JSON.stringify(path.join(temporary, "profile"))});
+app.whenReady().then(async()=>{const win=new BrowserWindow({show:false,
+webPreferences:{nodeIntegration:true,contextIsolation:false,offscreen:true}});
+try{await win.loadURL("data:text/html,<html><body></body></html>");
+await win.webContents.executeJavaScript(${JSON.stringify("const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(source) + ")")});
+win.destroy();app.exit(0);}catch(e){console.error(e);win.destroy();app.exit(1);}});`, "utf8");
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ await promisify(execFile)(require("electron") as unknown as string, [script], {env, timeout: 25000});
+ } finally {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+});
diff --git a/app/src/util/touchActivation.ts b/app/src/util/touchActivation.ts
new file mode 100644
index 0000000000..b6950894a1
--- /dev/null
+++ b/app/src/util/touchActivation.ts
@@ -0,0 +1,85 @@
+import {Constants} from "../constants";
+
+const controls = "button, [role=button], [role=tab], a[href], label, input[type=checkbox], input[type=radio], " +
+ "input[type=button], input[type=submit], input[type=reset], .b3-button, .b3-menu__item, .b3-list-item, " +
+ ".block__icon, .toolbar__item, .toolbar__icon, .dock__item, .b3-dialog__close, .layout-tab-bar .item, " +
+ ".protyle-breadcrumb__item, .b3-dialog__scrim, .b3-menu__scrim";
+
+const getControl = (target: Element) => {
+ if (!target) {
+ return;
+ }
+ // 输入、选词和原生选择器交给浏览器,避免菜单容器接管内部表单控件。
+ const input = target.closest("input");
+ const editable = target instanceof HTMLElement ? target.isContentEditable : target.parentElement?.isContentEditable;
+ if (editable || target.closest("textarea, select") ||
+ (input && !["checkbox", "radio", "button", "submit", "reset"].includes(input.type))) {
+ return;
+ }
+ const control = target.closest<HTMLElement>(controls);
+ if (!control || control.closest("[disabled], [aria-disabled=true], .b3-menu__item--readonly")) {
+ return;
+ }
+ if (control instanceof HTMLLabelElement && control.control &&
+ (!(control.control instanceof HTMLInputElement) || !["checkbox", "radio"].includes(control.control.type))) {
+ return;
+ }
+ return control;
+};
+
+// iOS 可能只派发悬停而吞掉短按的 click,在触摸处理结束后统一激活共用控件。
+export const bindTouchActivation = (view: Window) => {
+ let start: {id: number, x: number, y: number, time: number, target: Element, control: HTMLElement};
+ const cancel = () => {
+ start = undefined;
+ };
+ view.addEventListener("touchstart", (event: TouchEvent) => {
+ cancel();
+ if (event.defaultPrevented || event.touches.length !== 1 || !(event.target instanceof Element)) {
+ return;
+ }
+ const control = getControl(event.target);
+ if (!control) {
+ return;
+ }
+ const touch = event.touches[0];
+ start = {id: touch.identifier, x: touch.clientX, y: touch.clientY, time: event.timeStamp,
+ target: event.target, control};
+ }, {passive: true});
+ view.addEventListener("touchmove", (event: TouchEvent) => {
+ const touch = Array.from(event.touches).find(item => item.identifier === start?.id);
+ if (!start || event.touches.length !== 1 || !touch ||
+ Math.abs(touch.clientX - start.x) >= Constants.SIZE_DRAG_THRESHOLD ||
+ Math.abs(touch.clientY - start.y) >= Constants.SIZE_DRAG_THRESHOLD) {
+ cancel();
+ }
+ }, {passive: true});
+ view.addEventListener("touchcancel", cancel, {passive: true});
+ view.addEventListener("touchend", (event: TouchEvent) => {
+ const pressed = start;
+ cancel();
+ const touch = Array.from(event.changedTouches).find(item => item.identifier === pressed?.id);
+ if (!pressed || !touch || event.touches.length || event.defaultPrevented || !event.cancelable ||
+ window.siyuan.touchDragActive || !pressed.target.isConnected ||
+ event.timeStamp - pressed.time >= Constants.TIMEOUT_LONGPRESS ||
+ Math.abs(touch.clientX - pressed.x) >= Constants.SIZE_DRAG_THRESHOLD ||
+ Math.abs(touch.clientY - pressed.y) >= Constants.SIZE_DRAG_THRESHOLD ||
+ getControl(view.document.elementFromPoint(touch.clientX, touch.clientY)) !== pressed.control) {
+ return;
+ }
+ // window 冒泡阶段位于组件和 document 拖拽清理之后,取消原生兼容点击,避免重复执行。
+ event.preventDefault();
+ const options = {bubbles: true, cancelable: true, view,
+ clientX: touch.clientX, clientY: touch.clientY, button: 0, detail: 1,
+ altKey: event.altKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
+ const menuItem = pressed.target.closest(".b3-menu__item");
+ if (menuItem) {
+ // 桌面布局的子菜单复用悬停加载与展开逻辑,手机布局仍由 click 处理。
+ menuItem.dispatchEvent(new MouseEvent("mouseenter", {...options, bubbles: false}));
+ pressed.target.dispatchEvent(new MouseEvent("mouseover", options));
+ }
+ if (pressed.target.isConnected) {
+ pressed.target.dispatchEvent(new MouseEvent("click", options));
+ }
+ }, {passive: false});
+};
diff --git a/app/tests/compositionCaret.test.js b/app/tests/compositionCaret.test.js
index 6e06ea733c..0b50c6941f 100644
--- a/app/tests/compositionCaret.test.js
+++ b/app/tests/compositionCaret.test.js
@@ -64,7 +64,6 @@ const rendererSource = () => {
const getAVTemplateInteractiveElement = () => false;
const getBlockSelectionModeElement = () => undefined;
const revealTabsForTarget = () => {};
- const logKeyboardDiagnostic = () => {};
const getAtomicVerticalNavigationOwner = () => undefined;
const getSemanticMarkerPrefixLengthForNode = () => 0;
const normalizeInlineElementBoundaries = () => {};
diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.js
index e77b529b32..63ffce45a1 100644
--- a/app/tests/dialogFocus.test.js
+++ b/app/tests/dialogFocus.test.js
@@ -336,6 +336,186 @@ const runFlashcardCases = async (dialogSource, cardSource, mobile) => {
}
};
+const runSearchCases = async (dialogSource, focusSource, searchSource, mobileSource) => {
+ const assert = require("node:assert/strict");
+ const tick = () => new Promise(resolve => setTimeout(resolve, 20));
+ const constants = {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0, DIALOG_SEARCH: "search",
+ LOCAL_SEARCHDATA: "search", LOCAL_DIALOGPOSITION: "positions"};
+ window.siyuan = {dialogs: [], zIndex: 1, config: {}, storage: {search: {}, positions: {}},
+ menus: {menu: {element: document.createElement("div"), remove() {}}}};
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ editor.contentEditable = "true";
+ editor.textContent = "before after";
+ const other = document.createElement("input");
+ document.body.append(editor, other);
+ const placeCaret = () => {
+ editor.focus();
+ getSelection().setBaseAndExtent(editor.firstChild, 7, editor.firstChild, 7);
+ };
+ let resolvePath;
+ let rejectPath;
+ let ios = true;
+ let mobileOpened = false;
+ window.webkit = {messageHandlers: {finishKeyboardComposition: {postMessage: async () => true}}};
+ const modules = {
+ "../util/genID": {genUUID: () => String(Math.random())},
+ "../util/zIndex": {isAbove: () => false},
+ "./moveResize": {moveResize() {}},
+ "../util/functions": {isMobile: () => false},
+ "../constants": {Constants: constants},
+ "../block/panelOwnership": {getDialogBlockPanel() {}, destroyDialogBlockPanels() {}},
+ "../protyle/util/compatibility": {isInIOS: () => ios, isDisabledFeature: () => false},
+ "../protyle/util/selectionOffsets": {focusByRange: range => {
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ }},
+ "../util/fetch": {fetchSyncPost: () => new Promise((resolve, reject) => {
+ resolvePath = resolve;
+ rejectPath = reject;
+ })},
+ "../util/pathName": {getNotebookName: () => "Notebook", pathPosix: () => ({join: (...parts) => parts.join("/")})},
+ "./config": {hasExplicitSearchScope: () => true, setSearchConfigTemporaryPath() {}},
+ "./request": {cancelSearchRequest() {}},
+ "./util": {genSearch: (_app, _config, element) => {
+ element.innerHTML = '<input id="searchInput" value="previous query"><div id="searchList"></div>';
+ return {edit: {destroy() {}}, unRefEdit: {destroy() {}}};
+ }},
+ "../boot/globalEvent/command/global": {globalCommand: () => false},
+ "../boot/globalEvent/command/protyle": {onlyProtyleCommand: () => false},
+ "../mobile/menu/search": {popSearch: (_app, config, focusInput) => {
+ assert.equal(document.activeElement, editor);
+ assert.equal(focusInput, true);
+ assert.deepEqual(config.idPath, ["box//doc.sy"]);
+ mobileOpened = true;
+ }},
+ };
+ const load = source => {
+ const exports = {};
+ new Function("require", "exports", source)(name => modules[name] || {}, exports);
+ return exports;
+ };
+ modules["../dialog"] = load(dialogSource);
+ modules["./focus"] = modules["../search/focus"] = load(focusSource);
+ const {openSearch} = load(searchSource);
+ const mobile = load(mobileSource);
+ const search = () => openSearch({app: {}, hotkey: "search", notebookId: "box", searchPath: "/doc.sy"});
+ const mobileSearch = () => mobile.executeLegacyNativeCommand("search", {
+ app: {}, source: "shortcut", focus: "editor", range: getSelection().getRangeAt(0),
+ protyle: {notebookId: "box", path: "/doc.sy"},
+ });
+ for (const start of [search]) {
+ for (const failure of ["invalid", "network", "changed-focus"]) {
+ placeCaret();
+ const pending = start();
+ assert.equal(document.activeElement, editor);
+ if (failure === "changed-focus") {
+ other.focus();
+ }
+ if (failure === "network") {
+ rejectPath(new Error("offline"));
+ await assert.rejects(pending, /offline/);
+ } else {
+ resolvePath({code: -1, data: null});
+ await pending;
+ }
+ assert.equal(document.activeElement, failure === "changed-focus" ? other : editor);
+ if (failure !== "changed-focus") {
+ assert.equal(getSelection().anchorOffset, 7);
+ }
+ assert.equal(editor.textContent, "before after");
+ }
+ }
+ placeCaret();
+ const pending = search();
+ assert.equal(document.activeElement, editor);
+ assert.equal(window.siyuan.dialogs.length, 0);
+ // 异步期间原生选区可以变化,关闭搜索仍需恢复按键时的位置。
+ getSelection().collapse(editor.firstChild, 0);
+ resolvePath({code: 0, data: "/Document"});
+ await pending;
+ const dialog = window.siyuan.dialogs[0];
+ assert.ok(dialog.element.contains(document.activeElement));
+ dialog.destroy();
+ await tick();
+ assert.equal(document.activeElement, editor);
+ assert.equal(getSelection().anchorOffset, 7);
+ assert.equal(editor.textContent, "before after");
+
+ // iOS 外接键盘必须在按键事件内接管焦点,不能等待路径名称接口。
+ placeCaret();
+ const keyboardPending = openSearch({app: {}, hotkey: "search", notebookId: "box",
+ searchPath: "/doc.sy", focusInput: true});
+ assert.equal(window.siyuan.dialogs.length, 1);
+ const keyboardDialog = window.siyuan.dialogs[0];
+ assert.equal(document.activeElement.id, "searchInput");
+ assert.deepEqual(keyboardDialog.data.idPath, ["box//doc.sy"]);
+ assert.equal(document.activeElement.selectionStart, 0);
+ assert.equal(document.activeElement.selectionEnd, "previous query".length);
+ const input = document.activeElement;
+ const compositionCalls = [];
+ window.webkit.messageHandlers.finishKeyboardComposition.postMessage = async data => {
+ compositionCalls.push(data);
+ if (data === "") {
+ // WKWebView 结束原生会话会通知 blur,但仍保留网页 activeElement。
+ input.dispatchEvent(new FocusEvent("blur"));
+ }
+ return true;
+ };
+ let inputs = 0;
+ input.addEventListener("input", () => inputs++);
+ input.value = "f";
+ input.dispatchEvent(new InputEvent("input", {bubbles: true, isComposing: true}));
+ assert.equal(inputs, 0);
+ input.dispatchEvent(new KeyboardEvent("keyup", {key: "Meta"}));
+ await tick();
+ assert.equal(input.value, "previous query");
+ assert.equal(document.activeElement, input);
+ assert.deepEqual(compositionCalls, ["", "restore"]);
+ input.dispatchEvent(new KeyboardEvent("keydown", {key: "n"}));
+ input.value = "new query";
+ input.dispatchEvent(new InputEvent("input", {bubbles: true, isComposing: true}));
+ assert.equal(input.value, "new query");
+ assert.equal(inputs, 1);
+ // 原生回调返回前用户继续输入时,不覆盖新输入,也不继续拦截组词事件。
+ let finishComposition;
+ window.webkit.messageHandlers.finishKeyboardComposition.postMessage = () => new Promise(resolve => {
+ finishComposition = resolve;
+ });
+ modules["./focus"].focusSearchInput(input);
+ input.value = "p";
+ input.dispatchEvent(new InputEvent("input", {bubbles: true, isComposing: true}));
+ input.dispatchEvent(new KeyboardEvent("keyup", {key: "Meta"}));
+ input.dispatchEvent(new KeyboardEvent("keydown", {key: "n"}));
+ input.value = "newer query";
+ input.dispatchEvent(new InputEvent("input", {bubbles: true, isComposing: true}));
+ finishComposition(true);
+ await tick();
+ assert.equal(input.value, "newer query");
+ assert.equal(inputs, 2);
+ await keyboardPending;
+ keyboardDialog.destroy();
+ await tick();
+ assert.equal(document.activeElement, editor);
+ assert.equal(getSelection().anchorOffset, 7);
+
+ placeCaret();
+ const mobilePending = mobileSearch();
+ assert.equal(document.activeElement, editor);
+ await mobilePending;
+ assert.equal(mobileOpened, true);
+
+ ios = false;
+ placeCaret();
+ const desktopPending = search();
+ assert.equal(document.activeElement, editor);
+ resolvePath({code: -1, data: null});
+ await desktopPending;
+ assert.equal(document.activeElement, editor);
+ editor.remove();
+ other.remove();
+};
+
if (process.versions.electron && process.type === "browser") {
const {app, BrowserWindow, ipcMain} = require("electron");
app.setPath("userData", process.argv[2]);
@@ -365,6 +545,15 @@ if (process.versions.electron && process.type === "browser") {
await win.webContents.executeJavaScript(
`(${runPositionCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(positionSource)}, ${JSON.stringify(dialogCSS)})`);
const {parse} = require("ifdef-loader/preprocessor");
+ const compileSearch = (file, mobile = false) => ts.transpileModule(parse(
+ fs.readFileSync(path.join(__dirname, "../src", file), "utf8"),
+ {MOBILE: mobile, BROWSER: true}, false, true), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ await win.webContents.executeJavaScript(`(${runSearchCases.toString()})(
+ ${JSON.stringify(source)}, ${JSON.stringify(compileSearch("search/focus.ts"))},
+ ${JSON.stringify(compileSearch("search/spread.ts"))},
+ ${JSON.stringify(compileSearch("command/nativeRuntime.ts", true))})`);
const cardSource = fs.readFileSync(path.join(__dirname, "../src/card/openCard.ts"), "utf8");
for (const mobile of [false, true]) {
const compiled = ts.transpileModule(parse(cardSource, {MOBILE: mobile, BROWSER: true}, false, true), {
diff --git a/kernel/api/keyboard_diagnostic.go b/kernel/api/keyboard_diagnostic.go
deleted file mode 100644
index a17036e8b8..0000000000
--- a/kernel/api/keyboard_diagnostic.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package api
-
-import (
- "encoding/json"
- "net/http"
- "slices"
- "strings"
-
- "github.com/gin-gonic/gin"
- "github.com/siyuan-note/logging"
- "github.com/siyuan-note/siyuan/kernel/apicontract"
-)
-
-var appendKeyboardLog = contractHandler(apicontract.SystemAppendKeyboardLog,
- func(c *gin.Context, request apicontract.SystemKeyboardLogRequest) apicontract.Response[apicontract.Null] {
- if !validKeyboardLog(request) {
- return apicontract.Failure[apicontract.Null](-1, "invalid keyboard diagnostic records")
- }
- data, err := json.Marshal(request)
- if err != nil {
- return apicontract.Failure[apicontract.Null](-1, "encode keyboard diagnostic records failed")
- }
- logging.LogInfof("keyboard diagnostic [issue=20006] %s", data)
- return apicontract.Success(apicontract.Null{})
- }, func(c *gin.Context) *apicontract.Response[apicontract.Null] {
- // 限制读取大小,避免诊断接口接收无界请求。
- c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64*1024)
- return nil
- })
-
-func validKeyboardLog(request apicontract.SystemKeyboardLogRequest) bool {
- if len(request.Session) == 0 || len(request.Session) > 64 ||
- strings.IndexFunc(request.Session, func(r rune) bool {
- return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-')
- }) >= 0 || len(request.Entries) == 0 || len(request.Entries) > 50 {
- return false
- }
- for _, entry := range request.Entries {
- if entry.Seq < 1 || entry.Time < 1 || entry.Event < 0 ||
- !slices.Contains([]string{"", "keydown", "keyup", "input-target", "av-interactive", "composing", "progress",
- "error-log", "card-key", "plain-key", "default-prevented", "filtered", "search-keydown", "menu-keydown",
- "av-panel", "editor-handled", "missing-key", "executed", "notFound", "unavailable", "disabled",
- "exception", "string", "string-array", "invalid-data", "mobile"}, entry.Detail) ||
- !slices.Contains([]string{"environment", "capture", "settled", "compositionstart", "compositionend",
- "window-enter", "window-stop", "mobile-enter", "mobile-stop", "filter-stop", "editor-stop",
- "command-enter", "command-result", "command-error", "search-enter", "path-start", "path-error", "path-result", "path-stale",
- "dialog-created", "dialog-reused"}, entry.Stage) ||
- !slices.Contains([]string{"", "search", "globalSearch"}, entry.Command) {
- return false
- }
- if event := entry.Keyboard; event != nil {
- if !slices.Contains([]string{"f", "F", "p", "P", "Meta", "Control", "Unidentified", "Process", "Other"}, event.Key) ||
- !slices.Contains([]string{"KeyF", "KeyP", "MetaLeft", "MetaRight", "ControlLeft", "ControlRight", "Other"}, event.Code) ||
- !slices.Contains([]string{"input", "textarea", "editor", "body", "other"}, event.Target) ||
- event.KeyCode < 0 || event.KeyCode > 255 {
- return false
- }
- }
- if env := entry.Environment; env != nil {
- if len(env.Version) > 64 || len(env.UserAgent) > 512 || len(env.Platform) > 64 ||
- !slices.Contains([]string{"desktop", "mobile"}, env.Frontend) || len(env.Search) > 8 || len(env.GlobalSearch) > 8 {
- return false
- }
- for _, binding := range append(append([]string{}, env.Search...), env.GlobalSearch...) {
- if len(binding) > 64 {
- return false
- }
- }
- }
- }
- return true
-}
diff --git a/kernel/api/keyboard_diagnostic_test.go b/kernel/api/keyboard_diagnostic_test.go
deleted file mode 100644
index f9d969aa3e..0000000000
--- a/kernel/api/keyboard_diagnostic_test.go
+++ /dev/null
@@ -1,123 +0,0 @@
-package api
-
-import (
- archiveZip "archive/zip"
- "encoding/json"
- "io"
- "net/http"
- "net/http/httptest"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/gin-gonic/gin"
- "github.com/siyuan-note/logging"
- "github.com/siyuan-note/siyuan/kernel/apicontract"
- "github.com/siyuan-note/siyuan/kernel/model"
- "github.com/siyuan-note/siyuan/kernel/util"
-)
-
-func TestAPIContractKeyboardDiagnostic(t *testing.T) {
- oldConf, oldTemp, oldHome, oldLog, oldBypass := model.Conf, util.TempDir, util.HomeDir, logging.LogPath, util.SiYuanAccessAuthCodeBypass
- oldReadonly := util.ReadOnly
- model.Conf = model.NewAppConf()
- model.Conf.ReadOnly = true
- util.ReadOnly = true
- util.TempDir, util.HomeDir = t.TempDir(), t.TempDir()
- logging.SetLogPath(filepath.Join(util.TempDir, "siyuan.log"))
- util.SiYuanAccessAuthCodeBypass = false
- t.Cleanup(func() {
- model.Conf, util.TempDir, util.HomeDir = oldConf, oldTemp, oldHome
- logging.SetLogPath(oldLog)
- util.SiYuanAccessAuthCodeBypass = oldBypass
- util.ReadOnly = oldReadonly
- })
- request := func(role model.Role, body string) *httptest.ResponseRecorder {
- t.Helper()
- engine := gin.New()
- engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })
- ServeAPI(engine)
- recorder := httptest.NewRecorder()
- engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/system/appendKeyboardLog", strings.NewReader(body)))
- if recorder.Code == http.StatusOK {
- requireAPIContract(t, "POST", "/api/system/appendKeyboardLog", recorder)
- }
- return recorder
- }
- valid := `{"session":"test-20006","entries":[{"seq":1,"time":1,"stage":"command-enter","event":1,"command":"search"}]}`
- for _, role := range []model.Role{model.RoleReader, model.RoleEditor} {
- if response := request(role, valid); response.Code != http.StatusForbidden {
- t.Fatalf("non-admin admitted: %s", response.Body)
- }
- }
- if response := request(model.RoleVisitor, valid); response.Code != http.StatusUnauthorized {
- t.Fatalf("unauthenticated request admitted: %s", response.Body)
- }
- if response := request(model.RoleAdministrator, valid); !strings.Contains(response.Body.String(), `"code":0`) {
- t.Fatalf("read-only diagnostic write failed: %s", response.Body)
- }
- for _, body := range []string{
- `{}`, `{"session":"test","entries":[]}`, strings.Replace(valid, `"seq":1`, `"seq":"1"`, 1),
- strings.Replace(valid, `"stage":"command-enter"`, `"stage":"unknown"`, 1),
- strings.Replace(valid, `"command":"search"`, `"command":"private-document"`, 1),
- strings.Replace(valid, `"command":"search"`, `"detail":"private-pinyin"`, 1),
- strings.TrimSuffix(valid, "}") + `,"padding":"` + strings.Repeat("x", 65536) + `"}`,
- } {
- response := request(model.RoleAdministrator, body)
- var result struct {
- Code int `json:"code"`
- }
- if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Code >= 0 {
- t.Fatalf("invalid diagnostic accepted: %s", response.Body)
- }
- }
- data, err := os.ReadFile(logging.LogPath)
- if err != nil || !strings.Contains(string(data), "keyboard diagnostic [issue=20006]") || strings.Contains(string(data), "private-") {
- t.Fatalf("diagnostic log missing or contains rejected text: %s %v", data, err)
- }
- if path := model.ExportSystemLog(); path == "" {
- t.Fatal("system log export failed")
- }
- archive, err := archiveZip.OpenReader(filepath.Join(util.TempDir, "export", "system-log.zip"))
- if err != nil {
- t.Fatal(err)
- }
- defer archive.Close()
- for _, file := range archive.File {
- if strings.HasSuffix(file.Name, "/siyuan.log") {
- input, err := file.Open()
- if err != nil {
- t.Fatal(err)
- }
- exported, err := io.ReadAll(input)
- input.Close()
- if err != nil || !strings.Contains(string(exported), "test-20006") {
- t.Fatalf("export dropped keyboard diagnostics: %s %v", exported, err)
- }
- return
- }
- }
- t.Fatal("system log archive lacks siyuan.log")
-}
-
-func TestAPIContractKeyboardDiagnosticLimits(t *testing.T) {
- request := apicontract.SystemKeyboardLogRequest{Session: "test", Entries: []apicontract.SystemKeyboardLogEntry{{Seq: 1, Time: 1, Stage: "capture"}}}
- if !validKeyboardLog(request) {
- t.Fatal("valid diagnostic rejected")
- }
- request.Entries[0].Keyboard = &apicontract.SystemKeyboardLogEvent{Key: "private-pinyin", Code: "Other", Target: "editor"}
- if validKeyboardLog(request) {
- t.Fatal("arbitrary keyboard text accepted")
- }
- request.Entries[0].Keyboard.Key = "Other"
- if !validKeyboardLog(request) {
- t.Fatal("redacted keyboard event rejected")
- }
- for len(request.Entries) < 51 {
- request.Entries = append(request.Entries, request.Entries[0])
- }
- if validKeyboardLog(request) {
- t.Fatal("oversized batch accepted")
- }
-}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 0d26160039..9998c4a50e 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -170,7 +170,6 @@ func registerSystemRoutes(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/system/dismissOnboarding", contractRouteHandlers(apicontract.SystemDismissOnboarding, dismissOnboarding)...)
ginServer.Handle("POST", "/api/system/checkUpdate", contractRouteHandlers(apicontract.SystemCheckUpdate, checkUpdate)...)
ginServer.Handle("POST", "/api/system/exportLog", contractRouteHandlers(apicontract.SystemExportLog, exportLog)...)
- ginServer.Handle("POST", "/api/system/appendKeyboardLog", contractRouteHandlers(apicontract.SystemAppendKeyboardLog, appendKeyboardLog)...)
ginServer.Handle("POST", "/api/system/getChangelog", contractRouteHandlers(apicontract.SystemGetChangelog, getChangelog)...)
ginServer.Handle("POST", "/api/system/getNetwork", contractRouteHandlers(apicontract.GetNetwork, getNetwork)...)
ginServer.Handle("POST", "/api/system/exportConf", contractRouteHandlers(apicontract.SystemExportConf, exportConf)...)
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 5d03780e9b..1e1db8cd04 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1101,7 +1101,6 @@ var SystemEnsureOnboarding = define[EmptyRequest, *SystemOnboarding]("ensureOnbo
var SystemExit = define[SystemExitRequest, SystemExitData]("exit", "/api/system/exit", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 2}, DataOnError: true}, "POST")
var SystemExportConf = define[EmptyRequest, SystemExportConfData]("exportConf", "/api/system/exportConf", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportLog = define[EmptyRequest, SystemZipData]("exportLog", "/api/system/exportLog", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
-var SystemAppendKeyboardLog = define[SystemKeyboardLogRequest, Null]("appendKeyboardLog", "/api/system/appendKeyboardLog", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
var SystemExportTLSCABundle = define[EmptyRequest, SystemPathData]("exportTLSCABundle", "/api/system/exportTLSCABundle", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportTLSCACert = define[EmptyRequest, SystemPathData]("exportTLSCACert", "/api/system/exportTLSCACert", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemGetChangelog = define[SystemChangelogRequest, SystemChangelogData]("getChangelog", "/api/system/getChangelog", AuthenticatedAccess, LegacyOptionalBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/keyboard_diagnostic.go b/kernel/apicontract/keyboard_diagnostic.go
deleted file mode 100644
index 46615720fb..0000000000
--- a/kernel/apicontract/keyboard_diagnostic.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package apicontract
-
-// SystemKeyboardLogRequest 接收 iOS 快捷键诊断,每批 1 至 50 条,整个请求最多 64 KiB。
-// 仅管理员可写入,支持只读模式;记录不包含正文、组合输入文本、文档路径或设备标识。
-// session 是页面随机会话编号,seq 是会话内递增编号,event 关联同一次按键的处理阶段。
-// 文本字段限制长度,按键和目标只允许诊断用的固定分类;成功返回 null,非法记录返回 -1。
-type SystemKeyboardLogRequest struct {
- Session string `json:"session"`
- Entries []SystemKeyboardLogEntry `json:"entries"`
-}
-
-type SystemKeyboardLogEntry struct {
- Seq int `json:"seq"`
- Time int64 `json:"time"`
- Stage string `json:"stage"`
- Event int `json:"event" api:"optional"`
- Detail string `json:"detail" api:"optional"`
- Command string `json:"command" api:"optional"`
- ResponseCode *int `json:"responseCode,omitempty" api:"optional"`
- Keyboard *SystemKeyboardLogEvent `json:"keyboard,omitempty" api:"optional"`
- Environment *SystemKeyboardLogEnvironment `json:"environment,omitempty" api:"optional"`
-}
-
-type SystemKeyboardLogEvent struct {
- Key string `json:"key"`
- Code string `json:"code"`
- KeyCode int `json:"keyCode"`
- Meta bool `json:"meta"`
- Ctrl bool `json:"ctrl"`
- Alt bool `json:"alt"`
- Shift bool `json:"shift"`
- Composing bool `json:"composing"`
- Repeat bool `json:"repeat"`
- Trusted bool `json:"trusted"`
- DefaultPrevented bool `json:"defaultPrevented"`
- CancelBubble bool `json:"cancelBubble"`
- Target string `json:"target"`
- MatchSearch bool `json:"matchSearch"`
- MatchGlobalSearch bool `json:"matchGlobalSearch"`
-}
-
-type SystemKeyboardLogEnvironment struct {
- Version string `json:"version"`
- UserAgent string `json:"userAgent"`
- Platform string `json:"platform"`
- Frontend string `json:"frontend"`
- Search []string `json:"search"`
- GlobalSearch []string `json:"globalSearch"`
-}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index c4dc1d1cc6..18519ccd68 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -50974,190 +50974,6 @@
},
"additionalProperties": false
},
- "SystemKeyboardLogEntryInput": {
- "type": "object",
- "properties": {
- "command": {
- "type": "string"
- },
- "detail": {
- "type": "string"
- },
- "environment": {
- "anyOf": [
- {
- "$ref": "#/$defs/SystemKeyboardLogEnvironmentInput"
- },
- {
- "type": "null"
- }
- ]
- },
- "event": {
- "type": "integer"
- },
- "keyboard": {
- "anyOf": [
- {
- "$ref": "#/$defs/SystemKeyboardLogEventInput"
- },
- {
- "type": "null"
- }
- ]
- },
- "responseCode": {
- "anyOf": [
- {
- "type": "integer"
- },
- {
- "type": "null"
- }
- ]
- },
- "seq": {
- "type": "integer"
- },
- "stage": {
- "type": "string"
- },
- "time": {
- "type": "integer"
- }
- },
- "required": [
- "seq",
- "stage",
- "time"
- ],
- "additionalProperties": false
- },
- "SystemKeyboardLogEnvironmentInput": {
- "type": "object",
- "properties": {
- "frontend": {
- "type": "string"
- },
- "globalSearch": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "platform": {
- "type": "string"
- },
- "search": {
- "type": "array",
- "items": {
- "type": "string"
- }
- },
- "userAgent": {
- "type": "string"
- },
- "version": {
- "type": "string"
- }
- },
- "required": [
- "frontend",
- "globalSearch",
- "platform",
- "search",
- "userAgent",
- "version"
- ],
- "additionalProperties": false
- },
- "SystemKeyboardLogEventInput": {
- "type": "object",
- "properties": {
- "alt": {
- "type": "boolean"
- },
- "cancelBubble": {
- "type": "boolean"
- },
- "code": {
- "type": "string"
- },
- "composing": {
- "type": "boolean"
- },
- "ctrl": {
- "type": "boolean"
- },
- "defaultPrevented": {
- "type": "boolean"
- },
- "key": {
- "type": "string"
- },
- "keyCode": {
- "type": "integer"
- },
- "matchGlobalSearch": {
- "type": "boolean"
- },
- "matchSearch": {
- "type": "boolean"
- },
- "meta": {
- "type": "boolean"
- },
- "repeat": {
- "type": "boolean"
- },
- "shift": {
- "type": "boolean"
- },
- "target": {
- "type": "string"
- },
- "trusted": {
- "type": "boolean"
- }
- },
- "required": [
- "alt",
- "cancelBubble",
- "code",
- "composing",
- "ctrl",
- "defaultPrevented",
- "key",
- "keyCode",
- "matchGlobalSearch",
- "matchSearch",
- "meta",
- "repeat",
- "shift",
- "target",
- "trusted"
- ],
- "additionalProperties": false
- },
- "SystemKeyboardLogRequestInput": {
- "type": "object",
- "properties": {
- "entries": {
- "type": "array",
- "items": {
- "$ref": "#/$defs/SystemKeyboardLogEntryInput"
- }
- },
- "session": {
- "type": "string"
- }
- },
- "required": [
- "entries",
- "session"
- ],
- "additionalProperties": false
- },
"SystemLANSync": {
"type": "object",
"properties": {
@@ -167950,85 +167766,6 @@
]
}
},
- {
- "method": "POST",
- "path": "/api/system/appendKeyboardLog",
- "handler": "appendKeyboardLog",
- "authorization": [
- "authenticated",
- "admin"
- ],
- "body": "json",
- "request": {
- "$ref": "#/$defs/SystemKeyboardLogRequestInput"
- },
- "response": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "code": {
- "type": "integer",
- "enum": [
- 0
- ]
- },
- "data": {
- "type": "null"
- },
- "msg": {
- "type": "string"
- }
- },
- "required": [
- "code",
- "msg",
- "data"
- ],
- "additionalProperties": false
- },
- {
- "type": "object",
- "properties": {
- "code": {
- "type": "integer",
- "enum": [
- -1
- ]
- },
- "data": {
- "anyOf": [
- {
- "type": "object",
- "properties": {
- "closeTimeout": {
- "type": "number"
- }
- },
- "required": [
- "closeTimeout"
- ],
- "additionalProperties": false
- },
- {
- "type": "null"
- }
- ]
- },
- "msg": {
- "type": "string"
- }
- },
- "required": [
- "code",
- "msg",
- "data"
- ],
- "additionalProperties": true
- }
- ]
- }
- },
{
"method": "POST",
"path": "/api/system/bootProgress",