Skip to content

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

:bug: Reset hint context for direct block insertion https://github.com/siyuan-note/siyuan/issues/19996

Danielee8048a7df0c
diff --git a/app/src/command/insertCommands.test.ts b/app/src/command/insertCommands.test.ts
index 1eac91db57..0bd9017235 100644
--- a/app/src/command/insertCommands.test.ts
+++ b/app/src/command/insertCommands.test.ts
@@ -53,7 +53,12 @@ test("insert commands search and execute existing insertion actions at the saved
const protyle = {
lite: false, disabled: false, wysiwyg: {element: {contains: (node: unknown) => node === container}},
options: {upload: {accept: "image/*"}}, toolbar: {range: undefined as unknown},
- hint: {splitChar: "", lastIndex: 2, fill: (value: string) => fills.push(value),
+ hint: {fillCommand: (value: string, target: unknown, updateRange: boolean) => {
+ assert.equal(target, protyle);
+ assert.equal(updateRange, false);
+ assert.ok(protyle.toolbar.range);
+ fills.push(value);
+ },
bindUploadEvent: (_protyle: unknown, host: unknown) => { uploadBound = host === uploadHost; }},
};
const context = {
@@ -74,8 +79,6 @@ test("insert commands search and execute existing insertion actions at the saved
assert.equal(queryCommandPalette(registry, context, "", recent)[0].id, "core.mobile.insert.assets");
assert.equal((await registry.execute("core.mobile.insert.template", context)).status, "executed");
assert.deepEqual(fills, ["template-value"]);
- assert.equal(protyle.hint.splitChar, "/");
- assert.equal(protyle.hint.lastIndex, -1);
assert.equal(focused.length, 1);
assert.ok(protyle.toolbar.range);
await registry.execute("core.mobile.insert.ref", context);
diff --git a/app/src/command/insertCommands.ts b/app/src/command/insertCommands.ts
index 1849c36a9a..03004037f7 100644
--- a/app/src/command/insertCommands.ts
+++ b/app/src/command/insertCommands.ts
@@ -120,10 +120,8 @@ const executeInsert = (context: ICommandContextSnapshot, id: string) => {
return;
}
protyle.toolbar.range = context.range.cloneRange();
- protyle.hint.splitChar = "/";
- protyle.hint.lastIndex = -1;
focusByRange(protyle.toolbar.range);
- protyle.hint.fill(item.value, protyle, false);
+ protyle.hint.fillCommand(item.value, protyle, false);
if ((context.environment === "mobile" || context.environment === "browser-mobile") &&
(id === "ref" || id === "blockEmbed")) {
/// #if MOBILE
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index f8a2f99d19..2666cec14e 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -1573,7 +1573,7 @@ export const initKeyboardToolbar = () => {
}
hideKeyboardToolbarUtil();
}
- protyle.hint.fill(dataValue, protyle, false); // 点击后 range 会改变
+ protyle.hint.fillCommand(dataValue, protyle, false); // 点击后 range 会改变
event.preventDefault();
event.stopPropagation();
if (dataValue === "((" || dataValue === "{{") {
@@ -1693,7 +1693,7 @@ export const initKeyboardToolbar = () => {
const insert = MOBILE_TOOLBAR_INSERTS.find(item => item.name === type);
if (insert) {
protyle.toolbar.range = range.cloneRange();
- protyle.hint.fill(insert.value(Constants), protyle, false);
+ protyle.hint.fillCommand(insert.value(Constants), protyle, false);
return;
} else if (["a", "block-ref", "inline-math", "inline-memo"].includes(type)) {
if (!hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock")) {
diff --git a/app/src/protyle/hint/fillCommand.test.ts b/app/src/protyle/hint/fillCommand.test.ts
new file mode 100644
index 0000000000..ca25091608
--- /dev/null
+++ b/app/src/protyle/hint/fillCommand.test.ts
@@ -0,0 +1,103 @@
+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, isClassDeclaration, ScriptTarget, transpileModule} from "typescript";
+import {getAVBindingOperations} from "../render/av/binding";
+import {shouldCaptureHintUndoFocus} from "./blockHintRange";
+
+const source = createSourceFile("index.ts", readFileSync(join(__dirname, "index.ts"), "utf8"), ScriptTarget.Latest);
+const declaration = source.statements.find(node => isClassDeclaration(node) && node.name.text === "Hint");
+assert.ok(declaration && isClassDeclaration(declaration));
+const methods = declaration.members.filter(member => ["fillCommand", "fill"].includes(member.name?.getText(source)))
+ .map(member => member.getText(source)).join("\n");
+const code = transpileModule(`class Hint { ${methods} } new Hint();`, {
+ compilerOptions: {target: ScriptTarget.ES2020},
+}).outputText;
+
+for (const scenario of ["database shortcut", "database mobile toolbar", "tag search"]) {
+ test(`direct table insertion ignores residual ${scenario} context`, () => {
+ let rangeReads = 0;
+ let updated = false;
+ let mutated = false;
+ const original = {
+ outerHTML: "original paragraph",
+ getAttribute: (name: string) => name === "data-type" ? "NodeParagraph" : "original",
+ querySelector: (): null => null,
+ remove() {}, insertAdjacentHTML() {}, nextElementSibling: undefined as unknown,
+ };
+ const inserted = {
+ outerHTML: "inserted table",
+ getAttribute: (name: string) => name === "data-type" ? "NodeTable" : "new-table",
+ querySelectorAll: (): HTMLElement[] => [], classList: {contains: () => false}, previousElementSibling: original,
+ };
+ original.nextElementSibling = inserted;
+ const range = {startContainer: original, deleteContents() { mutated = true; }};
+ const staleRange = {startContainer: {}};
+ const savedRange = scenario === "database mobile toolbar";
+ const hint = runInNewContext(code, {
+ Constants: {BLOCK_HINT_KEYS: ["(("], INLINE_TYPE: [], ZWSP: "\u200b"},
+ Lute: {Caret: "caret"}, Element: class {}, getSelection: (): null => null,
+ document: {createElement: () => ({innerHTML: "", firstElementChild: {
+ getAttribute: () => "NodeTable",
+ }})},
+ hideElements() {}, isProtyleListItemFragment: () => false,
+ getEditorRange: () => { rangeReads++; return range; },
+ hasClosestBlock: (node: unknown) => node === original ? original : null,
+ hasClosestByClassName: () => false,
+ shouldCaptureHintUndoFocus, getUndoFocusContext: () => ({}),
+ getAVBindingCell: () => { throw new Error("table command entered database binding"); },
+ getContenteditableElement: () => ({textContent: ""}),
+ getSuperBlockCommandLayout: (): undefined => undefined,
+ focusByWbr() {},
+ updateTransaction: (_protyle: unknown, element: unknown, html: string) => {
+ assert.equal(element, inserted);
+ assert.equal(html, original.outerHTML);
+ updated = true;
+ },
+ });
+ Object.assign(hint, {source: scenario === "tag search" ? "hint" : "av", splitChar: "#", lastIndex: 12,
+ hashTagSearchElement: {isConnected: false}, fixImageCursor() {}});
+ const protyle = {
+ toolbar: {range: savedRange ? range : staleRange}, wysiwyg: {element: {}},
+ lute: {SpinBlockDOM: () => "new table"},
+ };
+ hint.fillCommand("| caret |\n| --- |", protyle, !savedRange);
+ assert.equal(updated, true);
+ assert.equal(mutated, true);
+ assert.equal(rangeReads, savedRange ? 0 : 1);
+ assert.equal(protyle.toolbar.range, range);
+ assert.equal(hint.hashTagSearchElement, undefined);
+ });
+}
+
+test("selecting a database binding candidate retains its field and creates a binding transaction", () => {
+ let operations: IOperation[];
+ const cell = {isConnected: true, hasAttribute: () => false};
+ const row = {dataset: {id: "item"}};
+ const block = {dataset: {nodeId: "database-block"}, getAttribute: () => "database"};
+ const range = {startContainer: cell};
+ const previousValue = {type: "block", isDetached: true, block: {content: "Draft"}};
+ const hint = runInNewContext(code, {
+ Constants: {BLOCK_HINT_KEYS: ["(("]},
+ window: {siyuan: {}}, hideElements() {}, isProtyleListItemFragment: () => false,
+ hasClosestBlock: () => block, getAVBindingCell: () => cell,
+ isTableLikeView: () => true, hasClosestByClassName: () => row,
+ genCellValueByElement: () => previousValue, getAVBindingOperations,
+ document: {createElement: () => ({innerHTML: "", firstElementChild: {
+ getAttribute: () => "target-block", textContent: "Target",
+ }})},
+ getEditorRange: () => { throw new Error("binding candidate replaced its saved field range"); },
+ transaction: (_protyle: unknown, doOperations: IOperation[]) => { operations = doOperations; },
+ updateAttrViewCellAnimation() {},
+ });
+ Object.assign(hint, {source: "av", splitChar: "/", lastIndex: -1});
+ const protyle = {id: "editor", toolbar: {range}, options: {}};
+ hint.fill('<span data-id="target-block">Target</span>', protyle);
+ assert.equal(protyle.toolbar.range, range);
+ assert.equal(operations.length, 1);
+ assert.equal(operations[0].action, "replaceAttrViewBlock");
+ assert.equal(operations[0].previousID, "item");
+ assert.equal(operations[0].nextID, "target-block");
+});
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 1ec9531546..1997c8b457 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -791,6 +791,15 @@ ${genHintItemHTML(item)}
this.emojiBrowseMode = false;
}
+ // 直接插入命令使用正文选区,不沿用候选面板的来源和触发位置。
+ public fillCommand(value: string, protyle: IProtyle, updateRange = true) {
+ this.source = "hint";
+ this.splitChar = "/";
+ this.lastIndex = -1;
+ this.hashTagSearchElement = undefined;
+ this.fill(value, protyle, updateRange);
+ }
+
public fill(value: string, protyle: IProtyle, updateRange = true, refIsS = false) {
this.bindingDismissController?.abort();
hideElements(["hint", "toolbar"], protyle);
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index 7aa4d4bbbc..2887dc616d 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -2284,9 +2284,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
type: "Blocks2Blockquote"
});
} else {
- protyle.hint.splitChar = "/";
- protyle.hint.lastIndex = -1;
- protyle.hint.fill(">" + Lute.Caret, protyle);
+ protyle.hint.fillCommand(">" + Lute.Caret, protyle);
}
} else {
const targetSubtype: TListSubtype = isMatchCheck ? "t" : (isMatchList ? "u" : "o");
@@ -2351,9 +2349,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
});
}
} else {
- protyle.hint.splitChar = "/";
- protyle.hint.lastIndex = -1;
- protyle.hint.fill((isMatchCheck ? "- [ ] " : (isMatchList ? "- " : "1. ")) + Lute.Caret, protyle);
+ protyle.hint.fillCommand((isMatchCheck ? "- [ ] " : (isMatchList ? "- " : "1. ")) + Lute.Caret, protyle);
}
}
} else {
@@ -2387,9 +2383,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
if (matchHotKey(window.siyuan.config.keymap.editor.insert.table, event) &&
!isInEmbedBlock(nodeElement)) {
- protyle.hint.splitChar = "/";
- protyle.hint.lastIndex = -1;
- protyle.hint.fill(`| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, protyle);
+ protyle.hint.fillCommand(`| ${Lute.Caret} | | |\n| --- | --- | --- |\n| | | |\n| | | |`, protyle);
event.preventDefault();
event.stopPropagation();
return;