Skip to content

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

:bug: Improve Chinese word selection on Android https://github.com/siyuan-note/siyuan/issues/20033

Daniel76de7fdb046d
diff --git a/app/src/mobile/util/wordSelection.ts b/app/src/mobile/util/wordSelection.ts
new file mode 100644
index 0000000000..4c4b192d04
--- /dev/null
+++ b/app/src/mobile/util/wordSelection.ts
@@ -0,0 +1,139 @@
+interface IWordTextPart {
+ node: Text;
+ offset: number;
+ text: string;
+}
+
+const WORD_SELECTION_BOUNDARY = '[contenteditable="false"], a, img, svg, br, input, textarea, select, button, ' +
+ '[data-type~="a"], [data-type~="block-ref"], [data-type~="virtual-block-ref"], [data-type~="code"], ' +
+ '[data-type~="kbd"], [data-type~="tag"], [data-type~="inline-math"], [data-type~="file-annotation-ref"], ' +
+ '[data-type~="inline-memo"], .protyle-action, .protyle-attr';
+
+const getWordTextParts = (element: Element, range: Range) => {
+ let parts: IWordTextPart[] = [];
+ let found: IWordTextPart[];
+ const flush = () => {
+ if (parts.some(part => part.node === range.startContainer && range.startOffset >= part.offset &&
+ range.startOffset < part.offset + part.text.length) &&
+ parts.some(part => part.node === range.endContainer && range.endOffset > part.offset &&
+ range.endOffset <= part.offset + part.text.length)) {
+ found = parts;
+ }
+ parts = [];
+ };
+ const walk = (node: Node) => {
+ if (found) {
+ return;
+ }
+ if (node.nodeType === Node.TEXT_NODE) {
+ const text = node.textContent;
+ let offset = 0;
+ // 隐藏标记与特殊行内元素是选词边界,普通格式元素中的文字可连续分词。
+ for (const match of text.matchAll(/[\u200b\u2060\ufeff]/g)) {
+ if (match.index > offset) {
+ parts.push({node: node as Text, offset, text: text.substring(offset, match.index)});
+ }
+ flush();
+ offset = match.index + 1;
+ }
+ if (offset < text.length) {
+ parts.push({node: node as Text, offset, text: text.substring(offset)});
+ }
+ } else if (node.nodeType === Node.ELEMENT_NODE) {
+ if ((node as Element).matches(WORD_SELECTION_BOUNDARY)) {
+ flush();
+ } else {
+ Array.from(node.childNodes).forEach(walk);
+ }
+ }
+ };
+ Array.from(element.childNodes).forEach(walk);
+ flush();
+ return found;
+};
+
+export const expandAndroidWordSelection = (blockElement: Element): Range | undefined => {
+ const bridge = window.JSAndroid;
+ const selection = blockElement.ownerDocument.getSelection();
+ if (!bridge?.getWordSelection || !selection?.rangeCount || selection.isCollapsed ||
+ !["NodeParagraph", "NodeHeading", "NodeTable"].includes(blockElement.getAttribute("data-type"))) {
+ return;
+ }
+ const range = selection.getRangeAt(0);
+ if (!/^\p{Script=Han}$/u.test(range.toString()) ||
+ range.startContainer.nodeType !== Node.TEXT_NODE || range.endContainer.nodeType !== Node.TEXT_NODE) {
+ return;
+ }
+ const element = range.startContainer.parentElement?.closest('[contenteditable="true"]');
+ const startBoundary = range.startContainer.parentElement.closest(WORD_SELECTION_BOUNDARY);
+ const endBoundary = range.endContainer.parentElement.closest(WORD_SELECTION_BOUNDARY);
+ if (!element || !blockElement.contains(element) || !element.contains(range.endContainer) ||
+ startBoundary && element.contains(startBoundary) || endBoundary && element.contains(endBoundary)) {
+ return;
+ }
+ const parts = getWordTextParts(element, range);
+ if (!parts) {
+ return;
+ }
+ let start = 0;
+ let end = 0;
+ let offset = 0;
+ parts.forEach(part => {
+ if (part.node === range.startContainer && range.startOffset >= part.offset &&
+ range.startOffset < part.offset + part.text.length) {
+ start = offset + range.startOffset - part.offset;
+ }
+ if (part.node === range.endContainer && range.endOffset > part.offset &&
+ range.endOffset <= part.offset + part.text.length) {
+ end = offset + range.endOffset - part.offset;
+ }
+ offset += part.text.length;
+ });
+ const text = parts.map(part => part.text).join("");
+ let contextStart = Math.max(0, start - 1024);
+ let contextEnd = Math.min(text.length, end + 1024);
+ // 截取上下文时保留完整代理对,原生接口与选区均使用 UTF-16 偏移。
+ if (contextStart > 0 && /[\uDC00-\uDFFF]/.test(text[contextStart])) {
+ contextStart--;
+ }
+ if (contextEnd < text.length && /[\uD800-\uDBFF]/.test(text[contextEnd - 1])) {
+ contextEnd++;
+ }
+ let boundaries: unknown;
+ try {
+ boundaries = JSON.parse(bridge.getWordSelection(text.substring(contextStart, contextEnd),
+ start - contextStart, end - contextStart));
+ } catch (error) {
+ return;
+ }
+ if (!Array.isArray(boundaries) || boundaries.length !== 2 ||
+ !boundaries.every(value => Number.isInteger(value)) ||
+ boundaries[0] < 0 || boundaries[0] > start - contextStart ||
+ boundaries[1] < end - contextStart || boundaries[1] > contextEnd - contextStart ||
+ boundaries[0] === start - contextStart && boundaries[1] === end - contextStart) {
+ return;
+ }
+ const expanded = range.cloneRange();
+ let remainingStart = boundaries[0] + contextStart;
+ let remainingEnd = boundaries[1] + contextStart;
+ for (const part of parts) {
+ if (remainingStart >= 0 && remainingStart < part.text.length) {
+ expanded.setStart(part.node, part.offset + remainingStart);
+ remainingStart = -1;
+ } else if (remainingStart >= 0) {
+ remainingStart -= part.text.length;
+ }
+ if (remainingEnd > 0 && remainingEnd <= part.text.length) {
+ expanded.setEnd(part.node, part.offset + remainingEnd);
+ remainingEnd = -1;
+ } else if (remainingEnd >= 0) {
+ remainingEnd -= part.text.length;
+ }
+ }
+ if (remainingStart !== -1 || remainingEnd !== -1) {
+ return;
+ }
+ selection.removeAllRanges();
+ selection.addRange(expanded);
+ return expanded;
+};
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index 6def3ea7ee..cbdb30a088 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -1,4 +1,5 @@
import {recordReplacementUndo} from "./replacementInput";
+import {expandAndroidWordSelection} from "../../mobile/util/wordSelection";
import {bindBoundedBlockDragSelect} from "./boundedBlockDragSelect";
import {bindEmbedToolbarVisibility} from "./embedToolbarVisibility";
import {bindSpellcheckFocus} from "../util/spellcheckFocus";
@@ -3887,6 +3888,10 @@ export class WYSIWYG {
protyle.wysiwyg.flushPendingInput();
setInsertWbrHTML(nodeElement, protyle.toolbar.range, protyle);
}
+ const wordRange = expandAndroidWordSelection(nodeElement);
+ if (wordRange) {
+ protyle.toolbar.range = wordRange;
+ }
contentMenu(protyle, hasClosestBlock(protyle.toolbar.range.startContainer) || nodeElement);
addSpellcheckMenuItems(spellcheckContext);
/// #if !MOBILE
@@ -4717,7 +4722,7 @@ export class WYSIWYG {
target.closest("[contenteditable]")?.getAttribute("contenteditable") !== "false" &&
selection?.rangeCount && !selection.isCollapsed && selection.toString() &&
nodeElement.contains(selection.anchorNode) && nodeElement.contains(selection.focusNode)) {
- protyle.toolbar.range = selection.getRangeAt(0);
+ protyle.toolbar.range = expandAndroidWordSelection(nodeElement) || selection.getRangeAt(0);
contentMenu(protyle, nodeElement);
}
/// #endif
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index dbeb52684a..4099a60b13 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -237,6 +237,7 @@ interface Window {
getScreenWidthPx(): number
exit(): void
setWebViewFocusable(enable: boolean): void
+ getWordSelection?(text: string, start: number, end: number): string
sendNotification(channel: string, title: string, body: string, delayInSeconds: number): number
cancelNotification(id: number): void
logInputEvent?(details: string): void
diff --git a/app/tests/mobileContentToolbar.test.js b/app/tests/mobileContentToolbar.test.js
index 5cd4b4bffe..517fd0c686 100644
--- a/app/tests/mobileContentToolbar.test.js
+++ b/app/tests/mobileContentToolbar.test.js
@@ -104,6 +104,82 @@ const runCases = async () => {
assert.equal(state.toolbar.subElement.classList.contains("fn__none"), true);
}
+ // Android 分词跨普通格式扩展选区,思源菜单使用扩展后的文字执行复制和剪切。
+ const selectChinese = state => {
+ const range = document.createRange();
+ range.selectNodeContents(state.editable.querySelector("b"));
+ range.setStart(state.editable.querySelector("b").firstChild, 0);
+ range.setEnd(state.editable.querySelector("b").firstChild, 1);
+ window.focusContentRange(range);
+ };
+ const nativeCalls = [];
+ window.JSAndroid = {getWordSelection(text, start, end) {
+ nativeCalls.push({text, start, end});
+ const offset = text.indexOf("为什么");
+ return JSON.stringify([offset, offset + 3]);
+ }};
+ for (const table of [false, true]) {
+ for (const action of ["copy", "cut"]) {
+ const state = createEditor(false, table);
+ state.editable.innerHTML = "😀呀,为什么".replace("什么", "<b>什</b>么");
+ selectChinese(state);
+ state.editable.querySelector("b").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));
+ assert.equal(getSelection().toString(), "为什么");
+ assert.equal(state.toolbar.range.toString(), "为什么");
+ assert.deepEqual(nativeCalls.at(-1), {text: "😀呀,为什么", start: 5, end: 6});
+ assert.equal(state.toolbar.subElement.classList.contains("fn__none"), false);
+ await click(state, action);
+ assert.deepEqual(commands.at(-1), {command: action, text: "为什么"});
+ }
+ }
+
+ // 特殊元素与隐藏标记切断分词上下文,已选词语、英文和代码块不重新分词。
+ for (const boundary of ['<span data-type="code">为</span>', "为\u200b", '<a href="#">为</a>']) {
+ const state = createEditor(false);
+ state.editable.innerHTML = boundary + "<b>什</b>么";
+ selectChinese(state);
+ window.JSAndroid.getWordSelection = (text, start, end) => {
+ assert.deepEqual({text, start, end}, {text: "什么", start: 0, end: 1});
+ return "[0,2]";
+ };
+ assert.equal(window.expandAndroidWordSelection(state.block).toString(), "什么");
+ }
+ window.JSAndroid.getWordSelection = () => { throw new Error("Unexpected native call"); };
+ const english = createEditor(false);
+ assert.equal(window.expandAndroidWordSelection(english.block), undefined);
+ assert.equal(getSelection().toString(), "lph");
+ const special = createEditor(false);
+ special.editable.innerHTML = "为<b>什</b>么";
+ selectChinese(special);
+ special.block.setAttribute("data-type", "NodeCodeBlock");
+ assert.equal(window.expandAndroidWordSelection(special.block), undefined);
+ special.block.setAttribute("data-type", "NodeParagraph");
+ special.editable.querySelector("b").setAttribute("data-type", "block-ref");
+ assert.equal(window.expandAndroidWordSelection(special.block), undefined);
+ special.editable.querySelector("b").removeAttribute("data-type");
+ const wordRange = getSelection().getRangeAt(0);
+ wordRange.setStart(special.editable.firstChild, 0);
+ wordRange.setEnd(special.editable.lastChild, 1);
+ assert.equal(window.expandAndroidWordSelection(special.block), undefined);
+ assert.equal(getSelection().toString(), "为什么");
+
+ // 旧客户端、原生失败与无效偏移保留原选区,避免错误选中相邻内容。
+ const fallback = createEditor(false);
+ fallback.editable.innerHTML = "为<b>什</b>么";
+ selectChinese(fallback);
+ for (const reply of ["", "null", "{}", "[0]", "[-1,3]", "[0,4]", "[2,3]", "[0,1]", "[0,2.5]", "[1,2]"]) {
+ window.JSAndroid.getWordSelection = () => reply;
+ assert.equal(window.expandAndroidWordSelection(fallback.block), undefined);
+ assert.equal(getSelection().toString(), "什");
+ }
+ window.JSAndroid.getWordSelection = () => { throw new Error("Unavailable"); };
+ assert.equal(window.expandAndroidWordSelection(fallback.block), undefined);
+ delete window.JSAndroid;
+ fallback.editable.querySelector("b").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));
+ assert.equal(fallback.toolbar.range.toString(), "什");
+ await click(fallback, "copy");
+ assert.deepEqual(commands.at(-1), {command: "copy", text: "什"});
+
// 有块菜单时继续支持再次全选,并通过现有多选菜单操作已选块。
const documentEditor = createEditor(true);
await click(documentEditor, "select");
@@ -161,6 +237,8 @@ const runElectron = async () => {
read("protyle/wysiwyg/blockSelection"),
read("protyle/toolbar/subElementLifecycle"),
read("mobile/util/multiSelectToolbar"),
+ read("mobile/util/wordSelection"),
+ "window.expandAndroidWordSelection = expandAndroidWordSelection;",
extract("protyle/wysiwyg/getBlock", ["getContenteditableElement"]),
extract("protyle/ui/hideElements", ["hideElements"]),
extract("protyle/util/selection", ["selectIsEditor", "selectAll", "getSelectionOffset", "focusByRange", "getEditorRange"]),
diff --git a/app/tests/textSelectionContextMenu.test.js b/app/tests/textSelectionContextMenu.test.js
index 27e3eea78a..d22ba140f5 100644
--- a/app/tests/textSelectionContextMenu.test.js
+++ b/app/tests/textSelectionContextMenu.test.js
@@ -23,6 +23,8 @@ const sources = () => {
const range = selection.statements.find(node => ts.isVariableStatement(node) &&
node.declarationList.declarations.some(item => item.name.getText(selection) === "getEditorRange"));
assert.ok(range);
+ const wordSelection = readFileSync(path.join(__dirname, "../src/mobile/util/wordSelection.ts"), "utf8")
+ .replace("export const ", "const ");
const preprocess = (source, mobile) => {
const active = [true];
return source.split("\n").filter(line => {
@@ -42,7 +44,7 @@ const sources = () => {
};
return [false, true].map(mobile => ts.transpileModule(preprocess(
`const bind = function(protyle) {let beforeContextmenuRange; ${bindings.join(";\n")};};\n` +
- range.getText(selection).replace("export ", ""), mobile), {
+ range.getText(selection).replace("export ", "") + "\n" + wordSelection, mobile), {
compilerOptions: {target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS},
}).outputText);
};
@@ -121,6 +123,25 @@ const cases = async compiled => {
check.equal(menus.length, 1);
check.equal(menus[0].block, blocks[1]);
check.equal(selection.isCollapsed, true);
+
+ // 长按菜单扩展 Android 的中文单字选区,并保留思源菜单与后续复制读取的选区。
+ texts[1].textContent = "我的天空大地呀为什么";
+ dependencies.window.JSAndroid = {getWordSelection(text, start, end) {
+ check.deepEqual({text, start, end}, {text: "我的天空大地呀为什么", start: 8, end: 9});
+ return "[7,10]";
+ }};
+ selection.setBaseAndExtent(texts[1], 8, texts[1], 9);
+ menus.length = 0;
+ callbacks.pointerdown();
+ let prevented = false;
+ await callbacks.contextmenu({shiftKey: false, target: blocks[1].firstElementChild, detail: {},
+ clientX: 20, clientY: 20, stopPropagation() {}, preventDefault() { prevented = true; }});
+ check.equal(prevented, true);
+ check.equal(menus.length, 1);
+ check.equal(menus[0].text, "为什么");
+ check.equal(menus[0].copy(), "为什么");
+ check.equal(selection.toString(), "为什么");
+ delete dependencies.window.JSAndroid;
}
return "Text selection context menu cases passed";
};