Skip to content

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

:bug: Recover input after interrupted composition https://github.com/siyuan-note/siyuan/issues/19877

Daniel47d249c7a47c
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 696cde9222..88c0966f7a 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -62,6 +62,7 @@ import {
} from "./touchSelection";
import {getVisibleViewportBounds} from "./visibleViewport";
import {createInlineMathSelection} from "./inlineMathSelection";
+import {isCommittedTextInput} from "../../protyle/wysiwyg/compositionInput";
import {
getTextWithoutSemanticMarkers,
stripSemanticMarkersFromRangeText
@@ -1365,6 +1366,11 @@ export const initKeyboardToolbar = () => {
document.addEventListener("compositionend", () => {
composing = false;
}, true);
+ document.addEventListener("input", (event: InputEvent) => {
+ if (isCommittedTextInput(event)) {
+ composing = false;
+ }
+ }, true);
document.addEventListener("selectionchange", () => {
inlineMathSelection.update(getMathEditor(), getSelection(), composing);
}, true);
diff --git a/app/src/protyle/util/longTextWrap.dom.test.ts b/app/src/protyle/util/longTextWrap.dom.test.ts
index 5f0237f69d..e23cc1777a 100644
--- a/app/src/protyle/util/longTextWrap.dom.test.ts
+++ b/app/src/protyle/util/longTextWrap.dom.test.ts
@@ -151,6 +151,17 @@ const browserCases = async (source: string) => {
check.equal(composing.textContent, long.substring(0, 12) + "输入z" + long.substring(12));
checkCaret(composing, 15);
+ // 组合结束事件缺失后,明确提交的文本恢复折行,候选更新仍保持原始文本节点。
+ composing.textContent = long;
+ select(composing.firstChild, 15);
+ renderLongTextRuns(editor);
+ editor.dispatchEvent(new CompositionEvent("compositionstart", {bubbles: true}));
+ editor.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertCompositionText", isComposing: false}));
+ check.equal(composing.querySelector('[data-inline-wrap="token"]'), null);
+ editor.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText", isComposing: false}));
+ check.ok(composing.querySelector('[data-inline-wrap="token"]'));
+ checkCaret(composing, 15);
+
// 编辑器之外的选区和无选区状态不受渲染影响。
const outside = document.createElement("div");
outside.contentEditable = "true";
@@ -176,7 +187,8 @@ test("long text wrapping preserves list input and DOM selection boundaries", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
timeout: 45000,
}, async () => {
- const source = transpileModule(readFileSync(path.join(__dirname, "longTextWrap.ts"), "utf8")
+ const source = transpileModule((readFileSync(path.join(__dirname, "../wysiwyg/compositionInput.ts"), "utf8") +
+ readFileSync(path.join(__dirname, "longTextWrap.ts"), "utf8").replace(/^import .*;\r?\n/gm, ""))
.replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-long-text-test-"));
const script = path.join(temporary, "run.cjs");
diff --git a/app/src/protyle/util/longTextWrap.ts b/app/src/protyle/util/longTextWrap.ts
index 8876f5fc05..48c8e8889f 100644
--- a/app/src/protyle/util/longTextWrap.ts
+++ b/app/src/protyle/util/longTextWrap.ts
@@ -1,3 +1,5 @@
+import {isCommittedTextInput} from "../wysiwyg/compositionInput";
+
const LONG_TEXT_SELECTOR = 'span[data-inline-wrap="token"]';
const TEXT_CONTAINER_SELECTOR = "[contenteditable], [data-table-cell-content]";
const EXCLUDED_SELECTOR = 'pre, script, style, svg, textarea, [data-type="NodeCodeBlock"], ' +
@@ -272,6 +274,11 @@ export const renderLongTextRuns = (root: Element) => {
editor.addEventListener("compositionend", () => {
composingEditors.delete(editor);
});
+ editor.addEventListener("input", (event: InputEvent) => {
+ if (isCommittedTextInput(event)) {
+ composingEditors.delete(editor);
+ }
+ }, true);
}
if (!composingEditors.has(editor) && !inputDepth.get(editor)) {
normalizeLongTextRuns(root);
diff --git a/app/src/protyle/util/spellcheckFocus.test.ts b/app/src/protyle/util/spellcheckFocus.test.ts
index a7eae6de76..935f7d14b2 100644
--- a/app/src/protyle/util/spellcheckFocus.test.ts
+++ b/app/src/protyle/util/spellcheckFocus.test.ts
@@ -162,6 +162,20 @@ describe("spellcheck focus after document restoration", () => {
f.dispose();
});
+ it("recovers after committed input without a composition end", () => {
+ const f = fixture();
+ f.restore();
+ f.listeners.get("compositionstart")();
+ f.listeners.get("input")({inputType: "insertCompositionText", isComposing: false});
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ f.listeners.get("input")({inputType: "insertText", isComposing: false});
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ f.dispose();
+ assert.equal(f.listeners.has("input"), false);
+ });
+
it("skips disabled, readonly, detached and no longer focused editors", () => {
for (const change of [
(f: ReturnType<typeof fixture>) => f.setEnabled(false),
diff --git a/app/src/protyle/util/spellcheckFocus.ts b/app/src/protyle/util/spellcheckFocus.ts
index bb15d7528a..b5794f8af2 100644
--- a/app/src/protyle/util/spellcheckFocus.ts
+++ b/app/src/protyle/util/spellcheckFocus.ts
@@ -1,3 +1,5 @@
+import {isCommittedTextInput} from "../wysiwyg/compositionInput";
+
const restoredFocusHandlers = new WeakMap<HTMLElement, () => void>();
export const recordRestoredSpellcheckFocus = (element: HTMLElement, previousActiveElement: Element | null) => {
@@ -66,6 +68,11 @@ export const bindSpellcheckFocus = (element: HTMLElement, isEnabled: () => boole
const onCompositionEnd = () => {
composing = false;
};
+ const onInput = (event: InputEvent) => {
+ if (isCommittedTextInput(event)) {
+ composing = false;
+ }
+ };
restoredFocusHandlers.set(element, () => {
pending = isEnabled();
});
@@ -74,6 +81,7 @@ export const bindSpellcheckFocus = (element: HTMLElement, isEnabled: () => boole
element.addEventListener("focusout", clear);
element.addEventListener("compositionstart", onCompositionStart, true);
element.addEventListener("compositionend", onCompositionEnd, true);
+ element.addEventListener("input", onInput, true);
view.addEventListener("mousedown", onWindowMouseDown);
return () => {
clear();
@@ -83,6 +91,7 @@ export const bindSpellcheckFocus = (element: HTMLElement, isEnabled: () => boole
element.removeEventListener("focusout", clear);
element.removeEventListener("compositionstart", onCompositionStart, true);
element.removeEventListener("compositionend", onCompositionEnd, true);
+ element.removeEventListener("input", onInput, true);
view.removeEventListener("mousedown", onWindowMouseDown);
};
};
diff --git a/app/src/protyle/wysiwyg/compositionInput.ts b/app/src/protyle/wysiwyg/compositionInput.ts
new file mode 100644
index 0000000000..fc3f58ba11
--- /dev/null
+++ b/app/src/protyle/wysiwyg/compositionInput.ts
@@ -0,0 +1,5 @@
+// 只将明确提交的文本输入作为恢复信号,避免提前结束仍在更新的输入法候选内容。
+export const isCommittedTextInput = (event: Pick<InputEvent, "isComposing" | "inputType">) => {
+ return event.isComposing === false &&
+ ["insertText", "insertReplacementText", "insertFromComposition"].includes(event.inputType);
+};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 8cfff0a77e..ba068dcd92 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -8,6 +8,7 @@ import {renderLongTextRuns} from "../util/longTextWrap";
import {repairHiddenTabSelection} from "../util/tabsSelection";
import {isTabTextBoundary} from "./tabsBoundary";
import {captureCompositionText} from "./compositionCaret";
+import {isCommittedTextInput} from "./compositionInput";
import {isDirectMathClick} from "../util/mathClick";
import {
beforePaste,
@@ -3978,6 +3979,8 @@ export class WYSIWYG {
// 输入法测试点 https://github.com/siyuan-note/siyuan/issues/3027
let isComposition = false; // for iPhone
+ let recoveredComposition = false;
+ let compositionSnapshot: {element: HTMLElement; html: string};
// 组合输入已由 beforeinput 处理时,忽略其后到达的 compositionend,避免重复生成事务。
let beforeInputCompositionHandled = false;
// 原生软换行在 input 触发前已经修改 DOM,需预存选区供撤销恢复。
@@ -4108,6 +4111,8 @@ export class WYSIWYG {
return;
}
isComposition = true;
+ recoveredComposition = false;
+ compositionSnapshot = undefined;
crossBlockComposition = undefined;
// 微软双拼由于 focusByRange 导致无法输入文字,因此不再 keydown 中记录了,但 keyup 会记录拼音字符,因此使用 isComposition 阻止 keyup 记录。
// 但搜狗输入法选中后继续输入不走 keydown,isComposition 阻止了 keyup 记录,因此需在此记录。
@@ -4142,6 +4147,12 @@ export class WYSIWYG {
if ((selectionModeElement || !isMac()) && nodeElement && !crossBlockComposition) {
setInsertWbrHTML(nodeElement, range, protyle);
}
+ if (nodeElement && !crossBlockComposition) {
+ compositionSnapshot = {
+ element: nodeElement,
+ html: this.lastHTMLs[nodeElement.getAttribute("data-node-id")],
+ };
+ }
event.stopPropagation();
});
@@ -4154,6 +4165,11 @@ export class WYSIWYG {
if (getAVTemplateInteractiveElement(event.target)) {
return;
}
+ // 已提交的文本会沿普通输入链路保存,迟到的结束事件不能再次提交或恢复旧光标。
+ if (recoveredComposition) {
+ return;
+ }
+ compositionSnapshot = undefined;
if (crossBlockComposition) {
const currentComposition = crossBlockComposition;
beforeInputCompositionHandled = false;
@@ -4388,6 +4404,22 @@ export class WYSIWYG {
if ([":", "(", "【", "(", "[", "{", "「", "『", "#", "/", "、"].includes(event.data)) {
protyle.hint.enableExtend = true;
}
+ // 外接键盘的结束事件可能缺失,收到明确提交的文本后恢复输入处理。
+ // 跨块组合由其独立事务完成,不能在这里拆开提交。
+ if (isComposition && !crossBlockComposition && isCommittedTextInput(event)) {
+ isComposition = false;
+ recoveredComposition = true;
+ beforeInputCompositionHandled = false;
+ compositionRange = undefined;
+ if (compositionSnapshot?.html && this.element.contains(compositionSnapshot.element)) {
+ if (compositionSnapshot.element === blockElement) {
+ this.lastHTMLs[blockElement.getAttribute("data-node-id")] = compositionSnapshot.html;
+ } else {
+ updateTransaction(protyle, compositionSnapshot.element, compositionSnapshot.html);
+ }
+ }
+ compositionSnapshot = undefined;
+ }
if (event.isComposing || isComposition ||
// https://github.com/siyuan-note/siyuan/issues/337 编辑器内容拖拽问题
event.inputType === "deleteByDrag" || event.inputType === "insertFromDrop"
diff --git a/app/tests/compositionCaret.test.js b/app/tests/compositionCaret.test.js
index 187df0e202..cf601dad89 100644
--- a/app/tests/compositionCaret.test.js
+++ b/app/tests/compositionCaret.test.js
@@ -15,20 +15,35 @@ const rendererSource = () => {
};
const wysiwyg = ts.createSourceFile("index.ts", read("wysiwyg/index"), ts.ScriptTarget.Latest, true);
const handlers = {};
+ const inputMethods = [];
let isAfterInlineMath;
const visit = node => {
if (ts.isCallExpression(node) && node.expression.getText(wysiwyg) === "this.element.addEventListener" &&
- ["compositionstart", "compositionend"].includes(node.arguments[0]?.text)) {
+ ["compositionstart", "compositionend", "input", "focusout"].includes(node.arguments[0]?.text)) {
handlers[node.arguments[0].text] = node.arguments[1].getText(wysiwyg);
}
+ if (ts.isMethodDeclaration(node) && ["scheduleInput", "runInput", "flushPendingInput"].includes(node.name.getText(wysiwyg))) {
+ inputMethods.push(node.getText(wysiwyg));
+ }
if (ts.isVariableDeclaration(node) && node.name.getText(wysiwyg) === "isAfterInlineMath") {
isAfterInlineMath = node.initializer.getText(wysiwyg);
}
ts.forEachChild(node, visit);
};
visit(wysiwyg);
- assert.deepEqual(Object.keys(handlers).sort(), ["compositionend", "compositionstart"]);
+ assert.deepEqual(Object.keys(handlers).sort(), ["compositionend", "compositionstart", "focusout", "input"]);
assert.ok(isAfterInlineMath);
+ const mobile = ts.createSourceFile("keyboardToolbar.ts", read("../mobile/util/keyboardToolbar"), ts.ScriptTarget.Latest, true);
+ let mobileInput;
+ const visitMobile = node => {
+ if (ts.isCallExpression(node) && node.expression.getText(mobile) === "document.addEventListener" &&
+ node.arguments[0]?.text === "input" && node.arguments[1].getText(mobile).includes("isCommittedTextInput")) {
+ mobileInput = node.arguments[1].getText(mobile);
+ }
+ ts.forEachChild(node, visitMobile);
+ };
+ visitMobile(mobile);
+ assert.ok(mobileInput);
// 使用实际事件入口、平台检测、选区恢复和事务生成,只替代网络及无关渲染。
const source = `
const Constants = {ZWSP: "\\u200b", ATTRIBUTE_EDITING: "data-editing"};
@@ -38,13 +53,25 @@ const rendererSource = () => {
const revealTabsForTarget = () => {};
const getAtomicVerticalNavigationOwner = () => undefined;
const getSemanticMarkerPrefixLengthForNode = () => 0;
+ const normalizeInlineElementBoundaries = () => {};
+ const renderLongTextRuns = () => {};
+ class InputQueue {
+ pendingInputTimeouts = new Map();
+ runningInputTasks = new Set();
+ ${inputMethods.join("\n")}
+ }
const cleanListMindmapHTML = html => html, cleanHeadingNumberHTML = html => html;
const cleanTableCellRichHTML = html => html, cleanBlockSelectionModeHTML = html => html;
const transaction = (protyle, doOperations, undoOperations) => {
protyle.transactions.push({doOperations, undoOperations});
};
- const input = protyle => { protyle.inputs++; };
- ` + read("wysiwyg/compositionCaret") + read("util/browserCompatibility") +
+ const input = (protyle, block) => {
+ protyle.inputs++;
+ const id = block.getAttribute("data-node-id");
+ updateTransaction(protyle, block, protyle.wysiwyg.lastHTMLs[id]);
+ protyle.wysiwyg.lastHTMLs[id] = block.outerHTML;
+ };
+ ` + read("wysiwyg/compositionCaret") + read("wysiwyg/compositionInput") + read("util/browserCompatibility") +
extract("util/compatibility", ["isIOSDevice", "isMac"]) +
extract("util/hasClosest", ["hasClosestBlock", "hasClosestByAttribute", "hasClosestByClassName",
"hasClosestByTag", "isBlockElement"]) +
@@ -52,16 +79,32 @@ const rendererSource = () => {
extract("util/selection", ["getEditorRange", "focusByRange", "getSelectionOffset", "selectIsEditor",
"focusByOffset", "searchNode", "setLastNodeRange", "setInsertWbrHTML", "focusByWbr"]) +
extract("wysiwyg/transaction", ["updateTransaction"]) + `
+ export function checkMobileInput(event) {
+ let composing = true;
+ (${mobileInput})(event);
+ return composing;
+ }
export function bind(protyle) {
let isComposition = false, beforeInputCompositionHandled = false;
+ let recoveredComposition = false, compositionSnapshot;
+ let lineBreakUndoContext, forwardDeleteUndoContext;
let compositionRange, crossBlockComposition;
const isAfterInlineMath = ${isAfterInlineMath};
const pending = [];
+ Object.assign(protyle.wysiwyg, new InputQueue());
+ for (const name of ["scheduleInput", "runInput", "flushPendingInput"]) {
+ protyle.wysiwyg[name] = InputQueue.prototype[name];
+ }
+ protyle.toolbar = {};
+ protyle.hint = {};
const handlers = (function () {
- return {start: ${handlers.compositionstart}, end: ${handlers.compositionend}};
+ return {start: ${handlers.compositionstart}, end: ${handlers.compositionend},
+ input: ${handlers.input}, focusout: ${handlers.focusout}};
}).call(protyle.wysiwyg);
protyle.wysiwyg.element.addEventListener("compositionstart", handlers.start);
protyle.wysiwyg.element.addEventListener("compositionend", event => pending.push(handlers.end(event)));
+ protyle.wysiwyg.element.addEventListener("input", handlers.input);
+ protyle.wysiwyg.element.addEventListener("focusout", handlers.focusout);
return () => Promise.all(pending.splice(0));
}
`;
@@ -123,6 +166,88 @@ const runCases = async () => {
return {element, protyle, start, finish, flush, setRange, assertCaret};
};
let cases = 0;
+ {
+ const {checkMobileInput} = window.compositionCaret;
+ assert.equal(checkMobileInput({isComposing: false, inputType: "insertText"}), false);
+ assert.equal(checkMobileInput({isComposing: true, inputType: "insertText"}), true);
+ assert.equal(checkMobileInput({isComposing: false, inputType: "insertCompositionText"}), true);
+ cases++;
+ }
+ {
+ const f = setup(paragraph("first") + paragraph("second").replace('data-node-id="p"', 'data-node-id="other"'));
+ const first = f.element.firstElementChild.querySelector('[contenteditable="true"]').firstChild;
+ const second = f.element.lastElementChild.querySelector('[contenteditable="true"]').firstChild;
+ f.start(first, first.length);
+ first.appendData("pending");
+ f.setRange(second, second.length);
+ setInsertWbrHTML(f.element.lastElementChild, getSelection().getRangeAt(0), f.protyle);
+ second.appendData("next");
+ f.setRange(second, second.length);
+ f.element.dispatchEvent(new InputEvent("input", {bubbles: true, inputType: "insertText", data: "next", isComposing: false}));
+ await f.protyle.wysiwyg.flushPendingInput();
+ assert.equal(f.protyle.transactions.length, 2);
+ assert.match(f.protyle.transactions[0].doOperations[0].data, /firstpending/);
+ assert.match(f.protyle.transactions[0].undoOperations[0].data, /first<wbr>/);
+ assert.match(f.protyle.transactions[1].doOperations[0].data, /secondnext/);
+ assert.match(f.protyle.transactions[1].undoOperations[0].data, /second<wbr>/);
+ await f.finish("");
+ assert.equal(f.protyle.transactions.length, 2);
+ f.assertCaret(second, second.length);
+ cases++;
+ }
+ for (const profile of profiles) {
+ for (const inputType of ["insertText", "insertReplacementText", "insertFromComposition"]) {
+ const f = setup(paragraph("base"), profile);
+ const node = f.element.querySelector('[contenteditable="true"]').firstChild;
+ const type = (text, type, isComposing) => {
+ node.appendData(text);
+ f.setRange(node, node.length);
+ const event = new InputEvent("input", {bubbles: true, data: text, inputType: type, isComposing});
+ // Chromium 会清空其不支持的输入类型,这里保留其他浏览器提交事件的类型。
+ if (event.inputType !== type) {
+ Object.defineProperty(event, "inputType", {value: type});
+ }
+ f.element.dispatchEvent(event);
+ };
+ f.start(node, node.length);
+ type("a", "insertCompositionText", true);
+ type("b", "insertCompositionText", false);
+ type("c", "insertText", true);
+ await f.protyle.wysiwyg.flushPendingInput();
+ assert.equal(f.protyle.inputs, 0, "candidate updates must not be committed");
+ f.element.dispatchEvent(new FocusEvent("focusout", {bubbles: true}));
+ // 模拟普通按键覆盖撤销快照,恢复时仍需保留组合输入开始前的内容。
+ setInsertWbrHTML(f.element.firstElementChild, getSelection().getRangeAt(0), f.protyle);
+ type("d", inputType, false);
+ await f.protyle.wysiwyg.flushPendingInput();
+ assert.equal(f.protyle.inputs, 1, `${profile.name}: ${inputType}`);
+ assert.equal(f.protyle.transactions.length, 1);
+ const saved = f.protyle.transactions[0];
+ assert.match(saved.doOperations[0].data, /baseabcd/);
+ assert.match(saved.undoOperations[0].data, /base<wbr>/);
+ assert.doesNotMatch(saved.undoOperations[0].data, /basea/);
+ await f.finish("");
+ await f.finish("abcd");
+ assert.equal(f.protyle.inputs, 1, "late end must not submit twice");
+ assert.equal(f.protyle.transactions.length, 1);
+ f.assertCaret(node, node.length);
+ type("e", "insertText", false);
+ await f.protyle.wysiwyg.flushPendingInput();
+ assert.equal(f.protyle.inputs, 2);
+ assert.match(f.protyle.transactions[1].doOperations[0].data, /baseabcde/);
+ f.start(node, node.length);
+ type("f", "insertCompositionText", true);
+ await f.finish("f");
+ await f.protyle.wysiwyg.flushPendingInput();
+ assert.equal(f.protyle.inputs, 3, "next composition must finish normally");
+ f.element.firstElementChild.outerHTML = saved.undoOperations[0].data;
+ focusByWbr(f.element, document.createRange());
+ assert.equal(f.element.textContent, "base");
+ f.element.firstElementChild.outerHTML = saved.doOperations[0].data;
+ assert.equal(f.element.textContent, "baseabcd");
+ cases++;
+ }
+ }
for (const profile of profiles) {
const f = setup(paragraph("前后"), profile);
const node = f.element.querySelector('[contenteditable="true"]').firstChild;
@@ -302,7 +427,7 @@ if (process.versions.electron && process.type === "browser") {
try {
const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 40000});
- assert.match(stdout, /Composition caret: 19 Electron cases passed/);
+ assert.match(stdout, /Composition caret: 39 Electron cases passed/);
} finally {
assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
assert.ok(path.basename(profile).startsWith("siyuan-composition-caret-"));