Skip to content

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

:bug: Insert block references from the mobile caret https://github.com/siyuan-note/siyuan/issues/20072

Daniel5638481edf6c
diff --git a/app/src/mobile/util/keyboardReference.test.ts b/app/src/mobile/util/keyboardReference.test.ts
new file mode 100644
index 0000000000..e0b8ec1c63
--- /dev/null
+++ b/app/src/mobile/util/keyboardReference.test.ts
@@ -0,0 +1,151 @@
+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 {createSourceFile, forEachChild, isCallExpression, isVariableDeclaration, Node, ScriptTarget, transpileModule} from "typescript";
+
+const source = createSourceFile("keyboardToolbar.ts", readFileSync(join(__dirname, "keyboardToolbar.ts"), "utf8"), ScriptTarget.Latest);
+let handlerSource: string;
+let keyboardSource: string;
+let entriesSource: string;
+const visit = (node: Node) => {
+ if (isCallExpression(node) && node.expression.getText(source) === "toolbarElement.addEventListener" &&
+ node.arguments[0].getText(source).includes('"touchend"')) {
+ handlerSource = node.arguments[1].getText(source);
+ }
+ if (isVariableDeclaration(node) && node.name.getText(source) === "keepBlockHintKeyboard") {
+ keyboardSource = node.initializer.getText(source);
+ }
+ if (isVariableDeclaration(node) && node.name.getText(source) === "applyKeyboardToolbarEntries") {
+ entriesSource = node.initializer.getText(source);
+ }
+ forEachChild(node, visit);
+};
+visit(source);
+assert.ok(handlerSource && keyboardSource && entriesSource);
+const compile = (text: string) => transpileModule(`(${text})`, {
+ compilerOptions: {target: ScriptTarget.ES2020},
+}).outputText;
+
+test("mobile reference remains available at a caret without exposing other selection-only tools", () => {
+ for (const hasText of [true, false]) {
+ for (const inCode of [true, false]) {
+ for (const hasRange of [true, false]) {
+ const protyle = {wysiwyg: {element: {contains: () => true}}};
+ const apply = runInNewContext(compile(entriesSource), {
+ getCurrentEditor: () => ({protyle}),
+ getSelection: () => ({rangeCount: hasRange ? 1 : 0, getRangeAt: () => ({})}),
+ hasClosestBlock: () => ({classList: {contains: () => inCode}}),
+ stripSemanticMarkersFromRangeText: () => hasText ? "selected" : "",
+ Constants: {ZWSP: "\u200b"}, getEntryOrder: (): string[] => [], isEntryVisible: () => false,
+ TOOLBAR_ENTRY_ROOT_PATH: "editor.toolbar", MOBILE_TOOLBAR_NAMES: ["block-ref", "strong"],
+ applyMobileToolbarEntries: (_element: unknown, _toolbar: unknown, options: {
+ isAvailable: (name: string) => boolean, isVisible: (key: string) => boolean,
+ }) => {
+ assert.equal(options.isAvailable("block-ref"), hasRange && !inCode);
+ assert.equal(options.isAvailable("strong"), hasRange && hasText && !inCode);
+ assert.equal(options.isVisible("block-ref"), false);
+ },
+ });
+ apply({}, []);
+ }
+ }
+ }
+});
+
+const setup = (options: {collapsed?: boolean, type?: string, disabled?: boolean, readonly?: boolean,
+ code?: boolean, editorDisabled?: boolean, moved?: boolean, missingRange?: boolean} = {}) => {
+ const calls: string[] = [];
+ const savedRange = {};
+ const range = {collapsed: options.collapsed !== false, startContainer: {}, cloneRange: () => savedRange};
+ const button = {
+ hasAttribute: () => !!options.disabled,
+ getAttribute: () => options.type || "block-ref",
+ classList: {contains: () => false},
+ };
+ const protyle = {
+ disabled: !!options.editorDisabled,
+ toolbar: {
+ range: {},
+ element: {querySelector: (selector: string) => ({dispatchEvent: () => calls.push(selector)})},
+ },
+ hint: {fillCommand: (value: string, owner: unknown, updateRange: boolean) => {
+ assert.equal(value, "((");
+ assert.equal(owner, protyle);
+ assert.equal(updateRange, false);
+ assert.equal(protyle.toolbar.range, savedRange);
+ calls.push("insert");
+ }},
+ };
+ const handler = runInNewContext(compile(handlerSource), {
+ takeMenuKeyboard() {}, moved: !!options.moved,
+ getCurrentEditor: () => ({protyle}), hasClosestByClassName: (): null => null,
+ hasClosestByTag: () => button, hasClosestByAttribute: () => !!options.code,
+ getSelection: () => ({rangeCount: options.missingRange ? 0 : 1, getRangeAt: () => range}),
+ window: {siyuan: {config: {readonly: !!options.readonly}}},
+ hasClosestBlock: () => ({}), MOBILE_TOOLBAR_INSERTS: [],
+ hideElements: () => calls.push("hide"),
+ keepBlockHintKeyboard: (owner: unknown) => { assert.equal(owner, protyle); calls.push("keyboard"); },
+ CustomEvent: class {},
+ });
+ return {calls, run: () => handler({target: {closest: (): null => null}, preventDefault() {}, stopPropagation() {}})};
+};
+
+test("collapsed mobile reference inserts the existing command using the current range", async () => {
+ const scenario = setup();
+ await scenario.run();
+ assert.deepEqual(scenario.calls, ["hide", "insert", "keyboard"]);
+});
+
+test("selected text and other inline tools retain their shared toolbar handlers", async () => {
+ for (const options of [{collapsed: false}, {type: "a"}, {type: "inline-math"}, {type: "inline-memo"}]) {
+ const scenario = setup(options);
+ await scenario.run();
+ assert.deepEqual(scenario.calls, ["hide", `[data-type="${options.type || "block-ref"}"]`]);
+ }
+});
+
+test("reference insertion retains disabled, readonly, code, gesture and range guards", async () => {
+ for (const options of [{disabled: true}, {readonly: true}, {editorDisabled: true},
+ {code: true}, {moved: true}, {missingRange: true}]) {
+ const scenario = setup(options);
+ await scenario.run();
+ assert.deepEqual(scenario.calls, []);
+ }
+});
+
+test("block hints preserve the keyboard and only restore the current attached editor range", () => {
+ for (const platform of ["android", "harmony", "ios"]) {
+ for (const change of ["none", "editor", "range", "detached", "outside"]) {
+ const calls: string[] = [];
+ let callback: () => void;
+ const node = {isConnected: true};
+ const range = {startContainer: node, endContainer: node};
+ let inside = true;
+ const protyle = {toolbar: {range}, wysiwyg: {element: {contains: () => inside}}};
+ let current = protyle;
+ const keepKeyboard = runInNewContext(compile(keyboardSource), {
+ hideKeyboardToolbarUtil: () => calls.push("hide"),
+ callMobileAppShowKeyboard: () => calls.push("keyboard"),
+ isInAndroid: () => platform === "android", isInHarmony: () => platform === "harmony",
+ getCurrentEditor: () => ({protyle: current}), Constants: {TIMEOUT_TRANSITION: 200},
+ setTimeout: (fn: () => void) => { callback = fn; },
+ focusByRange: (value: unknown) => { assert.equal(value, range); calls.push("focus"); },
+ });
+ keepKeyboard(protyle);
+ if (change === "editor") {
+ current = undefined;
+ } else if (change === "range") {
+ protyle.toolbar.range = {...range};
+ } else if (change === "detached") {
+ node.isConnected = false;
+ } else if (change === "outside") {
+ inside = false;
+ }
+ callback?.();
+ assert.deepEqual(calls, platform !== "ios" && change === "none" ?
+ ["hide", "keyboard", "focus"] : ["hide", "keyboard"]);
+ }
+ }
+});
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index bf7f153cd9..0b8f31ee57 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -118,6 +118,9 @@ const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string
if (name === "outdent" || name === "indent") {
return !!nodeElement?.parentElement.classList.contains("li") || !!inCode && hasText;
}
+ if (name === "block-ref") {
+ return !!range && !inCode;
+ }
if (name !== "block-type" && MOBILE_TOOLBAR_NAMES.includes(name)) {
return !inCode && hasText;
}
@@ -963,6 +966,23 @@ export const bindMobileMenuKeyboard = (element: HTMLElement, selector: string, g
};
};
+const keepBlockHintKeyboard = (protyle: IProtyle) => {
+ // 引用和嵌入候选没有输入框,关闭插入菜单后保留软键盘用于继续筛选。
+ hideKeyboardToolbarUtil();
+ callMobileAppShowKeyboard();
+ if (isInHarmony() || isInAndroid()) {
+ const range = protyle.toolbar.range;
+ setTimeout(() => {
+ if (getCurrentEditor()?.protyle === protyle && protyle.toolbar.range === range &&
+ range.startContainer.isConnected && range.endContainer.isConnected &&
+ protyle.wysiwyg.element.contains(range.startContainer) &&
+ protyle.wysiwyg.element.contains(range.endContainer)) {
+ focusByRange(range);
+ }
+ }, Constants.TIMEOUT_TRANSITION);
+ }
+};
+
const renderKeyboardToolbar = () => {
if (renderKeyboardToolbarFrame !== undefined) {
return;
@@ -1605,13 +1625,7 @@ export const initKeyboardToolbar = () => {
event.preventDefault();
event.stopPropagation();
if (dataValue === "((" || dataValue === "{{") {
- // (( / {{ 的候选列表无输入框,需保持键盘不收起,否则无法继续输入筛选 https://github.com/siyuan-note/siyuan/issues/17877
- // 关闭插入菜单,保留光标和软键盘用于输入查询条件
- hideKeyboardToolbarUtil();
- callMobileAppShowKeyboard();
- if (isInHarmony() || isInAndroid()) {
- setTimeout(() => focusByRange(protyle.toolbar.range), Constants.TIMEOUT_TRANSITION);
- }
+ keepBlockHintKeyboard(protyle);
} else if (slashBtnElement.getAttribute("data-focus") === "true" ||
liteSlashBtnElement && slashBtnElement.getAttribute("data-focus") !== "false") {
const selection = getSelection();
@@ -1738,6 +1752,12 @@ export const initKeyboardToolbar = () => {
} else if (["a", "block-ref", "inline-math", "inline-memo"].includes(type)) {
if (!hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {
hideElements(["util"], protyle);
+ if (type === "block-ref" && range.collapsed) {
+ protyle.toolbar.range = range.cloneRange();
+ protyle.hint.fillCommand("((", protyle, false);
+ keepBlockHintKeyboard(protyle);
+ return;
+ }
protyle.toolbar.element.querySelector(`[data-type="${type}"]`).dispatchEvent(new CustomEvent("click"));
}
return;
diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.ts
index ca25091608..229a9a3026 100644
--- a/app/src/protyle/hint/fillCommand.test.ts
+++ b/app/src/protyle/hint/fillCommand.test.ts
@@ -16,6 +16,49 @@ const code = transpileModule(`class Hint { ${methods} } new Hint();`, {
compilerOptions: {target: ScriptTarget.ES2020},
}).outputText;
+test("mobile reference command inserts at the saved caret and resets stale hint context", () => {
+ for (const [text, offset] of [["", 0], ["text", 0], ["text", 2], ["text", 4]] as const) {
+ for (const source of ["av", "search", "hint"]) {
+ let content: string = text;
+ let focused = false;
+ let queried = false;
+ const block = {outerHTML: "paragraph", getAttribute: () => "paragraph"};
+ const range = {
+ startContainer: block,
+ deleteContents() {},
+ insertNode: (node: {textContent: string}) => {
+ content = text.substring(0, offset) + node.textContent + text.substring(offset);
+ },
+ setEnd: (_node: unknown, value: number) => assert.equal(value, 2),
+ collapse: (toStart: boolean) => assert.equal(toStart, false),
+ };
+ const hint = runInNewContext(code, {
+ Constants: {BLOCK_HINT_KEYS: ["(("]},
+ hideElements() {}, isProtyleListItemFragment: () => false,
+ hasClosestBlock: () => block, hasClosestByAttribute: (): null => null,
+ getEditorRange: () => { throw new Error("reference insertion replaced the saved caret"); },
+ shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),
+ document: {createTextNode: (textContent: string) => ({textContent})},
+ hintRef: (key: string, _protyle: unknown, value: string) => {
+ assert.equal(key, "");
+ assert.equal(value, "hint");
+ queried = true;
+ },
+ focusByRange: (value: unknown) => { assert.equal(value, range); focused = true; },
+ });
+ Object.assign(hint, {source, splitChar: "#", lastIndex: 12, hashTagSearchElement: {}});
+ const protyle = {toolbar: {range}, wysiwyg: {element: {}}};
+ hint.fillCommand("((", protyle, false);
+ assert.equal(content, text.substring(0, offset) + "((" + text.substring(offset));
+ assert.equal(queried && focused, true);
+ assert.equal(hint.source, "hint");
+ assert.equal(hint.splitChar, "((");
+ assert.equal(hint.lastIndex, 0);
+ assert.equal(hint.hashTagSearchElement, undefined);
+ }
+ }
+});
+
for (const scenario of ["database shortcut", "database mobile toolbar", "tag search"]) {
test(`direct table insertion ignores residual ${scenario} context`, () => {
let rangeReads = 0;
diff --git a/app/tests/mobileEditingToolbar.test.js b/app/tests/mobileEditingToolbar.test.js
index b14ab145d9..8770f99b71 100644
--- a/app/tests/mobileEditingToolbar.test.js
+++ b/app/tests/mobileEditingToolbar.test.js
@@ -244,9 +244,21 @@ const runCases = async (sources, platform) => {
assert.equal(editable.getAttribute("inputmode"), "text");
assert.equal(toolbar.querySelector('[data-type="copy"]').classList.contains("fn__none"), true);
assert.equal(toolbar.querySelector('[data-type="cut"]').classList.contains("fn__none"), true);
- for (const name of ["indent", "outdent", "strong", "em", "a", "block-ref", "text"]) {
+ for (const name of ["indent", "outdent", "strong", "em", "a", "text"]) {
assert.equal(hidden(name), true);
}
+ assert.equal(hidden("block-ref"), false);
+ action("block-ref");
+ assert.equal(inserts.at(-1), "((");
+ assert.equal(current.toolbar.range.collapsed, true);
+ assert.equal(document.activeElement, editable);
+ await new Promise(resolve => setTimeout(resolve, constants.TIMEOUT_TRANSITION + 10));
+ visible.delete("block-ref");
+ await settle();
+ assert.equal(hidden("block-ref"), true);
+ visible.add("block-ref");
+ await settle();
+ assert.equal(hidden("block-ref"), false);
// 输入框不会因残留文档选区恢复文档工具栏。
const input = document.createElement("input");
document.body.append(input);