Skip to content

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

:art: Improve spell checking https://github.com/siyuan-note/siyuan/issues/19682

Daniel89fd3d58c8b4
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy
index b5ce992e1d..ba888aa4cb 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i.sy
@@ -7,7 +7,7 @@
"id": "20210808180303-h361q1i",
"title": "Editor",
"type": "doc",
- "updated": "20260830213256"
+ "updated": "20260920102915"
},
"Children": [
{
@@ -247,6 +247,122 @@
"TextMarkTextContent": "Heading and list layout"
}
]
+ },
+ {
+ "ID": "20260920102915-4hhz1ko",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260920102915-4hhz1ko",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Spell Check"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-3kq9ofr",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-3kq9ofr",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Enable this feature in "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Editor"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Spell Check"
+ },
+ {
+ "Type": "NodeText",
+ "Data": ". Misspelled words are marked with wavy underlines."
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-8dfar3l",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-8dfar3l",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Desktop app: right-click an underlined word and choose a spelling suggestion from SiYuan's menu. You can also add a correctly spelled word to the dictionary. Use a normal right-click without holding "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "."
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-kl8nygu",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-kl8nygu",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "Browser: enable spell checking and select the languages to check in your browser settings. In Chrome, hold "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " and right-click an underlined word to open the browser's native spelling menu."
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-7eun9ey",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-7eun9ey",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "When spell checking starts depends on the environment. After opening a document, even if the caret has been restored, you may need to click the document body and wait briefly for underlines to appear."
+ }
+ ]
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy
index c60f986db3..a872908591 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k.sy
@@ -7,7 +7,7 @@
"id": "20210808180320-abz7w6k",
"title": "编辑器",
"type": "doc",
- "updated": "20260830213256"
+ "updated": "20260920102915"
},
"Children": [
{
@@ -250,6 +250,122 @@
"TextMarkTextContent": "标题与列表混合排版"
}
]
+ },
+ {
+ "ID": "20260920102915-5a60iu6",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260920102915-5a60iu6",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拼写检查"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-3q0sf6u",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-3q0sf6u",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "设置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "编辑器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "拼写检查"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中启用此功能。拼写错误会用波浪线标记。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-5t9ysoy",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-5t9ysoy",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "桌面端:右键点击带波浪线的单词,在思源菜单中选择纠错建议,也可将正确的单词加入词典。桌面端请使用普通右键,无需按住 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-xn2qrxz",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-xn2qrxz",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "浏览器端:请在浏览器设置中启用拼写检查并选择检查语言。在 Chrome 中,按住 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 并右键点击带波浪线的单词,可使用浏览器原生纠错菜单。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-65bs43d",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-65bs43d",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拼写检查的触发时机取决于运行环境。打开文档后即使光标已恢复,也可能需要点击正文并等待片刻才显示波浪线。"
+ }
+ ]
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy
index 32d3926151..2afd9f8c91 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2.sy
@@ -7,7 +7,7 @@
"id": "20211226120854-dr1jfx2",
"title": "編輯器",
"type": "doc",
- "updated": "20260830213256"
+ "updated": "20260920102915"
},
"Children": [
{
@@ -222,6 +222,122 @@
"TextMarkTextContent": "標題與列表混合排版"
}
]
+ },
+ {
+ "ID": "20260920102915-zr83okq",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260920102915-zr83okq",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拼寫檢查"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-kqmazhq",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-kqmazhq",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "編輯器"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "拼寫檢查"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中啟用此功能。拼寫錯誤會以波浪線標記。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-2zycdok",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-2zycdok",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "桌面端:在帶有波浪線的單字上按右鍵,於思源選單中選擇更正建議,也可將正確的單字加入詞典。桌面端請使用一般右鍵,無需按住 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": "。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-yi3fmra",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-yi3fmra",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "瀏覽器端:請在瀏覽器設定中啟用拼寫檢查並選擇檢查語言。在 Chrome 中,按住 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 並在帶有波浪線的單字上按右鍵,即可使用瀏覽器原生的更正選單。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-3dmr3wm",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-3dmr3wm",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "拼寫檢查的觸發時機取決於執行環境。開啟文件後即使游標已恢復,也可能需要點選正文並稍候才會顯示波浪線。"
+ }
+ ]
}
]
}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy
index d2984600b3..23ff573b22 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79.sy
@@ -8,7 +8,7 @@
"id": "20240530101000-hnu6o79",
"title": "エディタ",
"type": "doc",
- "updated": "20260830213256"
+ "updated": "20260920102915"
},
"Children": [
{
@@ -251,6 +251,122 @@
"ID": "20240530101000-1wyq56l",
"id": "20240530101000-48icsc4"
}
+ },
+ {
+ "ID": "20260920102915-j2vppoi",
+ "Type": "NodeHeading",
+ "HeadingLevel": 2,
+ "Properties": {
+ "id": "20260920102915-j2vppoi",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "スペルチェック"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-bqpxzto",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-bqpxzto",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "この機能は "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "エディタ"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "スペルチェック"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で有効にできます。スペルミスのある単語には波線が表示されます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-bwh61nt",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-bwh61nt",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "デスクトップ版:波線のある単語を右クリックし、思源のメニューから修正候補を選択します。正しい単語を辞書に追加することもできます。通常の右クリックを使用し、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " キーを押す必要はありません。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-jffww3e",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-jffww3e",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "ブラウザ版:ブラウザの設定でスペルチェックを有効にし、チェックする言語を選択してください。Chrome では、"
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Shift"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " キーを押しながら波線のある単語を右クリックすると、ブラウザ標準のスペル修正メニューが開きます。"
+ }
+ ]
+ },
+ {
+ "ID": "20260920102915-5z2g0ww",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20260920102915-5z2g0ww",
+ "updated": "20260920102915"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "スペルチェックが始まるタイミングは実行環境によって異なります。ドキュメントを開いてカーソル位置が復元されても、波線が表示されるまで本文をクリックして少し待つ必要がある場合があります。"
+ }
+ ]
}
]
}
diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.ts
index 56c76d17ad..43be420777 100644
--- a/app/src/protyle/util/onGet.ts
+++ b/app/src/protyle/util/onGet.ts
@@ -39,6 +39,7 @@ import {forEachPluginSubscriber} from "../../plugin/EventBusCore";
import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";
import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";
import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";
+import {recordRestoredSpellcheckFocus} from "./spellcheckFocus";
import {applyPublishFoldStates} from "./viewFold";
/// #if MOBILE
import {updateMobileTitleReadonly} from "./setEditMode";
@@ -623,6 +624,7 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScr
}
if (!suppressFocus && (action.includes(Constants.CB_GET_FOCUS) || action.includes(Constants.CB_GET_FOCUSFIRST))) {
setTimeout(() => {
+ const previousActiveElement = protyle.wysiwyg.element.ownerDocument.activeElement;
let range: Range;
if (savedFocusElement === focusElement && hasFocusOffsets(scrollAttr)) {
range = focusByOffset(focusElement, scrollAttr.focusStart, scrollAttr.focusEnd) as Range;
@@ -630,6 +632,7 @@ const focusElementById = (protyle: IProtyle, action: string[], scrollAttr?: IScr
range = focusBlock(focusElement, undefined, !action.includes(Constants.CB_GET_OUTLINE),
focusAfterZoom) as Range;
}
+ recordRestoredSpellcheckFocus(protyle.wysiwyg.element, previousActiveElement);
/// #if !MOBILE
if (!action.includes(Constants.CB_GET_UNUNDO)) {
pushBack(protyle, range, focusElement);
diff --git a/app/src/protyle/util/reload.ts b/app/src/protyle/util/reload.ts
index d5e1014e01..dbdcaf033d 100644
--- a/app/src/protyle/util/reload.ts
+++ b/app/src/protyle/util/reload.ts
@@ -18,6 +18,7 @@ export const reloadProtyle = (protyle: IProtyle, focus: boolean, updateReadonly?
return;
}
updateBacklinkReferenceVisibility(protyle);
+ protyle.wysiwyg.element.setAttribute("spellcheck", window.siyuan.config.editor.spellcheck.toString());
invalidateTrackedRanges(protyle);
/// #if MOBILE
hideKeyboardToolbar();
diff --git a/app/src/protyle/util/spellcheckFocus.test.ts b/app/src/protyle/util/spellcheckFocus.test.ts
new file mode 100644
index 0000000000..a7eae6de76
--- /dev/null
+++ b/app/src/protyle/util/spellcheckFocus.test.ts
@@ -0,0 +1,213 @@
+import * as assert from "node:assert/strict";
+import {describe, it} from "node:test";
+import {bindSpellcheckFocus, recordRestoredSpellcheckFocus} from "./spellcheckFocus";
+
+const fixture = () => {
+ const listeners = new Map<string, (event?: any) => void>();
+ const windowListeners = new Map<string, (event: any) => void>();
+ const outside = {};
+ let enabled = true;
+ let blurCount = 0;
+ let selectedBlocks = false;
+ let excludedTarget = false;
+ const selection = {rangeCount: 1, isCollapsed: true, anchorNode: {}};
+ const doc = {
+ activeElement: outside,
+ getSelection: () => selection,
+ defaultView: {
+ addEventListener: (type: string, listener: (event: any) => void) => windowListeners.set(type, listener),
+ removeEventListener: (type: string) => windowListeners.delete(type),
+ },
+ };
+ const root = {
+ ownerDocument: doc,
+ isConnected: true,
+ isContentEditable: true,
+ spellcheck: true,
+ contains: (node: unknown) => node === selection.anchorNode,
+ querySelector: () => selectedBlocks ? {} : null,
+ addEventListener: (type: string, listener: (event: any) => void) => listeners.set(type, listener),
+ removeEventListener: (type: string) => listeners.delete(type),
+ blur: () => {
+ blurCount++;
+ doc.activeElement = outside;
+ listeners.get("focusout")?.();
+ },
+ };
+ const element = root as unknown as HTMLElement;
+ const block = {parentElement: root as unknown, isSameNode: (node: unknown) => node === block};
+ const editable = {parentElement: block};
+ const target = {
+ isContentEditable: true,
+ spellcheck: true,
+ closest: (selector: string) => selector === '[data-type="NodeParagraph"]' ? block :
+ selector === '[contenteditable="true"]' ? editable : excludedTarget ? {} : null,
+ };
+ const dispose = bindSpellcheckFocus(element, () => enabled);
+ const restore = () => {
+ const previousActiveElement = doc.activeElement;
+ doc.activeElement = root;
+ recordRestoredSpellcheckFocus(element, previousActiveElement as Element);
+ };
+ const mouseDown = (options: Record<string, unknown> = {}, afterCapture?: (event: any) => void,
+ pointerType = "mouse") => {
+ listeners.get("pointerdown")?.({isPrimary: true, pointerType});
+ const event = {
+ target, isTrusted: true, defaultPrevented: false, button: 0, detail: 1,
+ shiftKey: false, ctrlKey: false, metaKey: false, altKey: false, ...options,
+ };
+ listeners.get("mousedown")?.(event);
+ afterCapture?.(event);
+ windowListeners.get("mousedown")?.(event);
+ };
+ return {
+ root, element, target, block, doc, outside, selection, listeners, windowListeners, restore, mouseDown, dispose,
+ blurCount: () => blurCount,
+ setEnabled: (value: boolean) => enabled = value,
+ selectBlocks: () => selectedBlocks = true,
+ excludeTarget: () => excludedTarget = true,
+ };
+};
+
+describe("spellcheck focus after document restoration", () => {
+ it("releases restored focus once without replacing the selection or refocusing in script", () => {
+ const f = fixture();
+ f.restore();
+ const selection = {...f.selection};
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ assert.equal(f.doc.activeElement, f.outside);
+ assert.deepEqual(f.selection, selection);
+ // 模拟随后由浏览器默认鼠标行为聚焦,正常点击不再重复失焦。
+ f.doc.activeElement = f.root;
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ f.dispose();
+ });
+
+ it("leaves naturally focused editors and ordinary selection restoration alone", () => {
+ const f = fixture();
+ f.doc.activeElement = f.root;
+ f.restore();
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ });
+
+ it("discards pending work when focus leaves and allows another document restoration", () => {
+ const f = fixture();
+ f.restore();
+ f.listeners.get("focusout")();
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ f.doc.activeElement = f.outside;
+ f.restore();
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ f.dispose();
+ });
+
+ it("waits for ancestor handlers and preserves a later eligible click after cancellation", () => {
+ const f = fixture();
+ f.restore();
+ f.mouseDown({}, event => {
+ assert.equal(f.blurCount(), 0);
+ event.defaultPrevented = true;
+ });
+ assert.equal(f.blurCount(), 0);
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ f.dispose();
+ });
+
+ it("skips modified clicks, right click, repeated clicks and synthetic events", () => {
+ const f = fixture();
+ f.restore();
+ for (const options of [{shiftKey: true}, {ctrlKey: true}, {metaKey: true}, {altKey: true},
+ {button: 2}, {detail: 2}, {detail: 3}, {isTrusted: false}, {defaultPrevented: true}]) {
+ f.mouseDown(options);
+ }
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ });
+
+ it("preserves existing text selections even if editor handlers collapse them", () => {
+ const f = fixture();
+ f.restore();
+ f.selection.isCollapsed = false;
+ f.mouseDown({}, () => f.selection.isCollapsed = true);
+ assert.equal(f.blurCount(), 0);
+ f.mouseDown({}, () => f.selection.isCollapsed = false);
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ });
+
+ it("skips composition, including a composition that ends during this pointer gesture", () => {
+ const f = fixture();
+ f.restore();
+ f.listeners.get("compositionstart")();
+ f.mouseDown({}, () => f.listeners.get("compositionend")());
+ assert.equal(f.blurCount(), 0);
+ f.mouseDown();
+ assert.equal(f.blurCount(), 1);
+ f.dispose();
+ });
+
+ it("skips touch and pen compatibility mouse events", () => {
+ const f = fixture();
+ f.restore();
+ f.mouseDown({}, undefined, "touch");
+ f.mouseDown({}, undefined, "pen");
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ });
+
+ it("skips disabled, readonly, detached and no longer focused editors", () => {
+ for (const change of [
+ (f: ReturnType<typeof fixture>) => f.setEnabled(false),
+ (f: ReturnType<typeof fixture>) => f.root.isContentEditable = false,
+ (f: ReturnType<typeof fixture>) => f.root.spellcheck = false,
+ (f: ReturnType<typeof fixture>) => f.root.isConnected = false,
+ (f: ReturnType<typeof fixture>) => f.doc.activeElement = f.outside,
+ ]) {
+ const f = fixture();
+ f.restore();
+ f.mouseDown({}, () => change(f));
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ }
+ });
+
+ it("skips controls, nested blocks, non-editable text and block selections", () => {
+ for (const change of [
+ (f: ReturnType<typeof fixture>) => f.excludeTarget(),
+ (f: ReturnType<typeof fixture>) => f.block.parentElement = {},
+ (f: ReturnType<typeof fixture>) => f.target.isContentEditable = false,
+ (f: ReturnType<typeof fixture>) => f.target.spellcheck = false,
+ (f: ReturnType<typeof fixture>) => f.selectBlocks(),
+ ]) {
+ const f = fixture();
+ f.restore();
+ change(f);
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ }
+ });
+
+ it("does not arm while disabled and removes all listeners on destruction", () => {
+ const f = fixture();
+ f.setEnabled(false);
+ f.restore();
+ f.setEnabled(true);
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ f.dispose();
+ assert.equal(f.listeners.size, 0);
+ assert.equal(f.windowListeners.size, 0);
+ f.doc.activeElement = f.outside;
+ f.restore();
+ f.mouseDown();
+ assert.equal(f.blurCount(), 0);
+ });
+});
diff --git a/app/src/protyle/util/spellcheckFocus.ts b/app/src/protyle/util/spellcheckFocus.ts
new file mode 100644
index 0000000000..bb15d7528a
--- /dev/null
+++ b/app/src/protyle/util/spellcheckFocus.ts
@@ -0,0 +1,88 @@
+const restoredFocusHandlers = new WeakMap<HTMLElement, () => void>();
+
+export const recordRestoredSpellcheckFocus = (element: HTMLElement, previousActiveElement: Element | null) => {
+ // 只记录文档恢复时新获得的正文焦点,已聚焦编辑器中的选区更新不重新触发。
+ if (previousActiveElement !== element && element.ownerDocument.activeElement === element) {
+ restoredFocusHandlers.get(element)?.();
+ }
+};
+
+export const bindSpellcheckFocus = (element: HTMLElement, isEnabled: () => boolean) => {
+ const doc = element.ownerDocument;
+ const view = doc.defaultView;
+ let pending = false;
+ let composing = false;
+ let mousePointer = false;
+ let candidate: MouseEvent | undefined;
+ const clear = () => {
+ pending = false;
+ candidate = undefined;
+ };
+ const canRefresh = () => pending && !composing && isEnabled() && element.isConnected &&
+ element.isContentEditable && element.spellcheck && doc.activeElement === element;
+ const hasCollapsedSelection = () => {
+ const selection = doc.getSelection();
+ return selection?.rangeCount === 1 && selection.isCollapsed && element.contains(selection.anchorNode);
+ };
+ const onPointerDown = (event: PointerEvent) => {
+ mousePointer = !composing && event.isPrimary && event.pointerType === "mouse";
+ };
+ const onMouseDown = (event: MouseEvent) => {
+ candidate = undefined;
+ if (!canRefresh() || !mousePointer || !event.isTrusted || event.defaultPrevented || event.button !== 0 ||
+ event.detail !== 1 || event.shiftKey || event.ctrlKey || event.metaKey || event.altKey ||
+ !hasCollapsedSelection()) {
+ return;
+ }
+ const target = event.target as HTMLElement;
+ const block = target.closest('[data-type="NodeParagraph"]');
+ if (block?.parentElement !== element || !target.isContentEditable || !target.spellcheck ||
+ !target.closest('[contenteditable="true"]')?.parentElement?.isSameNode(block) ||
+ target.closest('a, button, input, textarea, select, [draggable="true"], [contenteditable="false"], ' +
+ '[data-type~="a"], [data-type~="block-ref"], [data-type~="file-annotation-ref"], ' +
+ '[data-type~="tag"], .img, .render-node, .protyle-attr') ||
+ element.querySelector(".protyle-wysiwyg--select")) {
+ return;
+ }
+ candidate = event;
+ };
+ const onWindowMouseDown = (event: MouseEvent) => {
+ if (candidate !== event) {
+ return;
+ }
+ candidate = undefined;
+ if (event.defaultPrevented || !canRefresh() || !hasCollapsedSelection()) {
+ return;
+ }
+ // 等编辑器及祖先的鼠标处理结束后释放焦点,由这次真实点击的默认行为重新聚焦。
+ // 不调用 focus 或修改选区,保留浏览器的点击定位和拖选行为。
+ clear();
+ element.blur();
+ };
+ const onCompositionStart = () => {
+ composing = true;
+ candidate = undefined;
+ };
+ const onCompositionEnd = () => {
+ composing = false;
+ };
+ restoredFocusHandlers.set(element, () => {
+ pending = isEnabled();
+ });
+ element.addEventListener("pointerdown", onPointerDown, true);
+ element.addEventListener("mousedown", onMouseDown, true);
+ element.addEventListener("focusout", clear);
+ element.addEventListener("compositionstart", onCompositionStart, true);
+ element.addEventListener("compositionend", onCompositionEnd, true);
+ view.addEventListener("mousedown", onWindowMouseDown);
+ return () => {
+ clear();
+ restoredFocusHandlers.delete(element);
+ element.removeEventListener("pointerdown", onPointerDown, true);
+ element.removeEventListener("mousedown", onMouseDown, true);
+ element.removeEventListener("focusout", clear);
+ element.removeEventListener("compositionstart", onCompositionStart, true);
+ element.removeEventListener("compositionend", onCompositionEnd, true);
+ view.removeEventListener("mousedown", onWindowMouseDown);
+ };
+};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index fa1a1915e0..2f6940da36 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -1,4 +1,5 @@
import {recordReplacementUndo} from "./replacementInput";
+import {bindSpellcheckFocus} from "../util/spellcheckFocus";
import {isTableLikeView} from "../render/av/viewType";
import {visibleTabsSelectionHTML} from "../render/tabsVisibility";
import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
@@ -392,6 +393,7 @@ export class WYSIWYG {
private pendingInputTimeouts = new Map<number, () => void | Promise<void>>();
public tableControl: TableControl;
private largeListVirtualizer?: LargeListVirtualizer;
+ private disposeSpellcheckFocus?: () => void;
private scheduleInput(callback: () => void | Promise<void>, delay = 0, replace = true) {
if (replace && this.inputTimeout) {
@@ -497,7 +499,7 @@ export class WYSIWYG {
this.protyle = protyle;
this.element = document.createElement("div");
this.element.className = "protyle-wysiwyg";
- this.element.setAttribute("spellcheck", "false");
+ this.element.setAttribute("spellcheck", window.siyuan.config.editor.spellcheck.toString());
// Android 和 iPhone 的原生编辑限于正文节点,避免输入法修改列表等结构容器。
this.element.setAttribute("contenteditable", (isIPhone() || isAndroid()) ? "false" : "true");
if (window.siyuan.config.editor.displayBookmarkIcon) {
@@ -508,6 +510,13 @@ export class WYSIWYG {
}
this.bindCommonEvent(protyle);
this.bindEvent(protyle);
+ /// #if BROWSER
+ if (!isMobile() && !isPhablet() && navigator.userAgent.includes("Chrome/")) {
+ this.disposeSpellcheckFocus = bindSpellcheckFocus(this.element, () =>
+ window.siyuan.config.editor.spellcheck && !protyle.disabled &&
+ !protyle.toolbar.isMultiSelectMode() && !getBlockSelectionModeElement(this.element));
+ }
+ /// #endif
if (!isMobile()) {
bindTouchBlockDragSelect(this.element, () => !protyle.toolbar.isMultiSelectMode());
}
@@ -529,6 +538,7 @@ export class WYSIWYG {
}
public destroy() {
+ this.disposeSpellcheckFocus?.();
this.largeListVirtualizer?.destroy();
}